initial commit

This commit is contained in:
Phillip Smith
2021-08-24 17:55:37 +10:00
commit 69e42aac8d
387 changed files with 69168 additions and 0 deletions

26
Makefile.am Normal file
View File

@@ -0,0 +1,26 @@
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
SUBDIRS = src

820
Makefile.in Normal file
View File

@@ -0,0 +1,820 @@
# Makefile.in generated by automake 1.15.1 from Makefile.am.
# @configure_input@
# Copyright (C) 1994-2017 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
VPATH = @srcdir@
am__is_gnu_make = { \
if test -z '$(MAKELEVEL)'; then \
false; \
elif test -n '$(MAKE_HOST)'; then \
true; \
elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
true; \
else \
false; \
fi; \
}
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgdatadir = $(datadir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkglibexecdir = $(libexecdir)/@PACKAGE@
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = .
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/ax_boost_asio.m4 \
$(top_srcdir)/m4/ax_boost_base.m4 \
$(top_srcdir)/m4/ax_cxx_compile_stdcxx.m4 \
$(top_srcdir)/standalone/config_files.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \
$(am__configure_deps) $(am__DIST_COMMON)
am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
configure.lineno config.status.lineno
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
AM_V_P = $(am__v_P_@AM_V@)
am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_@AM_V@)
am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_@AM_V@)
am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
am__v_at_0 = @
am__v_at_1 =
SOURCES =
DIST_SOURCES =
RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
ctags-recursive dvi-recursive html-recursive info-recursive \
install-data-recursive install-dvi-recursive \
install-exec-recursive install-html-recursive \
install-info-recursive install-pdf-recursive \
install-ps-recursive install-recursive installcheck-recursive \
installdirs-recursive pdf-recursive ps-recursive \
tags-recursive uninstall-recursive
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \
distclean-recursive maintainer-clean-recursive
am__recursive_targets = \
$(RECURSIVE_TARGETS) \
$(RECURSIVE_CLEAN_TARGETS) \
$(am__extra_recursive_targets)
AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
cscope distdir dist dist-all distcheck
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \
$(LISP)config.h.in
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
am__define_uniq_tagged_files = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
CSCOPE = cscope
DIST_SUBDIRS = $(SUBDIRS)
am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in ar-lib \
compile config.guess config.sub install-sh missing
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
distdir = $(PACKAGE)-$(VERSION)
top_distdir = $(distdir)
am__remove_distdir = \
if test -d "$(distdir)"; then \
find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
&& rm -rf "$(distdir)" \
|| { sleep 5 && rm -rf "$(distdir)"; }; \
else :; fi
am__post_remove_distdir = $(am__remove_distdir)
am__relativize = \
dir0=`pwd`; \
sed_first='s,^\([^/]*\)/.*$$,\1,'; \
sed_rest='s,^[^/]*/*,,'; \
sed_last='s,^.*/\([^/]*\)$$,\1,'; \
sed_butlast='s,/*[^/]*$$,,'; \
while test -n "$$dir1"; do \
first=`echo "$$dir1" | sed -e "$$sed_first"`; \
if test "$$first" != "."; then \
if test "$$first" = ".."; then \
dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
else \
first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
if test "$$first2" = "$$first"; then \
dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
else \
dir2="../$$dir2"; \
fi; \
dir0="$$dir0"/"$$first"; \
fi; \
fi; \
dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
done; \
reldir="$$dir2"
DIST_ARCHIVES = $(distdir).tar.gz
GZIP_ENV = --best
DIST_TARGETS = dist-gzip
distuninstallcheck_listfiles = find . -type f -print
am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \
| sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$'
distcleancheck_listfiles = find . -type f -print
ACLOCAL = @ACLOCAL@
AMTAR = @AMTAR@
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
AR = @AR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
BOOST_ASIO_LIB = @BOOST_ASIO_LIB@
BOOST_CPPFLAGS = @BOOST_CPPFLAGS@
BOOST_LDFLAGS = @BOOST_LDFLAGS@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CXX = @CXX@
CXXCPP = @CXXCPP@
CXXDEPMODE = @CXXDEPMODE@
CXXFLAGS = @CXXFLAGS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
GREP = @GREP@
HAVE_CXX17 = @HAVE_CXX17@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
LDFLAGS = @LDFLAGS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LTLIBOBJS = @LTLIBOBJS@
MAKEINFO = @MAKEINFO@
MKDIR_P = @MKDIR_P@
OBJEXT = @OBJEXT@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
RANLIB = @RANLIB@
RE2_CPPFLAGS = @RE2_CPPFLAGS@
RE2_LDFLAGS = @RE2_LDFLAGS@
RE2_LIBS = @RE2_LIBS@
RRDLIB = @RRDLIB@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
STRIP = @STRIP@
VERSION = @VERSION@
abs_builddir = @abs_builddir@
abs_srcdir = @abs_srcdir@
abs_top_builddir = @abs_top_builddir@
abs_top_srcdir = @abs_top_srcdir@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_CXX = @ac_ct_CXX@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
builddir = @builddir@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
localedir = @localedir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
nagios_headers = @nagios_headers@
oldincludedir = @oldincludedir@
pdfdir = @pdfdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
runstatedir = @runstatedir@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
srcdir = @srcdir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
top_build_prefix = @top_build_prefix@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
SUBDIRS = src
all: config.h
$(MAKE) $(AM_MAKEFLAGS) all-recursive
.SUFFIXES:
am--refresh: Makefile
@:
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \
$(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
echo ' $(SHELL) ./config.status'; \
$(SHELL) ./config.status;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
$(SHELL) ./config.status --recheck
$(top_srcdir)/configure: $(am__configure_deps)
$(am__cd) $(srcdir) && $(AUTOCONF)
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
$(am__aclocal_m4_deps):
config.h: stamp-h1
@test -f $@ || rm -f stamp-h1
@test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1
stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
@rm -f stamp-h1
cd $(top_builddir) && $(SHELL) ./config.status config.h
$(srcdir)/config.h.in: $(am__configure_deps)
($(am__cd) $(top_srcdir) && $(AUTOHEADER))
rm -f stamp-h1
touch $@
distclean-hdr:
-rm -f config.h stamp-h1
# This directory's subdirectories are mostly independent; you can cd
# into them and run 'make' without going through this Makefile.
# To change the values of 'make' variables: instead of editing Makefiles,
# (1) if the variable is set in 'config.status', edit 'config.status'
# (which will cause the Makefiles to be regenerated when you run 'make');
# (2) otherwise, pass the desired values on the 'make' command line.
$(am__recursive_targets):
@fail=; \
if $(am__make_keepgoing); then \
failcom='fail=yes'; \
else \
failcom='exit 1'; \
fi; \
dot_seen=no; \
target=`echo $@ | sed s/-recursive//`; \
case "$@" in \
distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
*) list='$(SUBDIRS)' ;; \
esac; \
for subdir in $$list; do \
echo "Making $$target in $$subdir"; \
if test "$$subdir" = "."; then \
dot_seen=yes; \
local_target="$$target-am"; \
else \
local_target="$$target"; \
fi; \
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|| eval $$failcom; \
done; \
if test "$$dot_seen" = "no"; then \
$(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
fi; test -z "$$fail"
ID: $(am__tagged_files)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-recursive
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
include_option=--etags-include; \
empty_fix=.; \
else \
include_option=--include; \
empty_fix=; \
fi; \
list='$(SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
test ! -f $$subdir/TAGS || \
set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
fi; \
done; \
$(am__define_uniq_tagged_files); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-recursive
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(am__define_uniq_tagged_files); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscope: cscope.files
test ! -s cscope.files \
|| $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS)
clean-cscope:
-rm -f cscope.files
cscope.files: clean-cscope cscopelist
cscopelist: cscopelist-recursive
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-rm -f cscope.out cscope.in.out cscope.po.out cscope.files
distdir: $(DISTFILES)
$(am__remove_distdir)
test -d "$(distdir)" || mkdir "$(distdir)"
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
$(am__make_dryrun) \
|| test -d "$(distdir)/$$subdir" \
|| $(MKDIR_P) "$(distdir)/$$subdir" \
|| exit 1; \
dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
$(am__relativize); \
new_distdir=$$reldir; \
dir1=$$subdir; dir2="$(top_distdir)"; \
$(am__relativize); \
new_top_distdir=$$reldir; \
echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
($(am__cd) $$subdir && \
$(MAKE) $(AM_MAKEFLAGS) \
top_distdir="$$new_top_distdir" \
distdir="$$new_distdir" \
am__remove_distdir=: \
am__skip_length_check=: \
am__skip_mode_fix=: \
distdir) \
|| exit 1; \
fi; \
done
-test -n "$(am__skip_mode_fix)" \
|| find "$(distdir)" -type d ! -perm -755 \
-exec chmod u+rwx,go+rx {} \; -o \
! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
! -type d ! -perm -400 -exec chmod a+r {} \; -o \
! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
|| chmod -R a+r "$(distdir)"
dist-gzip: distdir
tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz
$(am__post_remove_distdir)
dist-bzip2: distdir
tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2
$(am__post_remove_distdir)
dist-lzip: distdir
tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz
$(am__post_remove_distdir)
dist-xz: distdir
tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz
$(am__post_remove_distdir)
dist-tarZ: distdir
@echo WARNING: "Support for distribution archives compressed with" \
"legacy program 'compress' is deprecated." >&2
@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
$(am__post_remove_distdir)
dist-shar: distdir
@echo WARNING: "Support for shar distribution archives is" \
"deprecated." >&2
@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz
$(am__post_remove_distdir)
dist-zip: distdir
-rm -f $(distdir).zip
zip -rq $(distdir).zip $(distdir)
$(am__post_remove_distdir)
dist dist-all:
$(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:'
$(am__post_remove_distdir)
# This target untars the dist file and tries a VPATH configuration. Then
# it guarantees that the distribution is self-contained by making another
# tarfile.
distcheck: dist
case '$(DIST_ARCHIVES)' in \
*.tar.gz*) \
eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\
*.tar.bz2*) \
bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
*.tar.lz*) \
lzip -dc $(distdir).tar.lz | $(am__untar) ;;\
*.tar.xz*) \
xz -dc $(distdir).tar.xz | $(am__untar) ;;\
*.tar.Z*) \
uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
*.shar.gz*) \
eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\
*.zip*) \
unzip $(distdir).zip ;;\
esac
chmod -R a-w $(distdir)
chmod u+w $(distdir)
mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst
chmod a-w $(distdir)
test -d $(distdir)/_build || exit 0; \
dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
&& dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
&& am__cwd=`pwd` \
&& $(am__cd) $(distdir)/_build/sub \
&& ../../configure \
$(AM_DISTCHECK_CONFIGURE_FLAGS) \
$(DISTCHECK_CONFIGURE_FLAGS) \
--srcdir=../.. --prefix="$$dc_install_base" \
&& $(MAKE) $(AM_MAKEFLAGS) \
&& $(MAKE) $(AM_MAKEFLAGS) dvi \
&& $(MAKE) $(AM_MAKEFLAGS) check \
&& $(MAKE) $(AM_MAKEFLAGS) install \
&& $(MAKE) $(AM_MAKEFLAGS) installcheck \
&& $(MAKE) $(AM_MAKEFLAGS) uninstall \
&& $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
distuninstallcheck \
&& chmod -R a-w "$$dc_install_base" \
&& ({ \
(cd ../.. && umask 077 && mkdir "$$dc_destdir") \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
} || { rm -rf "$$dc_destdir"; exit 1; }) \
&& rm -rf "$$dc_destdir" \
&& $(MAKE) $(AM_MAKEFLAGS) dist \
&& rm -rf $(DIST_ARCHIVES) \
&& $(MAKE) $(AM_MAKEFLAGS) distcleancheck \
&& cd "$$am__cwd" \
|| exit 1
$(am__post_remove_distdir)
@(echo "$(distdir) archives ready for distribution: "; \
list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x'
distuninstallcheck:
@test -n '$(distuninstallcheck_dir)' || { \
echo 'ERROR: trying to run $@ with an empty' \
'$$(distuninstallcheck_dir)' >&2; \
exit 1; \
}; \
$(am__cd) '$(distuninstallcheck_dir)' || { \
echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \
exit 1; \
}; \
test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \
|| { echo "ERROR: files left after uninstall:" ; \
if test -n "$(DESTDIR)"; then \
echo " (check DESTDIR support)"; \
fi ; \
$(distuninstallcheck_listfiles) ; \
exit 1; } >&2
distcleancheck: distclean
@if test '$(srcdir)' = . ; then \
echo "ERROR: distcleancheck can only run from a VPATH build" ; \
exit 1 ; \
fi
@test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
|| { echo "ERROR: files left in build directory after distclean:" ; \
$(distcleancheck_listfiles) ; \
exit 1; } >&2
check-am: all-am
check: check-recursive
all-am: Makefile config.h
installdirs: installdirs-recursive
installdirs-am:
install: install-recursive
install-exec: install-exec-recursive
install-data: install-data-recursive
uninstall: uninstall-recursive
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-recursive
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-recursive
clean-am: clean-generic mostlyclean-am
distclean: distclean-recursive
-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-hdr distclean-tags
dvi: dvi-recursive
dvi-am:
html: html-recursive
html-am:
info: info-recursive
info-am:
install-data-am:
install-dvi: install-dvi-recursive
install-dvi-am:
install-exec-am:
install-html: install-html-recursive
install-html-am:
install-info: install-info-recursive
install-info-am:
install-man:
install-pdf: install-pdf-recursive
install-pdf-am:
install-ps: install-ps-recursive
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-recursive
-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-rm -rf $(top_srcdir)/autom4te.cache
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-recursive
mostlyclean-am: mostlyclean-generic
pdf: pdf-recursive
pdf-am:
ps: ps-recursive
ps-am:
uninstall-am:
.MAKE: $(am__recursive_targets) all install-am install-strip
.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \
am--refresh check check-am clean clean-cscope clean-generic \
cscope cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \
dist-gzip dist-lzip dist-shar dist-tarZ dist-xz dist-zip \
distcheck distclean distclean-generic distclean-hdr \
distclean-tags distcleancheck distdir distuninstallcheck dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs installdirs-am \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \
uninstall-am
.PRECIOUS: Makefile
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

1215
aclocal.m4 vendored Normal file

File diff suppressed because it is too large Load Diff

87
api/c++/Livestatus.cc Normal file
View File

@@ -0,0 +1,87 @@
// +------------------------------------------------------------------+
// | ____ _ _ __ __ _ __ |
// | / ___| |__ ___ ___| | __ | \/ | |/ / |
// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
// | | |___| | | | __/ (__| < | | | | . \ |
// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
// | |
// | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
// +------------------------------------------------------------------+
//
// This file is part of Check_MK.
// The official homepage is at http://mathias-kettner.de/check_mk.
//
// check_mk is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation in version 2. check_mk is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public License for more de-
// ails. You should have received a copy of the GNU General Public
// License along with GNU Make; see the file COPYING. If not, write
// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301 USA.
#include "Livestatus.h"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
void Livestatus::connectUNIX(const char *socket_path) {
_connection = socket(PF_LOCAL, SOCK_STREAM, 0);
struct sockaddr_un sockaddr;
sockaddr.sun_family = AF_UNIX;
strncpy(sockaddr.sun_path, socket_path, sizeof(sockaddr.sun_path) - 1);
sockaddr.sun_path[sizeof(sockaddr.sun_path) - 1] = '\0';
if (0 > connect(_connection, (const struct sockaddr *)&sockaddr,
sizeof(sockaddr))) {
close(_connection);
_connection = -1;
} else
_file = fdopen(_connection, "r");
}
Livestatus::~Livestatus() { disconnect(); }
void Livestatus::disconnect() {
if (isConnected()) {
if (_file)
fclose(_file);
else
close(_connection);
}
_connection = -1;
_file = 0;
}
void Livestatus::sendQuery(const char *query) {
write(_connection, query, strlen(query));
std::string separators = "Separators: 10 1 2 3\n";
write(_connection, separators.c_str(), separators.size());
shutdown(_connection, SHUT_WR);
}
std::vector<std::string> *Livestatus::nextRow() {
char line[65536];
if (0 != fgets(line, sizeof(line), _file)) {
// strip trailing linefeed
char *end = strlen(line) + line;
if (end > line && *(end - 1) == '\n') {
*(end - 1) = 0;
--end;
}
std::vector<std::string> *row = new std::vector<std::string>;
char *scan = line;
while (scan < end) {
char *zero = scan;
while (zero < end && *zero != '\001') zero++;
*zero = 0;
row->push_back(std::string(scan));
scan = zero + 1;
}
return row;
} else
return 0;
}

50
api/c++/Livestatus.h Normal file
View File

@@ -0,0 +1,50 @@
// +------------------------------------------------------------------+
// | ____ _ _ __ __ _ __ |
// | / ___| |__ ___ ___| | __ | \/ | |/ / |
// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
// | | |___| | | | __/ (__| < | | | | . \ |
// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
// | |
// | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
// +------------------------------------------------------------------+
//
// This file is part of Check_MK.
// The official homepage is at http://mathias-kettner.de/check_mk.
//
// check_mk is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation in version 2. check_mk is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public License for more de-
// ails. You should have received a copy of the GNU General Public
// License along with GNU Make; see the file COPYING. If not, write
// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301 USA.
#ifndef Livestatus_h
#define Livestatus_h
#include <stdio.h>
#include <string>
#include <vector>
// simple C++ API for accessing Livestatus from C++,
// currently supports only UNIX sockets, no TCP. But
// this is only a simple enhancement.
class Livestatus {
int _connection;
FILE *_file;
public:
Livestatus() : _connection(-1), _file(0){};
~Livestatus();
void connectUNIX(const char *socketpath);
bool isConnected() const { return _connection >= 0; };
void disconnect();
void sendQuery(const char *query);
std::vector<std::string> *nextRow();
};
#endif // Livestatus_h

42
api/c++/Makefile Normal file
View File

@@ -0,0 +1,42 @@
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
ifneq (DEBUG,)
CXXFLAGS += -g -DDEBUG
LDFLAGS += -g
endif
all: demo
demo.o: demo.cc Livestatus.h
$(CXX) $(CXXFLAGS) -c -o $@ $<
Livestatus.o: Livestatus.cc Livestatus.h
$(CXX) $(CXXFLAGS) -c -o $@ $<
demo: demo.o Livestatus.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^
clean:
$(RM) demo.o demo Livetatus.o

54
api/c++/demo.cc Normal file
View File

@@ -0,0 +1,54 @@
// +------------------------------------------------------------------+
// | ____ _ _ __ __ _ __ |
// | / ___| |__ ___ ___| | __ | \/ | |/ / |
// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
// | | |___| | | | __/ (__| < | | | | . \ |
// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
// | |
// | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
// +------------------------------------------------------------------+
//
// This file is part of Check_MK.
// The official homepage is at http://mathias-kettner.de/check_mk.
//
// check_mk is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation in version 2. check_mk is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public License for more de-
// ails. You should have received a copy of the GNU General Public
// License along with GNU Make; see the file COPYING. If not, write
// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301 USA.
#include <stdio.h>
#include "Livestatus.h"
const char *query =
"GET status\nColumns: livestatus_version program_version\nColumnHeaders: on\n";
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s SOCKETPATH\n", argv[0]);
return 1;
}
const char *socket_path = argv[1];
Livestatus live;
live.connectUNIX(socket_path);
if (live.isConnected()) {
fprintf(stderr, "Couldn't connect to socket '%s'\n", socket_path);
return 1;
}
live.sendQuery(query);
std::vector<std::string> *row;
while (0 != (row = live.nextRow())) {
printf("Line:\n");
for (size_t i = 0; i < row->size(); i++)
printf("%s\n", (*row)[i].c_str());
delete row;
}
live.disconnect();
return 0;
}

164
api/perl/Changes Normal file
View File

@@ -0,0 +1,164 @@
Revision history for Perl extension Monitoring::Livestatus.
0.74 Fri Apr 22 00:16:37 CEST 2011
- fixed problem with bulk commands
0.72 Tue Apr 19 15:38:34 CEST 2011
- fixed problem with inet timeout
0.70 Sat Apr 16 16:43:57 CEST 2011
- fixed tests using english
0.68 Wed Mar 23 23:16:22 CET 2011
- fixed typo
0.66 Tue Mar 22 23:19:23 CET 2011
- added support for additonal headers
0.64 Fri Nov 5 11:02:51 CET 2010
- removed useless test dependecies
0.62 Wed Nov 3 15:20:02 CET 2010
- fixed tests with threads > 1.79
0.60 Wed Aug 25 15:04:22 CEST 2010
- fixed package and made author tests optional
0.58 Wed Aug 11 09:30:30 CEST 2010
- added callback support
0.56 Tue Aug 10 09:45:28 CEST 2010
- changed parser from csv to JSON::XS
0.54 Wed Jun 23 16:43:11 CEST 2010
- fixed utf8 support
0.52 Mon May 17 15:54:42 CEST 2010
- fixed connection timeout
0.50 Mon May 17 12:29:20 CEST 2010
- fixed test requirements
0.48 Sun May 16 15:16:12 CEST 2010
- added retry option for better core restart handling
- added new columns from livestatus 1.1.4
0.46 Tue Mar 16 15:19:08 CET 2010
- error code have been changed in livestatus (1.1.3)
- fixed threads support
0.44 Sun Feb 28 12:19:56 CET 2010
- fixed bug when disabling backends and using threads
0.42 Thu Feb 25 21:32:37 CET 2010
- added possibility to disable specific backends
0.41 Sat Feb 20 20:37:36 CET 2010
- fixed tests on windows
0.40 Thu Feb 11 01:00:20 CET 2010
- fixed timeout for inet sockets
0.38 Fri Jan 29 20:54:50 CET 2010
- added limit option
0.37 Thu Jan 28 21:23:19 CET 2010
- removed inc from repository
0.36 Sun Jan 24 00:14:13 CET 2010
- added more backend tests
- fixed problem with summing up non numbers
0.35 Mon Jan 11 15:37:51 CET 2010
- added TCP_NODELAY option for inet sockets
- fixed undefined values
0.34 Sun Jan 10 12:29:57 CET 2010
- fixed return code with multi backend and different errors
0.32 Sat Jan 9 16:12:48 CET 2010
- added deepcopy option
0.31 Thu Jan 7 08:56:48 CET 2010
- added generic tests for livestatus backend
- fixed problem when selecting specific backend
0.30 Wed Jan 6 16:05:33 CET 2010
- renamed project to Monitoring::Livestatus
0.29 Mon Dec 28 00:11:53 CET 2009
- retain order of backends when merge outut
- renamed select_scalar_value to selectscalar_value
- fixed sums for selectscalar_value
- fixed missing META.yml
0.28 Sat Dec 19 19:19:13 CET 2009
- fixed bug in column alias
- added support for multiple peers
- changed to Module::Install
0.26 Fri Dec 4 08:25:07 CET 2009
- added peer name
- added peer arg (can be socket or server)
0.24 Wed Dec 2 23:41:34 CET 2009
- added support for StatsAnd: and StatsOr: queries
- table alias support for selectall_hashref and selectrow_hashref
- added support for Stats: ... as alias
- added support for StatsAnd:... as alias
- added support for StatsOr: ... as alias
- added support for StatsGroupBy: (with alias)
- added support column aliases for Column: header
0.22 Fri Nov 27 01:04:16 CET 2009
- fixed errors on socket problems
- fixed sending commands
0.20 Sun Nov 22 12:41:39 CET 2009
- added keepalive support
- added support for ResponseHeader: fixed16
- added error handling
- added pod test
- added tests with real socket / server
- added column aliases
- added timeout option
- implemented select_scalar_value()
- fixed perl::critic tests
0.18 Sat Nov 14 2009 08:58:02 GMT
- fixed requirements
- fixed typos
0.17 Fri Nov 13 17:15:44 CET 2009
- added support for tcp connections
0.16 Sun Nov 8 23:17:35 CET 2009
- added support for stats querys
0.15 Sat Nov 7 21:28:33 CET 2009
- fixed typos in doc
- minor bugfixes
0.14 Fri Nov 6 09:39:56 CET 2009
- implemented selectcol_arrayref
- implemented selectrow_array
- implemented selectrow_hashref
0.13 Fri Nov 6 00:03:38 CET 2009
- fixed tests on solaris
- implemented selectall_hashref()
0.12 Thu Nov 5 09:34:59 CET 2009
- fixed tests with thread support
- added more tests
0.11 Wed Nov 4 23:12:16 2009
- inital working version
0.10 Tue Nov 3 17:13:16 2009
- renamed to Nagios::MKLivestatus
0.01 Tue Nov 3 00:07:46 2009
- original version; created by h2xs 1.23 with options
-A -X -n Nagios::Livestatus

38
api/perl/MANIFEST Normal file
View File

@@ -0,0 +1,38 @@
Changes
examples/dump.pl
examples/test.pl
inc/Module/AutoInstall.pm
inc/Module/Install.pm
inc/Module/Install/AutoInstall.pm
inc/Module/Install/Base.pm
inc/Module/Install/Can.pm
inc/Module/Install/Fetch.pm
inc/Module/Install/Include.pm
inc/Module/Install/Makefile.pm
inc/Module/Install/Metadata.pm
inc/Module/Install/Win32.pm
inc/Module/Install/WriteAll.pm
lib/Monitoring/Livestatus.pm
lib/Monitoring/Livestatus/INET.pm
lib/Monitoring/Livestatus/MULTI.pm
lib/Monitoring/Livestatus/UNIX.pm
Makefile.PL
MANIFEST This list of files
META.yml
README
t/01-Monitoring-Livestatus-basic_tests.t
t/02-Monitoring-Livestatus-internals.t
t/03-Monitoring-Livestatus-MULTI-internals.t
t/20-Monitoring-Livestatus-test_socket.t
t/21-Monitoring-Livestatus-INET.t
t/22-Monitoring-Livestatus-UNIX.t
t/30-Monitoring-Livestatus-live-test.t
t/31-Monitoring-Livestatus-MULTI-live-test.t
t/32-Monitoring-Livestatus-backend-test.t
t/33-Monitoring-Livestatus-test_socket_timeout.t
t/34-Monitoring-Livestatus-utf8_support.t
t/35-Monitoring-Livestatus-callbacks_support.t
t/97-Pod.t
t/98-Pod-Coverage.t
t/99-Perl-Critic.t
t/perlcriticrc

37
api/perl/META.yml Normal file
View File

@@ -0,0 +1,37 @@
---
abstract: 'Perl API for check_mk livestatus to access runtime'
author:
- 'Sven Nierlein, <nierlein@cpan.org>'
build_requires:
ExtUtils::MakeMaker: 6.42
configure_requires:
ExtUtils::MakeMaker: 6.42
distribution_type: module
generated_by: 'Module::Install version 1.00'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: 1.4
name: Monitoring-Livestatus
no_index:
directory:
- examples
- inc
- t
requires:
Digest::MD5: 0
Encode: 0
IO::Socket::INET: 0
IO::Socket::UNIX: 0
JSON::XS: 0
Scalar::Util: 0
Test::More: 0.87
Thread::Queue: 2.11
perl: 5.6.0
utf8: 0
resources:
bugtracker: http://github.com/sni/Monitoring-Livestatus/issues
homepage: http://search.cpan.org/dist/Monitoring-Livestatus/
license: http://dev.perl.org/licenses/
repository: http://github.com/sni/Monitoring-Livestatus
version: 0.74

41
api/perl/Makefile.PL Normal file
View File

@@ -0,0 +1,41 @@
# IMPORTANT: if you delete this file your app will not work as
# expected. you have been warned
use inc::Module::Install;
name 'Monitoring-Livestatus';
all_from 'lib/Monitoring/Livestatus.pm';
perl_version '5.006';
license 'perl';
resources(
'homepage', => 'http://search.cpan.org/dist/Monitoring-Livestatus/',
'bugtracker' => 'http://github.com/sni/Monitoring-Livestatus/issues',
'repository', => 'http://github.com/sni/Monitoring-Livestatus',
);
requires 'IO::Socket::UNIX';
requires 'IO::Socket::INET';
requires 'Digest::MD5';
requires 'Scalar::Util';
requires 'Test::More' => '0.87';
requires 'Thread::Queue' => '2.11';
requires 'utf8';
requires 'Encode';
requires 'JSON::XS';
# test requirements
# these requirements still make it into the META.yml, so they are commented so far
#feature ('authortests',
# -default => 0,
# 'File::Copy::Recursive' => 0,
# 'Test::Pod' => 1.14,
# 'Test::Perl::Critic' => 0,
# 'Test::Pod::Coverage' => 0,
# 'Perl::Critic::Policy::Dynamic::NoIndirect' => 0,
# 'Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseSubs' => 0,
# 'Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData' => 0,
#);
auto_install;
WriteAll;

32
api/perl/README Normal file
View File

@@ -0,0 +1,32 @@
Monitoring-Livestatus
=====================
Monitoring::Livestatus can be used to access the data of the check_mk
Livestatus Addon for Nagios and Icinga.
INSTALLATION
To install this module type the following:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
This module requires no other modules.
SYNOPSIS
my $ml = Monitoring::Livestatus->new( socket => '/var/lib/livestatus/livestatus.sock' );
my $hosts = $ml->selectall_arrayref("GET hosts");
AUTHOR
Sven Nierlein <nierlein@cpan.org>
COPYRIGHT AND LICENCE
Copyright (C) 2009 by Sven Nierlein
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

104
api/perl/examples/dump.pl Executable file
View File

@@ -0,0 +1,104 @@
#!/usr/bin/env perl
=head1 NAME
dump.pl - print some information from a socket
=head1 SYNOPSIS
./dump.pl [ -h ] [ -v ] <socket|server>
=head1 DESCRIPTION
this script print some information from a given livestatus socket or server
=head1 ARGUMENTS
script has the following arguments
=over 4
=item help
-h
print help and exit
=item verbose
-v
verbose output
=item socket/server
server local socket file or
server remote address of livestatus
=back
=head1 EXAMPLE
./dump.pl /tmp/live.sock
=head1 AUTHOR
2009, Sven Nierlein, <nierlein@cpan.org>
=cut
use warnings;
use strict;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use lib 'lib';
use lib '../lib';
use Monitoring::Livestatus;
$Data::Dumper::Sortkeys = 1;
#########################################################################
# parse and check cmd line arguments
my ($opt_h, $opt_v, $opt_f);
Getopt::Long::Configure('no_ignore_case');
if(!GetOptions (
"h" => \$opt_h,
"v" => \$opt_v,
"<>" => \&add_file,
)) {
pod2usage( { -verbose => 1, -message => 'error in options' } );
exit 3;
}
if(defined $opt_h) {
pod2usage( { -verbose => 1 } );
exit 3;
}
my $verbose = 0;
if(defined $opt_v) {
$verbose = 1;
}
if(!defined $opt_f) {
pod2usage( { -verbose => 1, -message => 'socket/server is a required option' } );
exit 3;
}
#########################################################################
my $nl = Monitoring::Livestatus->new( peer => $opt_f, verbose => $opt_v );
#########################################################################
#my $hosts = $nl->selectall_hashref('GET hosts', 'name');
#print Dumper($hosts);
#########################################################################
my $services = $nl->selectall_arrayref("GET services\nColumns: description host_name state\nLimit: 2", { Slice => {}});
print Dumper($services);
#########################################################################
sub add_file {
my $file = shift;
$opt_f = $file;
}

143
api/perl/examples/test.pl Executable file
View File

@@ -0,0 +1,143 @@
#!/usr/bin/env perl
=head1 NAME
test.pl - print some information from a socket
=head1 SYNOPSIS
./test.pl [ -h ] [ -v ] <socket|server>
=head1 DESCRIPTION
this script print some information from a given livestatus socket or server
=head1 ARGUMENTS
script has the following arguments
=over 4
=item help
-h
print help and exit
=item verbose
-v
verbose output
=item socket/server
server local socket file or
server remote address of livestatus
=back
=head1 EXAMPLE
./test.pl /tmp/live.sock
=head1 AUTHOR
2009, Sven Nierlein, <nierlein@cpan.org>
=cut
use warnings;
use strict;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use Time::HiRes qw( gettimeofday tv_interval );
use Log::Log4perl qw(:easy);
use lib 'lib';
use lib '../lib';
use Monitoring::Livestatus;
$Data::Dumper::Sortkeys = 1;
#########################################################################
# parse and check cmd line arguments
my ($opt_h, $opt_v, @opt_f);
Getopt::Long::Configure('no_ignore_case');
if(!GetOptions (
"h" => \$opt_h,
"v" => \$opt_v,
"<>" => \&add_file,
)) {
pod2usage( { -verbose => 1, -message => 'error in options' } );
exit 3;
}
if(defined $opt_h) {
pod2usage( { -verbose => 1 } );
exit 3;
}
my $verbose = 0;
if(defined $opt_v) {
$verbose = 1;
}
if(scalar @opt_f == 0) {
pod2usage( { -verbose => 1, -message => 'socket/server is a required option' } );
exit 3;
}
#########################################################################
Log::Log4perl->easy_init($DEBUG);
my $nl = Monitoring::Livestatus->new(
peer => \@opt_f,
verbose => $opt_v,
timeout => 5,
keepalive => 1,
logger => get_logger(),
);
my $log = get_logger();
#########################################################################
my $querys = [
{ 'query' => "GET hostgroups\nColumns: members\nFilter: name = flap\nFilter: name = down\nOr: 2",
'sub' => "selectall_arrayref",
'opt' => {Slice => 1 }
},
# { 'query' => "GET comments",
# 'sub' => "selectall_arrayref",
# 'opt' => {Slice => 1 }
# },
# { 'query' => "GET downtimes",
# 'sub' => "selectall_arrayref",
# 'opt' => {Slice => 1, Sum => 1}
# },
# { 'query' => "GET log\nFilter: time > ".(time() - 600)."\nLimit: 1",
# 'sub' => "selectall_arrayref",
# 'opt' => {Slice => 1, AddPeer => 1}
# },
# { 'query' => "GET services\nFilter: contacts >= test\nFilter: host_contacts >= test\nOr: 2\nColumns: host_name description contacts host_contacts",
# 'sub' => "selectall_arrayref",
# 'opt' => {Slice => 1, AddPeer => 0}
# },
# { 'query' => "GET services\nFilter: host_name = test_host_00\nFilter: description = test_flap_02\nOr: 2\nColumns: host_name description contacts host_contacts",
# 'sub' => "selectall_arrayref",
# 'opt' => {Slice => 1, AddPeer => 0}
# },
];
for my $query (@{$querys}) {
my $sub = $query->{'sub'};
my $t0 = [gettimeofday];
my $stats = $nl->$sub($query->{'query'}, $query->{'opt'});
my $elapsed = tv_interval($t0);
print Dumper($stats);
print "Query took ".($elapsed)." seconds\n";
}
#########################################################################
sub add_file {
my $file = shift;
push @opt_f, $file;
}

View File

@@ -0,0 +1,820 @@
#line 1
package Module::AutoInstall;
use strict;
use Cwd ();
use ExtUtils::MakeMaker ();
use vars qw{$VERSION};
BEGIN {
$VERSION = '1.03';
}
# special map on pre-defined feature sets
my %FeatureMap = (
'' => 'Core Features', # XXX: deprecated
'-core' => 'Core Features',
);
# various lexical flags
my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS );
my (
$Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly, $AllDeps
);
my ( $PostambleActions, $PostambleUsed );
# See if it's a testing or non-interactive session
_accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN );
_init();
sub _accept_default {
$AcceptDefault = shift;
}
sub missing_modules {
return @Missing;
}
sub do_install {
__PACKAGE__->install(
[
$Config
? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
: ()
],
@Missing,
);
}
# initialize various flags, and/or perform install
sub _init {
foreach my $arg (
@ARGV,
split(
/[\s\t]+/,
$ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || ''
)
)
{
if ( $arg =~ /^--config=(.*)$/ ) {
$Config = [ split( ',', $1 ) ];
}
elsif ( $arg =~ /^--installdeps=(.*)$/ ) {
__PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) );
exit 0;
}
elsif ( $arg =~ /^--default(?:deps)?$/ ) {
$AcceptDefault = 1;
}
elsif ( $arg =~ /^--check(?:deps)?$/ ) {
$CheckOnly = 1;
}
elsif ( $arg =~ /^--skip(?:deps)?$/ ) {
$SkipInstall = 1;
}
elsif ( $arg =~ /^--test(?:only)?$/ ) {
$TestOnly = 1;
}
elsif ( $arg =~ /^--all(?:deps)?$/ ) {
$AllDeps = 1;
}
}
}
# overrides MakeMaker's prompt() to automatically accept the default choice
sub _prompt {
goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault;
my ( $prompt, $default ) = @_;
my $y = ( $default =~ /^[Yy]/ );
print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] ';
print "$default\n";
return $default;
}
# the workhorse
sub import {
my $class = shift;
my @args = @_ or return;
my $core_all;
print "*** $class version " . $class->VERSION . "\n";
print "*** Checking for Perl dependencies...\n";
my $cwd = Cwd::cwd();
$Config = [];
my $maxlen = length(
(
sort { length($b) <=> length($a) }
grep { /^[^\-]/ }
map {
ref($_)
? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} )
: ''
}
map { +{@args}->{$_} }
grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} }
)[0]
);
# We want to know if we're under CPAN early to avoid prompting, but
# if we aren't going to try and install anything anyway then skip the
# check entirely since we don't want to have to load (and configure)
# an old CPAN just for a cosmetic message
$UnderCPAN = _check_lock(1) unless $SkipInstall;
while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) {
my ( @required, @tests, @skiptests );
my $default = 1;
my $conflict = 0;
if ( $feature =~ m/^-(\w+)$/ ) {
my $option = lc($1);
# check for a newer version of myself
_update_to( $modules, @_ ) and return if $option eq 'version';
# sets CPAN configuration options
$Config = $modules if $option eq 'config';
# promote every features to core status
$core_all = ( $modules =~ /^all$/i ) and next
if $option eq 'core';
next unless $option eq 'core';
}
print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n";
$modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' );
unshift @$modules, -default => &{ shift(@$modules) }
if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability
while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) {
if ( $mod =~ m/^-(\w+)$/ ) {
my $option = lc($1);
$default = $arg if ( $option eq 'default' );
$conflict = $arg if ( $option eq 'conflict' );
@tests = @{$arg} if ( $option eq 'tests' );
@skiptests = @{$arg} if ( $option eq 'skiptests' );
next;
}
printf( "- %-${maxlen}s ...", $mod );
if ( $arg and $arg =~ /^\D/ ) {
unshift @$modules, $arg;
$arg = 0;
}
# XXX: check for conflicts and uninstalls(!) them.
my $cur = _load($mod);
if (_version_cmp ($cur, $arg) >= 0)
{
print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n";
push @Existing, $mod => $arg;
$DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
}
else {
if (not defined $cur) # indeed missing
{
print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n";
}
else
{
# no need to check $arg as _version_cmp ($cur, undef) would satisfy >= above
print "too old. ($cur < $arg)\n";
}
push @required, $mod => $arg;
}
}
next unless @required;
my $mandatory = ( $feature eq '-core' or $core_all );
if (
!$SkipInstall
and (
$CheckOnly
or ($mandatory and $UnderCPAN)
or $AllDeps
or _prompt(
qq{==> Auto-install the }
. ( @required / 2 )
. ( $mandatory ? ' mandatory' : ' optional' )
. qq{ module(s) from CPAN?},
$default ? 'y' : 'n',
) =~ /^[Yy]/
)
)
{
push( @Missing, @required );
$DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
}
elsif ( !$SkipInstall
and $default
and $mandatory
and
_prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', )
=~ /^[Nn]/ )
{
push( @Missing, @required );
$DisabledTests{$_} = 1 for map { glob($_) } @skiptests;
}
else {
$DisabledTests{$_} = 1 for map { glob($_) } @tests;
}
}
if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) {
require Config;
print
"*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n";
# make an educated guess of whether we'll need root permission.
print " (You may need to do that as the 'root' user.)\n"
if eval '$>';
}
print "*** $class configuration finished.\n";
chdir $cwd;
# import to main::
no strict 'refs';
*{'main::WriteMakefile'} = \&Write if caller(0) eq 'main';
return (@Existing, @Missing);
}
sub _running_under {
my $thing = shift;
print <<"END_MESSAGE";
*** Since we're running under ${thing}, I'll just let it take care
of the dependency's installation later.
END_MESSAGE
return 1;
}
# Check to see if we are currently running under CPAN.pm and/or CPANPLUS;
# if we are, then we simply let it taking care of our dependencies
sub _check_lock {
return unless @Missing or @_;
my $cpan_env = $ENV{PERL5_CPAN_IS_RUNNING};
if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) {
return _running_under($cpan_env ? 'CPAN' : 'CPANPLUS');
}
require CPAN;
if ($CPAN::VERSION > '1.89') {
if ($cpan_env) {
return _running_under('CPAN');
}
return; # CPAN.pm new enough, don't need to check further
}
# last ditch attempt, this -will- configure CPAN, very sorry
_load_cpan(1); # force initialize even though it's already loaded
# Find the CPAN lock-file
my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" );
return unless -f $lock;
# Check the lock
local *LOCK;
return unless open(LOCK, $lock);
if (
( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() )
and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore'
) {
print <<'END_MESSAGE';
*** Since we're running under CPAN, I'll just let it take care
of the dependency's installation later.
END_MESSAGE
return 1;
}
close LOCK;
return;
}
sub install {
my $class = shift;
my $i; # used below to strip leading '-' from config keys
my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } );
my ( @modules, @installed );
while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) {
# grep out those already installed
if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
push @installed, $pkg;
}
else {
push @modules, $pkg, $ver;
}
}
return @installed unless @modules; # nothing to do
return @installed if _check_lock(); # defer to the CPAN shell
print "*** Installing dependencies...\n";
return unless _connected_to('cpan.org');
my %args = @config;
my %failed;
local *FAILED;
if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) {
while (<FAILED>) { chomp; $failed{$_}++ }
close FAILED;
my @newmod;
while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) {
push @newmod, ( $k => $v ) unless $failed{$k};
}
@modules = @newmod;
}
if ( _has_cpanplus() and not $ENV{PERL_AUTOINSTALL_PREFER_CPAN} ) {
_install_cpanplus( \@modules, \@config );
} else {
_install_cpan( \@modules, \@config );
}
print "*** $class installation finished.\n";
# see if we have successfully installed them
while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
if ( _version_cmp( _load($pkg), $ver ) >= 0 ) {
push @installed, $pkg;
}
elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) {
print FAILED "$pkg\n";
}
}
close FAILED if $args{do_once};
return @installed;
}
sub _install_cpanplus {
my @modules = @{ +shift };
my @config = _cpanplus_config( @{ +shift } );
my $installed = 0;
require CPANPLUS::Backend;
my $cp = CPANPLUS::Backend->new;
my $conf = $cp->configure_object;
return unless $conf->can('conf') # 0.05x+ with "sudo" support
or _can_write($conf->_get_build('base')); # 0.04x
# if we're root, set UNINST=1 to avoid trouble unless user asked for it.
my $makeflags = $conf->get_conf('makeflags') || '';
if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) {
# 0.03+ uses a hashref here
$makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST};
} else {
# 0.02 and below uses a scalar
$makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
}
$conf->set_conf( makeflags => $makeflags );
$conf->set_conf( prereqs => 1 );
while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) {
$conf->set_conf( $key, $val );
}
my $modtree = $cp->module_tree;
while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
print "*** Installing $pkg...\n";
MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
my $success;
my $obj = $modtree->{$pkg};
if ( $obj and _version_cmp( $obj->{version}, $ver ) >= 0 ) {
my $pathname = $pkg;
$pathname =~ s/::/\\W/;
foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
delete $INC{$inc};
}
my $rv = $cp->install( modules => [ $obj->{module} ] );
if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) {
print "*** $pkg successfully installed.\n";
$success = 1;
} else {
print "*** $pkg installation cancelled.\n";
$success = 0;
}
$installed += $success;
} else {
print << ".";
*** Could not find a version $ver or above for $pkg; skipping.
.
}
MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
}
return $installed;
}
sub _cpanplus_config {
my @config = ();
while ( @_ ) {
my ($key, $value) = (shift(), shift());
if ( $key eq 'prerequisites_policy' ) {
if ( $value eq 'follow' ) {
$value = CPANPLUS::Internals::Constants::PREREQ_INSTALL();
} elsif ( $value eq 'ask' ) {
$value = CPANPLUS::Internals::Constants::PREREQ_ASK();
} elsif ( $value eq 'ignore' ) {
$value = CPANPLUS::Internals::Constants::PREREQ_IGNORE();
} else {
die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n";
}
} else {
die "*** Cannot convert option $key to CPANPLUS version.\n";
}
}
return @config;
}
sub _install_cpan {
my @modules = @{ +shift };
my @config = @{ +shift };
my $installed = 0;
my %args;
_load_cpan();
require Config;
if (CPAN->VERSION < 1.80) {
# no "sudo" support, probe for writableness
return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) )
and _can_write( $Config::Config{sitelib} );
}
# if we're root, set UNINST=1 to avoid trouble unless user asked for it.
my $makeflags = $CPAN::Config->{make_install_arg} || '';
$CPAN::Config->{make_install_arg} =
join( ' ', split( ' ', $makeflags ), 'UNINST=1' )
if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } );
# don't show start-up info
$CPAN::Config->{inhibit_startup_message} = 1;
# set additional options
while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) {
( $args{$opt} = $arg, next )
if $opt =~ /^force$/; # pseudo-option
$CPAN::Config->{$opt} = $arg;
}
local $CPAN::Config->{prerequisites_policy} = 'follow';
while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) {
MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall;
print "*** Installing $pkg...\n";
my $obj = CPAN::Shell->expand( Module => $pkg );
my $success = 0;
if ( $obj and _version_cmp( $obj->cpan_version, $ver ) >= 0 ) {
my $pathname = $pkg;
$pathname =~ s/::/\\W/;
foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) {
delete $INC{$inc};
}
my $rv = $args{force} ? CPAN::Shell->force( install => $pkg )
: CPAN::Shell->install($pkg);
$rv ||= eval {
$CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, )
->{install}
if $CPAN::META;
};
if ( $rv eq 'YES' ) {
print "*** $pkg successfully installed.\n";
$success = 1;
}
else {
print "*** $pkg installation failed.\n";
$success = 0;
}
$installed += $success;
}
else {
print << ".";
*** Could not find a version $ver or above for $pkg; skipping.
.
}
MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall;
}
return $installed;
}
sub _has_cpanplus {
return (
$HasCPANPLUS = (
$INC{'CPANPLUS/Config.pm'}
or _load('CPANPLUS::Shell::Default')
)
);
}
# make guesses on whether we're under the CPAN installation directory
sub _under_cpan {
require Cwd;
require File::Spec;
my $cwd = File::Spec->canonpath( Cwd::cwd() );
my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} );
return ( index( $cwd, $cpan ) > -1 );
}
sub _update_to {
my $class = __PACKAGE__;
my $ver = shift;
return
if _version_cmp( _load($class), $ver ) >= 0; # no need to upgrade
if (
_prompt( "==> A newer version of $class ($ver) is required. Install?",
'y' ) =~ /^[Nn]/
)
{
die "*** Please install $class $ver manually.\n";
}
print << ".";
*** Trying to fetch it from CPAN...
.
# install ourselves
_load($class) and return $class->import(@_)
if $class->install( [], $class, $ver );
print << '.'; exit 1;
*** Cannot bootstrap myself. :-( Installation terminated.
.
}
# check if we're connected to some host, using inet_aton
sub _connected_to {
my $site = shift;
return (
( _load('Socket') and Socket::inet_aton($site) ) or _prompt(
qq(
*** Your host cannot resolve the domain name '$site', which
probably means the Internet connections are unavailable.
==> Should we try to install the required module(s) anyway?), 'n'
) =~ /^[Yy]/
);
}
# check if a directory is writable; may create it on demand
sub _can_write {
my $path = shift;
mkdir( $path, 0755 ) unless -e $path;
return 1 if -w $path;
print << ".";
*** You are not allowed to write to the directory '$path';
the installation may fail due to insufficient permissions.
.
if (
eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt(
qq(
==> Should we try to re-execute the autoinstall process with 'sudo'?),
((-t STDIN) ? 'y' : 'n')
) =~ /^[Yy]/
)
{
# try to bootstrap ourselves from sudo
print << ".";
*** Trying to re-execute the autoinstall process with 'sudo'...
.
my $missing = join( ',', @Missing );
my $config = join( ',',
UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
if $Config;
return
unless system( 'sudo', $^X, $0, "--config=$config",
"--installdeps=$missing" );
print << ".";
*** The 'sudo' command exited with error! Resuming...
.
}
return _prompt(
qq(
==> Should we try to install the required module(s) anyway?), 'n'
) =~ /^[Yy]/;
}
# load a module and return the version it reports
sub _load {
my $mod = pop; # class/instance doesn't matter
my $file = $mod;
$file =~ s|::|/|g;
$file .= '.pm';
local $@;
return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 );
}
# Load CPAN.pm and it's configuration
sub _load_cpan {
return if $CPAN::VERSION and $CPAN::Config and not @_;
require CPAN;
# CPAN-1.82+ adds CPAN::Config::AUTOLOAD to redirect to
# CPAN::HandleConfig->load. CPAN reports that the redirection
# is deprecated in a warning printed at the user.
# CPAN-1.81 expects CPAN::HandleConfig->load, does not have
# $CPAN::HandleConfig::VERSION but cannot handle
# CPAN::Config->load
# Which "versions expect CPAN::Config->load?
if ( $CPAN::HandleConfig::VERSION
|| CPAN::HandleConfig->can('load')
) {
# Newer versions of CPAN have a HandleConfig module
CPAN::HandleConfig->load;
} else {
# Older versions had the load method in Config directly
CPAN::Config->load;
}
}
# compare two versions, either use Sort::Versions or plain comparison
# return values same as <=>
sub _version_cmp {
my ( $cur, $min ) = @_;
return -1 unless defined $cur; # if 0 keep comparing
return 1 unless $min;
$cur =~ s/\s+$//;
# check for version numbers that are not in decimal format
if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) {
if ( ( $version::VERSION or defined( _load('version') )) and
version->can('new')
) {
# use version.pm if it is installed.
return version->new($cur) <=> version->new($min);
}
elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) )
{
# use Sort::Versions as the sorting algorithm for a.b.c versions
return Sort::Versions::versioncmp( $cur, $min );
}
warn "Cannot reliably compare non-decimal formatted versions.\n"
. "Please install version.pm or Sort::Versions.\n";
}
# plain comparison
local $^W = 0; # shuts off 'not numeric' bugs
return $cur <=> $min;
}
# nothing; this usage is deprecated.
sub main::PREREQ_PM { return {}; }
sub _make_args {
my %args = @_;
$args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing }
if $UnderCPAN or $TestOnly;
if ( $args{EXE_FILES} and -e 'MANIFEST' ) {
require ExtUtils::Manifest;
my $manifest = ExtUtils::Manifest::maniread('MANIFEST');
$args{EXE_FILES} =
[ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ];
}
$args{test}{TESTS} ||= 't/*.t';
$args{test}{TESTS} = join( ' ',
grep { !exists( $DisabledTests{$_} ) }
map { glob($_) } split( /\s+/, $args{test}{TESTS} ) );
my $missing = join( ',', @Missing );
my $config =
join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} )
if $Config;
$PostambleActions = (
($missing and not $UnderCPAN)
? "\$(PERL) $0 --config=$config --installdeps=$missing"
: "\$(NOECHO) \$(NOOP)"
);
return %args;
}
# a wrapper to ExtUtils::MakeMaker::WriteMakefile
sub Write {
require Carp;
Carp::croak "WriteMakefile: Need even number of args" if @_ % 2;
if ($CheckOnly) {
print << ".";
*** Makefile not written in check-only mode.
.
return;
}
my %args = _make_args(@_);
no strict 'refs';
$PostambleUsed = 0;
local *MY::postamble = \&postamble unless defined &MY::postamble;
ExtUtils::MakeMaker::WriteMakefile(%args);
print << "." unless $PostambleUsed;
*** WARNING: Makefile written with customized MY::postamble() without
including contents from Module::AutoInstall::postamble() --
auto installation features disabled. Please contact the author.
.
return 1;
}
sub postamble {
$PostambleUsed = 1;
return <<"END_MAKE";
config :: installdeps
\t\$(NOECHO) \$(NOOP)
checkdeps ::
\t\$(PERL) $0 --checkdeps
installdeps ::
\t$PostambleActions
END_MAKE
}
1;
__END__
#line 1071

View File

@@ -0,0 +1,470 @@
#line 1
package Module::Install;
# For any maintainers:
# The load order for Module::Install is a bit magic.
# It goes something like this...
#
# IF ( host has Module::Install installed, creating author mode ) {
# 1. Makefile.PL calls "use inc::Module::Install"
# 2. $INC{inc/Module/Install.pm} set to installed version of inc::Module::Install
# 3. The installed version of inc::Module::Install loads
# 4. inc::Module::Install calls "require Module::Install"
# 5. The ./inc/ version of Module::Install loads
# } ELSE {
# 1. Makefile.PL calls "use inc::Module::Install"
# 2. $INC{inc/Module/Install.pm} set to ./inc/ version of Module::Install
# 3. The ./inc/ version of Module::Install loads
# }
use 5.005;
use strict 'vars';
use Cwd ();
use File::Find ();
use File::Path ();
use vars qw{$VERSION $MAIN};
BEGIN {
# All Module::Install core packages now require synchronised versions.
# This will be used to ensure we don't accidentally load old or
# different versions of modules.
# This is not enforced yet, but will be some time in the next few
# releases once we can make sure it won't clash with custom
# Module::Install extensions.
$VERSION = '1.00';
# Storage for the pseudo-singleton
$MAIN = undef;
*inc::Module::Install::VERSION = *VERSION;
@inc::Module::Install::ISA = __PACKAGE__;
}
sub import {
my $class = shift;
my $self = $class->new(@_);
my $who = $self->_caller;
#-------------------------------------------------------------
# all of the following checks should be included in import(),
# to allow "eval 'require Module::Install; 1' to test
# installation of Module::Install. (RT #51267)
#-------------------------------------------------------------
# Whether or not inc::Module::Install is actually loaded, the
# $INC{inc/Module/Install.pm} is what will still get set as long as
# the caller loaded module this in the documented manner.
# If not set, the caller may NOT have loaded the bundled version, and thus
# they may not have a MI version that works with the Makefile.PL. This would
# result in false errors or unexpected behaviour. And we don't want that.
my $file = join( '/', 'inc', split /::/, __PACKAGE__ ) . '.pm';
unless ( $INC{$file} ) { die <<"END_DIE" }
Please invoke ${\__PACKAGE__} with:
use inc::${\__PACKAGE__};
not:
use ${\__PACKAGE__};
END_DIE
# This reportedly fixes a rare Win32 UTC file time issue, but
# as this is a non-cross-platform XS module not in the core,
# we shouldn't really depend on it. See RT #24194 for detail.
# (Also, this module only supports Perl 5.6 and above).
eval "use Win32::UTCFileTime" if $^O eq 'MSWin32' && $] >= 5.006;
# If the script that is loading Module::Install is from the future,
# then make will detect this and cause it to re-run over and over
# again. This is bad. Rather than taking action to touch it (which
# is unreliable on some platforms and requires write permissions)
# for now we should catch this and refuse to run.
if ( -f $0 ) {
my $s = (stat($0))[9];
# If the modification time is only slightly in the future,
# sleep briefly to remove the problem.
my $a = $s - time;
if ( $a > 0 and $a < 5 ) { sleep 5 }
# Too far in the future, throw an error.
my $t = time;
if ( $s > $t ) { die <<"END_DIE" }
Your installer $0 has a modification time in the future ($s > $t).
This is known to create infinite loops in make.
Please correct this, then run $0 again.
END_DIE
}
# Build.PL was formerly supported, but no longer is due to excessive
# difficulty in implementing every single feature twice.
if ( $0 =~ /Build.PL$/i ) { die <<"END_DIE" }
Module::Install no longer supports Build.PL.
It was impossible to maintain duel backends, and has been deprecated.
Please remove all Build.PL files and only use the Makefile.PL installer.
END_DIE
#-------------------------------------------------------------
# To save some more typing in Module::Install installers, every...
# use inc::Module::Install
# ...also acts as an implicit use strict.
$^H |= strict::bits(qw(refs subs vars));
#-------------------------------------------------------------
unless ( -f $self->{file} ) {
foreach my $key (keys %INC) {
delete $INC{$key} if $key =~ /Module\/Install/;
}
local $^W;
require "$self->{path}/$self->{dispatch}.pm";
File::Path::mkpath("$self->{prefix}/$self->{author}");
$self->{admin} = "$self->{name}::$self->{dispatch}"->new( _top => $self );
$self->{admin}->init;
@_ = ($class, _self => $self);
goto &{"$self->{name}::import"};
}
local $^W;
*{"${who}::AUTOLOAD"} = $self->autoload;
$self->preload;
# Unregister loader and worker packages so subdirs can use them again
delete $INC{'inc/Module/Install.pm'};
delete $INC{'Module/Install.pm'};
# Save to the singleton
$MAIN = $self;
return 1;
}
sub autoload {
my $self = shift;
my $who = $self->_caller;
my $cwd = Cwd::cwd();
my $sym = "${who}::AUTOLOAD";
$sym->{$cwd} = sub {
my $pwd = Cwd::cwd();
if ( my $code = $sym->{$pwd} ) {
# Delegate back to parent dirs
goto &$code unless $cwd eq $pwd;
}
unless ($$sym =~ s/([^:]+)$//) {
# XXX: it looks like we can't retrieve the missing function
# via $$sym (usually $main::AUTOLOAD) in this case.
# I'm still wondering if we should slurp Makefile.PL to
# get some context or not ...
my ($package, $file, $line) = caller;
die <<"EOT";
Unknown function is found at $file line $line.
Execution of $file aborted due to runtime errors.
If you're a contributor to a project, you may need to install
some Module::Install extensions from CPAN (or other repository).
If you're a user of a module, please contact the author.
EOT
}
my $method = $1;
if ( uc($method) eq $method ) {
# Do nothing
return;
} elsif ( $method =~ /^_/ and $self->can($method) ) {
# Dispatch to the root M:I class
return $self->$method(@_);
}
# Dispatch to the appropriate plugin
unshift @_, ( $self, $1 );
goto &{$self->can('call')};
};
}
sub preload {
my $self = shift;
unless ( $self->{extensions} ) {
$self->load_extensions(
"$self->{prefix}/$self->{path}", $self
);
}
my @exts = @{$self->{extensions}};
unless ( @exts ) {
@exts = $self->{admin}->load_all_extensions;
}
my %seen;
foreach my $obj ( @exts ) {
while (my ($method, $glob) = each %{ref($obj) . '::'}) {
next unless $obj->can($method);
next if $method =~ /^_/;
next if $method eq uc($method);
$seen{$method}++;
}
}
my $who = $self->_caller;
foreach my $name ( sort keys %seen ) {
local $^W;
*{"${who}::$name"} = sub {
${"${who}::AUTOLOAD"} = "${who}::$name";
goto &{"${who}::AUTOLOAD"};
};
}
}
sub new {
my ($class, %args) = @_;
delete $INC{'FindBin.pm'};
{
# to suppress the redefine warning
local $SIG{__WARN__} = sub {};
require FindBin;
}
# ignore the prefix on extension modules built from top level.
my $base_path = Cwd::abs_path($FindBin::Bin);
unless ( Cwd::abs_path(Cwd::cwd()) eq $base_path ) {
delete $args{prefix};
}
return $args{_self} if $args{_self};
$args{dispatch} ||= 'Admin';
$args{prefix} ||= 'inc';
$args{author} ||= ($^O eq 'VMS' ? '_author' : '.author');
$args{bundle} ||= 'inc/BUNDLES';
$args{base} ||= $base_path;
$class =~ s/^\Q$args{prefix}\E:://;
$args{name} ||= $class;
$args{version} ||= $class->VERSION;
unless ( $args{path} ) {
$args{path} = $args{name};
$args{path} =~ s!::!/!g;
}
$args{file} ||= "$args{base}/$args{prefix}/$args{path}.pm";
$args{wrote} = 0;
bless( \%args, $class );
}
sub call {
my ($self, $method) = @_;
my $obj = $self->load($method) or return;
splice(@_, 0, 2, $obj);
goto &{$obj->can($method)};
}
sub load {
my ($self, $method) = @_;
$self->load_extensions(
"$self->{prefix}/$self->{path}", $self
) unless $self->{extensions};
foreach my $obj (@{$self->{extensions}}) {
return $obj if $obj->can($method);
}
my $admin = $self->{admin} or die <<"END_DIE";
The '$method' method does not exist in the '$self->{prefix}' path!
Please remove the '$self->{prefix}' directory and run $0 again to load it.
END_DIE
my $obj = $admin->load($method, 1);
push @{$self->{extensions}}, $obj;
$obj;
}
sub load_extensions {
my ($self, $path, $top) = @_;
my $should_reload = 0;
unless ( grep { ! ref $_ and lc $_ eq lc $self->{prefix} } @INC ) {
unshift @INC, $self->{prefix};
$should_reload = 1;
}
foreach my $rv ( $self->find_extensions($path) ) {
my ($file, $pkg) = @{$rv};
next if $self->{pathnames}{$pkg};
local $@;
my $new = eval { local $^W; require $file; $pkg->can('new') };
unless ( $new ) {
warn $@ if $@;
next;
}
$self->{pathnames}{$pkg} =
$should_reload ? delete $INC{$file} : $INC{$file};
push @{$self->{extensions}}, &{$new}($pkg, _top => $top );
}
$self->{extensions} ||= [];
}
sub find_extensions {
my ($self, $path) = @_;
my @found;
File::Find::find( sub {
my $file = $File::Find::name;
return unless $file =~ m!^\Q$path\E/(.+)\.pm\Z!is;
my $subpath = $1;
return if lc($subpath) eq lc($self->{dispatch});
$file = "$self->{path}/$subpath.pm";
my $pkg = "$self->{name}::$subpath";
$pkg =~ s!/!::!g;
# If we have a mixed-case package name, assume case has been preserved
# correctly. Otherwise, root through the file to locate the case-preserved
# version of the package name.
if ( $subpath eq lc($subpath) || $subpath eq uc($subpath) ) {
my $content = Module::Install::_read($subpath . '.pm');
my $in_pod = 0;
foreach ( split //, $content ) {
$in_pod = 1 if /^=\w/;
$in_pod = 0 if /^=cut/;
next if ($in_pod || /^=cut/); # skip pod text
next if /^\s*#/; # and comments
if ( m/^\s*package\s+($pkg)\s*;/i ) {
$pkg = $1;
last;
}
}
}
push @found, [ $file, $pkg ];
}, $path ) if -d $path;
@found;
}
#####################################################################
# Common Utility Functions
sub _caller {
my $depth = 0;
my $call = caller($depth);
while ( $call eq __PACKAGE__ ) {
$depth++;
$call = caller($depth);
}
return $call;
}
# Done in evals to avoid confusing Perl::MinimumVersion
eval( $] >= 5.006 ? <<'END_NEW' : <<'END_OLD' ); die $@ if $@;
sub _read {
local *FH;
open( FH, '<', $_[0] ) or die "open($_[0]): $!";
my $string = do { local $/; <FH> };
close FH or die "close($_[0]): $!";
return $string;
}
END_NEW
sub _read {
local *FH;
open( FH, "< $_[0]" ) or die "open($_[0]): $!";
my $string = do { local $/; <FH> };
close FH or die "close($_[0]): $!";
return $string;
}
END_OLD
sub _readperl {
my $string = Module::Install::_read($_[0]);
$string =~ s/(?:\015{1,2}\012|\015|\012)/\n/sg;
$string =~ s/(\n)\n*__(?:DATA|END)__\b.*\z/$1/s;
$string =~ s/\n\n=\w+.+?\n\n=cut\b.+?\n+/\n\n/sg;
return $string;
}
sub _readpod {
my $string = Module::Install::_read($_[0]);
$string =~ s/(?:\015{1,2}\012|\015|\012)/\n/sg;
return $string if $_[0] =~ /\.pod\z/;
$string =~ s/(^|\n=cut\b.+?\n+)[^=\s].+?\n(\n=\w+|\z)/$1$2/sg;
$string =~ s/\n*=pod\b[^\n]*\n+/\n\n/sg;
$string =~ s/\n*=cut\b[^\n]*\n+/\n\n/sg;
$string =~ s/^\n+//s;
return $string;
}
# Done in evals to avoid confusing Perl::MinimumVersion
eval( $] >= 5.006 ? <<'END_NEW' : <<'END_OLD' ); die $@ if $@;
sub _write {
local *FH;
open( FH, '>', $_[0] ) or die "open($_[0]): $!";
foreach ( 1 .. $#_ ) {
print FH $_[$_] or die "print($_[0]): $!";
}
close FH or die "close($_[0]): $!";
}
END_NEW
sub _write {
local *FH;
open( FH, "> $_[0]" ) or die "open($_[0]): $!";
foreach ( 1 .. $#_ ) {
print FH $_[$_] or die "print($_[0]): $!";
}
close FH or die "close($_[0]): $!";
}
END_OLD
# _version is for processing module versions (eg, 1.03_05) not
# Perl versions (eg, 5.8.1).
sub _version ($) {
my $s = shift || 0;
my $d =()= $s =~ /(\.)/g;
if ( $d >= 2 ) {
# Normalise multipart versions
$s =~ s/(\.)(\d{1,3})/sprintf("$1%03d",$2)/eg;
}
$s =~ s/^(\d+)\.?//;
my $l = $1 || 0;
my @v = map {
$_ . '0' x (3 - length $_)
} $s =~ /(\d{1,3})\D?/g;
$l = $l . '.' . join '', @v if @v;
return $l + 0;
}
sub _cmp ($$) {
_version($_[0]) <=> _version($_[1]);
}
# Cloned from Params::Util::_CLASS
sub _CLASS ($) {
(
defined $_[0]
and
! ref $_[0]
and
$_[0] =~ m/^[^\W\d]\w*(?:::\w+)*\z/s
) ? $_[0] : undef;
}
1;
# Copyright 2008 - 2010 Adam Kennedy.

View File

@@ -0,0 +1,82 @@
#line 1
package Module::Install::AutoInstall;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
sub AutoInstall { $_[0] }
sub run {
my $self = shift;
$self->auto_install_now(@_);
}
sub write {
my $self = shift;
$self->auto_install(@_);
}
sub auto_install {
my $self = shift;
return if $self->{done}++;
# Flatten array of arrays into a single array
my @core = map @$_, map @$_, grep ref,
$self->build_requires, $self->requires;
my @config = @_;
# We'll need Module::AutoInstall
$self->include('Module::AutoInstall');
require Module::AutoInstall;
my @features_require = Module::AutoInstall->import(
(@config ? (-config => \@config) : ()),
(@core ? (-core => \@core) : ()),
$self->features,
);
my %seen;
my @requires = map @$_, map @$_, grep ref, $self->requires;
while (my ($mod, $ver) = splice(@requires, 0, 2)) {
$seen{$mod}{$ver}++;
}
my @build_requires = map @$_, map @$_, grep ref, $self->build_requires;
while (my ($mod, $ver) = splice(@build_requires, 0, 2)) {
$seen{$mod}{$ver}++;
}
my @configure_requires = map @$_, map @$_, grep ref, $self->configure_requires;
while (my ($mod, $ver) = splice(@configure_requires, 0, 2)) {
$seen{$mod}{$ver}++;
}
my @deduped;
while (my ($mod, $ver) = splice(@features_require, 0, 2)) {
push @deduped, $mod => $ver unless $seen{$mod}{$ver}++;
}
$self->requires(@deduped);
$self->makemaker_args( Module::AutoInstall::_make_args() );
my $class = ref($self);
$self->postamble(
"# --- $class section:\n" .
Module::AutoInstall::postamble()
);
}
sub auto_install_now {
my $self = shift;
$self->auto_install(@_);
Module::AutoInstall::do_install();
}
1;

View File

@@ -0,0 +1,83 @@
#line 1
package Module::Install::Base;
use strict 'vars';
use vars qw{$VERSION};
BEGIN {
$VERSION = '1.00';
}
# Suspend handler for "redefined" warnings
BEGIN {
my $w = $SIG{__WARN__};
$SIG{__WARN__} = sub { $w };
}
#line 42
sub new {
my $class = shift;
unless ( defined &{"${class}::call"} ) {
*{"${class}::call"} = sub { shift->_top->call(@_) };
}
unless ( defined &{"${class}::load"} ) {
*{"${class}::load"} = sub { shift->_top->load(@_) };
}
bless { @_ }, $class;
}
#line 61
sub AUTOLOAD {
local $@;
my $func = eval { shift->_top->autoload } or return;
goto &$func;
}
#line 75
sub _top {
$_[0]->{_top};
}
#line 90
sub admin {
$_[0]->_top->{admin}
or
Module::Install::Base::FakeAdmin->new;
}
#line 106
sub is_admin {
! $_[0]->admin->isa('Module::Install::Base::FakeAdmin');
}
sub DESTROY {}
package Module::Install::Base::FakeAdmin;
use vars qw{$VERSION};
BEGIN {
$VERSION = $Module::Install::Base::VERSION;
}
my $fake;
sub new {
$fake ||= bless(\@_, $_[0]);
}
sub AUTOLOAD {}
sub DESTROY {}
# Restore warning handler
BEGIN {
$SIG{__WARN__} = $SIG{__WARN__}->();
}
1;
#line 159

View File

@@ -0,0 +1,81 @@
#line 1
package Module::Install::Can;
use strict;
use Config ();
use File::Spec ();
use ExtUtils::MakeMaker ();
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
# check if we can load some module
### Upgrade this to not have to load the module if possible
sub can_use {
my ($self, $mod, $ver) = @_;
$mod =~ s{::|\\}{/}g;
$mod .= '.pm' unless $mod =~ /\.pm$/i;
my $pkg = $mod;
$pkg =~ s{/}{::}g;
$pkg =~ s{\.pm$}{}i;
local $@;
eval { require $mod; $pkg->VERSION($ver || 0); 1 };
}
# check if we can run some command
sub can_run {
my ($self, $cmd) = @_;
my $_cmd = $cmd;
return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd));
for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') {
next if $dir eq '';
my $abs = File::Spec->catfile($dir, $_[1]);
return $abs if (-x $abs or $abs = MM->maybe_command($abs));
}
return;
}
# can we locate a (the) C compiler
sub can_cc {
my $self = shift;
my @chunks = split(/ /, $Config::Config{cc}) or return;
# $Config{cc} may contain args; try to find out the program part
while (@chunks) {
return $self->can_run("@chunks") || (pop(@chunks), next);
}
return;
}
# Fix Cygwin bug on maybe_command();
if ( $^O eq 'cygwin' ) {
require ExtUtils::MM_Cygwin;
require ExtUtils::MM_Win32;
if ( ! defined(&ExtUtils::MM_Cygwin::maybe_command) ) {
*ExtUtils::MM_Cygwin::maybe_command = sub {
my ($self, $file) = @_;
if ($file =~ m{^/cygdrive/}i and ExtUtils::MM_Win32->can('maybe_command')) {
ExtUtils::MM_Win32->maybe_command($file);
} else {
ExtUtils::MM_Unix->maybe_command($file);
}
}
}
}
1;
__END__
#line 156

View File

@@ -0,0 +1,93 @@
#line 1
package Module::Install::Fetch;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
sub get_file {
my ($self, %args) = @_;
my ($scheme, $host, $path, $file) =
$args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return;
if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) {
$args{url} = $args{ftp_url}
or (warn("LWP support unavailable!\n"), return);
($scheme, $host, $path, $file) =
$args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return;
}
$|++;
print "Fetching '$file' from $host... ";
unless (eval { require Socket; Socket::inet_aton($host) }) {
warn "'$host' resolve failed!\n";
return;
}
return unless $scheme eq 'ftp' or $scheme eq 'http';
require Cwd;
my $dir = Cwd::getcwd();
chdir $args{local_dir} or return if exists $args{local_dir};
if (eval { require LWP::Simple; 1 }) {
LWP::Simple::mirror($args{url}, $file);
}
elsif (eval { require Net::FTP; 1 }) { eval {
# use Net::FTP to get past firewall
my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600);
$ftp->login("anonymous", 'anonymous@example.com');
$ftp->cwd($path);
$ftp->binary;
$ftp->get($file) or (warn("$!\n"), return);
$ftp->quit;
} }
elsif (my $ftp = $self->can_run('ftp')) { eval {
# no Net::FTP, fallback to ftp.exe
require FileHandle;
my $fh = FileHandle->new;
local $SIG{CHLD} = 'IGNORE';
unless ($fh->open("|$ftp -n")) {
warn "Couldn't open ftp: $!\n";
chdir $dir; return;
}
my @dialog = split(/\n/, <<"END_FTP");
open $host
user anonymous anonymous\@example.com
cd $path
binary
get $file $file
quit
END_FTP
foreach (@dialog) { $fh->print("$_\n") }
$fh->close;
} }
else {
warn "No working 'ftp' program available!\n";
chdir $dir; return;
}
unless (-f $file) {
warn "Fetching failed: $@\n";
chdir $dir; return;
}
return if exists $args{size} and -s $file != $args{size};
system($args{run}) if exists $args{run};
unlink($file) if $args{remove};
print(((!exists $args{check_for} or -e $args{check_for})
? "done!" : "failed! ($!)"), "\n");
chdir $dir; return !$?;
}
1;

View File

@@ -0,0 +1,34 @@
#line 1
package Module::Install::Include;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
sub include {
shift()->admin->include(@_);
}
sub include_deps {
shift()->admin->include_deps(@_);
}
sub auto_include {
shift()->admin->auto_include(@_);
}
sub auto_include_deps {
shift()->admin->auto_include_deps(@_);
}
sub auto_include_dependent_dists {
shift()->admin->auto_include_dependent_dists(@_);
}
1;

View File

@@ -0,0 +1,415 @@
#line 1
package Module::Install::Makefile;
use strict 'vars';
use ExtUtils::MakeMaker ();
use Module::Install::Base ();
use Fcntl qw/:flock :seek/;
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
sub Makefile { $_[0] }
my %seen = ();
sub prompt {
shift;
# Infinite loop protection
my @c = caller();
if ( ++$seen{"$c[1]|$c[2]|$_[0]"} > 3 ) {
die "Caught an potential prompt infinite loop ($c[1]|$c[2]|$_[0])";
}
# In automated testing or non-interactive session, always use defaults
if ( ($ENV{AUTOMATED_TESTING} or -! -t STDIN) and ! $ENV{PERL_MM_USE_DEFAULT} ) {
local $ENV{PERL_MM_USE_DEFAULT} = 1;
goto &ExtUtils::MakeMaker::prompt;
} else {
goto &ExtUtils::MakeMaker::prompt;
}
}
# Store a cleaned up version of the MakeMaker version,
# since we need to behave differently in a variety of
# ways based on the MM version.
my $makemaker = eval $ExtUtils::MakeMaker::VERSION;
# If we are passed a param, do a "newer than" comparison.
# Otherwise, just return the MakeMaker version.
sub makemaker {
( @_ < 2 or $makemaker >= eval($_[1]) ) ? $makemaker : 0
}
# Ripped from ExtUtils::MakeMaker 6.56, and slightly modified
# as we only need to know here whether the attribute is an array
# or a hash or something else (which may or may not be appendable).
my %makemaker_argtype = (
C => 'ARRAY',
CONFIG => 'ARRAY',
# CONFIGURE => 'CODE', # ignore
DIR => 'ARRAY',
DL_FUNCS => 'HASH',
DL_VARS => 'ARRAY',
EXCLUDE_EXT => 'ARRAY',
EXE_FILES => 'ARRAY',
FUNCLIST => 'ARRAY',
H => 'ARRAY',
IMPORTS => 'HASH',
INCLUDE_EXT => 'ARRAY',
LIBS => 'ARRAY', # ignore ''
MAN1PODS => 'HASH',
MAN3PODS => 'HASH',
META_ADD => 'HASH',
META_MERGE => 'HASH',
PL_FILES => 'HASH',
PM => 'HASH',
PMLIBDIRS => 'ARRAY',
PMLIBPARENTDIRS => 'ARRAY',
PREREQ_PM => 'HASH',
CONFIGURE_REQUIRES => 'HASH',
SKIP => 'ARRAY',
TYPEMAPS => 'ARRAY',
XS => 'HASH',
# VERSION => ['version',''], # ignore
# _KEEP_AFTER_FLUSH => '',
clean => 'HASH',
depend => 'HASH',
dist => 'HASH',
dynamic_lib=> 'HASH',
linkext => 'HASH',
macro => 'HASH',
postamble => 'HASH',
realclean => 'HASH',
test => 'HASH',
tool_autosplit => 'HASH',
# special cases where you can use makemaker_append
CCFLAGS => 'APPENDABLE',
DEFINE => 'APPENDABLE',
INC => 'APPENDABLE',
LDDLFLAGS => 'APPENDABLE',
LDFROM => 'APPENDABLE',
);
sub makemaker_args {
my ($self, %new_args) = @_;
my $args = ( $self->{makemaker_args} ||= {} );
foreach my $key (keys %new_args) {
if ($makemaker_argtype{$key}) {
if ($makemaker_argtype{$key} eq 'ARRAY') {
$args->{$key} = [] unless defined $args->{$key};
unless (ref $args->{$key} eq 'ARRAY') {
$args->{$key} = [$args->{$key}]
}
push @{$args->{$key}},
ref $new_args{$key} eq 'ARRAY'
? @{$new_args{$key}}
: $new_args{$key};
}
elsif ($makemaker_argtype{$key} eq 'HASH') {
$args->{$key} = {} unless defined $args->{$key};
foreach my $skey (keys %{ $new_args{$key} }) {
$args->{$key}{$skey} = $new_args{$key}{$skey};
}
}
elsif ($makemaker_argtype{$key} eq 'APPENDABLE') {
$self->makemaker_append($key => $new_args{$key});
}
}
else {
if (defined $args->{$key}) {
warn qq{MakeMaker attribute "$key" is overriden; use "makemaker_append" to append values\n};
}
$args->{$key} = $new_args{$key};
}
}
return $args;
}
# For mm args that take multiple space-seperated args,
# append an argument to the current list.
sub makemaker_append {
my $self = shift;
my $name = shift;
my $args = $self->makemaker_args;
$args->{$name} = defined $args->{$name}
? join( ' ', $args->{$name}, @_ )
: join( ' ', @_ );
}
sub build_subdirs {
my $self = shift;
my $subdirs = $self->makemaker_args->{DIR} ||= [];
for my $subdir (@_) {
push @$subdirs, $subdir;
}
}
sub clean_files {
my $self = shift;
my $clean = $self->makemaker_args->{clean} ||= {};
%$clean = (
%$clean,
FILES => join ' ', grep { length $_ } ($clean->{FILES} || (), @_),
);
}
sub realclean_files {
my $self = shift;
my $realclean = $self->makemaker_args->{realclean} ||= {};
%$realclean = (
%$realclean,
FILES => join ' ', grep { length $_ } ($realclean->{FILES} || (), @_),
);
}
sub libs {
my $self = shift;
my $libs = ref $_[0] ? shift : [ shift ];
$self->makemaker_args( LIBS => $libs );
}
sub inc {
my $self = shift;
$self->makemaker_args( INC => shift );
}
sub _wanted_t {
}
sub tests_recursive {
my $self = shift;
my $dir = shift || 't';
unless ( -d $dir ) {
die "tests_recursive dir '$dir' does not exist";
}
my %tests = map { $_ => 1 } split / /, ($self->tests || '');
require File::Find;
File::Find::find(
sub { /\.t$/ and -f $_ and $tests{"$File::Find::dir/*.t"} = 1 },
$dir
);
$self->tests( join ' ', sort keys %tests );
}
sub write {
my $self = shift;
die "&Makefile->write() takes no arguments\n" if @_;
# Check the current Perl version
my $perl_version = $self->perl_version;
if ( $perl_version ) {
eval "use $perl_version; 1"
or die "ERROR: perl: Version $] is installed, "
. "but we need version >= $perl_version";
}
# Make sure we have a new enough MakeMaker
require ExtUtils::MakeMaker;
if ( $perl_version and $self->_cmp($perl_version, '5.006') >= 0 ) {
# MakeMaker can complain about module versions that include
# an underscore, even though its own version may contain one!
# Hence the funny regexp to get rid of it. See RT #35800
# for details.
my $v = $ExtUtils::MakeMaker::VERSION =~ /^(\d+\.\d+)/;
$self->build_requires( 'ExtUtils::MakeMaker' => $v );
$self->configure_requires( 'ExtUtils::MakeMaker' => $v );
} else {
# Allow legacy-compatibility with 5.005 by depending on the
# most recent EU:MM that supported 5.005.
$self->build_requires( 'ExtUtils::MakeMaker' => 6.42 );
$self->configure_requires( 'ExtUtils::MakeMaker' => 6.42 );
}
# Generate the MakeMaker params
my $args = $self->makemaker_args;
$args->{DISTNAME} = $self->name;
$args->{NAME} = $self->module_name || $self->name;
$args->{NAME} =~ s/-/::/g;
$args->{VERSION} = $self->version or die <<'EOT';
ERROR: Can't determine distribution version. Please specify it
explicitly via 'version' in Makefile.PL, or set a valid $VERSION
in a module, and provide its file path via 'version_from' (or
'all_from' if you prefer) in Makefile.PL.
EOT
$DB::single = 1;
if ( $self->tests ) {
my @tests = split ' ', $self->tests;
my %seen;
$args->{test} = {
TESTS => (join ' ', grep {!$seen{$_}++} @tests),
};
} elsif ( $Module::Install::ExtraTests::use_extratests ) {
# Module::Install::ExtraTests doesn't set $self->tests and does its own tests via harness.
# So, just ignore our xt tests here.
} elsif ( -d 'xt' and ($Module::Install::AUTHOR or $ENV{RELEASE_TESTING}) ) {
$args->{test} = {
TESTS => join( ' ', map { "$_/*.t" } grep { -d $_ } qw{ t xt } ),
};
}
if ( $] >= 5.005 ) {
$args->{ABSTRACT} = $self->abstract;
$args->{AUTHOR} = join ', ', @{$self->author || []};
}
if ( $self->makemaker(6.10) ) {
$args->{NO_META} = 1;
#$args->{NO_MYMETA} = 1;
}
if ( $self->makemaker(6.17) and $self->sign ) {
$args->{SIGN} = 1;
}
unless ( $self->is_admin ) {
delete $args->{SIGN};
}
if ( $self->makemaker(6.31) and $self->license ) {
$args->{LICENSE} = $self->license;
}
my $prereq = ($args->{PREREQ_PM} ||= {});
%$prereq = ( %$prereq,
map { @$_ } # flatten [module => version]
map { @$_ }
grep $_,
($self->requires)
);
# Remove any reference to perl, PREREQ_PM doesn't support it
delete $args->{PREREQ_PM}->{perl};
# Merge both kinds of requires into BUILD_REQUIRES
my $build_prereq = ($args->{BUILD_REQUIRES} ||= {});
%$build_prereq = ( %$build_prereq,
map { @$_ } # flatten [module => version]
map { @$_ }
grep $_,
($self->configure_requires, $self->build_requires)
);
# Remove any reference to perl, BUILD_REQUIRES doesn't support it
delete $args->{BUILD_REQUIRES}->{perl};
# Delete bundled dists from prereq_pm, add it to Makefile DIR
my $subdirs = ($args->{DIR} || []);
if ($self->bundles) {
my %processed;
foreach my $bundle (@{ $self->bundles }) {
my ($mod_name, $dist_dir) = @$bundle;
delete $prereq->{$mod_name};
$dist_dir = File::Basename::basename($dist_dir); # dir for building this module
if (not exists $processed{$dist_dir}) {
if (-d $dist_dir) {
# List as sub-directory to be processed by make
push @$subdirs, $dist_dir;
}
# Else do nothing: the module is already present on the system
$processed{$dist_dir} = undef;
}
}
}
unless ( $self->makemaker('6.55_03') ) {
%$prereq = (%$prereq,%$build_prereq);
delete $args->{BUILD_REQUIRES};
}
if ( my $perl_version = $self->perl_version ) {
eval "use $perl_version; 1"
or die "ERROR: perl: Version $] is installed, "
. "but we need version >= $perl_version";
if ( $self->makemaker(6.48) ) {
$args->{MIN_PERL_VERSION} = $perl_version;
}
}
if ($self->installdirs) {
warn qq{old INSTALLDIRS (probably set by makemaker_args) is overriden by installdirs\n} if $args->{INSTALLDIRS};
$args->{INSTALLDIRS} = $self->installdirs;
}
my %args = map {
( $_ => $args->{$_} ) } grep {defined($args->{$_} )
} keys %$args;
my $user_preop = delete $args{dist}->{PREOP};
if ( my $preop = $self->admin->preop($user_preop) ) {
foreach my $key ( keys %$preop ) {
$args{dist}->{$key} = $preop->{$key};
}
}
my $mm = ExtUtils::MakeMaker::WriteMakefile(%args);
$self->fix_up_makefile($mm->{FIRST_MAKEFILE} || 'Makefile');
}
sub fix_up_makefile {
my $self = shift;
my $makefile_name = shift;
my $top_class = ref($self->_top) || '';
my $top_version = $self->_top->VERSION || '';
my $preamble = $self->preamble
? "# Preamble by $top_class $top_version\n"
. $self->preamble
: '';
my $postamble = "# Postamble by $top_class $top_version\n"
. ($self->postamble || '');
local *MAKEFILE;
open MAKEFILE, "+< $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!";
eval { flock MAKEFILE, LOCK_EX };
my $makefile = do { local $/; <MAKEFILE> };
$makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /;
$makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g;
$makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g;
$makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m;
$makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m;
# Module::Install will never be used to build the Core Perl
# Sometimes PERL_LIB and PERL_ARCHLIB get written anyway, which breaks
# PREFIX/PERL5LIB, and thus, install_share. Blank them if they exist
$makefile =~ s/^PERL_LIB = .+/PERL_LIB =/m;
#$makefile =~ s/^PERL_ARCHLIB = .+/PERL_ARCHLIB =/m;
# Perl 5.005 mentions PERL_LIB explicitly, so we have to remove that as well.
$makefile =~ s/(\"?)-I\$\(PERL_LIB\)\1//g;
# XXX - This is currently unused; not sure if it breaks other MM-users
# $makefile =~ s/^pm_to_blib\s+:\s+/pm_to_blib :: /mg;
seek MAKEFILE, 0, SEEK_SET;
truncate MAKEFILE, 0;
print MAKEFILE "$preamble$makefile$postamble" or die $!;
close MAKEFILE or die $!;
1;
}
sub preamble {
my ($self, $text) = @_;
$self->{preamble} = $text . $self->{preamble} if defined $text;
$self->{preamble};
}
sub postamble {
my ($self, $text) = @_;
$self->{postamble} ||= $self->admin->postamble;
$self->{postamble} .= $text if defined $text;
$self->{postamble}
}
1;
__END__
#line 541

View File

@@ -0,0 +1,715 @@
#line 1
package Module::Install::Metadata;
use strict 'vars';
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
my @boolean_keys = qw{
sign
};
my @scalar_keys = qw{
name
module_name
abstract
version
distribution_type
tests
installdirs
};
my @tuple_keys = qw{
configure_requires
build_requires
requires
recommends
bundles
resources
};
my @resource_keys = qw{
homepage
bugtracker
repository
};
my @array_keys = qw{
keywords
author
};
*authors = \&author;
sub Meta { shift }
sub Meta_BooleanKeys { @boolean_keys }
sub Meta_ScalarKeys { @scalar_keys }
sub Meta_TupleKeys { @tuple_keys }
sub Meta_ResourceKeys { @resource_keys }
sub Meta_ArrayKeys { @array_keys }
foreach my $key ( @boolean_keys ) {
*$key = sub {
my $self = shift;
if ( defined wantarray and not @_ ) {
return $self->{values}->{$key};
}
$self->{values}->{$key} = ( @_ ? $_[0] : 1 );
return $self;
};
}
foreach my $key ( @scalar_keys ) {
*$key = sub {
my $self = shift;
return $self->{values}->{$key} if defined wantarray and !@_;
$self->{values}->{$key} = shift;
return $self;
};
}
foreach my $key ( @array_keys ) {
*$key = sub {
my $self = shift;
return $self->{values}->{$key} if defined wantarray and !@_;
$self->{values}->{$key} ||= [];
push @{$self->{values}->{$key}}, @_;
return $self;
};
}
foreach my $key ( @resource_keys ) {
*$key = sub {
my $self = shift;
unless ( @_ ) {
return () unless $self->{values}->{resources};
return map { $_->[1] }
grep { $_->[0] eq $key }
@{ $self->{values}->{resources} };
}
return $self->{values}->{resources}->{$key} unless @_;
my $uri = shift or die(
"Did not provide a value to $key()"
);
$self->resources( $key => $uri );
return 1;
};
}
foreach my $key ( grep { $_ ne "resources" } @tuple_keys) {
*$key = sub {
my $self = shift;
return $self->{values}->{$key} unless @_;
my @added;
while ( @_ ) {
my $module = shift or last;
my $version = shift || 0;
push @added, [ $module, $version ];
}
push @{ $self->{values}->{$key} }, @added;
return map {@$_} @added;
};
}
# Resource handling
my %lc_resource = map { $_ => 1 } qw{
homepage
license
bugtracker
repository
};
sub resources {
my $self = shift;
while ( @_ ) {
my $name = shift or last;
my $value = shift or next;
if ( $name eq lc $name and ! $lc_resource{$name} ) {
die("Unsupported reserved lowercase resource '$name'");
}
$self->{values}->{resources} ||= [];
push @{ $self->{values}->{resources} }, [ $name, $value ];
}
$self->{values}->{resources};
}
# Aliases for build_requires that will have alternative
# meanings in some future version of META.yml.
sub test_requires { shift->build_requires(@_) }
sub install_requires { shift->build_requires(@_) }
# Aliases for installdirs options
sub install_as_core { $_[0]->installdirs('perl') }
sub install_as_cpan { $_[0]->installdirs('site') }
sub install_as_site { $_[0]->installdirs('site') }
sub install_as_vendor { $_[0]->installdirs('vendor') }
sub dynamic_config {
my $self = shift;
unless ( @_ ) {
warn "You MUST provide an explicit true/false value to dynamic_config\n";
return $self;
}
$self->{values}->{dynamic_config} = $_[0] ? 1 : 0;
return 1;
}
sub perl_version {
my $self = shift;
return $self->{values}->{perl_version} unless @_;
my $version = shift or die(
"Did not provide a value to perl_version()"
);
# Normalize the version
$version = $self->_perl_version($version);
# We don't support the reall old versions
unless ( $version >= 5.005 ) {
die "Module::Install only supports 5.005 or newer (use ExtUtils::MakeMaker)\n";
}
$self->{values}->{perl_version} = $version;
}
sub all_from {
my ( $self, $file ) = @_;
unless ( defined($file) ) {
my $name = $self->name or die(
"all_from called with no args without setting name() first"
);
$file = join('/', 'lib', split(/-/, $name)) . '.pm';
$file =~ s{.*/}{} unless -e $file;
unless ( -e $file ) {
die("all_from cannot find $file from $name");
}
}
unless ( -f $file ) {
die("The path '$file' does not exist, or is not a file");
}
$self->{values}{all_from} = $file;
# Some methods pull from POD instead of code.
# If there is a matching .pod, use that instead
my $pod = $file;
$pod =~ s/\.pm$/.pod/i;
$pod = $file unless -e $pod;
# Pull the different values
$self->name_from($file) unless $self->name;
$self->version_from($file) unless $self->version;
$self->perl_version_from($file) unless $self->perl_version;
$self->author_from($pod) unless @{$self->author || []};
$self->license_from($pod) unless $self->license;
$self->abstract_from($pod) unless $self->abstract;
return 1;
}
sub provides {
my $self = shift;
my $provides = ( $self->{values}->{provides} ||= {} );
%$provides = (%$provides, @_) if @_;
return $provides;
}
sub auto_provides {
my $self = shift;
return $self unless $self->is_admin;
unless (-e 'MANIFEST') {
warn "Cannot deduce auto_provides without a MANIFEST, skipping\n";
return $self;
}
# Avoid spurious warnings as we are not checking manifest here.
local $SIG{__WARN__} = sub {1};
require ExtUtils::Manifest;
local *ExtUtils::Manifest::manicheck = sub { return };
require Module::Build;
my $build = Module::Build->new(
dist_name => $self->name,
dist_version => $self->version,
license => $self->license,
);
$self->provides( %{ $build->find_dist_packages || {} } );
}
sub feature {
my $self = shift;
my $name = shift;
my $features = ( $self->{values}->{features} ||= [] );
my $mods;
if ( @_ == 1 and ref( $_[0] ) ) {
# The user used ->feature like ->features by passing in the second
# argument as a reference. Accomodate for that.
$mods = $_[0];
} else {
$mods = \@_;
}
my $count = 0;
push @$features, (
$name => [
map {
ref($_) ? ( ref($_) eq 'HASH' ) ? %$_ : @$_ : $_
} @$mods
]
);
return @$features;
}
sub features {
my $self = shift;
while ( my ( $name, $mods ) = splice( @_, 0, 2 ) ) {
$self->feature( $name, @$mods );
}
return $self->{values}->{features}
? @{ $self->{values}->{features} }
: ();
}
sub no_index {
my $self = shift;
my $type = shift;
push @{ $self->{values}->{no_index}->{$type} }, @_ if $type;
return $self->{values}->{no_index};
}
sub read {
my $self = shift;
$self->include_deps( 'YAML::Tiny', 0 );
require YAML::Tiny;
my $data = YAML::Tiny::LoadFile('META.yml');
# Call methods explicitly in case user has already set some values.
while ( my ( $key, $value ) = each %$data ) {
next unless $self->can($key);
if ( ref $value eq 'HASH' ) {
while ( my ( $module, $version ) = each %$value ) {
$self->can($key)->($self, $module => $version );
}
} else {
$self->can($key)->($self, $value);
}
}
return $self;
}
sub write {
my $self = shift;
return $self unless $self->is_admin;
$self->admin->write_meta;
return $self;
}
sub version_from {
require ExtUtils::MM_Unix;
my ( $self, $file ) = @_;
$self->version( ExtUtils::MM_Unix->parse_version($file) );
# for version integrity check
$self->makemaker_args( VERSION_FROM => $file );
}
sub abstract_from {
require ExtUtils::MM_Unix;
my ( $self, $file ) = @_;
$self->abstract(
bless(
{ DISTNAME => $self->name },
'ExtUtils::MM_Unix'
)->parse_abstract($file)
);
}
# Add both distribution and module name
sub name_from {
my ($self, $file) = @_;
if (
Module::Install::_read($file) =~ m/
^ \s*
package \s*
([\w:]+)
\s* ;
/ixms
) {
my ($name, $module_name) = ($1, $1);
$name =~ s{::}{-}g;
$self->name($name);
unless ( $self->module_name ) {
$self->module_name($module_name);
}
} else {
die("Cannot determine name from $file\n");
}
}
sub _extract_perl_version {
if (
$_[0] =~ m/
^\s*
(?:use|require) \s*
v?
([\d_\.]+)
\s* ;
/ixms
) {
my $perl_version = $1;
$perl_version =~ s{_}{}g;
return $perl_version;
} else {
return;
}
}
sub perl_version_from {
my $self = shift;
my $perl_version=_extract_perl_version(Module::Install::_read($_[0]));
if ($perl_version) {
$self->perl_version($perl_version);
} else {
warn "Cannot determine perl version info from $_[0]\n";
return;
}
}
sub author_from {
my $self = shift;
my $content = Module::Install::_read($_[0]);
if ($content =~ m/
=head \d \s+ (?:authors?)\b \s*
([^\n]*)
|
=head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b \s*
.*? copyright .*? \d\d\d[\d.]+ \s* (?:\bby\b)? \s*
([^\n]*)
/ixms) {
my $author = $1 || $2;
# XXX: ugly but should work anyway...
if (eval "require Pod::Escapes; 1") {
# Pod::Escapes has a mapping table.
# It's in core of perl >= 5.9.3, and should be installed
# as one of the Pod::Simple's prereqs, which is a prereq
# of Pod::Text 3.x (see also below).
$author =~ s{ E<( (\d+) | ([A-Za-z]+) )> }
{
defined $2
? chr($2)
: defined $Pod::Escapes::Name2character_number{$1}
? chr($Pod::Escapes::Name2character_number{$1})
: do {
warn "Unknown escape: E<$1>";
"E<$1>";
};
}gex;
}
elsif (eval "require Pod::Text; 1" && $Pod::Text::VERSION < 3) {
# Pod::Text < 3.0 has yet another mapping table,
# though the table name of 2.x and 1.x are different.
# (1.x is in core of Perl < 5.6, 2.x is in core of
# Perl < 5.9.3)
my $mapping = ($Pod::Text::VERSION < 2)
? \%Pod::Text::HTML_Escapes
: \%Pod::Text::ESCAPES;
$author =~ s{ E<( (\d+) | ([A-Za-z]+) )> }
{
defined $2
? chr($2)
: defined $mapping->{$1}
? $mapping->{$1}
: do {
warn "Unknown escape: E<$1>";
"E<$1>";
};
}gex;
}
else {
$author =~ s{E<lt>}{<}g;
$author =~ s{E<gt>}{>}g;
}
$self->author($author);
} else {
warn "Cannot determine author info from $_[0]\n";
}
}
#Stolen from M::B
my %license_urls = (
perl => 'http://dev.perl.org/licenses/',
apache => 'http://apache.org/licenses/LICENSE-2.0',
apache_1_1 => 'http://apache.org/licenses/LICENSE-1.1',
artistic => 'http://opensource.org/licenses/artistic-license.php',
artistic_2 => 'http://opensource.org/licenses/artistic-license-2.0.php',
lgpl => 'http://opensource.org/licenses/lgpl-license.php',
lgpl2 => 'http://opensource.org/licenses/lgpl-2.1.php',
lgpl3 => 'http://opensource.org/licenses/lgpl-3.0.html',
bsd => 'http://opensource.org/licenses/bsd-license.php',
gpl => 'http://opensource.org/licenses/gpl-license.php',
gpl2 => 'http://opensource.org/licenses/gpl-2.0.php',
gpl3 => 'http://opensource.org/licenses/gpl-3.0.html',
mit => 'http://opensource.org/licenses/mit-license.php',
mozilla => 'http://opensource.org/licenses/mozilla1.1.php',
open_source => undef,
unrestricted => undef,
restrictive => undef,
unknown => undef,
);
sub license {
my $self = shift;
return $self->{values}->{license} unless @_;
my $license = shift or die(
'Did not provide a value to license()'
);
$license = __extract_license($license) || lc $license;
$self->{values}->{license} = $license;
# Automatically fill in license URLs
if ( $license_urls{$license} ) {
$self->resources( license => $license_urls{$license} );
}
return 1;
}
sub _extract_license {
my $pod = shift;
my $matched;
return __extract_license(
($matched) = $pod =~ m/
(=head \d \s+ L(?i:ICEN[CS]E|ICENSING)\b.*?)
(=head \d.*|=cut.*|)\z
/xms
) || __extract_license(
($matched) = $pod =~ m/
(=head \d \s+ (?:C(?i:OPYRIGHTS?)|L(?i:EGAL))\b.*?)
(=head \d.*|=cut.*|)\z
/xms
);
}
sub __extract_license {
my $license_text = shift or return;
my @phrases = (
'(?:under )?the same (?:terms|license) as (?:perl|the perl (?:\d )?programming language)' => 'perl', 1,
'(?:under )?the terms of (?:perl|the perl programming language) itself' => 'perl', 1,
'Artistic and GPL' => 'perl', 1,
'GNU general public license' => 'gpl', 1,
'GNU public license' => 'gpl', 1,
'GNU lesser general public license' => 'lgpl', 1,
'GNU lesser public license' => 'lgpl', 1,
'GNU library general public license' => 'lgpl', 1,
'GNU library public license' => 'lgpl', 1,
'GNU Free Documentation license' => 'unrestricted', 1,
'GNU Affero General Public License' => 'open_source', 1,
'(?:Free)?BSD license' => 'bsd', 1,
'Artistic license' => 'artistic', 1,
'Apache (?:Software )?license' => 'apache', 1,
'GPL' => 'gpl', 1,
'LGPL' => 'lgpl', 1,
'BSD' => 'bsd', 1,
'Artistic' => 'artistic', 1,
'MIT' => 'mit', 1,
'Mozilla Public License' => 'mozilla', 1,
'Q Public License' => 'open_source', 1,
'OpenSSL License' => 'unrestricted', 1,
'SSLeay License' => 'unrestricted', 1,
'zlib License' => 'open_source', 1,
'proprietary' => 'proprietary', 0,
);
while ( my ($pattern, $license, $osi) = splice(@phrases, 0, 3) ) {
$pattern =~ s#\s+#\\s+#gs;
if ( $license_text =~ /\b$pattern\b/i ) {
return $license;
}
}
return '';
}
sub license_from {
my $self = shift;
if (my $license=_extract_license(Module::Install::_read($_[0]))) {
$self->license($license);
} else {
warn "Cannot determine license info from $_[0]\n";
return 'unknown';
}
}
sub _extract_bugtracker {
my @links = $_[0] =~ m#L<(
\Qhttp://rt.cpan.org/\E[^>]+|
\Qhttp://github.com/\E[\w_]+/[\w_]+/issues|
\Qhttp://code.google.com/p/\E[\w_\-]+/issues/list
)>#gx;
my %links;
@links{@links}=();
@links=keys %links;
return @links;
}
sub bugtracker_from {
my $self = shift;
my $content = Module::Install::_read($_[0]);
my @links = _extract_bugtracker($content);
unless ( @links ) {
warn "Cannot determine bugtracker info from $_[0]\n";
return 0;
}
if ( @links > 1 ) {
warn "Found more than one bugtracker link in $_[0]\n";
return 0;
}
# Set the bugtracker
bugtracker( $links[0] );
return 1;
}
sub requires_from {
my $self = shift;
my $content = Module::Install::_readperl($_[0]);
my @requires = $content =~ m/^use\s+([^\W\d]\w*(?:::\w+)*)\s+([\d\.]+)/mg;
while ( @requires ) {
my $module = shift @requires;
my $version = shift @requires;
$self->requires( $module => $version );
}
}
sub test_requires_from {
my $self = shift;
my $content = Module::Install::_readperl($_[0]);
my @requires = $content =~ m/^use\s+([^\W\d]\w*(?:::\w+)*)\s+([\d\.]+)/mg;
while ( @requires ) {
my $module = shift @requires;
my $version = shift @requires;
$self->test_requires( $module => $version );
}
}
# Convert triple-part versions (eg, 5.6.1 or 5.8.9) to
# numbers (eg, 5.006001 or 5.008009).
# Also, convert double-part versions (eg, 5.8)
sub _perl_version {
my $v = $_[-1];
$v =~ s/^([1-9])\.([1-9]\d?\d?)$/sprintf("%d.%03d",$1,$2)/e;
$v =~ s/^([1-9])\.([1-9]\d?\d?)\.(0|[1-9]\d?\d?)$/sprintf("%d.%03d%03d",$1,$2,$3 || 0)/e;
$v =~ s/(\.\d\d\d)000$/$1/;
$v =~ s/_.+$//;
if ( ref($v) ) {
# Numify
$v = $v + 0;
}
return $v;
}
sub add_metadata {
my $self = shift;
my %hash = @_;
for my $key (keys %hash) {
warn "add_metadata: $key is not prefixed with 'x_'.\n" .
"Use appopriate function to add non-private metadata.\n" unless $key =~ /^x_/;
$self->{values}->{$key} = $hash{$key};
}
}
######################################################################
# MYMETA Support
sub WriteMyMeta {
die "WriteMyMeta has been deprecated";
}
sub write_mymeta_yaml {
my $self = shift;
# We need YAML::Tiny to write the MYMETA.yml file
unless ( eval { require YAML::Tiny; 1; } ) {
return 1;
}
# Generate the data
my $meta = $self->_write_mymeta_data or return 1;
# Save as the MYMETA.yml file
print "Writing MYMETA.yml\n";
YAML::Tiny::DumpFile('MYMETA.yml', $meta);
}
sub write_mymeta_json {
my $self = shift;
# We need JSON to write the MYMETA.json file
unless ( eval { require JSON; 1; } ) {
return 1;
}
# Generate the data
my $meta = $self->_write_mymeta_data or return 1;
# Save as the MYMETA.yml file
print "Writing MYMETA.json\n";
Module::Install::_write(
'MYMETA.json',
JSON->new->pretty(1)->canonical->encode($meta),
);
}
sub _write_mymeta_data {
my $self = shift;
# If there's no existing META.yml there is nothing we can do
return undef unless -f 'META.yml';
# We need Parse::CPAN::Meta to load the file
unless ( eval { require Parse::CPAN::Meta; 1; } ) {
return undef;
}
# Merge the perl version into the dependencies
my $val = $self->Meta->{values};
my $perl = delete $val->{perl_version};
if ( $perl ) {
$val->{requires} ||= [];
my $requires = $val->{requires};
# Canonize to three-dot version after Perl 5.6
if ( $perl >= 5.006 ) {
$perl =~ s{^(\d+)\.(\d\d\d)(\d*)}{join('.', $1, int($2||0), int($3||0))}e
}
unshift @$requires, [ perl => $perl ];
}
# Load the advisory META.yml file
my @yaml = Parse::CPAN::Meta::LoadFile('META.yml');
my $meta = $yaml[0];
# Overwrite the non-configure dependency hashs
delete $meta->{requires};
delete $meta->{build_requires};
delete $meta->{recommends};
if ( exists $val->{requires} ) {
$meta->{requires} = { map { @$_ } @{ $val->{requires} } };
}
if ( exists $val->{build_requires} ) {
$meta->{build_requires} = { map { @$_ } @{ $val->{build_requires} } };
}
return $meta;
}
1;

View File

@@ -0,0 +1,64 @@
#line 1
package Module::Install::Win32;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
# determine if the user needs nmake, and download it if needed
sub check_nmake {
my $self = shift;
$self->load('can_run');
$self->load('get_file');
require Config;
return unless (
$^O eq 'MSWin32' and
$Config::Config{make} and
$Config::Config{make} =~ /^nmake\b/i and
! $self->can_run('nmake')
);
print "The required 'nmake' executable not found, fetching it...\n";
require File::Basename;
my $rv = $self->get_file(
url => 'http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe',
ftp_url => 'ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe',
local_dir => File::Basename::dirname($^X),
size => 51928,
run => 'Nmake15.exe /o > nul',
check_for => 'Nmake.exe',
remove => 1,
);
die <<'END_MESSAGE' unless $rv;
-------------------------------------------------------------------------------
Since you are using Microsoft Windows, you will need the 'nmake' utility
before installation. It's available at:
http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe
or
ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe
Please download the file manually, save it to a directory in %PATH% (e.g.
C:\WINDOWS\COMMAND\), then launch the MS-DOS command line shell, "cd" to
that directory, and run "Nmake15.exe" from there; that will create the
'nmake.exe' file needed by this module.
You may then resume the installation process described in README.
-------------------------------------------------------------------------------
END_MESSAGE
}
1;

View File

@@ -0,0 +1,63 @@
#line 1
package Module::Install::WriteAll;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.00';
@ISA = qw{Module::Install::Base};
$ISCORE = 1;
}
sub WriteAll {
my $self = shift;
my %args = (
meta => 1,
sign => 0,
inline => 0,
check_nmake => 1,
@_,
);
$self->sign(1) if $args{sign};
$self->admin->WriteAll(%args) if $self->is_admin;
$self->check_nmake if $args{check_nmake};
unless ( $self->makemaker_args->{PL_FILES} ) {
# XXX: This still may be a bit over-defensive...
unless ($self->makemaker(6.25)) {
$self->makemaker_args( PL_FILES => {} ) if -f 'Build.PL';
}
}
# Until ExtUtils::MakeMaker support MYMETA.yml, make sure
# we clean it up properly ourself.
$self->realclean_files('MYMETA.yml');
if ( $args{inline} ) {
$self->Inline->write;
} else {
$self->Makefile->write;
}
# The Makefile write process adds a couple of dependencies,
# so write the META.yml files after the Makefile.
if ( $args{meta} ) {
$self->Meta->write;
}
# Experimental support for MYMETA
if ( $ENV{X_MYMETA} ) {
if ( $ENV{X_MYMETA} eq 'JSON' ) {
$self->Meta->write_mymeta_json;
} else {
$self->Meta->write_mymeta_yaml;
}
}
return 1;
}
1;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,121 @@
package Monitoring::Livestatus::INET;
use 5.000000;
use strict;
use warnings;
use IO::Socket::INET;
use Socket qw(IPPROTO_TCP TCP_NODELAY);
use Carp;
use base "Monitoring::Livestatus";
=head1 NAME
Monitoring::Livestatus::INET - connector with tcp sockets
=head1 SYNOPSIS
use Monitoring::Livestatus;
my $nl = Monitoring::Livestatus::INET->new( 'localhost:9999' );
my $hosts = $nl->selectall_arrayref("GET hosts");
=head1 CONSTRUCTOR
=head2 new ( [ARGS] )
Creates an C<Monitoring::Livestatus::INET> object. C<new> takes at least the server.
Arguments are the same as in C<Monitoring::Livestatus>.
If the constructor is only passed a single argument, it is assumed to
be a the C<server> specification. Use either socker OR server.
=cut
sub new {
my $class = shift;
unshift(@_, "peer") if scalar @_ == 1;
my(%options) = @_;
$options{'name'} = $options{'peer'} unless defined $options{'name'};
$options{'backend'} = $class;
my $self = Monitoring::Livestatus->new(%options);
bless $self, $class;
confess('not a scalar') if ref $self->{'peer'} ne '';
return $self;
}
########################################
=head1 METHODS
=cut
sub _open {
my $self = shift;
my $sock;
eval {
local $SIG{'ALRM'} = sub { die("connection timeout"); };
alarm($self->{'connect_timeout'});
$sock = IO::Socket::INET->new(
PeerAddr => $self->{'peer'},
Type => SOCK_STREAM,
Timeout => $self->{'connect_timeout'},
);
if(!defined $sock or !$sock->connected()) {
my $msg = "failed to connect to $self->{'peer'} :$!";
if($self->{'errors_are_fatal'}) {
croak($msg);
}
$Monitoring::Livestatus::ErrorCode = 500;
$Monitoring::Livestatus::ErrorMessage = $msg;
alarm(0);
return;
}
if(defined $self->{'query_timeout'}) {
# set timeout
$sock->timeout($self->{'query_timeout'});
}
setsockopt($sock, IPPROTO_TCP, TCP_NODELAY, 1);
};
alarm(0);
if($@) {
$Monitoring::Livestatus::ErrorCode = 500;
$Monitoring::Livestatus::ErrorMessage = $@;
return;
}
return($sock);
}
########################################
sub _close {
my $self = shift;
my $sock = shift;
return unless defined $sock;
return close($sock);
}
1;
=head1 AUTHOR
Sven Nierlein, E<lt>nierlein@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2009 by Sven Nierlein
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
__END__

View File

@@ -0,0 +1,922 @@
package Monitoring::Livestatus::MULTI;
use 5.000000;
use strict;
use warnings;
use Carp;
use Data::Dumper;
use Config;
use Time::HiRes qw/gettimeofday tv_interval/;
use Scalar::Util qw/looks_like_number/;
use Monitoring::Livestatus;
use base "Monitoring::Livestatus";
=head1 NAME
Monitoring::Livestatus::MULTI - connector with multiple peers
=head1 SYNOPSIS
use Monitoring::Livestatus;
my $nl = Monitoring::Livestatus::MULTI->new( qw{nagioshost1:9999 nagioshost2:9999 /var/spool/nagios/live.socket} );
my $hosts = $nl->selectall_arrayref("GET hosts");
=head1 CONSTRUCTOR
=head2 new ( [ARGS] )
Creates an C<Monitoring::Livestatus::MULTI> object. C<new> takes at least the server.
Arguments are the same as in L<Monitoring::Livestatus>.
=cut
sub new {
my $class = shift;
unshift(@_, "peer") if scalar @_ == 1;
my(%options) = @_;
$options{'backend'} = $class;
my $self = Monitoring::Livestatus->new(%options);
bless $self, $class;
if(!defined $self->{'peers'}) {
$self->{'peer'} = $self->_get_peers();
# set our peer(s) from the options
my %peer_options;
my $peers;
for my $opt_key (keys %options) {
$peer_options{$opt_key} = $options{$opt_key};
}
$peer_options{'errors_are_fatal'} = 0;
for my $peer (@{$self->{'peer'}}) {
$peer_options{'name'} = $peer->{'name'};
$peer_options{'peer'} = $peer->{'peer'};
delete $peer_options{'socket'};
delete $peer_options{'server'};
if($peer->{'type'} eq 'UNIX') {
push @{$peers}, new Monitoring::Livestatus::UNIX(%peer_options);
}
elsif($peer->{'type'} eq 'INET') {
push @{$peers}, new Monitoring::Livestatus::INET(%peer_options);
}
}
$self->{'peers'} = $peers;
delete $self->{'socket'};
delete $self->{'server'};
}
if(!defined $self->{'peers'}) {
croak('please specify at least one peer, socket or server');
}
# dont use threads with only one peer
if(scalar @{$self->{'peers'}} == 1) { $self->{'use_threads'} = 0; }
# check for threads support
if(!defined $self->{'use_threads'}) {
$self->{'use_threads'} = 0;
if($Config{useithreads}) {
$self->{'use_threads'} = 1;
}
}
if($self->{'use_threads'}) {
eval {
require threads;
require Thread::Queue;
};
if($@) {
$self->{'use_threads'} = 0;
$self->{'logger'}->debug('error initializing threads: '.$@) if defined $self->{'logger'};
} else {
$self->_start_worker;
}
}
# initialize peer keys
$self->{'peer_by_key'} = {};
$self->{'peer_by_addr'} = {};
for my $peer (@{$self->{'peers'}}) {
$self->{'peer_by_key'}->{$peer->peer_key} = $peer;
$self->{'peer_by_addr'}->{$peer->peer_addr} = $peer;
}
$self->{'name'} = 'multiple connector' unless defined $self->{'name'};
$self->{'logger'}->debug('initialized Monitoring::Livestatus::MULTI '.($self->{'use_threads'} ? 'with' : 'without' ).' threads') if $self->{'verbose'};
return $self;
}
########################################
=head1 METHODS
=head2 do
See L<Monitoring::Livestatus> for more information.
=cut
sub do {
my $self = shift;
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
$self->_do_on_peers("do", $opts->{'backends'}, @_);
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for do('.$_[0].') in total') if $self->{'verbose'};
return 1;
}
########################################
=head2 selectall_arrayref
See L<Monitoring::Livestatus> for more information.
=cut
sub selectall_arrayref {
my $self = shift;
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
$self->_log_statement($_[0], $opts, 0) if $self->{'verbose'};
my $return = $self->_merge_answer($self->_do_on_peers("selectall_arrayref", $opts->{'backends'}, @_));
my $elapsed = tv_interval ( $t0 );
if($self->{'verbose'}) {
my $total_results = 0;
$total_results = scalar @{$return} if defined $return;
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectall_arrayref() in total, results: '.$total_results);
}
return $return;
}
########################################
=head2 selectall_hashref
See L<Monitoring::Livestatus> for more information.
=cut
sub selectall_hashref {
my $self = shift;
my $opts = $self->_lowercase_and_verify_options($_[2]);
my $t0 = [gettimeofday];
my $return = $self->_merge_answer($self->_do_on_peers("selectall_hashref", $opts->{'backends'}, @_));
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectall_hashref() in total') if $self->{'verbose'};
return $return;
}
########################################
=head2 selectcol_arrayref
See L<Monitoring::Livestatus> for more information.
=cut
sub selectcol_arrayref {
my $self = shift;
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
my $return = $self->_merge_answer($self->_do_on_peers("selectcol_arrayref", $opts->{'backends'}, @_));
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectcol_arrayref() in total') if $self->{'verbose'};
return $return;
}
########################################
=head2 selectrow_array
See L<Monitoring::Livestatus> for more information.
=cut
sub selectrow_array {
my $self = shift;
my $statement = $_[0];
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
my @return;
if((defined $opts->{'sum'} and $opts->{'sum'} == 1) or (!defined $opts->{'sum'} and $statement =~ m/^Stats:/mx)) {
@return = @{$self->_sum_answer($self->_do_on_peers("selectrow_arrayref", $opts->{'backends'}, @_))};
} else {
if($self->{'warnings'}) {
carp("selectrow_arrayref without Stats on multi backend will not work as expected!");
}
my $rows = $self->_merge_answer($self->_do_on_peers("selectrow_arrayref", $opts->{'backends'}, @_));
@return = @{$rows} if defined $rows;
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectrow_array() in total') if $self->{'verbose'};
return @return;
}
########################################
=head2 selectrow_arrayref
See L<Monitoring::Livestatus> for more information.
=cut
sub selectrow_arrayref {
my $self = shift;
my $statement = $_[0];
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
my $return;
if((defined $opts->{'sum'} and $opts->{'sum'} == 1) or (!defined $opts->{'sum'} and $statement =~ m/^Stats:/mx)) {
$return = $self->_sum_answer($self->_do_on_peers("selectrow_arrayref", $opts->{'backends'}, @_));
} else {
if($self->{'warnings'}) {
carp("selectrow_arrayref without Stats on multi backend will not work as expected!");
}
my $rows = $self->_merge_answer($self->_do_on_peers("selectrow_arrayref", $opts->{'backends'}, @_));
$return = $rows->[0] if defined $rows->[0];
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectrow_arrayref() in total') if $self->{'verbose'};
return $return;
}
########################################
=head2 selectrow_hashref
See L<Monitoring::Livestatus> for more information.
=cut
sub selectrow_hashref {
my $self = shift;
my $statement = $_[0];
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
my $return;
if((defined $opts->{'sum'} and $opts->{'sum'} == 1) or (!defined $opts->{'sum'} and $statement =~ m/^Stats:/mx)) {
$return = $self->_sum_answer($self->_do_on_peers("selectrow_hashref", $opts->{'backends'}, @_));
} else {
if($self->{'warnings'}) {
carp("selectrow_hashref without Stats on multi backend will not work as expected!");
}
$return = $self->_merge_answer($self->_do_on_peers("selectrow_hashref", $opts->{'backends'}, @_));
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectrow_hashref() in total') if $self->{'verbose'};
return $return;
}
########################################
=head2 selectscalar_value
See L<Monitoring::Livestatus> for more information.
=cut
sub selectscalar_value {
my $self = shift;
my $statement = $_[0];
my $opts = $self->_lowercase_and_verify_options($_[1]);
my $t0 = [gettimeofday];
my $return;
if((defined $opts->{'sum'} and $opts->{'sum'} == 1) or (!defined $opts->{'sum'} and $statement =~ m/^Stats:/mx)) {
return $self->_sum_answer($self->_do_on_peers("selectscalar_value", $opts->{'backends'}, @_));
} else {
if($self->{'warnings'}) {
carp("selectscalar_value without Stats on multi backend will not work as expected!");
}
my $rows = $self->_merge_answer($self->_do_on_peers("selectscalar_value", $opts->{'backends'}, @_));
$return = $rows->[0] if defined $rows->[0];
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for selectscalar_value() in total') if $self->{'verbose'};
return $return;
}
########################################
=head2 errors_are_fatal
See L<Monitoring::Livestatus> for more information.
=cut
sub errors_are_fatal {
my $self = shift;
my $value = shift;
return $self->_change_setting('errors_are_fatal', $value);
}
########################################
=head2 warnings
See L<Monitoring::Livestatus> for more information.
=cut
sub warnings {
my $self = shift;
my $value = shift;
return $self->_change_setting('warnings', $value);
}
########################################
=head2 verbose
See L<Monitoring::Livestatus> for more information.
=cut
sub verbose {
my $self = shift;
my $value = shift;
return $self->_change_setting('verbose', $value);
}
########################################
=head2 peer_addr
See L<Monitoring::Livestatus> for more information.
=cut
sub peer_addr {
my $self = shift;
my @addrs;
for my $peer (@{$self->{'peers'}}) {
push @addrs, $peer->peer_addr;
}
return wantarray ? @addrs : undef;
}
########################################
=head2 peer_name
See L<Monitoring::Livestatus> for more information.
=cut
sub peer_name {
my $self = shift;
my @names;
for my $peer (@{$self->{'peers'}}) {
push @names, $peer->peer_name;
}
return wantarray ? @names : $self->{'name'};
}
########################################
=head2 peer_key
See L<Monitoring::Livestatus> for more information.
=cut
sub peer_key {
my $self = shift;
my @keys;
for my $peer (@{$self->{'peers'}}) {
push @keys, $peer->peer_key;
}
return wantarray ? @keys : $self->{'key'};
}
########################################
=head2 disable
$ml->disable()
disables this connection, returns the last state.
=cut
sub disable {
my $self = shift;
my $peer_key = shift;
if(!defined $peer_key) {
for my $peer (@{$self->{'peers'}}) {
$peer->disable();
}
return 1;
} else {
my $peer = $self->_get_peer_by_key($peer_key);
my $prev = $peer->{'disabled'};
$peer->{'disabled'} = 1;
return $prev;
}
}
########################################
=head2 enable
$ml->enable()
enables this connection, returns the last state.
=cut
sub enable {
my $self = shift;
my $peer_key = shift;
if(!defined $peer_key) {
for my $peer (@{$self->{'peers'}}) {
$peer->enable();
}
return 1;
} else {
my $peer = $self->_get_peer_by_key($peer_key);
my $prev = $peer->{'disabled'};
$peer->{'disabled'} = 0;
return $prev;
}
}
########################################
# INTERNAL SUBS
########################################
sub _change_setting {
my $self = shift;
my $key = shift;
my $value = shift;
my $old = $self->{$key};
# set new value
if(defined $value) {
$self->{$key} = $value;
for my $peer (@{$self->{'peers'}}) {
$peer->{$key} = $value;
}
# restart workers
if($self->{'use_threads'}) {
_stop_worker();
$self->_start_worker();
}
}
return $old;
}
########################################
sub _start_worker {
my $self = shift;
# create job transports
$self->{'WorkQueue'} = Thread::Queue->new;
$self->{'WorkResults'} = Thread::Queue->new;
# set signal handler before thread is started
# otherwise they would be killed when started
# and stopped immediately after start
$SIG{'USR1'} = sub { threads->exit(); };
# start worker threads
our %threads;
my $threadcount = scalar @{$self->{'peers'}};
for(my $x = 0; $x < $threadcount; $x++) {
$self->{'threads'}->[$x] = threads->new(\&_worker_thread, $self->{'peers'}, $self->{'WorkQueue'}, $self->{'WorkResults'}, $self->{'logger'});
}
# restore sig handler as it was only for the threads
$SIG{'USR1'} = 'DEFAULT';
return;
}
########################################
sub _stop_worker {
# try to kill our threads safely
eval {
for my $thr (threads->list()) {
$thr->kill('USR1')->detach();
}
};
return;
}
########################################
sub _worker_thread {
local $SIG{'USR1'} = sub { threads->exit(); };
my $peers = shift;
my $workQueue = shift;
my $workResults = shift;
my $logger = shift;
while (my $job = $workQueue->dequeue) {
my $erg;
eval {
$erg = _do_wrapper($peers->[$job->{'peer'}], $job->{'sub'}, $logger, @{$job->{'opts'}});
};
if($@) {
warn("Error in Thread ".$job->{'peer'}." :".$@);
$job->{'logger'}->error("Error in Thread ".$job->{'peer'}." :".$@) if defined $job->{'logger'};
};
$workResults->enqueue({ peer => $job->{'peer'}, result => $erg });
}
return;
}
########################################
sub _do_wrapper {
my $peer = shift;
my $sub = shift;
my $logger = shift;
my @opts = @_;
my $t0 = [gettimeofday];
my $data = $peer->$sub(@opts);
my $elapsed = tv_interval ( $t0 );
$logger->debug(sprintf('%.4f', $elapsed).' sec for fetching data on '.$peer->peer_name.' ('.$peer->peer_addr.')') if defined $logger;
$Monitoring::Livestatus::ErrorCode = 0 unless defined $Monitoring::Livestatus::ErrorCode;
$Monitoring::Livestatus::ErrorMessage = '' unless defined $Monitoring::Livestatus::ErrorMessage;
my $return = {
'msg' => $Monitoring::Livestatus::ErrorMessage,
'code' => $Monitoring::Livestatus::ErrorCode,
'data' => $data,
};
return $return;
}
########################################
sub _do_on_peers {
my $self = shift;
my $sub = shift;
my $backends = shift;
my @opts = @_;
my $statement = $opts[0];
my $use_threads = $self->{'use_threads'};
my $t0 = [gettimeofday];
my $return;
my %codes;
my %messages;
my $query_options;
if($sub eq 'selectall_hashref') {
$query_options = $self->_lowercase_and_verify_options($opts[2]);
} else {
$query_options = $self->_lowercase_and_verify_options($opts[1]);
}
# which peers affected?
my @peers;
if(defined $backends) {
my @backends;
if(ref $backends eq '') {
push @backends, $backends;
}
elsif(ref $backends eq 'ARRAY') {
@backends = @{$backends};
} else {
croak("unsupported type for backend: ".ref($backends));
}
for my $key (@backends) {
my $backend = $self->_get_peer_by_key($key);
push @peers, $backend unless $backend->{'disabled'};
}
} else {
# use all backends
@peers = @{$self->{'peers'}};
}
# its faster without threads for only one peer
if(scalar @peers <= 1) { $use_threads = 0; }
# if we have limits set, we cannot use threads
if(defined $query_options->{'limit_start'}) { $use_threads = 0; }
if($use_threads) {
# use the threaded variant
$self->{'logger'}->debug('using threads') if $self->{'verbose'};
my $peers_to_use;
for my $peer (@peers) {
if($peer->{'disabled'}) {
# dont send any query
}
elsif($peer->marked_bad) {
warn($peer->peer_name.' ('.$peer->peer_key.') is marked bad') if $self->{'verbose'};
}
else {
$peers_to_use->{$peer->peer_key} = 1;
}
}
my $x = 0;
for my $peer (@{$self->{'peers'}}) {
if(defined $peers_to_use->{$peer->peer_key}) {
my $job = {
'peer' => $x,
'sub' => $sub,
'opts' => \@opts,
};
$self->{'WorkQueue'}->enqueue($job);
}
$x++;
}
for(my $x = 0; $x < scalar keys %{$peers_to_use}; $x++) {
my $result = $self->{'WorkResults'}->dequeue;
my $peer = $self->{'peers'}->[$result->{'peer'}];
if(defined $result->{'result'}) {
push @{$codes{$result->{'result'}->{'code'}}}, { 'peer' => $peer->peer_key, 'msg' => $result->{'result'}->{'msg'} };
$return->{$peer->peer_key} = $result->{'result'}->{'data'};
} else {
warn("undefined result for: $statement");
}
}
} else {
$self->{'logger'}->debug('not using threads') if $self->{'verbose'};
for my $peer (@peers) {
if($peer->{'disabled'}) {
# dont send any query
}
elsif($peer->marked_bad) {
warn($peer->peer_name.' ('.$peer->peer_key.') is marked bad') if $self->{'verbose'};
} else {
my $erg = _do_wrapper($peer, $sub, $self->{'logger'}, @opts);
$return->{$peer->peer_key} = $erg->{'data'};
push @{$codes{$erg->{'code'}}}, { 'peer' => $peer, 'msg' => $erg->{'msg'} };
# compute limits
if(defined $query_options->{'limit_length'} and $peer->{'meta_data'}->{'result_count'}) {
last;
}
# set a new start if we had rows already
if(defined $query_options->{'limit_start'}) {
$query_options->{'limit_start'} = $query_options->{'limit_start'} - $peer->{'meta_data'}->{'row_count'};
}
}
}
}
# check if we different result stati
undef $Monitoring::Livestatus::ErrorMessage;
$Monitoring::Livestatus::ErrorCode = 0;
my @codes = sort keys %codes;
if(scalar @codes > 1) {
# got different results for our backends
if($self->{'verbose'}) {
$self->{'logger'}->warn("got different result stati: ".Dumper(\%codes));
}
} else {
# got same result codes for all backend
}
my $failed = 0;
my $code = $codes[0];
if(defined $code and $code >= 300) {
$failed = 1;
}
if($failed) {
my $msg = $codes{$code}->[0]->{'msg'};
$self->{'logger'}->debug("same: $code -> $msg") if $self->{'verbose'};
$Monitoring::Livestatus::ErrorMessage = $msg;
$Monitoring::Livestatus::ErrorCode = $code;
if($self->{'errors_are_fatal'}) {
croak("ERROR ".$code." - ".$Monitoring::Livestatus::ErrorMessage." in query:\n'".$statement."'\n");
}
return;
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for fetching all data') if $self->{'verbose'};
# deep copy result?
if($use_threads
and (
(defined $query_options->{'deepcopy'} and $query_options->{'deepcopy'} == 1)
or
(defined $self->{'deepcopy'} and $self->{'deepcopy'} == 1)
)
) {
# result has to be cloned to avoid "Invalid value for shared scalar" error
$return = $self->_clone($return, $self->{'logger'});
}
return($return);
}
########################################
sub _merge_answer {
my $self = shift;
my $data = shift;
my $return;
my $t0 = [gettimeofday];
# iterate over original peers to retain order
for my $peer (@{$self->{'peers'}}) {
my $key = $peer->peer_key;
next if !defined $data->{$key};
if(ref $data->{$key} eq 'ARRAY') {
$return = [] unless defined $return;
$return = [ @{$return}, @{$data->{$key}} ];
} elsif(ref $data->{$key} eq 'HASH') {
$return = {} unless defined $return;
$return = { %{$return}, %{$data->{$key}} };
} else {
push @{$return}, $data->{$key};
}
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for merging data') if $self->{'verbose'};
return($return);
}
########################################
sub _sum_answer {
my $self = shift;
my $data = shift;
my $return;
my $t0 = [gettimeofday];
for my $peername (keys %{$data}) {
if(ref $data->{$peername} eq 'HASH') {
for my $key (keys %{$data->{$peername}}) {
if(!defined $return->{$key}) {
$return->{$key} = $data->{$peername}->{$key};
} elsif(looks_like_number($data->{$peername}->{$key})) {
$return->{$key} += $data->{$peername}->{$key};
}
}
}
elsif(ref $data->{$peername} eq 'ARRAY') {
my $x = 0;
for my $val (@{$data->{$peername}}) {
if(!defined $return->[$x]) {
$return->[$x] = $data->{$peername}->[$x];
} else {
$return->[$x] += $data->{$peername}->[$x];
}
$x++;
}
} elsif(defined $data->{$peername}) {
$return = 0 unless defined $return;
next unless defined $data->{$peername};
$return += $data->{$peername};
}
}
my $elapsed = tv_interval ( $t0 );
$self->{'logger'}->debug(sprintf('%.4f', $elapsed).' sec for summarizing data') if $self->{'verbose'};
return $return;
}
########################################
sub _clone {
my $self = shift;
my $data = shift;
my $logger = shift;
my $t0 = [gettimeofday];
my $return;
if(ref $data eq '') {
$return = $data;
}
elsif(ref $data eq 'ARRAY') {
$return = [];
for my $dat (@{$data}) {
push @{$return}, $self->_clone($dat);
}
}
elsif(ref $data eq 'HASH') {
$return = {};
for my $key (keys %{$data}) {
$return->{$key} = $self->_clone($data->{$key});
}
}
else {
croak("cant clone: ".(ref $data));
}
my $elapsed = tv_interval ( $t0 );
$logger->debug(sprintf('%.4f', $elapsed).' sec for cloning data') if defined $logger;
return $return;
}
########################################
sub _get_peer_by_key {
my $self = shift;
my $key = shift;
return unless defined $key;
return unless defined $self->{'peer_by_key'}->{$key};
return $self->{'peer_by_key'}->{$key};
}
########################################
sub _get_peer_by_addr {
my $self = shift;
my $addr = shift;
return unless defined $addr;
return unless defined $self->{'peer_by_addr'}->{$addr};
return $self->{'peer_by_addr'}->{$addr};
}
########################################
END {
# try to kill our threads safely
_stop_worker();
}
########################################
1;
=head1 AUTHOR
Sven Nierlein, E<lt>nierlein@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2009 by Sven Nierlein
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
__END__

View File

@@ -0,0 +1,112 @@
package Monitoring::Livestatus::UNIX;
use 5.000000;
use strict;
use warnings;
use IO::Socket::UNIX;
use Carp;
use base "Monitoring::Livestatus";
=head1 NAME
Monitoring::Livestatus::UNIX - connector with unix sockets
=head1 SYNOPSIS
use Monitoring::Livestatus;
my $nl = Monitoring::Livestatus::UNIX->new( '/var/lib/livestatus/livestatus.sock' );
my $hosts = $nl->selectall_arrayref("GET hosts");
=head1 CONSTRUCTOR
=head2 new ( [ARGS] )
Creates an C<Monitoring::Livestatus::UNIX> object. C<new> takes at least the socketpath.
Arguments are the same as in C<Monitoring::Livestatus>.
If the constructor is only passed a single argument, it is assumed to
be a the C<socket> specification. Use either socker OR server.
=cut
sub new {
my $class = shift;
unshift(@_, "peer") if scalar @_ == 1;
my(%options) = @_;
$options{'name'} = $options{'peer'} unless defined $options{'name'};
$options{'backend'} = $class;
my $self = Monitoring::Livestatus->new(%options);
bless $self, $class;
confess('not a scalar') if ref $self->{'peer'} ne '';
return $self;
}
########################################
=head1 METHODS
=cut
sub _open {
my $self = shift;
if(!-S $self->{'peer'}) {
my $msg = "failed to open socket $self->{'peer'}: $!";
if($self->{'errors_are_fatal'}) {
croak($msg);
}
$Monitoring::Livestatus::ErrorCode = 500;
$Monitoring::Livestatus::ErrorMessage = $msg;
return;
}
my $sock = IO::Socket::UNIX->new(
Peer => $self->{'peer'},
Type => SOCK_STREAM,
);
if(!defined $sock or !$sock->connected()) {
my $msg = "failed to connect to $self->{'peer'} :$!";
if($self->{'errors_are_fatal'}) {
croak($msg);
}
$Monitoring::Livestatus::ErrorCode = 500;
$Monitoring::Livestatus::ErrorMessage = $msg;
return;
}
if(defined $self->{'query_timeout'}) {
# set timeout
$sock->timeout($self->{'query_timeout'});
}
return($sock);
}
########################################
sub _close {
my $self = shift;
my $sock = shift;
return unless defined $sock;
return close($sock);
}
1;
=head1 AUTHOR
Sven Nierlein, E<lt>nierlein@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2009 by Sven Nierlein
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
__END__

View File

@@ -0,0 +1,149 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use File::Temp;
use Data::Dumper;
use IO::Socket::UNIX qw( SOCK_STREAM SOMAXCONN );
use_ok('Monitoring::Livestatus');
BEGIN {
if( $^O eq 'MSWin32' ) {
plan skip_all => 'no sockets on windows';
}
else {
plan tests => 35;
}
}
#########################
# get a temp file from File::Temp and replace it with our socket
my $fh = File::Temp->new(UNLINK => 0);
my $socket_path = $fh->filename;
unlink($socket_path);
my $listener = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Listen => SOMAXCONN,
Local => $socket_path,
) or die("failed to open $socket_path as test socket: $!");
#########################
# create object with single arg
my $ml = Monitoring::Livestatus->new( $socket_path );
isa_ok($ml, 'Monitoring::Livestatus', 'single args');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
#########################
# create object with hash args
my $line_seperator = 10;
my $column_seperator = 0;
$ml = Monitoring::Livestatus->new(
verbose => 0,
socket => $socket_path,
line_seperator => $line_seperator,
column_seperator => $column_seperator,
);
isa_ok($ml, 'Monitoring::Livestatus', 'new hash args');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
#########################
# create object with peer arg
$ml = Monitoring::Livestatus->new(
peer => $socket_path,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg socket');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
isa_ok($ml->{'CONNECTOR'}, 'Monitoring::Livestatus::UNIX', 'peer backend UNIX');
#########################
# create object with peer arg
my $server = 'localhost:12345';
$ml = Monitoring::Livestatus->new(
peer => $server,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg server');
is($ml->peer_name(), $server, 'get peer_name()');
is($ml->peer_addr(), $server, 'get peer_addr()');
isa_ok($ml->{'CONNECTOR'}, 'Monitoring::Livestatus::INET', 'peer backend INET');
#########################
# create multi object with peers
$ml = Monitoring::Livestatus->new(
peer => [ $server, $socket_path ],
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi');
my @names = $ml->peer_name();
my @addrs = $ml->peer_addr();
my $name = $ml->peer_name();
my $expect = [ $server, $socket_path ];
is_deeply(\@names, $expect, 'list context get peer_name()') or diag("got peer names: ".Dumper(\@names)."but expected: ".Dumper($expect));
is($name, 'multiple connector', 'scalar context get peer_name()') or diag("got peer name: ".Dumper($name)."but expected: ".Dumper('multiple connector'));
is_deeply(\@addrs, $expect, 'list context get peer_addr()') or diag("got peer addrs: ".Dumper(\@addrs)."but expected: ".Dumper($expect));
#########################
# create multi object with peers and name
$ml = Monitoring::Livestatus->new(
peer => [ $server, $socket_path ],
name => 'test multi',
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi with name');
$name = $ml->peer_name();
is($name, 'test multi', 'peer_name()');
#########################
$ml = Monitoring::Livestatus->new(
peer => [ $socket_path ],
verbose => 0,
keepalive => 1,
logger => undef,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi with keepalive');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
#########################
# timeout checks
$ml = Monitoring::Livestatus->new(
peer => [ $socket_path ],
verbose => 0,
timeout => 13,
logger => undef,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi with general timeout');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
is($ml->{'connect_timeout'}, 13, 'connect_timeout');
is($ml->{'query_timeout'}, 13, 'query_timeout');
$ml = Monitoring::Livestatus->new(
peer => [ $socket_path ],
verbose => 0,
query_timeout => 14,
connect_timeout => 17,
logger => undef,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi with general timeout');
is($ml->peer_name(), $socket_path, 'get peer_name()');
is($ml->peer_addr(), $socket_path, 'get peer_addr()');
is($ml->{'connect_timeout'}, 17, 'connect_timeout');
is($ml->{'query_timeout'}, 14, 'query_timeout');
#########################
# error retry
$ml = Monitoring::Livestatus->new(
peer => [ $socket_path ],
verbose => 0,
retries_on_connection_error => 3,
retry_interval => 1,
logger => undef,
);
isa_ok($ml, 'Monitoring::Livestatus', 'peer hash arg multi with error retry');
#########################
# cleanup
unlink($socket_path);

View File

@@ -0,0 +1,148 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use File::Temp;
use Data::Dumper;
use IO::Socket::UNIX qw( SOCK_STREAM SOMAXCONN );
use_ok('Monitoring::Livestatus');
BEGIN {
if( $^O eq 'MSWin32' ) {
plan skip_all => 'no sockets on windows';
}
else {
plan tests => 14;
}
}
#########################
# get a temp file from File::Temp and replace it with our socket
my $fh = File::Temp->new(UNLINK => 0);
my $socket_path = $fh->filename;
unlink($socket_path);
my $listener = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Listen => SOMAXCONN,
Local => $socket_path,
) or die("failed to open $socket_path as test socket: $!");
#########################
# create object with single arg
my $ml = Monitoring::Livestatus->new( 'localhost:12345' );
isa_ok($ml, 'Monitoring::Livestatus', 'single args server');
isa_ok($ml->{'CONNECTOR'}, 'Monitoring::Livestatus::INET', 'single args server peer');
is($ml->{'CONNECTOR'}->peer_name, 'localhost:12345', 'single args server peer name');
is($ml->{'CONNECTOR'}->peer_addr, 'localhost:12345', 'single args server peer addr');
#########################
# create object with single arg
$ml = Monitoring::Livestatus->new( $socket_path );
isa_ok($ml, 'Monitoring::Livestatus', 'single args socket');
isa_ok($ml->{'CONNECTOR'}, 'Monitoring::Livestatus::UNIX', 'single args socket peer');
is($ml->{'CONNECTOR'}->peer_name, $socket_path, 'single args socket peer name');
is($ml->{'CONNECTOR'}->peer_addr, $socket_path, 'single args socket peer addr');
my $header = "404 43\n";
my($error,$error_msg) = $ml->_parse_header($header);
is($error, '404', 'error code 404');
isnt($error_msg, undef, 'error code 404 message');
#########################
my $stats_query1 = "GET services
Stats: state = 0
Stats: state = 1
Stats: state = 2
Stats: state = 3
Stats: state = 4
Stats: host_state != 0
Stats: state = 1
StatsAnd: 2
Stats: host_state != 0
Stats: state = 2
StatsAnd: 2
Stats: host_state != 0
Stats: state = 3
StatsAnd: 2
Stats: host_state != 0
Stats: state = 3
Stats: active_checks = 1
StatsAnd: 3
Stats: state = 3
Stats: active_checks = 1
StatsOr: 2";
my @expected_keys1 = (
'state = 0',
'state = 1',
'state = 2',
'state = 3',
'state = 4',
'host_state != 0 && state = 1',
'host_state != 0 && state = 2',
'host_state != 0 && state = 3',
'host_state != 0 && state = 3 && active_checks = 1',
'state = 3 || active_checks = 1',
);
my @got_keys1 = @{$ml->_extract_keys_from_stats_statement($stats_query1)};
is_deeply(\@got_keys1, \@expected_keys1, 'statsAnd, statsOr query keys')
or ( diag('got keys: '.Dumper(\@got_keys1)) );
#########################
my $stats_query2 = "GET services
Stats: state = 0 as all_ok
Stats: state = 1 as all_warning
Stats: state = 2 as all_critical
Stats: state = 3 as all_unknown
Stats: state = 4 as all_pending
Stats: host_state != 0
Stats: state = 1
StatsAnd: 2 as all_warning_on_down_hosts
Stats: host_state != 0
Stats: state = 2
StatsAnd: 2 as all_critical_on_down_hosts
Stats: host_state != 0
Stats: state = 3
StatsAnd: 2 as all_unknown_on_down_hosts
Stats: host_state != 0
Stats: state = 3
Stats: active_checks_enabled = 1
StatsAnd: 3 as all_unknown_active_on_down_hosts
Stats: state = 3
Stats: active_checks_enabled = 1
StatsOr: 2 as all_active_or_unknown";
my @expected_keys2 = (
'all_ok',
'all_warning',
'all_critical',
'all_unknown',
'all_pending',
'all_warning_on_down_hosts',
'all_critical_on_down_hosts',
'all_unknown_on_down_hosts',
'all_unknown_active_on_down_hosts',
'all_active_or_unknown',
);
my @got_keys2 = @{$ml->_extract_keys_from_stats_statement($stats_query2)};
is_deeply(\@got_keys2, \@expected_keys2, 'stats query keys2')
or ( diag('got keys: '.Dumper(\@got_keys2)) );
#########################
my $normal_query1 = "GET services
Columns: host_name as host is_flapping description as name state
";
my @expected_keys3 = (
'host',
'is_flapping',
'name',
'state',
);
my @got_keys3 = @{$ml->_extract_keys_from_columns_header($normal_query1)};
is_deeply(\@got_keys3, \@expected_keys3, 'normal query keys')
or ( diag('got keys: '.Dumper(\@got_keys3)) );
#########################
unlink($socket_path);

View File

@@ -0,0 +1,215 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use Data::Dumper;
use File::Temp;
use IO::Socket::UNIX qw( SOCK_STREAM SOMAXCONN );
use_ok('Monitoring::Livestatus::MULTI');
BEGIN {
if( $^O eq 'MSWin32' ) {
plan skip_all => 'no sockets on windows';
}
else {
plan tests => 57;
}
}
#########################
# create 2 test sockets
# get a temp file from File::Temp and replace it with our socket
my $fh = File::Temp->new(UNLINK => 0);
my $socket_path1 = $fh->filename;
unlink($socket_path1);
my $listener1 = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Listen => SOMAXCONN,
Local => $socket_path1,
) or die("failed to open $socket_path1 as test socket: $!");
$fh = File::Temp->new(UNLINK => 0);
my $socket_path2 = $fh->filename;
unlink($socket_path2);
my $listener2 = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Listen => SOMAXCONN,
Local => $socket_path2,
) or die("failed to open $socket_path2 as test socket: $!");
#########################
# test the _merge_answer
my $mergetests = [
{ # simple test for sliced selectall_arrayref
in => { '820e03551b95b42ec037c87aed9b8f4a' => [ { 'description' => 'test_flap_07', 'host_name' => 'test_host_000', 'state' => '0' }, { 'description' => 'test_flap_11', 'host_name' => 'test_host_000', 'state' => '0' } ],
'35bbb11a888f66131d429efd058fb141' => [ { 'description' => 'test_ok_00', 'host_name' => 'test_host_000', 'state' => '0' }, { 'description' => 'test_ok_01', 'host_name' => 'test_host_000', 'state' => '0' } ],
'70ea8fa14abb984761bdd45ef27685b0' => [ { 'description' => 'test_critical_00', 'host_name' => 'test_host_000', 'state' => '2' }, { 'description' => 'test_critical_19', 'host_name' => 'test_host_000', 'state' => '2' } ]
},
exp => [
{ 'description' => 'test_flap_07', 'host_name' => 'test_host_000', 'state' => '0' },
{ 'description' => 'test_flap_11', 'host_name' => 'test_host_000', 'state' => '0' },
{ 'description' => 'test_ok_00', 'host_name' => 'test_host_000', 'state' => '0' },
{ 'description' => 'test_ok_01', 'host_name' => 'test_host_000', 'state' => '0' },
{ 'description' => 'test_critical_00', 'host_name' => 'test_host_000', 'state' => '2' },
{ 'description' => 'test_critical_19', 'host_name' => 'test_host_000', 'state' => '2' },
]
},
];
#########################
# test object creation
my $ml = Monitoring::Livestatus::MULTI->new( [ $socket_path1, $socket_path2 ] );
isa_ok($ml, 'Monitoring::Livestatus', 'single args sockets');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::UNIX', 'single args sockets peer');
}
$ml = Monitoring::Livestatus::MULTI->new( [$socket_path1] );
isa_ok($ml, 'Monitoring::Livestatus', 'single array args socket');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::UNIX', 'single array args socket peer');
is($peer->peer_addr, $socket_path1, 'single arrays args socket peer addr');
is($peer->peer_name, $socket_path1, 'single arrays args socket peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( 'localhost:5001' );
isa_ok($ml, 'Monitoring::Livestatus', 'single args server');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::INET', 'single args server peer');
like($peer->peer_addr, qr/^localhost/, 'single args servers peer addr');
like($peer->peer_name, qr/^localhost/, 'single args servers peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( ['localhost:5001'] );
isa_ok($ml, 'Monitoring::Livestatus', 'single array args server');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::INET', 'single arrays args server peer');
like($peer->peer_addr, qr/^localhost/, 'single arrays args servers peer addr');
like($peer->peer_name, qr/^localhost/, 'single arrays args servers peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( [ 'localhost:5001', 'localhost:5002' ] );
isa_ok($ml, 'Monitoring::Livestatus', 'single args servers');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::INET', 'single args servers peer');
like($peer->peer_addr, qr/^localhost/, 'single args servers peer addr');
like($peer->peer_name, qr/^localhost/, 'single args servers peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( peer => [ 'localhost:5001', 'localhost:5002' ] );
isa_ok($ml, 'Monitoring::Livestatus', 'hash args servers');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::INET', 'hash args servers peer');
like($peer->peer_addr, qr/^localhost/, 'hash args servers peer addr');
like($peer->peer_name, qr/^localhost/, 'hash args servers peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( peer => [ $socket_path1, $socket_path2 ] );
isa_ok($ml, 'Monitoring::Livestatus', 'hash args sockets');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::UNIX', 'hash args sockets peer');
}
$ml = Monitoring::Livestatus::MULTI->new( peer => { $socket_path1 => 'Location 1', $socket_path2 => 'Location2' } );
isa_ok($ml, 'Monitoring::Livestatus', 'hash args hashed sockets');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::UNIX', 'hash args hashed sockets peer');
like($peer->peer_name, qr/^Location/, 'hash args hashed sockets peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( peer => { 'localhost:5001' => 'Location 1', 'localhost:5002' => 'Location2' } );
isa_ok($ml, 'Monitoring::Livestatus', 'hash args hashed servers');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::INET', 'hash args hashed servers peer');
like($peer->peer_addr, qr/^localhost/, 'hash args hashed servers peer addr');
like($peer->peer_name, qr/^Location/, 'hash args hashed servers peer name');
}
$ml = Monitoring::Livestatus::MULTI->new( $socket_path1 );
isa_ok($ml, 'Monitoring::Livestatus', 'single args socket');
for my $peer (@{$ml->{'peers'}}) {
isa_ok($peer, 'Monitoring::Livestatus::UNIX', 'single args socket peer');
}
#########################
# test internal subs
$ml = Monitoring::Livestatus::MULTI->new('peer' => ['192.168.123.2:9996', '192.168.123.2:9997', '192.168.123.2:9998' ] );
my $x = 0;
for my $test (@{$mergetests}) {
my $got = $ml->_merge_answer($test->{'in'});
is_deeply($got, $test->{'exp'}, '_merge_answer test '.$x)
or diag("got: ".Dumper($got)."\nbut expected ".Dumper($test->{'exp'}));
$x++;
}
#########################
# test the _sum_answer
my $sumtests = [
{ # hashes
in => { '192.168.123.2:9996' => { 'ok' => '12', 'warning' => '8' },
'192.168.123.2:9997' => { 'ok' => '17', 'warning' => '7' },
'192.168.123.2:9998' => { 'ok' => '13', 'warning' => '2' }
},
exp => { 'ok' => '42', 'warning' => '17' }
},
{ # hashes, undefs
in => { '192.168.123.2:9996' => { 'ok' => '12', 'warning' => '8' },
'192.168.123.2:9997' => undef,
'192.168.123.2:9998' => { 'ok' => '13', 'warning' => '2' }
},
exp => { 'ok' => '25', 'warning' => '10' }
},
{ # hashes, undefs
in => { '192.168.123.2:9996' => { 'ok' => '12', 'warning' => '8' },
'192.168.123.2:9997' => {},
'192.168.123.2:9998' => { 'ok' => '13', 'warning' => '2' }
},
exp => { 'ok' => '25', 'warning' => '10' }
},
{ # arrays
in => { '192.168.123.2:9996' => [ '3302', '235' ],
'192.168.123.2:9997' => [ '3324', '236' ],
'192.168.123.2:9998' => [ '3274', '236' ]
},
exp => [ 9900, 707 ]
},
{ # undefs / scalars
in => { 'e69322abf0352888e598da3e2514df4a' => undef,
'f42530d7e8c2b52732ba427b1e5e0a8e' => '1'
},
exp => 1,
},
{ # arrays, undefs
in => { '192.168.123.2:9996' => [ '2', '5' ],
'192.168.123.2:9997' => [ ],
'192.168.123.2:9998' => [ '4', '6' ]
},
exp => [ 6, 11 ]
},
{ # arrays, undefs
in => { '192.168.123.2:9996' => [ '2', '5' ],
'192.168.123.2:9997' => undef,
'192.168.123.2:9998' => [ '4', '6' ]
},
exp => [ 6, 11 ]
},
];
$x = 1;
for my $test (@{$sumtests}) {
my $got = $ml->_sum_answer($test->{'in'});
is_deeply($got, $test->{'exp'}, '_sum_answer test '.$x)
or diag("got: ".Dumper($got)."\nbut expected ".Dumper($test->{'exp'}));
$x++;
}
#########################
# clone test
my $clone = $ml->_clone($mergetests);
is_deeply($clone, $mergetests, 'merge test clone');
$clone = $ml->_clone($sumtests);
is_deeply($clone, $sumtests, 'sum test clone');

View File

@@ -0,0 +1,329 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use IO::Socket::UNIX qw( SOCK_STREAM SOMAXCONN );
use Data::Dumper;
use JSON::XS;
BEGIN {
eval {require threads;};
if ( $@ ) {
plan skip_all => 'need threads support for testing a real socket'
}
elsif( $^O eq 'MSWin32' ) {
plan skip_all => 'no sockets on windows';
}
else{
plan tests => 109
}
}
use File::Temp;
BEGIN { use_ok('Monitoring::Livestatus') };
#########################
# Normal Querys
#########################
my $line_seperator = 10;
my $column_seperator = 0;
my $test_data = [ ["alias","name","contacts"], # table header
["alias1","host1","contact1"], # row 1
["alias2","host2","contact2"], # row 2
["alias3","host3","contact3"], # row 3
];
my $test_hostgroups = [['']]; # test one row with no data
# expected results
my $selectall_arrayref1 = [ [ 'alias1', 'host1', 'contact1' ],
[ 'alias2', 'host2', 'contact2' ],
[ 'alias3', 'host3', 'contact3' ]
];
my $selectall_arrayref2 = [
{ 'contacts' => 'contact1', 'name' => 'host1', 'alias' => 'alias1' },
{ 'contacts' => 'contact2', 'name' => 'host2', 'alias' => 'alias2' },
{ 'contacts' => 'contact3', 'name' => 'host3', 'alias' => 'alias3' }
];
my $selectall_hashref = {
'host1' => { 'contacts' => 'contact1', 'name' => 'host1', 'alias' => 'alias1' },
'host2' => { 'contacts' => 'contact2', 'name' => 'host2', 'alias' => 'alias2' },
'host3' => { 'contacts' => 'contact3', 'name' => 'host3', 'alias' => 'alias3' }
};
my $selectcol_arrayref1 = [ 'alias1', 'alias2', 'alias3' ];
my $selectcol_arrayref2 = [ 'alias1', 'host1', 'alias2', 'host2', 'alias3', 'host3' ];
my $selectcol_arrayref3 = [ 'alias1', 'host1', 'contact1', 'alias2', 'host2', 'contact2', 'alias3', 'host3', 'contact3' ];
my @selectrow_array = ( 'alias1', 'host1', 'contact1' );
my $selectrow_arrayref = [ 'alias1', 'host1', 'contact1' ];
my $selectrow_hashref = { 'contacts' => 'contact1', 'name' => 'host1', 'alias' => 'alias1' };
#########################
# Single Querys
#########################
my $single_statement = "GET hosts\nColumns: alias\nFilter: name = host1";
my $selectscalar_value = 'alias1';
#########################
# Stats Querys
#########################
my $stats_statement = "GET services\nStats: state = 0\nStats: state = 1\nStats: state = 2\nStats: state = 3";
my $stats_data = [[4297,13,9,0]];
# expected results
my $stats_selectall_arrayref1 = [ [4297,13,9,0] ];
my $stats_selectall_arrayref2 = [ { 'state = 0' => '4297', 'state = 1' => '13', 'state = 2' => '9', 'state = 3' => 0 } ];
my $stats_selectcol_arrayref = [ '4297' ];
my @stats_selectrow_array = ( '4297', '13', '9', '0' );
my $stats_selectrow_arrayref = [ '4297', '13', '9', '0' ];
my $stats_selectrow_hashref = { 'state = 0' => '4297', 'state = 1' => '13', 'state = 2' => '9', 'state = 3' => 0 };
#########################
# Empty Querys
#########################
my $empty_statement = "GET services\nFilter: description = empty";
# expected results
my $empty_selectall_arrayref = [];
my $empty_selectcol_arrayref = [];
my @empty_selectrow_array;
my $empty_selectrow_arrayref;
my $empty_selectrow_hashref;
#########################
# get a temp file from File::Temp and replace it with our socket
my $fh = File::Temp->new(UNLINK => 0);
my $socket_path = $fh->filename;
unlink($socket_path);
my $thr1 = threads->create('create_socket', 'unix');
#########################
# get a temp file from File::Temp and replace it with our socket
my $server = 'localhost:32987';
my $thr2 = threads->create('create_socket', 'inet');
sleep(1);
#########################
my $objects_to_test = {
# create unix object with hash args
'unix_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
socket => $socket_path,
line_seperator => $line_seperator,
column_seperator => $column_seperator,
),
# create unix object with a single arg
'unix_single_arg' => Monitoring::Livestatus::UNIX->new( $socket_path ),
# create inet object with hash args
'inet_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
server => $server,
line_seperator => $line_seperator,
column_seperator => $column_seperator,
),
# create inet object with a single arg
'inet_single_arg' => Monitoring::Livestatus::INET->new( $server ),
};
for my $key (keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus');
# we dont need warnings for testing
$ml->warnings(0);
##################################################
# test settings
my $rt = $ml->verbose(1);
is($rt, '0', 'enable verbose');
$rt = $ml->verbose(0);
is($rt, '1', 'disable verbose');
$rt = $ml->errors_are_fatal(0);
is($rt, '1', 'disable errors_are_fatal');
$rt = $ml->errors_are_fatal(1);
is($rt, '0', 'enable errors_are_fatal');
##################################################
# do some sample querys
my $statement = "GET hosts";
#########################
my $ary_ref = $ml->selectall_arrayref($statement);
is_deeply($ary_ref, $selectall_arrayref1, 'selectall_arrayref($statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectall_arrayref1));
#########################
$ary_ref = $ml->selectall_arrayref($statement, { Slice => {} });
is_deeply($ary_ref, $selectall_arrayref2, 'selectall_arrayref($statement, { Slice => {} })')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectall_arrayref2));
#########################
my $hash_ref = $ml->selectall_hashref($statement, 'name');
is_deeply($hash_ref, $selectall_hashref, 'selectall_hashref($statement, "name")')
or diag("got: ".Dumper($hash_ref)."\nbut expected ".Dumper($selectall_hashref));
#########################
$ary_ref = $ml->selectcol_arrayref($statement);
is_deeply($ary_ref, $selectcol_arrayref1, 'selectcol_arrayref($statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectcol_arrayref1));
#########################
$ary_ref = $ml->selectcol_arrayref($statement, { Columns=>[1,2] });
is_deeply($ary_ref, $selectcol_arrayref2, 'selectcol_arrayref($statement, { Columns=>[1,2] })')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectcol_arrayref2));
$ary_ref = $ml->selectcol_arrayref($statement, { Columns=>[1,2,3] });
is_deeply($ary_ref, $selectcol_arrayref3, 'selectcol_arrayref($statement, { Columns=>[1,2,3] })')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectcol_arrayref3));
#########################
my @row_ary = $ml->selectrow_array($statement);
is_deeply(\@row_ary, \@selectrow_array, 'selectrow_array($statement)')
or diag("got: ".Dumper(\@row_ary)."\nbut expected ".Dumper(\@selectrow_array));
#########################
$ary_ref = $ml->selectrow_arrayref($statement);
is_deeply($ary_ref, $selectrow_arrayref, 'selectrow_arrayref($statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectrow_arrayref));
#########################
$hash_ref = $ml->selectrow_hashref($statement);
is_deeply($hash_ref, $selectrow_hashref, 'selectrow_hashref($statement)')
or diag("got: ".Dumper($hash_ref)."\nbut expected ".Dumper($selectrow_hashref));
##################################################
# stats querys
##################################################
$ary_ref = $ml->selectall_arrayref($stats_statement);
is_deeply($ary_ref, $stats_selectall_arrayref1, 'selectall_arrayref($stats_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($stats_selectall_arrayref1));
$ary_ref = $ml->selectall_arrayref($stats_statement, { Slice => {} });
is_deeply($ary_ref, $stats_selectall_arrayref2, 'selectall_arrayref($stats_statement, { Slice => {} })')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($stats_selectall_arrayref2));
$ary_ref = $ml->selectcol_arrayref($stats_statement);
is_deeply($ary_ref, $stats_selectcol_arrayref, 'selectcol_arrayref($stats_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($stats_selectcol_arrayref));
@row_ary = $ml->selectrow_array($stats_statement);
is_deeply(\@row_ary, \@stats_selectrow_array, 'selectrow_arrayref($stats_statement)')
or diag("got: ".Dumper(\@row_ary)."\nbut expected ".Dumper(\@stats_selectrow_array));
$ary_ref = $ml->selectrow_arrayref($stats_statement);
is_deeply($ary_ref, $stats_selectrow_arrayref, 'selectrow_arrayref($stats_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($stats_selectrow_arrayref));
$hash_ref = $ml->selectrow_hashref($stats_statement);
is_deeply($hash_ref, $stats_selectrow_hashref, 'selectrow_hashref($stats_statement)')
or diag("got: ".Dumper($hash_ref)."\nbut expected ".Dumper($stats_selectrow_hashref));
my $scal = $ml->selectscalar_value($single_statement);
is($scal, $selectscalar_value, 'selectscalar_value($single_statement)')
or diag("got: ".Dumper($scal)."\nbut expected ".Dumper($selectscalar_value));
##################################################
# empty querys
##################################################
$ary_ref = $ml->selectall_arrayref($empty_statement);
is_deeply($ary_ref, $empty_selectall_arrayref, 'selectall_arrayref($empty_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($empty_selectall_arrayref));
$ary_ref = $ml->selectcol_arrayref($empty_statement);
is_deeply($ary_ref, $empty_selectcol_arrayref, 'selectcol_arrayref($empty_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($empty_selectcol_arrayref));
@row_ary = $ml->selectrow_array($empty_statement);
is_deeply(\@row_ary, \@empty_selectrow_array, 'selectrow_arrayref($empty_statement)')
or diag("got: ".Dumper(\@row_ary)."\nbut expected ".Dumper(\@empty_selectrow_array));
$ary_ref = $ml->selectrow_arrayref($empty_statement);
is_deeply($ary_ref, $empty_selectrow_arrayref, 'selectrow_arrayref($empty_statement)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($empty_selectrow_arrayref));
$hash_ref = $ml->selectrow_hashref($empty_statement);
is_deeply($hash_ref, $empty_selectrow_hashref, 'selectrow_hashref($empty_statement)')
or diag("got: ".Dumper($hash_ref)."\nbut expected ".Dumper($empty_selectrow_hashref));
##################################################
# empty rows and columns
##################################################
my $empty_hostgroups_stm = "GET hostgroups\nColumns: members";
$ary_ref = $ml->selectall_arrayref($empty_hostgroups_stm);
is_deeply($ary_ref, $test_hostgroups, 'selectall_arrayref($empty_hostgroups_stm)')
or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($test_hostgroups));
}
##################################################
# exit threads
$thr1->kill('KILL')->detach();
$thr2->kill('KILL')->detach();
exit;
#########################
# SUBS
#########################
# test socket server
sub create_socket {
my $type = shift;
my $listener;
$SIG{'KILL'} = sub { threads->exit(); };
if($type eq 'unix') {
print "creating unix socket\n";
$listener = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Listen => SOMAXCONN,
Local => $socket_path,
) or die("failed to open $socket_path as test socket: $!");
}
elsif($type eq 'inet') {
print "creating tcp socket\n";
$listener = IO::Socket::INET->new(
LocalAddr => $server,
Proto => 'tcp',
Listen => 1,
Reuse => 1,
) or die("failed to listen on $server: $!");
} else {
die("unknown type");
}
while( my $socket = $listener->accept() or die('cannot accept: $!') ) {
my $recv = "";
while(<$socket>) { $recv .= $_; last if $_ eq "\n" }
my $data;
my $status = 200;
if($recv =~ m/^GET .*?\s+Filter:.*?empty/m) {
$data = '';
}
elsif($recv =~ m/^GET hosts\s+Columns: alias/m) {
my @data = @{$test_data}[1..3];
$data = encode_json(\@data)."\n";
}
elsif($recv =~ m/^GET hosts\s+Columns: name/m) {
$data = encode_json(\@{$test_data}[1..3])."\n";
}
elsif($recv =~ m/^GET hosts/) {
$data = encode_json($test_data)."\n";
}
elsif($recv =~ m/^GET hostgroups/) {
$data = encode_json(\@{$test_hostgroups})."\n";
}
elsif($recv =~ m/^GET services/ and $recv =~ m/Stats:/m) {
$data = encode_json(\@{$stats_data})."\n";
}
my $content_length = sprintf("%11s", length($data));
print $socket $status." ".$content_length."\n";
print $socket $data;
close($socket);
}
unlink($socket_path);
}

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More tests => 3;
use IO::Socket::INET;
BEGIN { use_ok('Monitoring::Livestatus::INET') };
#########################
# create a tmp listener
my $server = 'localhost:9999';
my $listener = IO::Socket::INET->new(
) or die("failed to open port as test listener: $!");
#########################
# create object with single arg
my $ml = Monitoring::Livestatus::INET->new( $server );
isa_ok($ml, 'Monitoring::Livestatus', 'Monitoring::Livestatus::INET->new()');
#########################
# create object with hash args
my $line_seperator = 10;
my $column_seperator = 0;
$ml = Monitoring::Livestatus::INET->new(
verbose => 0,
server => $server,
line_seperator => $line_seperator,
column_seperator => $column_seperator,
);
isa_ok($ml, 'Monitoring::Livestatus', 'Monitoring::Livestatus::INET->new(%args)');

View File

@@ -0,0 +1,26 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More tests => 3;
use IO::Socket::INET;
BEGIN { use_ok('Monitoring::Livestatus::UNIX') };
#########################
# create object with single arg
my $socket = "/tmp/blah.socket";
my $ml = Monitoring::Livestatus::UNIX->new( $socket );
isa_ok($ml, 'Monitoring::Livestatus', 'Monitoring::Livestatus::UNIX->new()');
#########################
# create object with hash args
my $line_seperator = 10;
my $column_seperator = 0;
$ml = Monitoring::Livestatus::UNIX->new(
verbose => 0,
socket => $socket,
line_seperator => $line_seperator,
column_seperator => $column_seperator,
);
isa_ok($ml, 'Monitoring::Livestatus', 'Monitoring::Livestatus::UNIX->new(%args)');

View File

@@ -0,0 +1,472 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use Data::Dumper;
if ( ! defined $ENV{TEST_SOCKET} or !defined $ENV{TEST_SERVER} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} to run';
plan( skip_all => $msg );
} else {
plan( tests => 727 );
}
# set an alarm
my $lastquery;
$SIG{ALRM} = sub {
my @caller = caller;
print STDERR 'last query: '.$lastquery if defined $lastquery;
die "timeout reached:".Dumper(\@caller)."\n"
};
alarm(120);
use_ok('Monitoring::Livestatus');
#########################
my $line_seperator = 10;
my $column_seperator = 0;
my $objects_to_test = {
# UNIX
# create unix object with a single arg
# '01 unix_single_arg' => Monitoring::Livestatus::UNIX->new( $ENV{TEST_SOCKET} ),
# create unix object with hash args
'02 unix_few_args' => Monitoring::Livestatus->new(
#verbose => 1,
socket => $ENV{TEST_SOCKET},
line_seperator => $line_seperator,
column_seperator => $column_seperator,
),
# create unix object with hash args
'03 unix_keepalive' => Monitoring::Livestatus->new(
verbose => 0,
socket => $ENV{TEST_SOCKET},
keepalive => 1,
),
# TCP
# create inet object with a single arg
'04 inet_single_arg' => Monitoring::Livestatus::INET->new( $ENV{TEST_SERVER} ),
# create inet object with hash args
'05 inet_few_args' => Monitoring::Livestatus->new(
verbose => 0,
server => $ENV{TEST_SERVER},
line_seperator => $line_seperator,
column_seperator => $column_seperator,
),
# create inet object with keepalive
'06 inet_keepalive' => Monitoring::Livestatus->new(
verbose => 0,
server => $ENV{TEST_SERVER},
keepalive => 1,
),
# create multi single args
'07 multi_keepalive' => Monitoring::Livestatus->new( [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ] ),
# create multi object with keepalive
'08 multi_keepalive_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
peer => [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ],
keepalive => 1,
),
# create multi object without keepalive
'09 multi_no_keepalive' => Monitoring::Livestatus->new(
peer => [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ],
keepalive => 0,
),
# create multi object without threads
'10 multi_no_threads' => Monitoring::Livestatus->new(
peer => [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ],
use_threads => 0,
),
# create multi object with only one peer
'11 multi_one_peer' => Monitoring::Livestatus::MULTI->new(
peer => $ENV{TEST_SERVER},
),
# create multi object without threads
'12 multi_two_peers' => Monitoring::Livestatus::MULTI->new(
peer => [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ],
),
};
my $expected_keys = {
'columns' => [
'description','name','table','type'
],
'commands' => [
'line','name'
],
'comments' => [
'__all_from_hosts__', '__all_from_services__',
'author','comment','entry_time','entry_type','expire_time','expires', 'id','persistent',
'source','type'
],
'contacts' => [
'address1','address2','address3','address4','address5','address6','alias',
'can_submit_commands','custom_variable_names','custom_variable_values','email',
'host_notification_period','host_notifications_enabled','in_host_notification_period',
'in_service_notification_period','name','modified_attributes','modified_attributes_list',
'pager','service_notification_period','service_notifications_enabled'
],
'contactgroups' => [ 'name', 'alias', 'members' ],
'downtimes' => [
'__all_from_hosts__', '__all_from_services__',
'author','comment','duration','end_time','entry_time','fixed','id','start_time',
'triggered_by','type'
],
'hostgroups' => [
'action_url','alias','members','name','members_with_state','notes','notes_url','num_hosts','num_hosts_down',
'num_hosts_pending','num_hosts_unreach','num_hosts_up','num_services','num_services_crit',
'num_services_hard_crit','num_services_hard_ok','num_services_hard_unknown',
'num_services_hard_warn','num_services_ok','num_services_pending','num_services_unknown',
'num_services_warn','worst_host_state','worst_service_hard_state','worst_service_state'
],
'hosts' => [
'accept_passive_checks','acknowledged','acknowledgement_type','action_url','action_url_expanded',
'active_checks_enabled','address','alias','check_command','check_freshness','check_interval',
'check_options','check_period','check_type','checks_enabled','childs','comments','comments_with_info',
'contacts','current_attempt','current_notification_number','custom_variable_names',
'custom_variable_values','display_name','downtimes','downtimes_with_info','event_handler_enabled',
'execution_time','first_notification_delay','flap_detection_enabled','groups','hard_state','has_been_checked',
'high_flap_threshold','icon_image','icon_image_alt','icon_image_expanded','in_check_period',
'in_notification_period','initial_state','is_executing','is_flapping','last_check','last_hard_state',
'last_hard_state_change','last_notification','last_state','last_state_change','latency','last_time_down',
'last_time_unreachable','last_time_up','long_plugin_output','low_flap_threshold','max_check_attempts','name',
'modified_attributes','modified_attributes_list','next_check',
'next_notification','notes','notes_expanded','notes_url','notes_url_expanded','notification_interval',
'notification_period','notifications_enabled','num_services','num_services_crit','num_services_hard_crit',
'num_services_hard_ok','num_services_hard_unknown','num_services_hard_warn','num_services_ok',
'num_services_pending','num_services_unknown','num_services_warn','obsess_over_host','parents',
'pending_flex_downtime','percent_state_change','perf_data','plugin_output',
'process_performance_data','retry_interval','scheduled_downtime_depth','services','services_with_state',
'state','state_type','statusmap_image','total_services','worst_service_hard_state','worst_service_state',
'x_3d','y_3d','z_3d'
],
'hostsbygroup' => [
'__all_from_hosts__', '__all_from_hostgroups__'
],
'log' => [
'__all_from_hosts__','__all_from_services__','__all_from_contacts__','__all_from_commands__',
'attempt','class','command_name','comment','contact_name','host_name','lineno','message','options',
'plugin_output','service_description','state','state_type','time','type'
],
'servicegroups' => [
'action_url','alias','members','name','members_with_state','notes','notes_url','num_services','num_services_crit',
'num_services_hard_crit','num_services_hard_ok','num_services_hard_unknown',
'num_services_hard_warn','num_services_ok','num_services_pending','num_services_unknown',
'num_services_warn','worst_service_state'
],
'servicesbygroup' => [
'__all_from_services__', '__all_from_hosts__', '__all_from_servicegroups__'
],
'services' => [
'__all_from_hosts__',
'accept_passive_checks','acknowledged','acknowledgement_type','action_url','action_url_expanded',
'active_checks_enabled','check_command','check_interval','check_options','check_period',
'check_type','checks_enabled','comments','comments_with_info','contacts','current_attempt',
'current_notification_number','custom_variable_names','custom_variable_values',
'description','display_name','downtimes','downtimes_with_info','event_handler','event_handler_enabled',
'execution_time','first_notification_delay','flap_detection_enabled','groups',
'has_been_checked','high_flap_threshold','icon_image','icon_image_alt','icon_image_expanded','in_check_period',
'in_notification_period','initial_state','is_executing','is_flapping','last_check',
'last_hard_state','last_hard_state_change','last_notification','last_state',
'last_state_change','latency','last_time_critical','last_time_ok','last_time_unknown','last_time_warning',
'long_plugin_output','low_flap_threshold','max_check_attempts','modified_attributes','modified_attributes_list',
'next_check','next_notification','notes','notes_expanded','notes_url','notes_url_expanded',
'notification_interval','notification_period','notifications_enabled','obsess_over_service',
'percent_state_change','perf_data','plugin_output','process_performance_data','retry_interval',
'scheduled_downtime_depth','state','state_type'
],
'servicesbyhostgroup' => [
'__all_from_services__', '__all_from_hosts__', '__all_from_hostgroups__'
],
'status' => [
'accept_passive_host_checks','accept_passive_service_checks','cached_log_messages',
'check_external_commands','check_host_freshness','check_service_freshness','connections',
'connections_rate','enable_event_handlers','enable_flap_detection','enable_notifications',
'execute_host_checks','execute_service_checks','forks','forks_rate','host_checks','host_checks_rate','interval_length',
'last_command_check','last_log_rotation','livestatus_version','log_messages','log_messages_rate','nagios_pid','neb_callbacks',
'neb_callbacks_rate','obsess_over_hosts','obsess_over_services','process_performance_data',
'program_start','program_version','requests','requests_rate','service_checks','service_checks_rate'
],
'timeperiods' => [ 'in', 'name', 'alias' ],
};
my $author = 'Monitoring::Livestatus test';
for my $key (sort keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus') or BAIL_OUT("no need to continue without a proper Monitoring::Livestatus object: ".$key);
# dont die on errors
$ml->errors_are_fatal(0);
$ml->warnings(0);
#########################
# set downtime for a host and service
my $downtimes = $ml->selectall_arrayref("GET downtimes\nColumns: id");
my $num_downtimes = 0;
$num_downtimes = scalar @{$downtimes} if defined $downtimes;
my $firsthost = $ml->selectscalar_value("GET hosts\nColumns: name\nLimit: 1");
isnt($firsthost, undef, 'get test hostname') or BAIL_OUT($key.': got not test hostname');
$ml->do('COMMAND ['.time().'] SCHEDULE_HOST_DOWNTIME;'.$firsthost.';'.time().';'.(time()+300).';1;0;300;'.$author.';perl test: '.$0);
my $firstservice = $ml->selectscalar_value("GET services\nColumns: description\nFilter: host_name = $firsthost\nLimit: 1");
isnt($firstservice, undef, 'get test servicename') or BAIL_OUT('got not test servicename');
$ml->do('COMMAND ['.time().'] SCHEDULE_SVC_DOWNTIME;'.$firsthost.';'.$firstservice.';'.time().';'.(time()+300).';1;0;300;'.$author.';perl test: '.$0);
# sometimes it takes while till the downtime is accepted
my $waited = 0;
while(scalar @{$ml->selectall_arrayref("GET downtimes\nColumns: id")} < $num_downtimes + 2) {
print "waiting for the downtime...\n";
sleep(1);
$waited++;
BAIL_OUT('waited 30 seconds for the downtime...') if $waited > 30;
}
#########################
#########################
# check tables
my $data = $ml->selectall_hashref("GET columns\nColumns: table", 'table');
my @tables = sort keys %{$data};
my @expected_tables = sort keys %{$expected_keys};
is_deeply(\@tables, \@expected_tables, $key.' tables') or BAIL_OUT("got tables:\n".join(', ', @tables)."\nbut expected\n".join(', ', @expected_tables));
#########################
# check keys
for my $type (keys %{$expected_keys}) {
my $filter = "";
$filter = "Filter: time > ".(time() - 86400)."\n" if $type eq 'log';
$filter .= "Filter: time < ".(time())."\n" if $type eq 'log';
my $expected_keys = get_expected_keys($type);
my $statement = "GET $type\n".$filter."Limit: 1";
$lastquery = $statement;
my $hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is(ref $hash_ref, 'HASH', $type.' keys are a hash') or BAIL_OUT($type.'keys are not in hash format, got '.Dumper($hash_ref));
my @keys = sort keys %{$hash_ref};
is_deeply(\@keys, $expected_keys, $key.' '.$type.' table columns') or BAIL_OUT("got $type keys:\n".join(', ', @keys)."\nbut expected\n".join(', ', @{$expected_keys}));
}
my $statement = "GET hosts\nColumns: name as hostname state\nLimit: 1";
$lastquery = $statement;
my $hash_ref = $ml->selectrow_hashref($statement);
undef $lastquery;
isnt($hash_ref, undef, $key.' test column alias');
is($Monitoring::Livestatus::ErrorCode, 0, $key.' test column alias') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
#########################
# send a test command
# commands still dont work and breaks livestatus
my $rt = $ml->do('COMMAND ['.time().'] SAVE_STATE_INFORMATION');
is($rt, '1', $key.' test command');
#########################
# check for errors
#$ml->{'verbose'} = 1;
$statement = "GET hosts\nLimit: 1";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
isnt($hash_ref, undef, $key.' test error 200 body');
is($Monitoring::Livestatus::ErrorCode, 0, $key.' test error 200 status') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "BLAH hosts";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 401 body');
is($Monitoring::Livestatus::ErrorCode, '401', $key.' test error 401 status') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nLimit: ";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 403 body');
is($Monitoring::Livestatus::ErrorCode, '403', $key.' test error 403 status') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET unknowntable\nLimit: 1";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 404 body');
is($Monitoring::Livestatus::ErrorCode, '404', $key.' test error 404 status') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nColumns: unknown";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 405 body');
TODO: {
local $TODO = 'livestatus returns wrong status';
is($Monitoring::Livestatus::ErrorCode, '405', $key.' test error 405 status') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
};
#########################
# some more broken statements
$statement = "GET ";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement);
undef $lastquery;
is($hash_ref, undef, $key.' test error 403 body');
is($Monitoring::Livestatus::ErrorCode, '403', $key.' test error 403 status: GET ') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nColumns: name, name";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 405 body');
is($Monitoring::Livestatus::ErrorCode, '405', $key.' test error 405 status: GET hosts\nColumns: name, name') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nColumns: ";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 405 body');
is($Monitoring::Livestatus::ErrorCode, '405', $key.' test error 405 status: GET hosts\nColumns: ') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
#########################
# some forbidden headers
$statement = "GET hosts\nKeepAlive: on";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 496 body');
is($Monitoring::Livestatus::ErrorCode, '496', $key.' test error 496 status: KeepAlive: on') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nResponseHeader: fixed16";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 495 body');
is($Monitoring::Livestatus::ErrorCode, '495', $key.' test error 495 status: ResponseHeader: fixed16') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nColumnHeaders: on";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 494 body');
is($Monitoring::Livestatus::ErrorCode, '494', $key.' test error 494 status: ColumnHeader: on') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nOuputFormat: json";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 493 body');
is($Monitoring::Livestatus::ErrorCode, '493', $key.' test error 493 status: OutputForma: json') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
$statement = "GET hosts\nSeparators: 0 1 2 3";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($hash_ref, undef, $key.' test error 492 body');
is($Monitoring::Livestatus::ErrorCode, '492', $key.' test error 492 status: Seperators: 0 1 2 3') or
diag('got error: '.$Monitoring::Livestatus::ErrorMessage);
#########################
# check some fancy stats queries
my $stats_query = "GET services
Stats: state = 0 as all_ok
Stats: state = 1 as all_warning
Stats: state = 2 as all_critical
Stats: state = 3 as all_unknown
Stats: state = 4 as all_pending
Stats: host_state != 0
Stats: state = 1
StatsAnd: 2 as all_warning_on_down_hosts
Stats: host_state != 0
Stats: state = 2
StatsAnd: 2 as all_critical_on_down_hosts
Stats: host_state != 0
Stats: state = 3
StatsAnd: 2 as all_unknown_on_down_hosts
Stats: host_state != 0
Stats: state = 3
Stats: active_checks_enabled = 1
StatsAnd: 3 as all_unknown_active_on_down_hosts
Stats: state = 3
Stats: active_checks_enabled = 1
StatsOr: 2 as all_active_or_unknown";
$lastquery = $stats_query;
$hash_ref = $ml->selectrow_hashref($stats_query );
undef $lastquery;
isnt($hash_ref, undef, $key.' test fancy stats query') or
diag('got error: '.Dumper($hash_ref));
}
# generate expected keys
sub get_expected_keys {
my $type = shift;
my $skip = shift;
my @keys = @{$expected_keys->{$type}};
my @new_keys;
for my $key (@keys) {
my $replaced = 0;
for my $replace_with (keys %{$expected_keys}) {
if($key eq '__all_from_'.$replace_with.'__') {
$replaced = 1;
next if $skip;
my $prefix = $replace_with.'_';
if($replace_with eq "hosts") { $prefix = 'host_'; }
if($replace_with eq "services") { $prefix = 'service_'; }
if($replace_with eq "commands") { $prefix = 'command_'; }
if($replace_with eq "contacts") { $prefix = 'contact_'; }
if($replace_with eq "servicegroups") { $prefix = 'servicegroup_'; }
if($replace_with eq "hostgroups") { $prefix = 'hostgroup_'; }
if($type eq "log") { $prefix = 'current_'.$prefix; }
if($type eq "servicesbygroup" and $replace_with eq 'services') { $prefix = ''; }
if($type eq "servicesbyhostgroup" and $replace_with eq 'services') { $prefix = ''; }
if($type eq "hostsbygroup" and $replace_with eq 'hosts') { $prefix = ''; }
my $replace_keys = get_expected_keys($replace_with, 1);
for my $key2 (@{$replace_keys}) {
push @new_keys, $prefix.$key2;
}
}
}
if($replaced == 0) {
push @new_keys, $key;
}
}
# has been fixed in 1.1.1rc
#if($type eq 'log') {
# my %keys = map { $_ => 1 } @new_keys;
# delete $keys{'current_contact_can_submit_commands'};
# delete $keys{'current_contact_host_notifications_enabled'};
# delete $keys{'current_contact_in_host_notification_period'};
# delete $keys{'current_contact_in_service_notification_period'};
# delete $keys{'current_contact_service_notifications_enabled'};
# @new_keys = keys %keys;
#}
my @return = sort @new_keys;
return(\@return);
}

View File

@@ -0,0 +1,95 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use Data::Dumper;
if ( ! defined $ENV{TEST_SOCKET} or !defined $ENV{TEST_SERVER} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} to run';
plan( skip_all => $msg );
} else {
plan( tests => 22 );
}
use_ok('Monitoring::Livestatus::MULTI');
#########################
# create new test object
my $objects_to_test = {
'multi_one' => Monitoring::Livestatus::MULTI->new( peer => [ $ENV{TEST_SERVER} ], warnings => 0 ),
'multi_two' => Monitoring::Livestatus::MULTI->new( peer => [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ], warnings => 0 ),
'multi_three' => Monitoring::Livestatus::MULTI->new(
'verbose' => '0',
'warnings' => '0',
'timeout' => '10',
'peer' => [
{ 'name' => 'Mon 1', 'peer' => $ENV{TEST_SERVER} },
{ 'name' => 'Mon 2', 'peer' => $ENV{TEST_SOCKET} },
],
'keepalive' => '1'
),
};
# dont die on errors
#$ml->errors_are_fatal(0);
for my $key (keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus::MULTI') or BAIL_OUT("no need to continue without a proper Monitoring::Livestatus::MULTI object");
#########################
# DATA INTEGRITY
#########################
my $statement = "GET hosts\nColumns: state name alias\nLimit: 1";
my $data1 = $ml->selectall_arrayref($statement, {Slice => 1});
my $data2 = $ml->selectall_arrayref($statement, {Slice => 1, AddPeer => 1});
for my $data (@{$data2}) {
delete $data->{'peer_name'};
delete $data->{'peer_addr'};
delete $data->{'peer_key'};
}
is_deeply($data1, $data2, "data integrity with peers added and Column");
$statement = "GET hosts\nLimit: 1";
$data1 = $ml->selectall_arrayref($statement, {Slice => 1, Deepcopy => 1});
$data2 = $ml->selectall_arrayref($statement, {Slice => 1, AddPeer => 1, Deepcopy => 1});
for my $data (@{$data2}) {
delete $data->{'peer_name'};
delete $data->{'peer_addr'};
delete $data->{'peer_key'};
}
is_deeply($data1, $data2, "data integrity with peers added without Columns");
#########################
# try to change result set to scalar
for my $data (@{$data1}) { $data->{'peer_name'} = 1; }
for my $data (@{$data2}) { $data->{'peer_name'} = 1; }
is_deeply($data1, $data2, "data integrity with changed result set");
#########################
# try to change result set to hash
for my $data (@{$data1}) { $data->{'peer_name'} = {}; }
for my $data (@{$data2}) { $data->{'peer_name'} = {}; }
is_deeply($data1, $data2, "data integrity with changed result set");
#########################
# BACKENDS
#########################
my @backends = $ml->peer_key();
$data1 = $ml->selectall_arrayref($statement, {Slice => 1});
$data2 = $ml->selectall_arrayref($statement, {Slice => 1, Backend => \@backends });
is_deeply($data1, $data2, "data integrity with backends");
#########################
# BUGS
#########################
#########################
# Bug: Can't use string ("flap") as an ARRAY ref while "strict refs" in use at Monitoring/Livestatus/MULTI.pm line 206.
$statement = "GET servicegroups\nColumns: name alias\nFilter: name = flap\nLimit: 1";
$data1 = $ml->selectrow_array($statement);
isnt($data1, undef, "bug check: Can't use string (\"group\")...");
}

View File

@@ -0,0 +1,106 @@
#!/usr/bin/env perl
#########################
use strict;
use Carp;
use Test::More;
use Data::Dumper;
if ( ! defined $ENV{TEST_SOCKET} or !defined $ENV{TEST_SERVER} or !defined $ENV{TEST_BACKEND} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} and $ENV{TEST_BACKEND} to run';
plan( skip_all => $msg );
} else {
# we dont know yet how many tests we got
plan( tests => 55237 );
}
# set an alarm
my $lastquery;
$SIG{ALRM} = sub {
my @caller = caller;
$lastquery =~ s/\n+/\n/g;
print STDERR 'last query: '.$lastquery."\n" if defined $lastquery;
confess "timeout reached:".Dumper(\@caller)."\n"
};
use_ok('Monitoring::Livestatus');
#########################
my $objects_to_test = {
# UNIX
'01 unix_single_arg' => Monitoring::Livestatus::UNIX->new( $ENV{TEST_SOCKET} ),
# TCP
'02 inet_single_arg' => Monitoring::Livestatus::INET->new( $ENV{TEST_SERVER} ),
# MULTI
'03 multi_keepalive' => Monitoring::Livestatus->new( [ $ENV{TEST_SERVER}, $ENV{TEST_SOCKET} ] ),
};
for my $key (sort keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus') or BAIL_OUT("no need to continue without a proper Monitoring::Livestatus object: ".$key);
# dont die on errors
$ml->errors_are_fatal(0);
$ml->warnings(0);
#########################
# get tables
my $data = $ml->selectall_hashref("GET columns\nColumns: table", 'table');
my @tables = sort keys %{$data};
#########################
# check keys
for my $type (@tables) {
alarm(120);
my $filter = "";
$filter = "Filter: time > ".(time() - 86400)."\n" if $type eq 'log';
$filter .= "Filter: time < ".(time())."\n" if $type eq 'log';
my $statement = "GET $type\n".$filter."Limit: 1";
$lastquery = $statement;
my $keys = $ml->selectrow_hashref($statement );
undef $lastquery;
is(ref $keys, 'HASH', $type.' keys are a hash');# or BAIL_OUT('keys are not in hash format, got '.Dumper($keys));
# status has no filter implemented
next if $type eq 'status';
for my $key (keys %{$keys}) {
my $value = $keys->{$key};
if(index($value, ',') > 0) { my @vals = split /,/, $value; $value = $vals[0]; }
my $typefilter = "Filter: $key >= $value\n";
if($value eq '') {
$typefilter = "Filter: $key =\n";
}
my $statement = "GET $type\n".$filter.$typefilter."Limit: 1";
$lastquery = $statement;
my $hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($Monitoring::Livestatus::ErrorCode, 0, "GET ".$type." Filter: ".$key." >= ".$value) or BAIL_OUT("query failed: ".$statement);
#isnt($hash_ref, undef, "GET ".$type." Filter: ".$key." >= ".$value);# or BAIL_OUT("got undef for ".$statement);
# send test stats query
my $stats_query = [ $key.' = '.$value, 'std '.$key, 'min '.$key, 'max '.$key, 'avg '.$key, 'sum '.$key ];
for my $stats_part (@{$stats_query}) {
my $statement = "GET $type\n".$filter.$typefilter."\nStats: $stats_part";
$lastquery = $statement;
my $hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($Monitoring::Livestatus::ErrorCode, 0, "GET ".$type." Filter: ".$key." >= ".$value." Stats: $stats_part") or BAIL_OUT("query failed:\n".$statement);
$statement = "GET $type\n".$filter.$typefilter."\nStats: $stats_part\nStatsGroupBy: $key";
$lastquery = $statement;
$hash_ref = $ml->selectrow_hashref($statement );
undef $lastquery;
is($Monitoring::Livestatus::ErrorCode, 0, "GET ".$type." Filter: ".$key." >= ".$value." Stats: $stats_part StatsGroupBy: $key") or BAIL_OUT("query failed:\n".$statement);
}
# wait till backend is started up again
if(!defined $hash_ref and $Monitoring::Livestatus::ErrorCode > 200) {
sleep(2);
}
}
}
}

View File

@@ -0,0 +1,74 @@
#!/usr/bin/env perl
#########################
use strict;
use Test::More;
use Data::Dumper;
if ( !defined $ENV{TEST_SERVER} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} to run';
plan( skip_all => $msg );
} else {
plan( tests => 7 );
}
# set an alarm
my $lastquery;
$SIG{ALRM} = sub {
my @caller = caller;
print STDERR 'last query: '.$lastquery if defined $lastquery;
die "timeout reached:".Dumper(\@caller)."\n"
};
alarm(30);
use_ok('Monitoring::Livestatus');
#use Log::Log4perl qw(:easy);
#Log::Log4perl->easy_init($DEBUG);
#########################
# Test Query
#########################
my $statement = "GET hosts\nColumns: alias\nFilter: name = host1";
#########################
my $objects_to_test = {
# create inet object with hash args
'01 inet_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
server => $ENV{TEST_SERVER},
keepalive => 1,
timeout => 3,
retries_on_connection_error => 0,
# logger => get_logger(),
),
# create inet object with a single arg
'02 inet_single_arg' => Monitoring::Livestatus::INET->new( $ENV{TEST_SERVER} ),
};
for my $key (sort keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus');
# we dont need warnings for testing
$ml->warnings(0);
#########################
my $ary_ref = $ml->selectall_arrayref($statement);
is($Monitoring::Livestatus::ErrorCode, 0, 'Query Status 0');
#is_deeply($ary_ref, $selectall_arrayref1, 'selectall_arrayref($statement)')
# or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectall_arrayref1));
sleep(10);
$ary_ref = $ml->selectall_arrayref($statement);
is($Monitoring::Livestatus::ErrorCode, 0, 'Query Status 0');
#is_deeply($ary_ref, $selectall_arrayref1, 'selectall_arrayref($statement)')
# or diag("got: ".Dumper($ary_ref)."\nbut expected ".Dumper($selectall_arrayref1));
#print Dumper($Monitoring::Livestatus::ErrorCode);
#print Dumper($Monitoring::Livestatus::ErrorMessage);
}

View File

@@ -0,0 +1,78 @@
#!/usr/bin/env perl
#########################
use strict;
use Encode;
use Test::More;
use Data::Dumper;
if ( !defined $ENV{TEST_SERVER} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} to run';
plan( skip_all => $msg );
} else {
plan( tests => 9 );
}
use_ok('Monitoring::Livestatus');
#use Log::Log4perl qw(:easy);
#Log::Log4perl->easy_init($DEBUG);
#########################
my $objects_to_test = {
# create inet object with hash args
'01 inet_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
server => $ENV{TEST_SERVER},
keepalive => 1,
timeout => 3,
retries_on_connection_error => 0,
# logger => get_logger(),
),
# create inet object with a single arg
'02 inet_single_arg' => Monitoring::Livestatus::INET->new( $ENV{TEST_SERVER} ),
};
my $author = 'Monitoring::Livestatus test';
for my $key (sort keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus');
# we dont need warnings for testing
$ml->warnings(0);
#########################
my $downtimes = $ml->selectall_arrayref("GET downtimes\nColumns: id");
my $num_downtimes = 0;
$num_downtimes = scalar @{$downtimes} if defined $downtimes;
#########################
# get a test host
my $firsthost = $ml->selectscalar_value("GET hosts\nColumns: name\nLimit: 1");
isnt($firsthost, undef, 'get test hostname') or BAIL_OUT($key.': got not test hostname');
my $expect = "aa ²&é\"'''(§è!çà)- %s ''%s'' aa ~ € bb";
#my $expect = "öäüß";
my $teststrings = [
$expect,
"aa \x{c2}\x{b2}&\x{c3}\x{a9}\"'''(\x{c2}\x{a7}\x{c3}\x{a8}!\x{c3}\x{a7}\x{c3}\x{a0})- %s ''%s'' aa ~ \x{e2}\x{82}\x{ac} bb",
];
for my $string (@{$teststrings}) {
$ml->do('COMMAND ['.time().'] SCHEDULE_HOST_DOWNTIME;'.$firsthost.';'.time().';'.(time()+300).';1;0;300;'.$author.';'.$string);
# sometimes it takes while till the downtime is accepted
my $waited = 0;
while($downtimes = $ml->selectall_arrayref("GET downtimes\nColumns: id comment", { Slice => 1 }) and scalar @{$downtimes} < $num_downtimes + 1) {
print "waiting for the downtime...\n";
sleep(1);
$waited++;
BAIL_OUT('waited 30 seconds for the downtime...') if $waited > 30;
}
my $last_downtime = pop @{$downtimes};
#utf8::decode($expect);
is($last_downtime->{'comment'}, $expect, 'get same utf8 comment: got '.Dumper($last_downtime));
}
}

View File

@@ -0,0 +1,53 @@
#!/usr/bin/env perl
#########################
use strict;
use Encode;
use Test::More;
use Data::Dumper;
if ( !defined $ENV{TEST_SERVER} ) {
my $msg = 'Author test. Set $ENV{TEST_SOCKET} and $ENV{TEST_SERVER} to run';
plan( skip_all => $msg );
} else {
plan( tests => 15 );
}
use_ok('Monitoring::Livestatus');
#use Log::Log4perl qw(:easy);
#Log::Log4perl->easy_init($DEBUG);
#########################
my $objects_to_test = {
# create inet object with hash args
'01 inet_hash_args' => Monitoring::Livestatus->new(
verbose => 0,
server => $ENV{TEST_SERVER},
keepalive => 1,
timeout => 3,
retries_on_connection_error => 0,
# logger => get_logger(),
),
# create inet object with a single arg
'02 inet_single_arg' => Monitoring::Livestatus::INET->new( $ENV{TEST_SERVER} ),
};
for my $key (sort keys %{$objects_to_test}) {
my $ml = $objects_to_test->{$key};
isa_ok($ml, 'Monitoring::Livestatus');
my $got = $ml->selectall_arrayref("GET hosts\nColumns: name alias state\nLimit: 1", { Slice => 1, callbacks => { 'c1' => sub { return $_[0]->{'alias'}; } } });
isnt($got->[0]->{'alias'}, undef, 'got a test host');
is($got->[0]->{'alias'}, $got->[0]->{'c1'}, 'callback for sliced results');
$got = $ml->selectall_arrayref("GET hosts\nColumns: name alias state\nLimit: 1", { Slice => 1, callbacks => { 'name' => sub { return $_[0]->{'alias'}; } } });
isnt($got->[0]->{'alias'}, undef, 'got a test host');
is($got->[0]->{'alias'}, $got->[0]->{'name'}, 'callback for sliced results which overwrites key');
$got = $ml->selectall_arrayref("GET hosts\nColumns: name alias state\nLimit: 1", { callbacks => { 'c1' => sub { return $_[0]->[1]; } } });
isnt($got->[0]->[1], undef, 'got a test host');
is($got->[0]->[1], $got->[0]->[3], 'callback for non sliced results');
}

9
api/perl/t/97-Pod.t Normal file
View File

@@ -0,0 +1,9 @@
use strict;
use warnings;
use Test::More;
eval "use Test::Pod 1.14";
plan skip_all => 'Test::Pod 1.14 required' if $@;
plan skip_all => 'Author test. Set $ENV{TEST_AUTHOR} to a true value to run.' unless $ENV{TEST_AUTHOR};
all_pod_files_ok();

View File

@@ -0,0 +1,23 @@
#!/usr/bin/env perl
#
# $Id$
#
use strict;
use warnings;
use File::Spec;
use Test::More;
if ( not $ENV{TEST_AUTHOR} ) {
my $msg = 'Author test. Set $ENV{TEST_AUTHOR} to a true value to run.';
plan( skip_all => $msg );
}
eval { require Test::Pod::Coverage; };
if ( $@ ) {
my $msg = 'Test::Pod::Coverage required to criticise pod';
plan( skip_all => $msg );
}
eval "use Test::Pod::Coverage 1.00";
all_pod_coverage_ok();

View File

@@ -0,0 +1,24 @@
#!/usr/bin/env perl
#
# $Id$
#
use strict;
use warnings;
use File::Spec;
use Test::More;
if ( not $ENV{TEST_AUTHOR} ) {
my $msg = 'Author test. Set $ENV{TEST_AUTHOR} to a true value to run.';
plan( skip_all => $msg );
}
eval { require Test::Perl::Critic; };
if ( $@ ) {
my $msg = 'Test::Perl::Critic required to criticise code';
plan( skip_all => $msg );
}
my $rcfile = File::Spec->catfile( 't', 'perlcriticrc' );
Test::Perl::Critic->import( -profile => $rcfile );
all_critic_ok();

286
api/perl/t/perlcriticrc Normal file
View File

@@ -0,0 +1,286 @@
##############################################################################
# This Perl::Critic configuration file sets the Policy severity levels
# according to Damian Conway's own personal recommendations. Feel free to
# use this as your own, or make modifications.
##############################################################################
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitAccessOfPrivateData]
severity = 3
[Perl::Critic::Policy::BuiltinFunctions::ProhibitLvalueSubstr]
severity = 3
[Perl::Critic::Policy::BuiltinFunctions::ProhibitReverseSortBlock]
severity = 1
[Perl::Critic::Policy::BuiltinFunctions::ProhibitSleepViaSelect]
severity = 5
[Perl::Critic::Policy::BuiltinFunctions::ProhibitStringyEval]
severity = 5
[Perl::Critic::Policy::BuiltinFunctions::ProhibitStringySplit]
severity = 2
[Perl::Critic::Policy::BuiltinFunctions::ProhibitUniversalCan]
severity = 4
[Perl::Critic::Policy::BuiltinFunctions::ProhibitUniversalIsa]
severity = 4
[Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidGrep]
severity = 3
[Perl::Critic::Policy::BuiltinFunctions::ProhibitVoidMap]
severity = 3
[Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep]
severity = 4
[Perl::Critic::Policy::BuiltinFunctions::RequireBlockMap]
severity = 4
[Perl::Critic::Policy::BuiltinFunctions::RequireGlobFunction]
severity = 5
[Perl::Critic::Policy::BuiltinFunctions::RequireSimpleSortBlock]
severity = 3
[Perl::Critic::Policy::ClassHierarchies::ProhibitAutoloading]
severity = 3
[Perl::Critic::Policy::ClassHierarchies::ProhibitExplicitISA]
severity = 4
[Perl::Critic::Policy::ClassHierarchies::ProhibitOneArgBless]
severity = 5
[Perl::Critic::Policy::CodeLayout::ProhibitHardTabs]
severity = 3
[Perl::Critic::Policy::CodeLayout::ProhibitParensWithBuiltins]
severity = 1
[Perl::Critic::Policy::CodeLayout::ProhibitQuotedWordLists]
severity = 2
[Perl::Critic::Policy::CodeLayout::RequireConsistentNewlines]
severity = 4
[Perl::Critic::Policy::CodeLayout::RequireTidyCode]
severity = 1
[Perl::Critic::Policy::CodeLayout::RequireTrailingCommas]
severity = 3
[Perl::Critic::Policy::ControlStructures::ProhibitCStyleForLoops]
severity = 3
[Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse]
severity = 3
[Perl::Critic::Policy::ControlStructures::ProhibitDeepNests]
severity = 3
[Perl::Critic::Policy::ControlStructures::ProhibitMutatingListFunctions]
severity = 5
[Perl::Critic::Policy::ControlStructures::ProhibitPostfixControls]
severity = 4
[Perl::Critic::Policy::ControlStructures::ProhibitUnlessBlocks]
severity = 4
[Perl::Critic::Policy::ControlStructures::ProhibitUnreachableCode]
severity = 4
[Perl::Critic::Policy::ControlStructures::ProhibitUntilBlocks]
severity = 4
[Perl::Critic::Policy::Documentation::RequirePodAtEnd]
severity = 2
[Perl::Critic::Policy::Documentation::RequirePodSections]
severity = 2
[Perl::Critic::Policy::ErrorHandling::RequireCarping]
severity = 4
[Perl::Critic::Policy::InputOutput::ProhibitBacktickOperators]
severity = 3
[Perl::Critic::Policy::InputOutput::ProhibitBarewordFileHandles]
severity = 5
[Perl::Critic::Policy::InputOutput::ProhibitInteractiveTest]
severity = 4
[Perl::Critic::Policy::InputOutput::ProhibitOneArgSelect]
severity = 4
[Perl::Critic::Policy::InputOutput::ProhibitReadlineInForLoop]
severity = 5
[Perl::Critic::Policy::InputOutput::ProhibitTwoArgOpen]
severity = 4
[Perl::Critic::Policy::InputOutput::RequireBracedFileHandleWithPrint]
severity = 3
[Perl::Critic::Policy::Miscellanea::ProhibitFormats]
severity = 3
[Perl::Critic::Policy::Miscellanea::ProhibitTies]
severity = 4
[-Perl::Critic::Policy::Miscellanea::RequireRcsKeywords]
[Perl::Critic::Policy::Modules::ProhibitAutomaticExportation]
severity = 4
[Perl::Critic::Policy::Modules::ProhibitEvilModules]
severity = 5
[Perl::Critic::Policy::Modules::ProhibitMultiplePackages]
severity = 4
[Perl::Critic::Policy::Modules::RequireBarewordIncludes]
severity = 5
[Perl::Critic::Policy::Modules::RequireEndWithOne]
severity = 4
[Perl::Critic::Policy::Modules::RequireExplicitPackage]
severity = 4
[Perl::Critic::Policy::Modules::RequireFilenameMatchesPackage]
severity = 5
[Perl::Critic::Policy::Modules::RequireVersionVar]
severity = 4
[Perl::Critic::Policy::NamingConventions::ProhibitAmbiguousNames]
severity = 3
[Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseSubs]
severity = 1
[Perl::Critic::Policy::NamingConventions::ProhibitMixedCaseVars]
severity = 1
[Perl::Critic::Policy::References::ProhibitDoubleSigils]
severity = 4
[Perl::Critic::Policy::RegularExpressions::ProhibitCaptureWithoutTest]
severity = 4
[Perl::Critic::Policy::RegularExpressions::RequireExtendedFormatting]
severity = 5
[Perl::Critic::Policy::RegularExpressions::RequireLineBoundaryMatching]
severity = 5
[Perl::Critic::Policy::Subroutines::ProhibitAmpersandSigils]
severity = 2
[Perl::Critic::Policy::Subroutines::ProhibitBuiltinHomonyms]
severity = 4
[Perl::Critic::Policy::Subroutines::ProhibitExcessComplexity]
severity = 3
[Perl::Critic::Policy::Subroutines::ProhibitExplicitReturnUndef]
severity = 5
[Perl::Critic::Policy::Subroutines::ProhibitSubroutinePrototypes]
severity = 4
[Perl::Critic::Policy::Subroutines::ProtectPrivateSubs]
severity = 3
[Perl::Critic::Policy::Subroutines::RequireFinalReturn]
severity = 5
[Perl::Critic::Policy::TestingAndDebugging::ProhibitNoStrict]
severity = 5
[Perl::Critic::Policy::TestingAndDebugging::ProhibitNoWarnings]
severity = 4
[Perl::Critic::Policy::TestingAndDebugging::ProhibitProlongedStrictureOverride]
severity = 4
[Perl::Critic::Policy::TestingAndDebugging::RequireTestLabels]
severity = 3
[Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict]
severity = 5
[Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings]
severity = 4
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitConstantPragma]
severity = 4
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitEmptyQuotes]
severity = 2
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitEscapedCharacters]
severity = 2
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitInterpolationOfLiterals]
severity = 1
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitLeadingZeros]
severity = 5
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitMismatchedOperators]
severity = 2
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitMixedBooleanOperators]
severity = 4
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitNoisyQuotes]
severity = 2
[Perl::Critic::Policy::ValuesAndExpressions::ProhibitVersionStrings]
severity = 3
[Perl::Critic::Policy::ValuesAndExpressions::RequireInterpolationOfMetachars]
severity = 1
[Perl::Critic::Policy::ValuesAndExpressions::RequireNumberSeparators]
severity = 2
[Perl::Critic::Policy::ValuesAndExpressions::RequireQuotedHeredocTerminator]
severity = 4
[Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator]
severity = 4
[Perl::Critic::Policy::Variables::ProhibitConditionalDeclarations]
severity = 5
[Perl::Critic::Policy::Variables::ProhibitLocalVars]
severity = 2
[Perl::Critic::Policy::Variables::ProhibitMatchVars]
severity = 4
[Perl::Critic::Policy::Variables::ProhibitPackageVars]
severity = 3
[Perl::Critic::Policy::Variables::ProhibitPunctuationVars]
severity = 2
[Perl::Critic::Policy::Variables::ProtectPrivateVars]
severity = 3
[Perl::Critic::Policy::Variables::RequireInitializationForLocalVars]
severity = 5
[Perl::Critic::Policy::Variables::RequireLexicalLoopIterators]
severity = 5
[Perl::Critic::Policy::Variables::RequireNegativeIndices]
severity = 4

23
api/python/README Normal file
View File

@@ -0,0 +1,23 @@
This directory contains a very efficient API to MK Livestatus
for Python. It is directly taken from the Multisite GUI and
has the following features:
* It supports keep alive
* It returns typed values
* It support transparent multi-site access
* It supports persistent connection caching
* It supports parallelized queries (though still single-threaded)
* It supports detection of dead sites (via "status_host")
Please look at the two examples:
example.py: Example for a single site
example_multisite.py: Example querying several sites
Both example are written to be run within an OMD instance
and need no further configuration.
If you are not using OMD, you need to modify the examples
and enter the correct path to you livestatus socket.
Or even better: give OMD a try --> omdistro.org. This will
make you live *really* easier!

72
api/python/example.py Executable file
View File

@@ -0,0 +1,72 @@
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import os, sys
import livestatus
try:
omd_root = os.getenv("OMD_ROOT")
socket_path = "unix:" + omd_root + "/tmp/run/live"
except:
sys.stderr.write("This example is indented to run in an OMD site\n")
sys.stderr.write("Please change socket_path in this example, if you are\n")
sys.stderr.write("not using OMD.\n")
sys.exit(1)
try:
# Make a single connection for each query
print "\nPerformance:"
for key, value in livestatus.SingleSiteConnection(socket_path).query_row_assoc("GET status").items():
print "%-30s: %s" % (key, value)
print "\nHosts:"
hosts = livestatus.SingleSiteConnection(socket_path).query_table("GET hosts\nColumns: name alias address")
for name, alias, address in hosts:
print "%-16s %-16s %s" % (name, address, alias)
# Do several queries in one connection
conn = livestatus.SingleSiteConnection(socket_path)
num_up = conn.query_value("GET hosts\nStats: hard_state = 0")
print "\nHosts up: %d" % num_up
stats = conn.query_row(
"GET services\n"
"Stats: state = 0\n"
"Stats: state = 1\n"
"Stats: state = 2\n"
"Stats: state = 3\n")
print "Service stats: %d/%d/%d/%d" % tuple(stats)
print "List of commands: %s" % \
", ".join(conn.query_column("GET commands\nColumns: name"))
print "Query error:"
conn.query_value("GET hosts\nColumns: hirni")
except Exception, e: # livestatus.MKLivestatusException, e:
print "Livestatus error: %s" % str(e)

94
api/python/example_multisite.py Executable file
View File

@@ -0,0 +1,94 @@
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import os
import sys
import livestatus
try:
omd_root = os.getenv("OMD_ROOT")
socket_path = "unix:" + omd_root + "/tmp/run/live"
except:
sys.stderr.write("This example is indented to run in an OMD site\n")
sys.stderr.write("Please change socket_path in this example, if you are\n")
sys.stderr.write("not using OMD.\n")
sys.exit(1)
sites = {
"muc" : {
"socket" : socket_path,
"alias" : "Munich",
},
"sitea" : {
"alias" : "Augsburg",
"socket" : "tcp:sitea:6557",
"nagios_url" : "/nagios/",
"timeout" : 2,
},
"siteb" : {
"alias" : "Berlin",
"socket" : "tcp:siteb:6557",
"nagios_url" : "/nagios/",
"timeout" : 10,
},
}
c = livestatus.MultiSiteConnection(sites)
c.set_prepend_site(True)
print c.query("GET hosts\nColumns: name state\n")
c.set_prepend_site(False)
print c.query("GET hosts\nColumns: name state\n")
# Beware: When doing stats, you need to aggregate yourself:
print sum(c.query_column("GET hosts\nStats: state >= 0\n"))
# Detect errors:
sites = {
"muc" : {
"socket" : "unix:/var/run/nagios/rw/live",
"alias" : "Munich",
},
"sitea" : {
"alias" : "Augsburg",
"socket" : "tcp:sitea:6558", # BROKEN
"nagios_url" : "/nagios/",
"timeout" : 2,
},
"siteb" : {
"alias" : "Berlin",
"socket" : "tcp:siteb:6557",
"nagios_url" : "/nagios/",
"timeout" : 10,
},
}
c = livestatus.MultiSiteConnection(sites)
for name, state in c.query("GET hosts\nColumns: name state\n"):
print "%-15s: %d" % (name, state)
print "Dead sites:"
for sitename, info in c.dead_sites().items():
print "%s: %s" % (sitename, info["exception"])

839
api/python/livestatus.py Normal file
View File

@@ -0,0 +1,839 @@
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import socket, time, re, os
import ast
"""MK Livestatus Python API"""
# .--Globals-------------------------------------------------------------.
# | ____ _ _ _ |
# | / ___| | ___ | |__ __ _| |___ |
# | | | _| |/ _ \| '_ \ / _` | / __| |
# | | |_| | | (_) | |_) | (_| | \__ \ |
# | \____|_|\___/|_.__/ \__,_|_|___/ |
# | |
# +----------------------------------------------------------------------+
# | Global variables and Exception classes |
# '----------------------------------------------------------------------'
# Keep a global array of persistant connections
persistent_connections = {}
# Regular expression for removing Cache: headers if caching is not allowed
remove_cache_regex = re.compile("\nCache:[^\n]*")
class MKLivestatusException(Exception):
def __init__(self, value):
self.parameter = value
super(MKLivestatusException, self).__init__(value)
def __str__(self):
return str(self.parameter)
class MKLivestatusSocketError(MKLivestatusException):
pass
class MKLivestatusSocketClosed(MKLivestatusSocketError):
pass
class MKLivestatusConfigError(MKLivestatusException):
pass
class MKLivestatusQueryError(MKLivestatusException):
pass
class MKLivestatusNotFoundError(MKLivestatusException):
def __str__(self):
return "No matching entries found for query %s" % str(self.parameter)
class MKLivestatusTableNotFoundError(MKLivestatusException):
pass
# We need some unique value here
NO_DEFAULT = lambda: None
#.
# .--Helpers-------------------------------------------------------------.
# | _ _ _ |
# | | | | | ___| |_ __ ___ _ __ ___ |
# | | |_| |/ _ \ | '_ \ / _ \ '__/ __| |
# | | _ | __/ | |_) | __/ | \__ \ |
# | |_| |_|\___|_| .__/ \___|_| |___/ |
# | |_| |
# +----------------------------------------------------------------------+
# | Helper class implementing some generic shortcut functions, e.g. |
# | for fetching just one row or one single value. |
# '----------------------------------------------------------------------'
class Helpers:
def query(self, query, add_headers = ""):
raise NotImplementedError()
def query_value(self, query, deflt = NO_DEFAULT):
"""Issues a query that returns exactly one line and one columns and returns
the response as a single value"""
result = self.query(query, "ColumnHeaders: off\n")
try:
return result[0][0]
except:
if deflt == NO_DEFAULT:
raise MKLivestatusNotFoundError(query)
else:
return deflt
def query_row(self, query):
"""Issues a query that returns one line of data and returns the elements
of that line as list"""
result = self.query(query, "ColumnHeaders: off\n")
try:
return result[0]
except IndexError:
raise MKLivestatusNotFoundError(query)
def query_row_assoc(self, query):
"""Issues a query that returns one line of data and returns the elements
of that line as a dictionary from column names to values"""
r = self.query(query, "ColumnHeaders: on\n")[0:2]
return dict(zip(r[0], r[1]))
def query_column(self, query):
"""Issues a query that returns exactly one column and returns the values
of all lines in that column as a single list"""
return [ l[0] for l in self.query(query, "ColumnHeaders: off\n") ]
def query_column_unique(self, query):
"""Issues a query that returns exactly one column and returns the values
of all lines with duplicates removed"""
result = []
for line in self.query(query, "ColumnHeaders: off\n"):
if line[0] not in result:
result.append(line[0])
return result
def query_table(self, query):
"""Issues a query that may return multiple lines and columns and returns
a list of lists"""
return self.query(query, "ColumnHeaders: off\n")
def query_table_assoc(self, query):
"""Issues a query that may return multiple lines and columns and returns
a dictionary from column names to values for each line. This can be
very ineffective for large response sets."""
response = self.query(query, "ColumnHeaders: on\n")
headers = response[0]
result = []
for line in response[1:]:
result.append(dict(zip(headers, line)))
return result
def query_summed_stats(self, query, add_headers = ""):
"""Conveniance function for adding up numbers from Stats queries
Adds up results column-wise. This is useful for multisite queries."""
data = self.query(query, add_headers)
if len(data) == 1:
return data[0]
elif len(data) == 0:
raise MKLivestatusNotFoundError("Empty result to Stats-Query")
result = []
for x in range(0, len(data[0])):
result.append(sum([row[x] for row in data]))
return result
# TODO: Add more functionality to the Query class:
# - set_prepend_site
# - set_only_sites
# - set_auth_domain
# All these are mostly set for a single query and reset back to another
# value after the query. But nearly all of these usages does not care
# about resetting the option in case of an exception. This could be
# handled better using the query class
class Query(object):
"""This object can be passed to all livestatus methods accepting a livestatus
query. The object can be used to hand over the handling code some flags, for
example to influence the error handling during query processing."""
default_suppressed_exceptions = [MKLivestatusTableNotFoundError]
def __init__(self, query, suppress_exceptions=None):
super(Query, self).__init__()
self._query = self._ensure_unicode(query)
if suppress_exceptions == None:
self.suppress_exceptions = self.default_suppressed_exceptions
else:
self.suppress_exceptions = suppress_exceptions
def _ensure_unicode(self, thing):
try:
return unicode(thing)
except UnicodeDecodeError:
return thing.decode("utf-8")
def __unicode__(self):
return self._query
def __str__(self):
return self._query.encode("utf-8")
#.
# .--BaseConnection----------------------------------------------------------.
# | ____ ____ _ _ |
# || __ ) __ _ ___ ___ / ___|___ _ __ _ __ ___ ___| |_(_) ___ _ __ |
# || _ \ / _` / __|/ _ \ | / _ \| '_ \| '_ \ / _ \/ __| __| |/ _ \ | '_ \ |
# || |_) | (_| \__ \ __/ |__| (_) | | | | | | | __/ (__| |_| | (_) || | | ||
# ||____/ \__,_|___/\___|\____\___/|_| |_|_| |_|\___|\___|\__|_|\___/ |_| |_||
# | |
# +--------------------------------------------------------------------------+
# | Abstract base class of SingleSiteConnection and MultiSiteConnection |
# '--------------------------------------------------------------------------'
class BaseConnection:
def __init__(self, socketurl, persist = False, allow_cache = False):
"""Create a new connection to a MK Livestatus socket"""
self.add_headers = ""
self.auth_header = ""
self.persist = persist
self.allow_cache = allow_cache
self.socketurl = socketurl
self.socket = None
self.timeout = None
self.successful_persistence = False
def successfully_persisted(self):
return self.successful_persistence
def add_header(self, header):
self.add_headers += header + "\n"
def set_timeout(self, timeout):
self.timeout = timeout
if self.socket:
self.socket.settimeout(float(timeout))
def connect(self):
if self.persist and self.socketurl in persistent_connections:
self.socket = persistent_connections[self.socketurl]
self.successful_persistence = True
return
self.successful_persistence = False
# Create new socket
self.socket = None
url = self.socketurl
parts = url.split(":")
if parts[0] == "unix":
if len(parts) != 2:
raise MKLivestatusConfigError("Invalid livestatus unix URL: %s. "
"Correct example is 'unix:/var/run/nagios/rw/live'" % url)
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
target = parts[1]
elif parts[0] == "tcp":
try:
host = parts[1]
port = int(parts[2])
except:
raise MKLivestatusConfigError("Invalid livestatus tcp URL '%s'. "
"Correct example is 'tcp:somehost:6557'" % url)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target = (host, port)
else:
raise MKLivestatusConfigError("Invalid livestatus URL '%s'. "
"Must begin with 'tcp:' or 'unix:'" % url)
# If a timeout is set, then we retry after a failure with mild
# a binary backoff.
if self.timeout:
before = time.time()
sleep_interval = 0.1
while True:
try:
if self.timeout:
self.socket.settimeout(float(sleep_interval))
self.socket.connect(target)
break
except Exception, e:
if self.timeout:
time_left = self.timeout - (time.time() - before)
# only try again, if there is substantial time left
if time_left > sleep_interval:
time.sleep(sleep_interval)
sleep_interval *= 1.5
continue
self.socket = None
raise MKLivestatusSocketError("Cannot connect to '%s': %s" % (self.socketurl, e))
if self.persist:
persistent_connections[self.socketurl] = self.socket
def disconnect(self):
self.socket = None
if self.persist:
try:
del persistent_connections[self.socketurl]
except KeyError:
pass
def receive_data(self, size):
result = b""
# Timeout is only honored when connecting
self.socket.settimeout(None)
while size > 0:
packet = self.socket.recv(size)
if len(packet) == 0:
raise MKLivestatusSocketClosed("Read zero data from socket, nagios server closed connection")
size -= len(packet)
result += packet
return result
def do_query(self, query, add_headers = ""):
self.send_query(query, add_headers)
return self.recv_response(query, add_headers)
def send_query(self, query_obj, add_headers = "", do_reconnect=True):
orig_query = query_obj
query = "%s" % query_obj
if not self.allow_cache:
query = remove_cache_regex.sub("", query)
if self.socket == None:
self.connect()
if not query.endswith("\n"):
query += "\n"
query += self.auth_header + self.add_headers
query += "Localtime: %d\nOutputFormat: python\nKeepAlive: on\nResponseHeader: fixed16\n" % int(time.time())
query += add_headers
if not query.endswith("\n"):
query += "\n"
query += "\n"
try:
# socket.send() will implicitely cast to str(), we need ot
# convert to UTF-8 in order to avoid exceptions
if type(query) == unicode:
query = query.encode("utf-8")
self.socket.send(query)
except IOError, e:
if self.persist:
del persistent_connections[self.socketurl]
self.successful_persistence = False
self.socket = None
if do_reconnect:
# Automatically try to reconnect in case of an error, but
# only once.
self.connect()
self.send_query(orig_query, add_headers, False)
return
raise MKLivestatusSocketError("RC1:" + str(e))
# Reads a response from the livestatus socket. If the socket is closed
# by the livestatus server, we automatically make a reconnect and send
# the query again (once). This is due to timeouts during keepalive.
def recv_response(self, query = None, add_headers = "", timeout_at = None):
try:
# Headers are always ASCII encoded
resp = self.receive_data(16)
code = resp[0:3]
try:
length = int(resp[4:15].lstrip())
except:
self.disconnect()
raise MKLivestatusSocketError("Malformed output. Livestatus TCP socket might be unreachable.")
data = self.receive_data(length).decode("utf-8")
if code == "200":
try:
return ast.literal_eval(data)
except:
self.disconnect()
raise MKLivestatusSocketError("Malformed output")
elif code == "404":
raise MKLivestatusTableNotFoundError("Not Found (%s): %s" % (code, data.strip()))
else:
raise MKLivestatusQueryError("%s: %s" % (code, data.strip()))
except (MKLivestatusSocketClosed, IOError), e:
# In case of an IO error or the other side having
# closed the socket do a reconnect and try again
self.disconnect()
now = time.time()
if query and (not timeout_at or timeout_at > now):
if timeout_at == None:
# Try until timeout reached in case there was a timeout configured.
# Otherwise only retry once.
timeout_at = now
if self.timeout:
timeout_at += self.timeout
time.sleep(0.1)
self.connect()
self.send_query(query, add_headers)
return self.recv_response(query, add_headers, timeout_at) # do not send query again -> danger of infinite loop
else:
raise MKLivestatusSocketError(str(e))
except MKLivestatusTableNotFoundError:
raise
except Exception, e:
# Catches
# MKLivestatusQueryError
# MKLivestatusSocketError
# FIXME: ? self.disconnect()
raise MKLivestatusSocketError("Unhandled exception: %s" % e)
def do_command(self, command):
if self.socket == None:
self.connect()
if not command.endswith("\n"):
command += "\n"
try:
self.socket.send("COMMAND " + command + "\n")
except IOError, e:
self.socket = None
if self.persist:
del persistent_connections[self.socketurl]
raise MKLivestatusSocketError(str(e))
#.
# .--SingleSiteConn------------------------------------------------------.
# | ____ _ _ ____ _ _ ____ |
# | / ___|(_)_ __ __ _| | ___/ ___|(_) |_ ___ / ___|___ _ __ _ __ |
# | \___ \| | '_ \ / _` | |/ _ \___ \| | __/ _ \ | / _ \| '_ \| '_ \ |
# | ___) | | | | | (_| | | __/___) | | || __/ |__| (_) | | | | | | | |
# | |____/|_|_| |_|\__, |_|\___|____/|_|\__\___|\____\___/|_| |_|_| |_| |
# | |___/ |
# +----------------------------------------------------------------------+
# | Connections to one local Unix or remote TCP socket. |
# '----------------------------------------------------------------------'
class SingleSiteConnection(BaseConnection, Helpers):
def __init__(self, socketurl, persist = False, allow_cache = False):
BaseConnection.__init__(self, socketurl, persist, allow_cache)
self.prepend_site = False
self.auth_users = {}
self.deadsites = {} # never filled, just for compatibility
self.limit = None
def set_prepend_site(self, p):
self.prepend_site = p
def set_only_sites(self, os = None):
pass
def set_limit(self, limit = None):
self.limit = limit
def query(self, query, add_headers = ""):
if self.limit != None:
query += "Limit: %d\n" % self.limit
data = self.do_query(query, add_headers)
if self.prepend_site:
return [ [''] + line for line in data ]
else:
return data
def command(self, command, site = None):
self.do_command(command)
# Set user to be used in certain authorization domain
def set_auth_user(self, domain, user):
if user:
self.auth_users[domain] = user
elif domain in self.auth_users:
del self.auth_users[domain]
# Switch future request to new authorization domain
def set_auth_domain(self, domain):
auth_user = self.auth_users.get(domain)
if auth_user:
self.auth_header = "AuthUser: %s\n" % auth_user
else:
self.auth_header = ""
#.
# .--MultiSiteConn-------------------------------------------------------.
# | __ __ _ _ _ ____ _ _ ____ |
# | | \/ |_ _| | |_(_) ___|(_) |_ ___ / ___|___ _ __ _ __ |
# | | |\/| | | | | | __| \___ \| | __/ _ \ | / _ \| '_ \| '_ \ |
# | | | | | |_| | | |_| |___) | | || __/ |__| (_) | | | | | | | |
# | |_| |_|\__,_|_|\__|_|____/|_|\__\___|\____\___/|_| |_|_| |_| |
# | |
# +----------------------------------------------------------------------+
# | Connections to a list of local and remote sites. |
# '----------------------------------------------------------------------'
# sites is a dictionary from site name to a dict.
# Keys in the dictionary:
# socket: socketurl (obligatory)
# timeout: timeout for tcp/unix in seconds
# TODO: Move the connect/disconnect stuff to separate methods. Then make
# it possible to connect/disconnect duing existance of a single object.
class MultiSiteConnection(Helpers):
def __init__(self, sites, disabled_sites = None):
if disabled_sites is None:
disabled_sites = {}
self.sites = sites
self.connections = []
self.deadsites = {}
self.prepend_site = False
self.only_sites = None
self.limit = None
self.parallelize = True
# Helper function for connecting to a site
def connect_to_site(sitename, site, temporary=False):
try:
url = site["socket"]
persist = not temporary and site.get("persist", False)
connection = SingleSiteConnection(url, persist, allow_cache=site.get("cache", False))
if "timeout" in site:
connection.set_timeout(int(site["timeout"]))
connection.connect()
self.connections.append((sitename, site, connection))
except Exception, e:
self.deadsites[sitename] = {
"exception" : e,
"site" : site,
}
# Needed for temporary connection for status_hosts in disabled sites
def disconnect_site(sitename):
i = 0
for name, site, connection in self.connections:
if name == sitename:
del self.connections[i]
return
i += 1
# Status host: A status host helps to prevent trying to connect
# to a remote site which is unreachable. This is done by looking
# at the current state of a certain host on a local site that is
# representing the connection to the remote site. The status host
# is specified as an optional pair of (site, host) in the entry
# "status_host". We first connect to all sites without a status_host
# entry, then retrieve the host states of the status hosts and then
# connect to the remote site which are reachable
# Tackle very special problem: If the user disables a site which
# provides status_host information for other sites, the dead-detection
# would not work. For that cases we make a temporary connection just
# to fetch the status information
extra_status_sites = {}
if len(disabled_sites) > 0:
status_sitenames = set([])
for sitename, site in sites.items():
try:
s, h = site.get("status_host")
status_sitenames.add(s)
except:
continue
for sitename in status_sitenames:
site = disabled_sites.get(sitename)
if site:
extra_status_sites[sitename] = site
# First connect to sites without status host. Collect status
# hosts at the same time.
status_hosts = {} # dict from site to list of status_hosts
for sitename, site in sites.items() + extra_status_sites.items():
status_host = site.get("status_host")
if status_host:
if type(status_host) != tuple or len(status_host) != 2:
raise MKLivestatusConfigError("Status host of site %s is %r, but must be pair of site and host" %
(sitename, status_host))
s, h = status_host
status_hosts[s] = status_hosts.get(s, []) + [h]
else:
connect_to_site(sitename, site)
# Now learn current states of status hosts and store it in a dictionary
# from (local_site, host) => state
status_host_states = {}
for sitename, hosts in status_hosts.items():
# Fetch all the states of status hosts of this local site in one query
query = "GET hosts\nColumns: name state has_been_checked last_time_up\n"
for host in hosts:
query += "Filter: name = %s\n" % host
query += "Or: %d\n" % len(hosts)
self.set_only_sites([sitename]) # only connect one site
try:
result = self.query_table(query)
# raise MKLivestatusConfigError("TRESulT: %s" % (result,))
for host, state, has_been_checked, lastup in result:
if has_been_checked == 0:
state = 3
status_host_states[(sitename, host)] = (state, lastup)
except Exception, e:
raise MKLivestatusConfigError(e)
status_host_states[(sitename, host)] = (str(e), None)
self.set_only_sites() # clear site filter
# Disconnect from disabled sites that we connected to only to
# get status information from
for sitename, site in extra_status_sites.items():
disconnect_site(sitename)
# Now loop over all sites having a status_host and take that state
# of that into consideration
for sitename, site in sites.items():
status_host = site.get("status_host")
if status_host:
now = time.time()
shs, lastup = status_host_states.get(status_host, (4, now)) # None => Status host not existing
deltatime = now - lastup
if shs == 0 or shs == None:
connect_to_site(sitename, site)
else:
if shs == 1:
ex = "The remote monitoring host is down"
elif shs == 2:
ex = "The remote monitoring host is unreachable"
elif shs == 3:
ex = "The remote monitoring host's state it not yet determined"
elif shs == 4:
ex = "Invalid status host: site %s has no host %s" % (status_host[0], status_host[1])
else:
ex = "Error determining state of remote monitoring host: %s" % shs
self.deadsites[sitename] = {
"site" : site,
"status_host_state" : shs,
"exception" : ex,
}
def add_header(self, header):
for sitename, site, connection in self.connections:
connection.add_header(header)
def set_prepend_site(self, p):
self.prepend_site = p
def set_only_sites(self, sites=None):
"""Make future queries only contact the given sites.
Provide a list of site IDs to not contact all configured sites, but only the listed
site IDs. In case None is given, the limitation is removed.
"""
self.only_sites = sites
# Impose Limit on number of returned datasets (distributed amoung sites)
def set_limit(self, limit = None):
self.limit = limit
def dead_sites(self):
return self.deadsites
def alive_sites(self):
return [ s[0] for s in self.connections ]
def successfully_persisted(self):
for sitename, site, connection in self.connections:
if connection.successfully_persisted():
return True
return False
def set_auth_user(self, domain, user):
for sitename, site, connection in self.connections:
connection.set_auth_user(domain, user)
def set_auth_domain(self, domain):
for sitename, site, connection in self.connections:
connection.set_auth_domain(domain)
def query(self, query, add_headers = ""):
if self.parallelize:
return self.query_parallel(query, add_headers)
else:
return self.query_non_parallel(query, add_headers)
def query_non_parallel(self, query, add_headers = ""):
result = []
stillalive = []
limit = self.limit
for sitename, site, connection in self.connections:
if self.only_sites != None and sitename not in self.only_sites:
stillalive.append( (sitename, site, connection) ) # state unknown, assume still alive
continue
try:
if limit != None:
limit_header = "Limit: %d\n" % limit
else:
limit_header = ""
r = connection.query(query, add_headers + limit_header)
if self.prepend_site:
r = [ [sitename] + l for l in r ]
if limit != None:
limit -= len(r) # Account for portion of limit used by this site
result += r
stillalive.append( (sitename, site, connection) )
except Exception, e:
connection.disconnect()
self.deadsites[sitename] = {
"exception" : e,
"site" : site,
}
self.connections = stillalive
return result
# New parallelized version of query(). The semantics differs in the handling
# of Limit: since all sites are queried in parallel, the Limit: is simply
# applied to all sites - resulting in possibly more results then Limit requests.
def query_parallel(self, query, add_headers = ""):
stillalive = []
if self.only_sites != None:
connect_to_sites = [ c for c in self.connections if c[0] in self.only_sites ]
# Unused sites are assumed to be alive
stillalive.extend( [ c for c in self.connections if c[0] not in self.only_sites])
else:
connect_to_sites = self.connections
start_time = time.time()
limit = self.limit
if limit != None:
limit_header = "Limit: %d\n" % limit
else:
limit_header = ""
# First send all queries
for sitename, site, connection in connect_to_sites:
try:
connection.send_query(query, add_headers + limit_header)
except Exception, e:
self.deadsites[sitename] = {
"exception" : e,
"site" : site,
}
if isinstance(query, Query):
suppress_exceptions = tuple(query.suppress_exceptions)
else:
suppress_exceptions = tuple(Query.default_suppressed_exceptions)
# Then retrieve all answers. We will be as slow as the slowest of all
# connections.
result = []
for sitename, site, connection in connect_to_sites:
try:
r = connection.recv_response(query, add_headers + limit_header)
stillalive.append( (sitename, site, connection) )
if self.prepend_site:
r = [ [sitename] + l for l in r ]
result += r
except suppress_exceptions:
stillalive.append( (sitename, site, connection) )
continue
except Exception, e:
connection.disconnect()
self.deadsites[sitename] = {
"exception" : e,
"site" : site,
}
self.connections = stillalive
return result
def command(self, command, sitename = "local"):
if sitename in self.deadsites:
raise MKLivestatusSocketError("Connection to site %s is dead: %s" % \
(sitename, self.deadsites[sitename]["exception"]))
conn = [t[2] for t in self.connections if t[0] == sitename]
if len(conn) == 0:
raise MKLivestatusConfigError("Cannot send command to unconfigured site '%s'" % sitename)
conn[0].do_command(command)
# Return connection to localhost (UNIX), if available
def local_connection(self):
for sitename, site, connection in self.connections:
if site["socket"].startswith("unix:") and "liveproxy" not in site["socket"]:
return connection
raise MKLivestatusConfigError("No livestatus connection to local host")
#.
# .--LocalConn-----------------------------------------------------------.
# | _ _ ____ |
# | | | ___ ___ __ _| |/ ___|___ _ __ _ __ |
# | | | / _ \ / __/ _` | | | / _ \| '_ \| '_ \ |
# | | |__| (_) | (_| (_| | | |__| (_) | | | | | | | |
# | |_____\___/ \___\__,_|_|\____\___/|_| |_|_| |_| |
# | |
# +----------------------------------------------------------------------+
# | LocalConnection is a convenciance class for connecting to the |
# | local Livestatus socket within an OMD site. It only works within |
# | OMD context. It immediately connects() |
# '----------------------------------------------------------------------'
class LocalConnection(SingleSiteConnection):
def __init__(self, *args, **kwargs):
omd_root = os.getenv("OMD_ROOT")
if not omd_root:
raise MKLivestatusConfigError("OMD_ROOT is not set. You are not running in OMD context.")
SingleSiteConnection.__init__(self, "unix:" + omd_root + "/tmp/run/live", *args, **kwargs)
self.connect()

119
api/python/make_nagvis_map.py Executable file
View File

@@ -0,0 +1,119 @@
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
# This is an example for a usage of Livestatus: it creates
# a NagVis map using actual live data from a running Nagios
# system. Most things are hardcoded here but this might by
# a useful example for coding your own stuff...
import livestatus
g_y = 50
y_title = 40
lineheight = 30
x_hostgroup = 30
x_therm = 200
x_usv = 560
def make_label(text, x, y, width):
print """
define textbox {
text=%s
x=%d
y=%d
background_color=#C0C0C1
border_color=#000055
w=%d
}""" % (text, x, y, width)
def render_hostgroup(name, alias):
global g_y
g_y += lineheight
# Name des Serverraums
make_label(alias, x_hostgroup, g_y, x_therm - x_hostgroup - 20)
def display_servicegroup(name, x):
if live.query_value("GET servicegroups\nStats: name = %s\n" % name) == 1:
print """
define servicegroup {
servicegroup_name = %s
x=%d
y=%d
}""" % (name, x, g_y)
# Einzelauflistung der Thermometer
num = 0
shift = 16
for host, service in live.query("GET services\nFilter: groups >= %s\nColumns: host_name description" % name):
num += 1
print """
define service {
host_name=%s
service_description=%s
x=%d
y=%d
url=/pnp4nagios/graph?host=%s&srv=%s
}
""" % (host, service, x + 30 + shift * num, g_y, host, service)
# Gesamtzustand Thermometer
display_servicegroup(name + "_therm", x_therm)
# Auflistung der USV-Parameter
display_servicegroup(name + "_usv", x_usv)
socket_path = "unix:/var/run/nagios/rw/live"
live = livestatus.SingleSiteConnection(socket_path)
print """
define global {
allowed_for_config=nagiosadmin
allowed_user=nagiosadmin
map_image=demo_background.png
iconset=std_medium
}
"""
# hostgroups = live.query("GET hostgroups\nColumns: name alias")
hostgroups = [
( "s02", "S-02" ),
( "s06", "S-06" ),
( "s48", "S-48" ),
( "ad214", "AD-214" ),
( "ik026", "IK-026" ),
( "etage", "Etagenverteiler" ),
]
for name, alias in hostgroups:
render_hostgroup(name, alias)
make_label("Temperaturen", x_therm, y_title, 250)
make_label("USV-Status", x_usv, y_title, 160)

270
ar-lib Executable file
View File

@@ -0,0 +1,270 @@
#! /bin/sh
# Wrapper for Microsoft lib.exe
me=ar-lib
scriptversion=2012-03-01.08; # UTC
# Copyright (C) 2010-2017 Free Software Foundation, Inc.
# Written by Peter Rosin <peda@lysator.liu.se>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
# func_error message
func_error ()
{
echo "$me: $1" 1>&2
exit 1
}
file_conv=
# func_file_conv build_file
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv in
mingw)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin)
file=`cygpath -m "$file" || echo "$file"`
;;
wine)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_at_file at_file operation archive
# Iterate over all members in AT_FILE performing OPERATION on ARCHIVE
# for each of them.
# When interpreting the content of the @FILE, do NOT use func_file_conv,
# since the user would need to supply preconverted file names to
# binutils ar, at least for MinGW.
func_at_file ()
{
operation=$2
archive=$3
at_file_contents=`cat "$1"`
eval set x "$at_file_contents"
shift
for member
do
$AR -NOLOGO $operation:"$member" "$archive" || exit $?
done
}
case $1 in
'')
func_error "no command. Try '$0 --help' for more information."
;;
-h | --h*)
cat <<EOF
Usage: $me [--help] [--version] PROGRAM ACTION ARCHIVE [MEMBER...]
Members may be specified in a file named with @FILE.
EOF
exit $?
;;
-v | --v*)
echo "$me, version $scriptversion"
exit $?
;;
esac
if test $# -lt 3; then
func_error "you must specify a program, an action and an archive"
fi
AR=$1
shift
while :
do
if test $# -lt 2; then
func_error "you must specify a program, an action and an archive"
fi
case $1 in
-lib | -LIB \
| -ltcg | -LTCG \
| -machine* | -MACHINE* \
| -subsystem* | -SUBSYSTEM* \
| -verbose | -VERBOSE \
| -wx* | -WX* )
AR="$AR $1"
shift
;;
*)
action=$1
shift
break
;;
esac
done
orig_archive=$1
shift
func_file_conv "$orig_archive"
archive=$file
# strip leading dash in $action
action=${action#-}
delete=
extract=
list=
quick=
replace=
index=
create=
while test -n "$action"
do
case $action in
d*) delete=yes ;;
x*) extract=yes ;;
t*) list=yes ;;
q*) quick=yes ;;
r*) replace=yes ;;
s*) index=yes ;;
S*) ;; # the index is always updated implicitly
c*) create=yes ;;
u*) ;; # TODO: don't ignore the update modifier
v*) ;; # TODO: don't ignore the verbose modifier
*)
func_error "unknown action specified"
;;
esac
action=${action#?}
done
case $delete$extract$list$quick$replace,$index in
yes,* | ,yes)
;;
yesyes*)
func_error "more than one action specified"
;;
*)
func_error "no action specified"
;;
esac
if test -n "$delete"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
for member
do
case $1 in
@*)
func_at_file "${1#@}" -REMOVE "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -REMOVE:"$file" "$archive" || exit $?
;;
esac
done
elif test -n "$extract"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
if test $# -gt 0; then
for member
do
case $1 in
@*)
func_at_file "${1#@}" -EXTRACT "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -EXTRACT:"$file" "$archive" || exit $?
;;
esac
done
else
$AR -NOLOGO -LIST "$archive" | sed -e 's/\\/\\\\/g' | while read member
do
$AR -NOLOGO -EXTRACT:"$member" "$archive" || exit $?
done
fi
elif test -n "$quick$replace"; then
if test ! -f "$orig_archive"; then
if test -z "$create"; then
echo "$me: creating $orig_archive"
fi
orig_archive=
else
orig_archive=$archive
fi
for member
do
case $1 in
@*)
func_file_conv "${1#@}"
set x "$@" "@$file"
;;
*)
func_file_conv "$1"
set x "$@" "$file"
;;
esac
shift
shift
done
if test -n "$orig_archive"; then
$AR -NOLOGO -OUT:"$archive" "$orig_archive" "$@" || exit $?
else
$AR -NOLOGO -OUT:"$archive" "$@" || exit $?
fi
elif test -n "$list"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
$AR -NOLOGO -LIST "$archive" || exit $?
fi

347
compile Executable file
View File

@@ -0,0 +1,347 @@
#! /bin/sh
# Wrapper for compilers which do not understand '-c -o'.
scriptversion=2012-10-14.11; # UTC
# Copyright (C) 1999-2014 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
nl='
'
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent tools from complaining about whitespace usage.
IFS=" "" $nl"
file_conv=
# func_file_conv build_file lazy
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts. If the determined conversion
# type is listed in (the comma separated) LAZY, no conversion will
# take place.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv/,$2, in
*,$file_conv,*)
;;
mingw/*)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin/*)
file=`cygpath -m "$file" || echo "$file"`
;;
wine/*)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_cl_dashL linkdir
# Make cl look for libraries in LINKDIR
func_cl_dashL ()
{
func_file_conv "$1"
if test -z "$lib_path"; then
lib_path=$file
else
lib_path="$lib_path;$file"
fi
linker_opts="$linker_opts -LIBPATH:$file"
}
# func_cl_dashl library
# Do a library search-path lookup for cl
func_cl_dashl ()
{
lib=$1
found=no
save_IFS=$IFS
IFS=';'
for dir in $lib_path $LIB
do
IFS=$save_IFS
if $shared && test -f "$dir/$lib.dll.lib"; then
found=yes
lib=$dir/$lib.dll.lib
break
fi
if test -f "$dir/$lib.lib"; then
found=yes
lib=$dir/$lib.lib
break
fi
if test -f "$dir/lib$lib.a"; then
found=yes
lib=$dir/lib$lib.a
break
fi
done
IFS=$save_IFS
if test "$found" != yes; then
lib=$lib.lib
fi
}
# func_cl_wrapper cl arg...
# Adjust compile command to suit cl
func_cl_wrapper ()
{
# Assume a capable shell
lib_path=
shared=:
linker_opts=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
eat=1
case $2 in
*.o | *.[oO][bB][jJ])
func_file_conv "$2"
set x "$@" -Fo"$file"
shift
;;
*)
func_file_conv "$2"
set x "$@" -Fe"$file"
shift
;;
esac
;;
-I)
eat=1
func_file_conv "$2" mingw
set x "$@" -I"$file"
shift
;;
-I*)
func_file_conv "${1#-I}" mingw
set x "$@" -I"$file"
shift
;;
-l)
eat=1
func_cl_dashl "$2"
set x "$@" "$lib"
shift
;;
-l*)
func_cl_dashl "${1#-l}"
set x "$@" "$lib"
shift
;;
-L)
eat=1
func_cl_dashL "$2"
;;
-L*)
func_cl_dashL "${1#-L}"
;;
-static)
shared=false
;;
-Wl,*)
arg=${1#-Wl,}
save_ifs="$IFS"; IFS=','
for flag in $arg; do
IFS="$save_ifs"
linker_opts="$linker_opts $flag"
done
IFS="$save_ifs"
;;
-Xlinker)
eat=1
linker_opts="$linker_opts $2"
;;
-*)
set x "$@" "$1"
shift
;;
*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
func_file_conv "$1"
set x "$@" -Tp"$file"
shift
;;
*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
func_file_conv "$1" mingw
set x "$@" "$file"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -n "$linker_opts"; then
linker_opts="-link$linker_opts"
fi
exec "$@" $linker_opts
exit 1
}
eat=
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand '-c -o'.
Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file 'INSTALL'.
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "compile $scriptversion"
exit $?
;;
cl | *[/\\]cl | cl.exe | *[/\\]cl.exe )
func_cl_wrapper "$@" # Doesn't return...
;;
esac
ofile=
cfile=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
# So we strip '-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no '-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# '.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
# Create the lock directory.
# Note: use '[/\\:.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC"
# time-stamp-end: "; # UTC"
# End:

1480
config.guess vendored Executable file

File diff suppressed because it is too large Load Diff

226
config.h.in Normal file
View File

@@ -0,0 +1,226 @@
/* config.h.in. Generated from configure.ac by autoheader. */
/* we do not want any old stuff */
#undef BOOST_SYSTEM_NO_DEPRECATED
/* C++ compiler */
#undef BUILD_CXX
/* build date */
#undef BUILD_DATE
/* name of the build host */
#undef BUILD_HOSTNAME
/* Define to 1 if you have the `accept4' function. */
#undef HAVE_ACCEPT4
/* Define to 1 if you have the <arpa/inet.h> header file. */
#undef HAVE_ARPA_INET_H
/* define if the Boost library is available */
#undef HAVE_BOOST
/* define if the Boost::ASIO library is available */
#undef HAVE_BOOST_ASIO
/* define if the compiler supports basic C++17 syntax */
#undef HAVE_CXX17
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#undef HAVE_DIRENT_H
/* Define to 1 if you have the <fcntl.h> header file. */
#undef HAVE_FCNTL_H
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the `socket' library (-lsocket). */
#undef HAVE_LIBSOCKET
/* Define to 1 if you have the <limits.h> header file. */
#undef HAVE_LIMITS_H
/* Define to 1 if you have the `memmove' function. */
#undef HAVE_MEMMOVE
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
#undef HAVE_NDIR_H
/* Define to 1 if you have the <netdb.h> header file. */
#undef HAVE_NETDB_H
/* Define to 1 if you have the <netinet/in.h> header file. */
#undef HAVE_NETINET_IN_H
/* Define to 1 if RE2 should be used. */
#undef HAVE_RE2
/* Define to 1 if you have the `select' function. */
#undef HAVE_SELECT
/* Define to 1 if you have the `socket' function. */
#undef HAVE_SOCKET
/* Define to 1 if `stat' has the bug that it succeeds when given the
zero-length file name argument. */
#undef HAVE_STAT_EMPTY_STRING_BUG
/* Define to 1 if stdbool.h conforms to C99. */
#undef HAVE_STDBOOL_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the `strerror' function. */
#undef HAVE_STRERROR
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the `strtoul' function. */
#undef HAVE_STRTOUL
/* Define to 1 if you have the <syslog.h> header file. */
#undef HAVE_SYSLOG_H
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
#undef HAVE_SYS_DIR_H
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
#undef HAVE_SYS_NDIR_H
/* Define to 1 if you have the <sys/select.h> header file. */
#undef HAVE_SYS_SELECT_H
/* Define to 1 if you have the <sys/socket.h> header file. */
#undef HAVE_SYS_SOCKET_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/timeb.h> header file. */
#undef HAVE_SYS_TIMEB_H
/* Define to 1 if you have the <sys/time.h> header file. */
#undef HAVE_SYS_TIME_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
#undef HAVE_SYS_WAIT_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if the system has the type `_Bool'. */
#undef HAVE__BOOL
/* Define to 1 if `lstat' dereferences a symlink specified with a trailing
slash. */
#undef LSTAT_FOLLOWS_SLASHED_SYMLINK
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define as the return type of signal handlers (`int' or `void'). */
#undef RETSIGTYPE
/* Define to the type of arg 1 for `select'. */
#undef SELECT_TYPE_ARG1
/* Define to the type of args 2, 3 and 4 for `select'. */
#undef SELECT_TYPE_ARG234
/* Define to the type of arg 5 for `select'. */
#undef SELECT_TYPE_ARG5
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Version number of package */
#undef VERSION
/* the maximum number of states the regex NFA can have */
#undef _GLIBCXX_REGEX_STATE_LIMIT
/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
#undef _UINT32_T
/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
#undef _UINT64_T
/* we want C11 library extensions */
#ifndef __STDC_WANT_LIB_EXT1__
# define __STDC_WANT_LIB_EXT1__ 1
#endif
/* Define to empty if `const' does not conform to ANSI C. */
#undef const
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
#undef inline
#endif
/* Define to the type of a signed integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
#undef int32_t
/* Define to the type of a signed integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
#undef int64_t
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
/* Define to `int' if <sys/types.h> does not define. */
#undef ssize_t
/* Define to the type of an unsigned integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
#undef uint32_t
/* Define to the type of an unsigned integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
#undef uint64_t

1801
config.sub vendored Executable file

File diff suppressed because it is too large Load Diff

10407
configure vendored Executable file

File diff suppressed because it is too large Load Diff

216
configure.ac Normal file
View File

@@ -0,0 +1,216 @@
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.61)
AC_INIT([MK Livestatus], [1.5.0p23], [mk@mathias-kettner.de])
AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([config.h.in])
AC_CONFIG_HEADER([config.h])
AC_DEFINE_UNQUOTED([BUILD_DATE], ["`date -R`"], [build date])
AC_DEFINE_UNQUOTED([BUILD_HOSTNAME], ["`uname -n`"], [name of the build host])
AC_REQUIRE_AUX_FILE([compile])
AC_REQUIRE_AUX_FILE([config.guess])
AC_REQUIRE_AUX_FILE([config.sub])
# Old (pre-1.6.0) versions of librrd were not thread-safe, so one has to use the
# thread-safe variant librrd_th explicitly. This in itself is already tragic
# enough, but to make things worse, you can't write a compile-time check to
# distinguish these versions. :-/ So we default to the assumption that librrd is
# thread-safe (which is the case within OMD) and the user of e.g. a standalone
# version of Livestatus on an old system has to use the configure flag below.
# Not really nice, but we can't really do much about that.
AC_ARG_ENABLE([rrd-is-thread-safe],
AS_HELP_STRING([--disable-rrd-is-thread-safe], [Use librrd_th instead of librrd]))
AS_IF([test "x$enable_rrd_is_thread_safe" != "xno"], [RRDLIB_TO_CHECK=rrd],
[RRDLIB_TO_CHECK=rrd_th])
# Checks for programs.
AC_PROG_CC([gcc-9 clang-8 gcc-8 clang-7 gcc-7 clang-6.0 clang-5.0 gcc clang])
AC_PROG_CC_C99([], [])
if test "x$ac_cv_prog_cc_c99" = xno; then
AC_MSG_ERROR([Need a C99-compliant C compiler])
fi
AC_PROG_CXX([g++-9 clang++-8 g++-8 clang++-7 g++-7 clang++-6.0 clang++-5.0 g++ clang++])
AC_DEFINE_UNQUOTED([BUILD_CXX], ["`$CXX --version | head -n1`"], [C++ compiler])
AX_CXX_COMPILE_STDCXX([17], [noext], [mandatory])
AC_PROG_RANLIB
# automake 1.12 seems to require this, but automake 1.11 doesn't recognize it. :-P
m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
# Checks for libraries.
AC_CHECK_LIB(socket, socket)
AC_CHECK_LIB(socket, connect)
AC_CHECK_LIB(socket, shutdown)
# Passing through the right RRD library is a bit tricky: We can't simply put
# -lrrd_th or -lrrd globally into LIBS. The problem is that our SUID programs
# icmpsender and icmpreceiver would be linked with that option, too, but because
# of security reasons the dynamic linker will ignore our LD_LIBRARY_PATH => no
# RRD library found or even the wrong one... :-/
RRDLIB=
old_LIBS=$LIBS
AC_SEARCH_LIBS([rrd_xport], [$RRDLIB_TO_CHECK],
[test "$ac_cv_search_rrd_xport" = "none required" || RRDLIB="$ac_cv_search_rrd_xport"],
[AC_MSG_ERROR([unable to find the rrd_xport function])])
LIBS=$old_LIBS
AC_SUBST(RRDLIB)
# Checks for header files.
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_HEADER_SYS_WAIT
AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h netdb.h netinet/in.h stdint.h stdlib.h string.h strings.h sys/socket.h sys/time.h sys/timeb.h syslog.h unistd.h])
# Checks for C++ features
AX_BOOST_BASE(,,AC_MSG_ERROR([Boost library not found or too old]))
AX_BOOST_ASIO
if test "x$ax_cv_boost_asio" = xno; then
AC_MSG_ERROR([Boost::ASIO library not found])
fi
AC_LANG_PUSH([C++])
AC_MSG_CHECKING([whether C++17 headers are supported by default])
AC_COMPILE_IFELSE(
[AC_LANG_PROGRAM([#include <optional>
#include <shared_mutex>], [std::shared_mutex sm])],
[AC_MSG_RESULT([yes])],
[AC_MSG_RESULT([no])
CXX="$CXX -stdlib=libc++"
CXXCPP="$CXXCPP -stdlib=libc++"
AC_MSG_CHECKING([whether C++17 headers are supported with -stdlib=libc++])
AC_COMPILE_IFELSE(
[AC_LANG_PROGRAM([#include <optional>
#include <shared_mutex>], [std::shared_mutex sm])],
[AC_MSG_RESULT([yes])],
[AC_MSG_RESULT([no])
AC_MSG_ERROR([C++ headers are too old. Please install a newer g++/clang/libc++-dev package.])])])
# RE2 stuff
AC_ARG_WITH([re2],
[AS_HELP_STRING([--with-re2@<:@=ARG@:>@],
[use RE2 library from a standard location (ARG=yes),
from the specified location (ARG=<path>),
or disable it (ARG=no) @<:@ARG=no@:>@ ])],
[AS_CASE([$withval],
[no],[want_re2="no";_AX_RE2_BASE_re2_path=""],
[yes],[want_re2="yes";_AX_RE2_BASE_re2_path=""],
[want_re2="yes";_AX_RE2_BASE_re2_path="$withval"])],
[want_re2="no"])
RE2_CPPFLAGS=""
RE2_LDFLAGS=""
RE2_LIBS=""
AS_IF([test "x$want_re2" = "xyes"],
[AS_IF([test "x$_AX_RE2_BASE_re2_path" != x],
[RE2_CPPFLAGS="-I$_AX_RE2_BASE_re2_path/include"
RE2_LDFLAGS="-L$_AX_RE2_BASE_re2_path/lib"])
RE2_LIBS="-lre2"
CPPFLAGS_SAVED=$CPPFLAGS
CPPFLAGS="$CPPFLAGS $RE2_CPPFLAGS"
AC_CHECK_HEADER([re2/re2.h], [], [AC_MSG_ERROR([could not find a working RE2 header])])
AC_MSG_CHECKING([for RE2 library])
LDFLAGS_SAVED=$LDFLAGS
LDFLAGS="$LDFLAGS $RE2_LDFLAGS"
LIBS_SAVED=$LIBS
LIBS="$LIBS $RE2_LIBS -pthread"
AC_LINK_IFELSE([AC_LANG_PROGRAM([[@%:@include <re2/re2.h>]],
[[RE2::FullMatch("hello", "e")]])],
[AC_MSG_RESULT([yes])],
[AC_MSG_RESULT([no])
AC_MSG_ERROR([could not find a working RE2 library])])
LIBS=$LIBS_SAVED
LDFLAGS=$LDFLAGS_SAVED
CPPFLAGS=$CPPFLAGS_SAVED
AC_DEFINE([HAVE_RE2], [1], [Define to 1 if RE2 should be used.])])
AC_SUBST(RE2_CPPFLAGS)
AC_SUBST(RE2_LDFLAGS)
AC_SUBST(RE2_LIBS)
AC_LANG_POP([C++])
# Checks for typedefs, structures, and compiler characteristics.
AC_HEADER_STDBOOL
AC_C_CONST
AC_C_INLINE
AC_TYPE_INT32_T
AC_TYPE_INT64_T
AC_TYPE_SIZE_T
AC_TYPE_SSIZE_T
AC_HEADER_TIME
AC_TYPE_UINT32_T
AC_TYPE_UINT64_T
# Checks for library functions.
AC_FUNC_SELECT_ARGTYPES
AC_TYPE_SIGNAL
AC_FUNC_STAT
AC_CHECK_FUNCS([accept4 memmove select socket strerror strtoul])
AC_ARG_WITH(nagios4,AC_HELP_STRING([--with-nagios4],[enabled compilation for nagios 4]), [
CPPFLAGS="${CFLAGS} -DNAGIOS4"
nagios_headers=nagios4
],
nagios_headers=nagios)
AC_SUBST(nagios_headers)
# Compiling or executing a std::regex can fail with a stack overflow, causing
# our Livestatus threads to die, see e.g. the related bug report
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61582. A workaround for this is
# to limit the number of NFA states, but this must be done at compile-time. To
# be sure that the limit is defined before <regex> is included, we set it
# here. If the limit is reached during runtime, the regex library will throw a
# std::regex_error with a std::regex_constants::error_space code. This whole
# thing is a kind of a hack, but currently there seems to be no way around that,
# at least not until the libstdc++ uses heap allocated memory instead of the
# stack... :-/
#
# Some numbers for x86_64: At the point where we compile or execute a regex, we
# already use almost 12kB stack. For compilation of a regex, each level of
# recursion uses additional 112 bytes. For executing a regex, each level of
# recursion uses additional 384 bytes. Our current stack size for the Livestatus
# threads is 1MB, so we can handle roughly 2700 states. To be on the safe side,
# we leave some breathing room and use a slightly lower limit.
AC_DEFINE([_GLIBCXX_REGEX_STATE_LIMIT], [2500],
[the maximum number of states the regex NFA can have])
AC_DEFINE([BOOST_SYSTEM_NO_DEPRECATED], [1], [we do not want any old stuff])
# GCC is a bit picky about redefinitions of built-in macros. Alas, "built-in"
# simply means "starts with double underscore", so we have to hack around that
# below. Note that clang is happy, even without the guard.
AH_VERBATIM([__STDC_WANT_LIB_EXT1__], [/* we want C11 library extensions */
#ifndef __STDC_WANT_LIB_EXT1__
# define __STDC_WANT_LIB_EXT1__ 1
#endif])
# HACKING ALERT: automake can't really handle optional subdirectories, so we
# have to do this in a slightly hacky way by using M4's silent includes.
m4_sinclude([livestatus/config_files.m4])
m4_sinclude([enterprise/config_files.m4])
m4_sinclude([standalone/config_files.m4])
AC_OUTPUT

791
depcomp Executable file
View File

@@ -0,0 +1,791 @@
#! /bin/sh
# depcomp - compile a program generating dependencies as side-effects
scriptversion=2016-01-11.22; # UTC
# Copyright (C) 1999-2017 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
Run PROGRAMS ARGS to compile a file, generating dependencies
as side-effects.
Environment variables:
depmode Dependency tracking mode.
source Source file read by 'PROGRAMS ARGS'.
object Object file output by 'PROGRAMS ARGS'.
DEPDIR directory where to store dependencies.
depfile Dependency file to output.
tmpdepfile Temporary file to use when outputting dependencies.
libtool Whether libtool is used (yes/no).
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "depcomp $scriptversion"
exit $?
;;
esac
# Get the directory component of the given path, and save it in the
# global variables '$dir'. Note that this directory component will
# be either empty or ending with a '/' character. This is deliberate.
set_dir_from ()
{
case $1 in
*/*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;;
*) dir=;;
esac
}
# Get the suffix-stripped basename of the given path, and save it the
# global variable '$base'.
set_base_from ()
{
base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'`
}
# If no dependency file was actually created by the compiler invocation,
# we still have to create a dummy depfile, to avoid errors with the
# Makefile "include basename.Plo" scheme.
make_dummy_depfile ()
{
echo "#dummy" > "$depfile"
}
# Factor out some common post-processing of the generated depfile.
# Requires the auxiliary global variable '$tmpdepfile' to be set.
aix_post_process_depfile ()
{
# If the compiler actually managed to produce a dependency file,
# post-process it.
if test -f "$tmpdepfile"; then
# Each line is of the form 'foo.o: dependency.h'.
# Do two passes, one to just change these to
# $object: dependency.h
# and one to simply output
# dependency.h:
# which is needed to avoid the deleted-header problem.
{ sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile"
sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile"
} > "$depfile"
rm -f "$tmpdepfile"
else
make_dummy_depfile
fi
}
# A tabulation character.
tab=' '
# A newline character.
nl='
'
# Character ranges might be problematic outside the C locale.
# These definitions help.
upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lower=abcdefghijklmnopqrstuvwxyz
digits=0123456789
alpha=${upper}${lower}
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
echo "depcomp: Variables source, object and depmode must be set" 1>&2
exit 1
fi
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
depfile=${depfile-`echo "$object" |
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
rm -f "$tmpdepfile"
# Avoid interferences from the environment.
gccflag= dashmflag=
# Some modes work just like other modes, but use different flags. We
# parameterize here, but still list the modes in the big case below,
# to make depend.m4 easier to write. Note that we *cannot* use a case
# here, because this file can only contain one case statement.
if test "$depmode" = hp; then
# HP compiler uses -M and no extra arg.
gccflag=-M
depmode=gcc
fi
if test "$depmode" = dashXmstdout; then
# This is just like dashmstdout with a different argument.
dashmflag=-xM
depmode=dashmstdout
fi
cygpath_u="cygpath -u -f -"
if test "$depmode" = msvcmsys; then
# This is just like msvisualcpp but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvisualcpp
fi
if test "$depmode" = msvc7msys; then
# This is just like msvc7 but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvc7
fi
if test "$depmode" = xlc; then
# IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information.
gccflag=-qmakedep=gcc,-MF
depmode=gcc
fi
case "$depmode" in
gcc3)
## gcc 3 implements dependency tracking that does exactly what
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
## it if -MD -MP comes after the -MF stuff. Hmm.
## Unfortunately, FreeBSD c89 acceptance of flags depends upon
## the command line argument order; so add the flags where they
## appear in depend2.am. Note that the slowdown incurred here
## affects only configure: in makefiles, %FASTDEP% shortcuts this.
for arg
do
case $arg in
-c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
*) set fnord "$@" "$arg" ;;
esac
shift # fnord
shift # $arg
done
"$@"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
mv "$tmpdepfile" "$depfile"
;;
gcc)
## Note that this doesn't just cater to obsosete pre-3.x GCC compilers.
## but also to in-use compilers like IMB xlc/xlC and the HP C compiler.
## (see the conditional assignment to $gccflag above).
## There are various ways to get dependency output from gcc. Here's
## why we pick this rather obscure method:
## - Don't want to use -MD because we'd like the dependencies to end
## up in a subdir. Having to rename by hand is ugly.
## (We might end up doing this anyway to support other compilers.)
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
## -MM, not -M (despite what the docs say). Also, it might not be
## supported by the other compilers which use the 'gcc' depmode.
## - Using -M directly means running the compiler twice (even worse
## than renaming).
if test -z "$gccflag"; then
gccflag=-MD,
fi
"$@" -Wp,"$gccflag$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The second -e expression handles DOS-style file names with drive
# letters.
sed -e 's/^[^:]*: / /' \
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
## This next piece of magic avoids the "deleted header file" problem.
## The problem is that when a header file which appears in a .P file
## is deleted, the dependency causes make to die (because there is
## typically no way to rebuild the header). We avoid this by adding
## dummy dependencies for each header file. Too bad gcc doesn't do
## this for us directly.
## Some versions of gcc put a space before the ':'. On the theory
## that the space means something, we add a space to the output as
## well. hp depmode also adds that space, but also prefixes the VPATH
## to the object. Take care to not repeat it in the output.
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
sgi)
if test "$libtool" = yes; then
"$@" "-Wp,-MDupdate,$tmpdepfile"
else
"$@" -MDupdate "$tmpdepfile"
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
echo "$object : \\" > "$depfile"
# Clip off the initial element (the dependent). Don't try to be
# clever and replace this with sed code, as IRIX sed won't handle
# lines with more than a fixed number of characters (4096 in
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
# the IRIX cc adds comments like '#:fec' to the end of the
# dependency line.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \
| tr "$nl" ' ' >> "$depfile"
echo >> "$depfile"
# The second pass generates a dummy entry for each header file.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
>> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile"
;;
xlc)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
aix)
# The C for AIX Compiler uses -M and outputs the dependencies
# in a .u file. In older versions, this file always lives in the
# current directory. Also, the AIX compiler puts '$object:' at the
# start of each line; $object doesn't have directory information.
# Version 6 uses the directory in both cases.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.u
tmpdepfile2=$base.u
tmpdepfile3=$dir.libs/$base.u
"$@" -Wc,-M
else
tmpdepfile1=$dir$base.u
tmpdepfile2=$dir$base.u
tmpdepfile3=$dir$base.u
"$@" -M
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
aix_post_process_depfile
;;
tcc)
# tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26
# FIXME: That version still under development at the moment of writing.
# Make that this statement remains true also for stable, released
# versions.
# It will wrap lines (doesn't matter whether long or short) with a
# trailing '\', as in:
#
# foo.o : \
# foo.c \
# foo.h \
#
# It will put a trailing '\' even on the last line, and will use leading
# spaces rather than leading tabs (at least since its commit 0394caf7
# "Emit spaces for -MD").
"$@" -MD -MF "$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each non-empty line is of the form 'foo.o : \' or ' dep.h \'.
# We have to change lines of the first kind to '$object: \'.
sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile"
# And for each line of the second kind, we have to emit a 'dep.h:'
# dummy dependency, to avoid the deleted-header problem.
sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile"
rm -f "$tmpdepfile"
;;
## The order of this option in the case statement is important, since the
## shell code in configure will try each of these formats in the order
## listed in this file. A plain '-MD' option would be understood by many
## compilers, so we must ensure this comes after the gcc and icc options.
pgcc)
# Portland's C compiler understands '-MD'.
# Will always output deps to 'file.d' where file is the root name of the
# source file under compilation, even if file resides in a subdirectory.
# The object file name does not affect the name of the '.d' file.
# pgcc 10.2 will output
# foo.o: sub/foo.c sub/foo.h
# and will wrap long lines using '\' :
# foo.o: sub/foo.c ... \
# sub/foo.h ... \
# ...
set_dir_from "$object"
# Use the source, not the object, to determine the base name, since
# that's sadly what pgcc will do too.
set_base_from "$source"
tmpdepfile=$base.d
# For projects that build the same source file twice into different object
# files, the pgcc approach of using the *source* file root name can cause
# problems in parallel builds. Use a locking strategy to avoid stomping on
# the same $tmpdepfile.
lockdir=$base.d-lock
trap "
echo '$0: caught signal, cleaning up...' >&2
rmdir '$lockdir'
exit 1
" 1 2 13 15
numtries=100
i=$numtries
while test $i -gt 0; do
# mkdir is a portable test-and-set.
if mkdir "$lockdir" 2>/dev/null; then
# This process acquired the lock.
"$@" -MD
stat=$?
# Release the lock.
rmdir "$lockdir"
break
else
# If the lock is being held by a different process, wait
# until the winning process is done or we timeout.
while test -d "$lockdir" && test $i -gt 0; do
sleep 1
i=`expr $i - 1`
done
fi
i=`expr $i - 1`
done
trap - 1 2 13 15
if test $i -le 0; then
echo "$0: failed to acquire lock after $numtries attempts" >&2
echo "$0: check lockdir '$lockdir'" >&2
exit 1
fi
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each line is of the form `foo.o: dependent.h',
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp2)
# The "hp" stanza above does not work with aCC (C++) and HP's ia64
# compilers, which have integrated preprocessors. The correct option
# to use with these is +Maked; it writes dependencies to a file named
# 'foo.d', which lands next to the object file, wherever that
# happens to be.
# Much of this is similar to the tru64 case; see comments there.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir.libs/$base.d
"$@" -Wc,+Maked
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
"$@" +Maked
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile"
# Add 'dependent.h:' lines.
sed -ne '2,${
s/^ *//
s/ \\*$//
s/$/:/
p
}' "$tmpdepfile" >> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile" "$tmpdepfile2"
;;
tru64)
# The Tru64 compiler uses -MD to generate dependencies as a side
# effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'.
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
# dependencies in 'foo.d' instead, so we check for that too.
# Subdirectories are respected.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
# Libtool generates 2 separate objects for the 2 libraries. These
# two compilations output dependencies in $dir.libs/$base.o.d and
# in $dir$base.o.d. We have to check for both files, because
# one of the two compilations can be disabled. We should prefer
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
# automatically cleaned when .libs/ is deleted, while ignoring
# the former would cause a distcleancheck panic.
tmpdepfile1=$dir$base.o.d # libtool 1.5
tmpdepfile2=$dir.libs/$base.o.d # Likewise.
tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504
"$@" -Wc,-MD
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
tmpdepfile3=$dir$base.d
"$@" -MD
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
# Same post-processing that is required for AIX mode.
aix_post_process_depfile
;;
msvc7)
if test "$libtool" = yes; then
showIncludes=-Wc,-showIncludes
else
showIncludes=-showIncludes
fi
"$@" $showIncludes > "$tmpdepfile"
stat=$?
grep -v '^Note: including file: ' "$tmpdepfile"
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The first sed program below extracts the file names and escapes
# backslashes for cygpath. The second sed program outputs the file
# name when reading, but also accumulates all include files in the
# hold buffer in order to output them again at the end. This only
# works with sed implementations that can handle large buffers.
sed < "$tmpdepfile" -n '
/^Note: including file: *\(.*\)/ {
s//\1/
s/\\/\\\\/g
p
}' | $cygpath_u | sort -u | sed -n '
s/ /\\ /g
s/\(.*\)/'"$tab"'\1 \\/p
s/.\(.*\) \\/\1:/
H
$ {
s/.*/'"$tab"'/
G
p
}' >> "$depfile"
echo >> "$depfile" # make sure the fragment doesn't end with a backslash
rm -f "$tmpdepfile"
;;
msvc7msys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
#nosideeffect)
# This comment above is used by automake to tell side-effect
# dependency tracking mechanisms from slower ones.
dashmstdout)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
test -z "$dashmflag" && dashmflag=-M
# Require at least two characters before searching for ':'
# in the target name. This is to cope with DOS-style filenames:
# a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise.
"$@" $dashmflag |
sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this sed invocation
# correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
dashXmstdout)
# This case only exists to satisfy depend.m4. It is never actually
# run, as this mode is specially recognized in the preamble.
exit 1
;;
makedepend)
"$@" || exit $?
# Remove any Libtool call
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# X makedepend
shift
cleared=no eat=no
for arg
do
case $cleared in
no)
set ""; shift
cleared=yes ;;
esac
if test $eat = yes; then
eat=no
continue
fi
case "$arg" in
-D*|-I*)
set fnord "$@" "$arg"; shift ;;
# Strip any option that makedepend may not understand. Remove
# the object too, otherwise makedepend will parse it as a source file.
-arch)
eat=yes ;;
-*|$object)
;;
*)
set fnord "$@" "$arg"; shift ;;
esac
done
obj_suffix=`echo "$object" | sed 's/^.*\././'`
touch "$tmpdepfile"
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
rm -f "$depfile"
# makedepend may prepend the VPATH from the source file name to the object.
# No need to regex-escape $object, excess matching of '.' is harmless.
sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process the last invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed '1,2d' "$tmpdepfile" \
| tr ' ' "$nl" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile" "$tmpdepfile".bak
;;
cpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
"$@" -E \
| sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
| sed '$ s: \\$::' > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
cat < "$tmpdepfile" >> "$depfile"
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvisualcpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
IFS=" "
for arg
do
case "$arg" in
-o)
shift
;;
$object)
shift
;;
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
set fnord "$@"
shift
shift
;;
*)
set fnord "$@" "$arg"
shift
shift
;;
esac
done
"$@" -E 2>/dev/null |
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile"
echo "$tab" >> "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvcmsys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
none)
exec "$@"
;;
*)
echo "Unknown depmode $depmode" 1>&2
exit 1
;;
esac
exit 0
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:

508
install-sh Executable file
View File

@@ -0,0 +1,508 @@
#!/bin/sh
# install - install a program, script, or datafile
scriptversion=2014-09-12.12; # UTC
# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# 'make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
tab=' '
nl='
'
IFS=" $tab$nl"
# Set DOITPROG to "echo" to test this script.
doit=${DOITPROG-}
doit_exec=${doit:-exec}
# Put in absolute file names if you don't have them in your path;
# or use environment vars.
chgrpprog=${CHGRPPROG-chgrp}
chmodprog=${CHMODPROG-chmod}
chownprog=${CHOWNPROG-chown}
cmpprog=${CMPPROG-cmp}
cpprog=${CPPROG-cp}
mkdirprog=${MKDIRPROG-mkdir}
mvprog=${MVPROG-mv}
rmprog=${RMPROG-rm}
stripprog=${STRIPPROG-strip}
posix_mkdir=
# Desired mode of installed file.
mode=0755
chgrpcmd=
chmodcmd=$chmodprog
chowncmd=
mvcmd=$mvprog
rmcmd="$rmprog -f"
stripcmd=
src=
dst=
dir_arg=
dst_arg=
copy_on_change=false
is_target_a_directory=possibly
usage="\
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
or: $0 [OPTION]... SRCFILES... DIRECTORY
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
or: $0 [OPTION]... -d DIRECTORIES...
In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.
Options:
--help display this help and exit.
--version display version info and exit.
-c (ignored)
-C install only if different (preserve the last data modification time)
-d create directories instead of installing files.
-g GROUP $chgrpprog installed files to GROUP.
-m MODE $chmodprog installed files to MODE.
-o USER $chownprog installed files to USER.
-s $stripprog installed files.
-t DIRECTORY install into DIRECTORY.
-T report an error if DSTFILE is a directory.
Environment variables override the default commands:
CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
RMPROG STRIPPROG
"
while test $# -ne 0; do
case $1 in
-c) ;;
-C) copy_on_change=true;;
-d) dir_arg=true;;
-g) chgrpcmd="$chgrpprog $2"
shift;;
--help) echo "$usage"; exit $?;;
-m) mode=$2
case $mode in
*' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
echo "$0: invalid mode: $mode" >&2
exit 1;;
esac
shift;;
-o) chowncmd="$chownprog $2"
shift;;
-s) stripcmd=$stripprog;;
-t)
is_target_a_directory=always
dst_arg=$2
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
shift;;
-T) is_target_a_directory=never;;
--version) echo "$0 $scriptversion"; exit $?;;
--) shift
break;;
-*) echo "$0: invalid option: $1" >&2
exit 1;;
*) break;;
esac
shift
done
# We allow the use of options -d and -T together, by making -d
# take the precedence; this is for compatibility with GNU install.
if test -n "$dir_arg"; then
if test -n "$dst_arg"; then
echo "$0: target directory not allowed when installing a directory." >&2
exit 1
fi
fi
if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
# When -d is used, all remaining arguments are directories to create.
# When -t is used, the destination is already specified.
# Otherwise, the last argument is the destination. Remove it from $@.
for arg
do
if test -n "$dst_arg"; then
# $@ is not empty: it contains at least $arg.
set fnord "$@" "$dst_arg"
shift # fnord
fi
shift # arg
dst_arg=$arg
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
done
fi
if test $# -eq 0; then
if test -z "$dir_arg"; then
echo "$0: no input file specified." >&2
exit 1
fi
# It's OK to call 'install-sh -d' without argument.
# This can happen when creating conditional directories.
exit 0
fi
if test -z "$dir_arg"; then
if test $# -gt 1 || test "$is_target_a_directory" = always; then
if test ! -d "$dst_arg"; then
echo "$0: $dst_arg: Is not a directory." >&2
exit 1
fi
fi
fi
if test -z "$dir_arg"; then
do_exit='(exit $ret); exit $ret'
trap "ret=129; $do_exit" 1
trap "ret=130; $do_exit" 2
trap "ret=141; $do_exit" 13
trap "ret=143; $do_exit" 15
# Set umask so as not to create temps with too-generous modes.
# However, 'strip' requires both read and write access to temps.
case $mode in
# Optimize common cases.
*644) cp_umask=133;;
*755) cp_umask=22;;
*[0-7])
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw='% 200'
fi
cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
*)
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw=,u+rw
fi
cp_umask=$mode$u_plus_rw;;
esac
fi
for src
do
# Protect names problematic for 'test' and other utilities.
case $src in
-* | [=\(\)!]) src=./$src;;
esac
if test -n "$dir_arg"; then
dst=$src
dstdir=$dst
test -d "$dstdir"
dstdir_status=$?
else
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if test ! -f "$src" && test ! -d "$src"; then
echo "$0: $src does not exist." >&2
exit 1
fi
if test -z "$dst_arg"; then
echo "$0: no destination specified." >&2
exit 1
fi
dst=$dst_arg
# If destination is a directory, append the input filename; won't work
# if double slashes aren't ignored.
if test -d "$dst"; then
if test "$is_target_a_directory" = never; then
echo "$0: $dst_arg: Is a directory" >&2
exit 1
fi
dstdir=$dst
dst=$dstdir/`basename "$src"`
dstdir_status=0
else
dstdir=`dirname "$dst"`
test -d "$dstdir"
dstdir_status=$?
fi
fi
obsolete_mkdir_used=false
if test $dstdir_status != 0; then
case $posix_mkdir in
'')
# Create intermediate dirs using mode 755 as modified by the umask.
# This is like FreeBSD 'install' as of 1997-10-28.
umask=`umask`
case $stripcmd.$umask in
# Optimize common cases.
*[2367][2367]) mkdir_umask=$umask;;
.*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
*[0-7])
mkdir_umask=`expr $umask + 22 \
- $umask % 100 % 40 + $umask % 20 \
- $umask % 10 % 4 + $umask % 2
`;;
*) mkdir_umask=$umask,go-w;;
esac
# With -d, create the new directory with the user-specified mode.
# Otherwise, rely on $mkdir_umask.
if test -n "$dir_arg"; then
mkdir_mode=-m$mode
else
mkdir_mode=
fi
posix_mkdir=false
case $umask in
*[123567][0-7][0-7])
# POSIX mkdir -p sets u+wx bits regardless of umask, which
# is incompatible with FreeBSD 'install' when (umask & 300) != 0.
;;
*)
# $RANDOM is not portable (e.g. dash); use it when possible to
# lower collision chance
tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
trap 'ret=$?; rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null; exit $ret' 0
# As "mkdir -p" follows symlinks and we work in /tmp possibly; so
# create the $tmpdir first (and fail if unsuccessful) to make sure
# that nobody tries to guess the $tmpdir name.
if (umask $mkdir_umask &&
$mkdirprog $mkdir_mode "$tmpdir" &&
exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
then
if test -z "$dir_arg" || {
# Check for POSIX incompatibilities with -m.
# HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
# other-writable bit of parent directory when it shouldn't.
# FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
test_tmpdir="$tmpdir/a"
ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
case $ls_ld_tmpdir in
d????-?r-*) different_mode=700;;
d????-?--*) different_mode=755;;
*) false;;
esac &&
$mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
}
}
then posix_mkdir=:
fi
rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
else
# Remove any dirs left behind by ancient mkdir implementations.
rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
fi
trap '' 0;;
esac;;
esac
if
$posix_mkdir && (
umask $mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
)
then :
else
# The umask is ridiculous, or mkdir does not conform to POSIX,
# or it failed possibly due to a race condition. Create the
# directory the slow way, step by step, checking for races as we go.
case $dstdir in
/*) prefix='/';;
[-=\(\)!]*) prefix='./';;
*) prefix='';;
esac
oIFS=$IFS
IFS=/
set -f
set fnord $dstdir
shift
set +f
IFS=$oIFS
prefixes=
for d
do
test X"$d" = X && continue
prefix=$prefix$d
if test -d "$prefix"; then
prefixes=
else
if $posix_mkdir; then
(umask=$mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
# Don't fail if two instances are running concurrently.
test -d "$prefix" || exit 1
else
case $prefix in
*\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
*) qprefix=$prefix;;
esac
prefixes="$prefixes '$qprefix'"
fi
fi
prefix=$prefix/
done
if test -n "$prefixes"; then
# Don't fail if two instances are running concurrently.
(umask $mkdir_umask &&
eval "\$doit_exec \$mkdirprog $prefixes") ||
test -d "$dstdir" || exit 1
obsolete_mkdir_used=true
fi
fi
fi
if test -n "$dir_arg"; then
{ test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
{ test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
else
# Make a couple of temp file names in the proper directory.
dsttmp=$dstdir/_inst.$$_
rmtmp=$dstdir/_rm.$$_
# Trap to clean up those temp files at exit.
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
# Copy the file name to the temp name.
(umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
# and set any options; do chmod last to preserve setuid bits.
#
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $cpprog $src $dsttmp" command.
#
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
{ test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
{ test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
# If -C, don't bother to copy if it wouldn't change the file.
if $copy_on_change &&
old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` &&
new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
set -f &&
set X $old && old=:$2:$4:$5:$6 &&
set X $new && new=:$2:$4:$5:$6 &&
set +f &&
test "$old" = "$new" &&
$cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
then
rm -f "$dsttmp"
else
# Rename the file to the real destination.
$doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
# The rename failed, perhaps because mv can't rename something else
# to itself, or perhaps because mv is so ancient that it does not
# support -f.
{
# Now remove or move aside any old file at destination location.
# We try this two ways since rm can't unlink itself on some
# systems and the destination file might be busy for other
# reasons. In this case, the final cleanup might fail but the new
# file should still install successfully.
{
test ! -f "$dst" ||
$doit $rmcmd -f "$dst" 2>/dev/null ||
{ $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
{ $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
} ||
{ echo "$0: cannot unlink or rename $dst" >&2
(exit 1); exit 1
}
} &&
# Now rename the file to the real destination.
$doit $mvcmd "$dsttmp" "$dst"
}
fi || exit 1
trap '' 0
fi
done
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC"
# time-stamp-end: "; # UTC"
# End:

115
m4/ax_boost_asio.m4 Normal file
View File

@@ -0,0 +1,115 @@
# ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_boost_asio.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_BOOST_ASIO
#
# DESCRIPTION
#
# Test for Asio library from the Boost C++ libraries. The macro requires a
# preceding call to AX_BOOST_BASE. Further documentation is available at
# <http://randspringer.de/boost/index.html>.
#
# This macro calls:
#
# AC_SUBST(BOOST_ASIO_LIB)
#
# And sets:
#
# HAVE_BOOST_ASIO
#
# LICENSE
#
# Copyright (c) 2008 Thomas Porschberg <thomas@randspringer.de>
# Copyright (c) 2008 Pete Greenwell <pete@mu.org>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 17
AC_DEFUN([AX_BOOST_ASIO],
[
AC_ARG_WITH([boost-asio],
AS_HELP_STRING([--with-boost-asio@<:@=special-lib@:>@],
[use the ASIO library from boost - it is possible to specify a certain library for the linker
e.g. --with-boost-asio=boost_system-gcc41-mt-1_34 ]),
[
if test "$withval" = "no"; then
want_boost="no"
elif test "$withval" = "yes"; then
want_boost="yes"
ax_boost_user_asio_lib=""
else
want_boost="yes"
ax_boost_user_asio_lib="$withval"
fi
],
[want_boost="yes"]
)
if test "x$want_boost" = "xyes"; then
AC_REQUIRE([AC_PROG_CC])
CPPFLAGS_SAVED="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
export CPPFLAGS
LDFLAGS_SAVED="$LDFLAGS"
LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
export LDFLAGS
AC_CACHE_CHECK(whether the Boost::ASIO library is available,
ax_cv_boost_asio,
[AC_LANG_PUSH([C++])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ @%:@include <boost/asio.hpp>
]],
[[
boost::asio::io_service io;
boost::system::error_code timer_result;
boost::asio::deadline_timer t(io);
t.cancel();
io.run_one();
return 0;
]])],
ax_cv_boost_asio=yes, ax_cv_boost_asio=no)
AC_LANG_POP([C++])
])
if test "x$ax_cv_boost_asio" = "xyes"; then
AC_DEFINE(HAVE_BOOST_ASIO,,[define if the Boost::ASIO library is available])
BN=boost_system
BOOSTLIBDIR=`echo $BOOST_LDFLAGS | sed -e 's/@<:@^\/@:>@*//'`
# NOTE: The AC_LANG_PUSH/POP below is a local modification! Without it, AC_CHECK_LIB
# would use the C compiler for compilation and linking of C++ libraries, which is wrong
# in general: C++ compilers usually add some magic linking flags etc. behind the scenes.
AC_LANG_PUSH([C++])
if test "x$ax_boost_user_asio_lib" = "x"; then
for ax_lib in `ls $BOOSTLIBDIR/libboost_system*.so* $BOOSTLIBDIR/libboost_system*.dylib* $BOOSTLIBDIR/libboost_system*.a* 2>/dev/null | sed 's,.*/,,' | sed -e 's;^lib\(boost_system.*\)\.so.*$;\1;' -e 's;^lib\(boost_system.*\)\.dylib.*$;\1;' -e 's;^lib\(boost_system.*\)\.a.*$;\1;' ` ; do
AC_CHECK_LIB($ax_lib, main, [BOOST_ASIO_LIB="-l$ax_lib" AC_SUBST(BOOST_ASIO_LIB) link_thread="yes" break],
[link_thread="no"])
done
else
for ax_lib in $ax_boost_user_asio_lib $BN-$ax_boost_user_asio_lib; do
AC_CHECK_LIB($ax_lib, main,
[BOOST_ASIO_LIB="-l$ax_lib" AC_SUBST(BOOST_ASIO_LIB) link_asio="yes" break],
[link_asio="no"])
done
fi
AC_LANG_POP([C++])
if test "x$ax_lib" = "x"; then
AC_MSG_ERROR(Could not find a version of the library!)
fi
if test "x$link_asio" = "xno"; then
AC_MSG_ERROR(Could not link against $ax_lib !)
fi
fi
CPPFLAGS="$CPPFLAGS_SAVED"
LDFLAGS="$LDFLAGS_SAVED"
fi
])

301
m4/ax_boost_base.m4 Normal file
View File

@@ -0,0 +1,301 @@
# ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_boost_base.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_BOOST_BASE([MINIMUM-VERSION], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# DESCRIPTION
#
# Test for the Boost C++ libraries of a particular version (or newer)
#
# If no path to the installed boost library is given the macro searchs
# under /usr, /usr/local, /opt and /opt/local and evaluates the
# $BOOST_ROOT environment variable. Further documentation is available at
# <http://randspringer.de/boost/index.html>.
#
# This macro calls:
#
# AC_SUBST(BOOST_CPPFLAGS) / AC_SUBST(BOOST_LDFLAGS)
#
# And sets:
#
# HAVE_BOOST
#
# LICENSE
#
# Copyright (c) 2008 Thomas Porschberg <thomas@randspringer.de>
# Copyright (c) 2009 Peter Adolphs
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 43
# example boost program (need to pass version)
m4_define([_AX_BOOST_BASE_PROGRAM],
[AC_LANG_PROGRAM([[
#include <boost/version.hpp>
]],[[
(void) ((void)sizeof(char[1 - 2*!!((BOOST_VERSION) < ($1))]));
]])])
AC_DEFUN([AX_BOOST_BASE],
[
AC_ARG_WITH([boost],
[AS_HELP_STRING([--with-boost@<:@=ARG@:>@],
[use Boost library from a standard location (ARG=yes),
from the specified location (ARG=<path>),
or disable it (ARG=no)
@<:@ARG=yes@:>@ ])],
[
AS_CASE([$withval],
[no],[want_boost="no";_AX_BOOST_BASE_boost_path=""],
[yes],[want_boost="yes";_AX_BOOST_BASE_boost_path=""],
[want_boost="yes";_AX_BOOST_BASE_boost_path="$withval"])
],
[want_boost="yes"])
AC_ARG_WITH([boost-libdir],
[AS_HELP_STRING([--with-boost-libdir=LIB_DIR],
[Force given directory for boost libraries.
Note that this will override library path detection,
so use this parameter only if default library detection fails
and you know exactly where your boost libraries are located.])],
[
AS_IF([test -d "$withval"],
[_AX_BOOST_BASE_boost_lib_path="$withval"],
[AC_MSG_ERROR([--with-boost-libdir expected directory name])])
],
[_AX_BOOST_BASE_boost_lib_path=""])
BOOST_LDFLAGS=""
BOOST_CPPFLAGS=""
AS_IF([test "x$want_boost" = "xyes"],
[_AX_BOOST_BASE_RUNDETECT([$1],[$2],[$3])])
AC_SUBST(BOOST_CPPFLAGS)
AC_SUBST(BOOST_LDFLAGS)
])
# convert a version string in $2 to numeric and affect to polymorphic var $1
AC_DEFUN([_AX_BOOST_BASE_TONUMERICVERSION],[
AS_IF([test "x$2" = "x"],[_AX_BOOST_BASE_TONUMERICVERSION_req="1.20.0"],[_AX_BOOST_BASE_TONUMERICVERSION_req="$2"])
_AX_BOOST_BASE_TONUMERICVERSION_req_shorten=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\.[[0-9]]*\)'`
_AX_BOOST_BASE_TONUMERICVERSION_req_major=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\)'`
AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_major" = "x"],
[AC_MSG_ERROR([You should at least specify libboost major version])])
_AX_BOOST_BASE_TONUMERICVERSION_req_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.\([[0-9]]*\)'`
AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_minor" = "x"],
[_AX_BOOST_BASE_TONUMERICVERSION_req_minor="0"])
_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'`
AS_IF([test "X$_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor" = "X"],
[_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor="0"])
_AX_BOOST_BASE_TONUMERICVERSION_RET=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req_major \* 100000 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_minor \* 100 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor`
AS_VAR_SET($1,$_AX_BOOST_BASE_TONUMERICVERSION_RET)
])
dnl Run the detection of boost should be run only if $want_boost
AC_DEFUN([_AX_BOOST_BASE_RUNDETECT],[
_AX_BOOST_BASE_TONUMERICVERSION(WANT_BOOST_VERSION,[$1])
succeeded=no
AC_REQUIRE([AC_CANONICAL_HOST])
dnl On 64-bit systems check for system libraries in both lib64 and lib.
dnl The former is specified by FHS, but e.g. Debian does not adhere to
dnl this (as it rises problems for generic multi-arch support).
dnl The last entry in the list is chosen by default when no libraries
dnl are found, e.g. when only header-only libraries are installed!
AS_CASE([${host_cpu}],
[x86_64],[libsubdirs="lib64 libx32 lib lib64"],
[ppc64|s390x|sparc64|aarch64|ppc64le],[libsubdirs="lib64 lib lib64"],
[libsubdirs="lib"]
)
dnl allow for real multi-arch paths e.g. /usr/lib/x86_64-linux-gnu. Give
dnl them priority over the other paths since, if libs are found there, they
dnl are almost assuredly the ones desired.
AS_CASE([${host_cpu}],
[i?86],[multiarch_libsubdir="lib/i386-${host_os}"],
[multiarch_libsubdir="lib/${host_cpu}-${host_os}"]
)
dnl first we check the system location for boost libraries
dnl this location ist chosen if boost libraries are installed with the --layout=system option
dnl or if you install boost with RPM
AS_IF([test "x$_AX_BOOST_BASE_boost_path" != "x"],[
AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) includes in "$_AX_BOOST_BASE_boost_path/include"])
AS_IF([test -d "$_AX_BOOST_BASE_boost_path/include" && test -r "$_AX_BOOST_BASE_boost_path/include"],[
AC_MSG_RESULT([yes])
BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include"
for _AX_BOOST_BASE_boost_path_tmp in $multiarch_libsubdir $libsubdirs; do
AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) lib path in "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp"])
AS_IF([test -d "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" && test -r "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" ],[
AC_MSG_RESULT([yes])
BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp";
break;
],
[AC_MSG_RESULT([no])])
done],[
AC_MSG_RESULT([no])])
],[
if test X"$cross_compiling" = Xyes; then
search_libsubdirs=$multiarch_libsubdir
else
search_libsubdirs="$multiarch_libsubdir $libsubdirs"
fi
for _AX_BOOST_BASE_boost_path_tmp in /usr /usr/local /opt /opt/local ; do
if test -d "$_AX_BOOST_BASE_boost_path_tmp/include/boost" && test -r "$_AX_BOOST_BASE_boost_path_tmp/include/boost" ; then
for libsubdir in $search_libsubdirs ; do
if ls "$_AX_BOOST_BASE_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi
done
BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path_tmp/$libsubdir"
BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path_tmp/include"
break;
fi
done
])
dnl overwrite ld flags if we have required special directory with
dnl --with-boost-libdir parameter
AS_IF([test "x$_AX_BOOST_BASE_boost_lib_path" != "x"],
[BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_lib_path"])
AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION)])
CPPFLAGS_SAVED="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
export CPPFLAGS
LDFLAGS_SAVED="$LDFLAGS"
LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
export LDFLAGS
AC_REQUIRE([AC_PROG_CXX])
AC_LANG_PUSH(C++)
AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[
AC_MSG_RESULT(yes)
succeeded=yes
found_system=yes
],[
])
AC_LANG_POP([C++])
dnl if we found no boost with system layout we search for boost libraries
dnl built and installed without the --layout=system option or for a staged(not installed) version
if test "x$succeeded" != "xyes" ; then
CPPFLAGS="$CPPFLAGS_SAVED"
LDFLAGS="$LDFLAGS_SAVED"
BOOST_CPPFLAGS=
if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then
BOOST_LDFLAGS=
fi
_version=0
if test -n "$_AX_BOOST_BASE_boost_path" ; then
if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path"; then
for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do
_version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'`
V_CHECK=`expr $_version_tmp \> $_version`
if test "x$V_CHECK" = "x1" ; then
_version=$_version_tmp
fi
VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'`
BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include/boost-$VERSION_UNDERSCORE"
done
dnl if nothing found search for layout used in Windows distributions
if test -z "$BOOST_CPPFLAGS"; then
if test -d "$_AX_BOOST_BASE_boost_path/boost" && test -r "$_AX_BOOST_BASE_boost_path/boost"; then
BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path"
fi
fi
dnl if we found something and BOOST_LDFLAGS was unset before
dnl (because "$_AX_BOOST_BASE_boost_lib_path" = ""), set it here.
if test -n "$BOOST_CPPFLAGS" && test -z "$BOOST_LDFLAGS"; then
for libsubdir in $libsubdirs ; do
if ls "$_AX_BOOST_BASE_boost_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi
done
BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$libsubdir"
fi
fi
else
if test "x$cross_compiling" != "xyes" ; then
for _AX_BOOST_BASE_boost_path in /usr /usr/local /opt /opt/local ; do
if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path" ; then
for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do
_version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'`
V_CHECK=`expr $_version_tmp \> $_version`
if test "x$V_CHECK" = "x1" ; then
_version=$_version_tmp
best_path=$_AX_BOOST_BASE_boost_path
fi
done
fi
done
VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'`
BOOST_CPPFLAGS="-I$best_path/include/boost-$VERSION_UNDERSCORE"
if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then
for libsubdir in $libsubdirs ; do
if ls "$best_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi
done
BOOST_LDFLAGS="-L$best_path/$libsubdir"
fi
fi
if test -n "$BOOST_ROOT" ; then
for libsubdir in $libsubdirs ; do
if ls "$BOOST_ROOT/stage/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi
done
if test -d "$BOOST_ROOT" && test -r "$BOOST_ROOT" && test -d "$BOOST_ROOT/stage/$libsubdir" && test -r "$BOOST_ROOT/stage/$libsubdir"; then
version_dir=`expr //$BOOST_ROOT : '.*/\(.*\)'`
stage_version=`echo $version_dir | sed 's/boost_//' | sed 's/_/./g'`
stage_version_shorten=`expr $stage_version : '\([[0-9]]*\.[[0-9]]*\)'`
V_CHECK=`expr $stage_version_shorten \>\= $_version`
if test "x$V_CHECK" = "x1" && test -z "$_AX_BOOST_BASE_boost_lib_path" ; then
AC_MSG_NOTICE(We will use a staged boost library from $BOOST_ROOT)
BOOST_CPPFLAGS="-I$BOOST_ROOT"
BOOST_LDFLAGS="-L$BOOST_ROOT/stage/$libsubdir"
fi
fi
fi
fi
CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
export CPPFLAGS
LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
export LDFLAGS
AC_LANG_PUSH(C++)
AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[
AC_MSG_RESULT(yes)
succeeded=yes
found_system=yes
],[
])
AC_LANG_POP([C++])
fi
if test "x$succeeded" != "xyes" ; then
if test "x$_version" = "x0" ; then
AC_MSG_NOTICE([[We could not detect the boost libraries (version $1 or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in <boost/version.hpp>. See http://randspringer.de/boost for more documentation.]])
else
AC_MSG_NOTICE([Your boost libraries seems to old (version $_version).])
fi
# execute ACTION-IF-NOT-FOUND (if present):
ifelse([$3], , :, [$3])
else
AC_DEFINE(HAVE_BOOST,,[define if the Boost library is available])
# execute ACTION-IF-FOUND (if present):
ifelse([$2], , :, [$2])
fi
CPPFLAGS="$CPPFLAGS_SAVED"
LDFLAGS="$LDFLAGS_SAVED"
])

982
m4/ax_cxx_compile_stdcxx.m4 Normal file
View File

@@ -0,0 +1,982 @@
# ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional])
#
# DESCRIPTION
#
# Check for baseline language coverage in the compiler for the specified
# version of the C++ standard. If necessary, add switches to CXX and
# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard)
# or '14' (for the C++14 standard).
#
# The second argument, if specified, indicates whether you insist on an
# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g.
# -std=c++11). If neither is specified, you get whatever works, with
# preference for an extended mode.
#
# The third argument, if specified 'mandatory' or if left unspecified,
# indicates that baseline support for the specified C++ standard is
# required and that the macro should error out if no mode with that
# support is found. If specified 'optional', then configuration proceeds
# regardless, after defining HAVE_CXX${VERSION} if and only if a
# supporting mode is found.
#
# LICENSE
#
# Copyright (c) 2008 Benjamin Kosnik <bkoz@redhat.com>
# Copyright (c) 2012 Zack Weinberg <zackw@panix.com>
# Copyright (c) 2013 Roy Stogner <roystgnr@ices.utexas.edu>
# Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov <sokolov@google.com>
# Copyright (c) 2015 Paul Norman <penorman@mac.com>
# Copyright (c) 2015 Moritz Klammler <moritz@klammler.eu>
# Copyright (c) 2016 Krzesimir Nowak <qdlacz@gmail.com>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 7
dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro
dnl (serial version number 13).
AX_REQUIRE_DEFINED([AC_MSG_WARN])
AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl
m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"],
[$1], [14], [ax_cxx_compile_alternatives="14 1y"],
[$1], [17], [ax_cxx_compile_alternatives="17 1z"],
[m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl
m4_if([$2], [], [],
[$2], [ext], [],
[$2], [noext], [],
[m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl
m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true],
[$3], [mandatory], [ax_cxx_compile_cxx$1_required=true],
[$3], [optional], [ax_cxx_compile_cxx$1_required=false],
[m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])])
AC_LANG_PUSH([C++])dnl
ac_success=no
AC_CACHE_CHECK(whether $CXX supports C++$1 features by default,
ax_cv_cxx_compile_cxx$1,
[AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])],
[ax_cv_cxx_compile_cxx$1=yes],
[ax_cv_cxx_compile_cxx$1=no])])
if test x$ax_cv_cxx_compile_cxx$1 = xyes; then
ac_success=yes
fi
m4_if([$2], [noext], [], [dnl
if test x$ac_success = xno; then
for alternative in ${ax_cxx_compile_alternatives}; do
switch="-std=gnu++${alternative}"
cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch])
AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch,
$cachevar,
[ac_save_CXX="$CXX"
CXX="$CXX $switch"
AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])],
[eval $cachevar=yes],
[eval $cachevar=no])
CXX="$ac_save_CXX"])
if eval test x\$$cachevar = xyes; then
CXX="$CXX $switch"
if test -n "$CXXCPP" ; then
CXXCPP="$CXXCPP $switch"
fi
ac_success=yes
break
fi
done
fi])
m4_if([$2], [ext], [], [dnl
if test x$ac_success = xno; then
dnl HP's aCC needs +std=c++11 according to:
dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf
dnl Cray's crayCC needs "-h std=c++11"
for alternative in ${ax_cxx_compile_alternatives}; do
for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do
cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch])
AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch,
$cachevar,
[ac_save_CXX="$CXX"
CXX="$CXX $switch"
AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])],
[eval $cachevar=yes],
[eval $cachevar=no])
CXX="$ac_save_CXX"])
if eval test x\$$cachevar = xyes; then
CXX="$CXX $switch"
if test -n "$CXXCPP" ; then
CXXCPP="$CXXCPP $switch"
fi
ac_success=yes
break
fi
done
if test x$ac_success = xyes; then
break
fi
done
fi])
AC_LANG_POP([C++])
if test x$ax_cxx_compile_cxx$1_required = xtrue; then
if test x$ac_success = xno; then
AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.])
fi
fi
if test x$ac_success = xno; then
HAVE_CXX$1=0
AC_MSG_NOTICE([No compiler with C++$1 support was found])
else
HAVE_CXX$1=1
AC_DEFINE(HAVE_CXX$1,1,
[define if the compiler supports basic C++$1 syntax])
fi
AC_SUBST(HAVE_CXX$1)
# m4_if([$1], [17], [AC_MSG_WARN([C++17 is not yet standardized, so the checks may change in incompatible ways anytime])])
])
dnl Test body for checking C++11 support
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11],
_AX_CXX_COMPILE_STDCXX_testbody_new_in_11
)
dnl Test body for checking C++14 support
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14],
_AX_CXX_COMPILE_STDCXX_testbody_new_in_11
_AX_CXX_COMPILE_STDCXX_testbody_new_in_14
)
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17],
_AX_CXX_COMPILE_STDCXX_testbody_new_in_11
_AX_CXX_COMPILE_STDCXX_testbody_new_in_14
_AX_CXX_COMPILE_STDCXX_testbody_new_in_17
)
dnl Tests for new features in C++11
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[
// If the compiler admits that it is not ready for C++11, why torture it?
// Hopefully, this will speed up the test.
#ifndef __cplusplus
#error "This is not a C++ compiler"
#elif __cplusplus < 201103L
#error "This is not a C++11 compiler"
#else
namespace cxx11
{
namespace test_static_assert
{
template <typename T>
struct check
{
static_assert(sizeof(int) <= sizeof(T), "not big enough");
};
}
namespace test_final_override
{
struct Base
{
virtual void f() {}
};
struct Derived : public Base
{
virtual void f() override {}
};
}
namespace test_double_right_angle_brackets
{
template < typename T >
struct check {};
typedef check<void> single_type;
typedef check<check<void>> double_type;
typedef check<check<check<void>>> triple_type;
typedef check<check<check<check<void>>>> quadruple_type;
}
namespace test_decltype
{
int
f()
{
int a = 1;
decltype(a) b = 2;
return a + b;
}
}
namespace test_type_deduction
{
template < typename T1, typename T2 >
struct is_same
{
static const bool value = false;
};
template < typename T >
struct is_same<T, T>
{
static const bool value = true;
};
template < typename T1, typename T2 >
auto
add(T1 a1, T2 a2) -> decltype(a1 + a2)
{
return a1 + a2;
}
int
test(const int c, volatile int v)
{
static_assert(is_same<int, decltype(0)>::value == true, "");
static_assert(is_same<int, decltype(c)>::value == false, "");
static_assert(is_same<int, decltype(v)>::value == false, "");
auto ac = c;
auto av = v;
auto sumi = ac + av + 'x';
auto sumf = ac + av + 1.0;
static_assert(is_same<int, decltype(ac)>::value == true, "");
static_assert(is_same<int, decltype(av)>::value == true, "");
static_assert(is_same<int, decltype(sumi)>::value == true, "");
static_assert(is_same<int, decltype(sumf)>::value == false, "");
static_assert(is_same<int, decltype(add(c, v))>::value == true, "");
return (sumf > 0.0) ? sumi : add(c, v);
}
}
namespace test_noexcept
{
int f() { return 0; }
int g() noexcept { return 0; }
static_assert(noexcept(f()) == false, "");
static_assert(noexcept(g()) == true, "");
}
namespace test_constexpr
{
template < typename CharT >
unsigned long constexpr
strlen_c_r(const CharT *const s, const unsigned long acc) noexcept
{
return *s ? strlen_c_r(s + 1, acc + 1) : acc;
}
template < typename CharT >
unsigned long constexpr
strlen_c(const CharT *const s) noexcept
{
return strlen_c_r(s, 0UL);
}
static_assert(strlen_c("") == 0UL, "");
static_assert(strlen_c("1") == 1UL, "");
static_assert(strlen_c("example") == 7UL, "");
static_assert(strlen_c("another\0example") == 7UL, "");
}
namespace test_rvalue_references
{
template < int N >
struct answer
{
static constexpr int value = N;
};
answer<1> f(int&) { return answer<1>(); }
answer<2> f(const int&) { return answer<2>(); }
answer<3> f(int&&) { return answer<3>(); }
void
test()
{
int i = 0;
const int c = 0;
static_assert(decltype(f(i))::value == 1, "");
static_assert(decltype(f(c))::value == 2, "");
static_assert(decltype(f(0))::value == 3, "");
}
}
namespace test_uniform_initialization
{
struct test
{
static const int zero {};
static const int one {1};
};
static_assert(test::zero == 0, "");
static_assert(test::one == 1, "");
}
namespace test_lambdas
{
void
test1()
{
auto lambda1 = [](){};
auto lambda2 = lambda1;
lambda1();
lambda2();
}
int
test2()
{
auto a = [](int i, int j){ return i + j; }(1, 2);
auto b = []() -> int { return '0'; }();
auto c = [=](){ return a + b; }();
auto d = [&](){ return c; }();
auto e = [a, &b](int x) mutable {
const auto identity = [](int y){ return y; };
for (auto i = 0; i < a; ++i)
a += b--;
return x + identity(a + b);
}(0);
return a + b + c + d + e;
}
int
test3()
{
const auto nullary = [](){ return 0; };
const auto unary = [](int x){ return x; };
using nullary_t = decltype(nullary);
using unary_t = decltype(unary);
const auto higher1st = [](nullary_t f){ return f(); };
const auto higher2nd = [unary](nullary_t f1){
return [unary, f1](unary_t f2){ return f2(unary(f1())); };
};
return higher1st(nullary) + higher2nd(nullary)(unary);
}
}
namespace test_variadic_templates
{
template <int...>
struct sum;
template <int N0, int... N1toN>
struct sum<N0, N1toN...>
{
static constexpr auto value = N0 + sum<N1toN...>::value;
};
template <>
struct sum<>
{
static constexpr auto value = 0;
};
static_assert(sum<>::value == 0, "");
static_assert(sum<1>::value == 1, "");
static_assert(sum<23>::value == 23, "");
static_assert(sum<1, 2>::value == 3, "");
static_assert(sum<5, 5, 11>::value == 21, "");
static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, "");
}
// http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae
// Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function
// because of this.
namespace test_template_alias_sfinae
{
struct foo {};
template<typename T>
using member = typename T::member_type;
template<typename T>
void func(...) {}
template<typename T>
void func(member<T>*) {}
void test();
void test() { func<foo>(0); }
}
} // namespace cxx11
#endif // __cplusplus >= 201103L
]])
dnl Tests for new features in C++14
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[
// If the compiler admits that it is not ready for C++14, why torture it?
// Hopefully, this will speed up the test.
#ifndef __cplusplus
#error "This is not a C++ compiler"
#elif __cplusplus < 201402L
#error "This is not a C++14 compiler"
#else
namespace cxx14
{
namespace test_polymorphic_lambdas
{
int
test()
{
const auto lambda = [](auto&&... args){
const auto istiny = [](auto x){
return (sizeof(x) == 1UL) ? 1 : 0;
};
const int aretiny[] = { istiny(args)... };
return aretiny[0];
};
return lambda(1, 1L, 1.0f, '1');
}
}
namespace test_binary_literals
{
constexpr auto ivii = 0b0000000000101010;
static_assert(ivii == 42, "wrong value");
}
namespace test_generalized_constexpr
{
template < typename CharT >
constexpr unsigned long
strlen_c(const CharT *const s) noexcept
{
auto length = 0UL;
for (auto p = s; *p; ++p)
++length;
return length;
}
static_assert(strlen_c("") == 0UL, "");
static_assert(strlen_c("x") == 1UL, "");
static_assert(strlen_c("test") == 4UL, "");
static_assert(strlen_c("another\0test") == 7UL, "");
}
namespace test_lambda_init_capture
{
int
test()
{
auto x = 0;
const auto lambda1 = [a = x](int b){ return a + b; };
const auto lambda2 = [a = lambda1(x)](){ return a; };
return lambda2();
}
}
namespace test_digit_separators
{
constexpr auto ten_million = 100'000'000;
static_assert(ten_million == 100000000, "");
}
namespace test_return_type_deduction
{
auto f(int& x) { return x; }
decltype(auto) g(int& x) { return x; }
template < typename T1, typename T2 >
struct is_same
{
static constexpr auto value = false;
};
template < typename T >
struct is_same<T, T>
{
static constexpr auto value = true;
};
int
test()
{
auto x = 0;
static_assert(is_same<int, decltype(f(x))>::value, "");
static_assert(is_same<int&, decltype(g(x))>::value, "");
return x;
}
}
} // namespace cxx14
#endif // __cplusplus >= 201402L
]])
dnl Tests for new features in C++17
m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[
// If the compiler admits that it is not ready for C++17, why torture it?
// Hopefully, this will speed up the test.
#ifndef __cplusplus
#error "This is not a C++ compiler"
#elif __cplusplus <= 201402L
#error "This is not a C++17 compiler"
#else
#if defined(__clang__)
#define REALLY_CLANG
#else
#if defined(__GNUC__)
#define REALLY_GCC
#endif
#endif
#include <initializer_list>
#include <utility>
#include <type_traits>
namespace cxx17
{
#if !defined(REALLY_CLANG)
namespace test_constexpr_lambdas
{
// TODO: test it with clang++ from git
constexpr int foo = [](){return 42;}();
}
#endif // !defined(REALLY_CLANG)
namespace test::nested_namespace::definitions
{
}
namespace test_fold_expression
{
template<typename... Args>
int multiply(Args... args)
{
return (args * ... * 1);
}
template<typename... Args>
bool all(Args... args)
{
return (args && ...);
}
}
namespace test_extended_static_assert
{
static_assert (true);
}
namespace test_auto_brace_init_list
{
auto foo = {5};
auto bar {5};
static_assert(std::is_same<std::initializer_list<int>, decltype(foo)>::value);
static_assert(std::is_same<int, decltype(bar)>::value);
}
namespace test_typename_in_template_template_parameter
{
template<template<typename> typename X> struct D;
}
namespace test_fallthrough_nodiscard_maybe_unused_attributes
{
int f1()
{
return 42;
}
[[nodiscard]] int f2()
{
[[maybe_unused]] auto unused = f1();
switch (f1())
{
case 17:
f1();
[[fallthrough]];
case 42:
f1();
}
return f1();
}
}
namespace test_extended_aggregate_initialization
{
struct base1
{
int b1, b2 = 42;
};
struct base2
{
base2() {
b3 = 42;
}
int b3;
};
struct derived : base1, base2
{
int d;
};
derived d1 {{1, 2}, {}, 4}; // full initialization
derived d2 {{}, {}, 4}; // value-initialized bases
}
namespace test_general_range_based_for_loop
{
struct iter
{
int i;
int& operator* ()
{
return i;
}
const int& operator* () const
{
return i;
}
iter& operator++()
{
++i;
return *this;
}
};
struct sentinel
{
int i;
};
bool operator== (const iter& i, const sentinel& s)
{
return i.i == s.i;
}
bool operator!= (const iter& i, const sentinel& s)
{
return !(i == s);
}
struct range
{
iter begin() const
{
return {0};
}
sentinel end() const
{
return {5};
}
};
void f()
{
range r {};
for (auto i : r)
{
[[maybe_unused]] auto v = i;
}
}
}
namespace test_lambda_capture_asterisk_this_by_value
{
struct t
{
int i;
int foo()
{
return [*this]()
{
return i;
}();
}
};
}
namespace test_enum_class_construction
{
enum class byte : unsigned char
{};
byte foo {42};
}
namespace test_constexpr_if
{
template <bool cond>
int f ()
{
if constexpr(cond)
{
return 13;
}
else
{
return 42;
}
}
}
namespace test_selection_statement_with_initializer
{
int f()
{
return 13;
}
int f2()
{
if (auto i = f(); i > 0)
{
return 3;
}
switch (auto i = f(); i + 4)
{
case 17:
return 2;
default:
return 1;
}
}
}
#if !defined(REALLY_CLANG)
namespace test_template_argument_deduction_for_class_templates
{
// TODO: test it with clang++ from git
template <typename T1, typename T2>
struct pair
{
pair (T1 p1, T2 p2)
: m1 {p1},
m2 {p2}
{}
T1 m1;
T2 m2;
};
void f()
{
[[maybe_unused]] auto p = pair{13, 42u};
}
}
#endif // !defined(REALLY_CLANG)
namespace test_non_type_auto_template_parameters
{
template <auto n>
struct B
{};
B<5> b1;
B<'a'> b2;
}
#if !defined(REALLY_CLANG)
namespace test_structured_bindings
{
// TODO: test it with clang++ from git
int arr[2] = { 1, 2 };
std::pair<int, int> pr = { 1, 2 };
auto f1() -> int(&)[2]
{
return arr;
}
auto f2() -> std::pair<int, int>&
{
return pr;
}
struct S
{
int x1 : 2;
volatile double y1;
};
S f3()
{
return {};
}
auto [ x1, y1 ] = f1();
auto& [ xr1, yr1 ] = f1();
auto [ x2, y2 ] = f2();
auto& [ xr2, yr2 ] = f2();
const auto [ x3, y3 ] = f3();
}
#endif // !defined(REALLY_CLANG)
#if !defined(REALLY_CLANG)
namespace test_exception_spec_type_system
{
// TODO: test it with clang++ from git
struct Good {};
struct Bad {};
void g1() noexcept;
void g2();
template<typename T>
Bad
f(T*, T*);
template<typename T1, typename T2>
Good
f(T1*, T2*);
static_assert (std::is_same_v<Good, decltype(f(g1, g2))>);
}
#endif // !defined(REALLY_CLANG)
namespace test_inline_variables
{
template<class T> void f(T)
{}
template<class T> inline T g(T)
{
return T{};
}
template<> inline void f<>(int)
{}
template<> int g<>(int)
{
return 5;
}
}
} // namespace cxx17
#endif // __cplusplus <= 201402L
]])

215
missing Executable file
View File

@@ -0,0 +1,215 @@
#! /bin/sh
# Common wrapper for a few potentially missing GNU programs.
scriptversion=2013-10-28.13; # UTC
# Copyright (C) 1996-2014 Free Software Foundation, Inc.
# Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
if test $# -eq 0; then
echo 1>&2 "Try '$0 --help' for more information"
exit 1
fi
case $1 in
--is-lightweight)
# Used by our autoconf macros to check whether the available missing
# script is modern enough.
exit 0
;;
--run)
# Back-compat with the calling convention used by older automake.
shift
;;
-h|--h|--he|--hel|--help)
echo "\
$0 [OPTION]... PROGRAM [ARGUMENT]...
Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due
to PROGRAM being missing or too old.
Options:
-h, --help display this help and exit
-v, --version output version information and exit
Supported PROGRAM values:
aclocal autoconf autoheader autom4te automake makeinfo
bison yacc flex lex help2man
Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and
'g' are ignored when checking the name.
Send bug reports to <bug-automake@gnu.org>."
exit $?
;;
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
echo "missing $scriptversion (GNU Automake)"
exit $?
;;
-*)
echo 1>&2 "$0: unknown '$1' option"
echo 1>&2 "Try '$0 --help' for more information"
exit 1
;;
esac
# Run the given program, remember its exit status.
"$@"; st=$?
# If it succeeded, we are done.
test $st -eq 0 && exit 0
# Also exit now if we it failed (or wasn't found), and '--version' was
# passed; such an option is passed most likely to detect whether the
# program is present and works.
case $2 in --version|--help) exit $st;; esac
# Exit code 63 means version mismatch. This often happens when the user
# tries to use an ancient version of a tool on a file that requires a
# minimum version.
if test $st -eq 63; then
msg="probably too old"
elif test $st -eq 127; then
# Program was missing.
msg="missing on your system"
else
# Program was found and executed, but failed. Give up.
exit $st
fi
perl_URL=http://www.perl.org/
flex_URL=http://flex.sourceforge.net/
gnu_software_URL=http://www.gnu.org/software
program_details ()
{
case $1 in
aclocal|automake)
echo "The '$1' program is part of the GNU Automake package:"
echo "<$gnu_software_URL/automake>"
echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/autoconf>"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
autoconf|autom4te|autoheader)
echo "The '$1' program is part of the GNU Autoconf package:"
echo "<$gnu_software_URL/autoconf/>"
echo "It also requires GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
esac
}
give_advice ()
{
# Normalize program name to check for.
normalized_program=`echo "$1" | sed '
s/^gnu-//; t
s/^gnu//; t
s/^g//; t'`
printf '%s\n' "'$1' is $msg."
configure_deps="'configure.ac' or m4 files included by 'configure.ac'"
case $normalized_program in
autoconf*)
echo "You should only need it if you modified 'configure.ac',"
echo "or m4 files included by it."
program_details 'autoconf'
;;
autoheader*)
echo "You should only need it if you modified 'acconfig.h' or"
echo "$configure_deps."
program_details 'autoheader'
;;
automake*)
echo "You should only need it if you modified 'Makefile.am' or"
echo "$configure_deps."
program_details 'automake'
;;
aclocal*)
echo "You should only need it if you modified 'acinclude.m4' or"
echo "$configure_deps."
program_details 'aclocal'
;;
autom4te*)
echo "You might have modified some maintainer files that require"
echo "the 'autom4te' program to be rebuilt."
program_details 'autom4te'
;;
bison*|yacc*)
echo "You should only need it if you modified a '.y' file."
echo "You may want to install the GNU Bison package:"
echo "<$gnu_software_URL/bison/>"
;;
lex*|flex*)
echo "You should only need it if you modified a '.l' file."
echo "You may want to install the Fast Lexical Analyzer package:"
echo "<$flex_URL>"
;;
help2man*)
echo "You should only need it if you modified a dependency" \
"of a man page."
echo "You may want to install the GNU Help2man package:"
echo "<$gnu_software_URL/help2man/>"
;;
makeinfo*)
echo "You should only need it if you modified a '.texi' file, or"
echo "any other file indirectly affecting the aspect of the manual."
echo "You might want to install the Texinfo package:"
echo "<$gnu_software_URL/texinfo/>"
echo "The spurious makeinfo call might also be the consequence of"
echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might"
echo "want to install GNU make:"
echo "<$gnu_software_URL/make/>"
;;
*)
echo "You might have modified some files without having the proper"
echo "tools for further handling them. Check the 'README' file, it"
echo "often tells you about the needed prerequisites for installing"
echo "this package. You may also peek at any GNU archive site, in"
echo "case some other package contains this missing '$1' program."
;;
esac
}
give_advice "$1" | sed -e '1s/^/WARNING: /' \
-e '2,$s/^/ /' >&2
# Propagate the correct exit status (expected to be 127 for a program
# not found, 63 for a program that failed due to version mismatch).
exit $st
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC"
# time-stamp-end: "; # UTC"
# End:

2
nagios/README Normal file
View File

@@ -0,0 +1,2 @@
These files are taken directly from Nagios 3.2.0 with a minimal patch
that fixes one compilation error on g++.

223
nagios/broker.h Normal file
View File

@@ -0,0 +1,223 @@
/*****************************************************************************
*
* BROKER.H - Event broker includes for Nagios
*
* Copyright (c) 2002-2006 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 12-12-2006
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _BROKER_H
#define _BROKER_H
#include "config.h"
#include "nagios.h"
#ifdef __cplusplus
extern "C" {
#endif
/*************** EVENT BROKER OPTIONS *****************/
#define BROKER_NOTHING 0
#define BROKER_EVERYTHING 1048575
#define BROKER_PROGRAM_STATE 1 /* DONE */
#define BROKER_TIMED_EVENTS 2 /* DONE */
#define BROKER_SERVICE_CHECKS 4 /* DONE */
#define BROKER_HOST_CHECKS 8 /* DONE */
#define BROKER_EVENT_HANDLERS 16 /* DONE */
#define BROKER_LOGGED_DATA 32 /* DONE */
#define BROKER_NOTIFICATIONS 64 /* DONE */
#define BROKER_FLAPPING_DATA 128 /* DONE */
#define BROKER_COMMENT_DATA 256 /* DONE */
#define BROKER_DOWNTIME_DATA 512 /* DONE */
#define BROKER_SYSTEM_COMMANDS 1024 /* DONE */
#define BROKER_OCP_DATA 2048 /* DONE */
#define BROKER_STATUS_DATA 4096 /* DONE */
#define BROKER_ADAPTIVE_DATA 8192 /* DONE */
#define BROKER_EXTERNALCOMMAND_DATA 16384 /* DONE */
#define BROKER_RETENTION_DATA 32768 /* DONE */
#define BROKER_ACKNOWLEDGEMENT_DATA 65536
#define BROKER_STATECHANGE_DATA 131072
#define BROKER_RESERVED18 262144
#define BROKER_RESERVED19 524288
/****** EVENT TYPES ************************/
#define NEBTYPE_NONE 0
#define NEBTYPE_HELLO 1
#define NEBTYPE_GOODBYE 2
#define NEBTYPE_INFO 3
#define NEBTYPE_PROCESS_START 100
#define NEBTYPE_PROCESS_DAEMONIZE 101
#define NEBTYPE_PROCESS_RESTART 102
#define NEBTYPE_PROCESS_SHUTDOWN 103
#define NEBTYPE_PROCESS_PRELAUNCH 104 /* before objects are read or verified */
#define NEBTYPE_PROCESS_EVENTLOOPSTART 105
#define NEBTYPE_PROCESS_EVENTLOOPEND 106
#define NEBTYPE_TIMEDEVENT_ADD 200
#define NEBTYPE_TIMEDEVENT_REMOVE 201
#define NEBTYPE_TIMEDEVENT_EXECUTE 202
#define NEBTYPE_TIMEDEVENT_DELAY 203 /* NOT IMPLEMENTED */
#define NEBTYPE_TIMEDEVENT_SKIP 204 /* NOT IMPLEMENTED */
#define NEBTYPE_TIMEDEVENT_SLEEP 205
#define NEBTYPE_LOG_DATA 300
#define NEBTYPE_LOG_ROTATION 301
#define NEBTYPE_SYSTEM_COMMAND_START 400
#define NEBTYPE_SYSTEM_COMMAND_END 401
#define NEBTYPE_EVENTHANDLER_START 500
#define NEBTYPE_EVENTHANDLER_END 501
#define NEBTYPE_NOTIFICATION_START 600
#define NEBTYPE_NOTIFICATION_END 601
#define NEBTYPE_CONTACTNOTIFICATION_START 602
#define NEBTYPE_CONTACTNOTIFICATION_END 603
#define NEBTYPE_CONTACTNOTIFICATIONMETHOD_START 604
#define NEBTYPE_CONTACTNOTIFICATIONMETHOD_END 605
#define NEBTYPE_SERVICECHECK_INITIATE 700
#define NEBTYPE_SERVICECHECK_PROCESSED 701
#define NEBTYPE_SERVICECHECK_RAW_START 702 /* NOT IMPLEMENTED */
#define NEBTYPE_SERVICECHECK_RAW_END 703 /* NOT IMPLEMENTED */
#define NEBTYPE_SERVICECHECK_ASYNC_PRECHECK 704
#define NEBTYPE_HOSTCHECK_INITIATE 800 /* a check of the route to the host has been initiated */
#define NEBTYPE_HOSTCHECK_PROCESSED 801 /* the processed/final result of a host check */
#define NEBTYPE_HOSTCHECK_RAW_START 802 /* the start of a "raw" host check */
#define NEBTYPE_HOSTCHECK_RAW_END 803 /* a finished "raw" host check */
#define NEBTYPE_HOSTCHECK_ASYNC_PRECHECK 804
#define NEBTYPE_HOSTCHECK_SYNC_PRECHECK 805
#define NEBTYPE_COMMENT_ADD 900
#define NEBTYPE_COMMENT_DELETE 901
#define NEBTYPE_COMMENT_LOAD 902
#define NEBTYPE_FLAPPING_START 1000
#define NEBTYPE_FLAPPING_STOP 1001
#define NEBTYPE_DOWNTIME_ADD 1100
#define NEBTYPE_DOWNTIME_DELETE 1101
#define NEBTYPE_DOWNTIME_LOAD 1102
#define NEBTYPE_DOWNTIME_START 1103
#define NEBTYPE_DOWNTIME_STOP 1104
#define NEBTYPE_PROGRAMSTATUS_UPDATE 1200
#define NEBTYPE_HOSTSTATUS_UPDATE 1201
#define NEBTYPE_SERVICESTATUS_UPDATE 1202
#define NEBTYPE_CONTACTSTATUS_UPDATE 1203
#define NEBTYPE_ADAPTIVEPROGRAM_UPDATE 1300
#define NEBTYPE_ADAPTIVEHOST_UPDATE 1301
#define NEBTYPE_ADAPTIVESERVICE_UPDATE 1302
#define NEBTYPE_ADAPTIVECONTACT_UPDATE 1303
#define NEBTYPE_EXTERNALCOMMAND_START 1400
#define NEBTYPE_EXTERNALCOMMAND_END 1401
#define NEBTYPE_AGGREGATEDSTATUS_STARTDUMP 1500
#define NEBTYPE_AGGREGATEDSTATUS_ENDDUMP 1501
#define NEBTYPE_RETENTIONDATA_STARTLOAD 1600
#define NEBTYPE_RETENTIONDATA_ENDLOAD 1601
#define NEBTYPE_RETENTIONDATA_STARTSAVE 1602
#define NEBTYPE_RETENTIONDATA_ENDSAVE 1603
#define NEBTYPE_ACKNOWLEDGEMENT_ADD 1700
#define NEBTYPE_ACKNOWLEDGEMENT_REMOVE 1701 /* NOT IMPLEMENTED */
#define NEBTYPE_ACKNOWLEDGEMENT_LOAD 1702 /* NOT IMPLEMENTED */
#define NEBTYPE_STATECHANGE_START 1800 /* NOT IMPLEMENTED */
#define NEBTYPE_STATECHANGE_END 1801
/****** EVENT FLAGS ************************/
#define NEBFLAG_NONE 0
#define NEBFLAG_PROCESS_INITIATED 1 /* event was initiated by Nagios process */
#define NEBFLAG_USER_INITIATED 2 /* event was initiated by a user request */
#define NEBFLAG_MODULE_INITIATED 3 /* event was initiated by an event broker module */
/****** EVENT ATTRIBUTES *******************/
#define NEBATTR_NONE 0
#define NEBATTR_SHUTDOWN_NORMAL 1
#define NEBATTR_SHUTDOWN_ABNORMAL 2
#define NEBATTR_RESTART_NORMAL 4
#define NEBATTR_RESTART_ABNORMAL 8
#define NEBATTR_FLAPPING_STOP_NORMAL 1
#define NEBATTR_FLAPPING_STOP_DISABLED 2 /* flapping stopped because flap detection was disabled */
#define NEBATTR_DOWNTIME_STOP_NORMAL 1
#define NEBATTR_DOWNTIME_STOP_CANCELLED 2
/****** EVENT BROKER FUNCTIONS *************/
#ifdef USE_EVENT_BROKER
struct timeval get_broker_timestamp(struct timeval *);
void broker_program_state(int,int,int,struct timeval *);
void broker_timed_event(int,int,int,timed_event *,struct timeval *);
void broker_log_data(int,int,int,char *,unsigned long,time_t,struct timeval *);
void broker_event_handler(int,int,int,int,void *,int,int,struct timeval,struct timeval,double,int,int,int,char *,char *,char *,struct timeval *);
void broker_ocp_data(int,int,int,void *,int,int,double,int,int,struct timeval *);
void broker_system_command(int,int,int,struct timeval,struct timeval,double,int,int,int,char *,char *,struct timeval *);
int broker_host_check(int,int,int,host *,int,int,int,struct timeval,struct timeval,char *,double,double,int,int,int,char *,char *,char *,char *,struct timeval *);
int broker_service_check(int,int,int,service *,int,struct timeval,struct timeval,char *,double,double,int,int,int,char *,struct timeval *);
void broker_comment_data(int,int,int,int,int,char *,char *,time_t,char *,char *,int,int,int,time_t,unsigned long,struct timeval *);
void broker_downtime_data(int,int,int,int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long,struct timeval *);
void broker_flapping_data(int,int,int,int,void *,double,double,double,struct timeval *);
void broker_program_status(int,int,int,struct timeval *);
void broker_host_status(int,int,int,host *,struct timeval *);
void broker_service_status(int,int,int,service *,struct timeval *);
void broker_contact_status(int,int,int,contact *,struct timeval *);
void broker_notification_data(int,int,int,int,int,struct timeval,struct timeval,void *,char *,char *,int,int,struct timeval *);
void broker_contact_notification_data(int,int,int,int,int,struct timeval,struct timeval,void *,contact *,char *,char *,int,struct timeval *);
void broker_contact_notification_method_data(int,int,int,int,int,struct timeval,struct timeval,void *,contact *,char *,char *,char *,int,struct timeval *);
void broker_adaptive_program_data(int,int,int,int,unsigned long,unsigned long,unsigned long,unsigned long,struct timeval *);
void broker_adaptive_host_data(int,int,int,host *,int,unsigned long,unsigned long,struct timeval *);
void broker_adaptive_service_data(int,int,int,service *,int,unsigned long,unsigned long,struct timeval *);
void broker_adaptive_contact_data(int,int,int,contact *,int,unsigned long,unsigned long,unsigned long,unsigned long,unsigned long,unsigned long, struct timeval *);
void broker_external_command(int,int,int,int,time_t,char *,char *,struct timeval *);
void broker_aggregated_status_data(int,int,int,struct timeval *);
void broker_retention_data(int,int,int,struct timeval *);
void broker_acknowledgement_data(int,int,int,int,void *,char *,char *,int,int,int,struct timeval *);
void broker_statechange_data(int,int,int,int,void *,int,int,int,int,struct timeval *);
#endif
#ifdef __cplusplus
}
#endif
#endif

74
nagios/cgiauth.h Normal file
View File

@@ -0,0 +1,74 @@
/*****************************************************************************
*
* CGIAUTH.H - Authorization utilities header file
*
* Last Modified: 11-24-2005
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _AUTH_H
#define _AUTH_H
#include "common.h"
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct authdata_struct{
char *username;
int authorized_for_all_hosts;
int authorized_for_all_host_commands;
int authorized_for_all_services;
int authorized_for_all_service_commands;
int authorized_for_system_information;
int authorized_for_system_commands;
int authorized_for_configuration_information;
int authorized_for_read_only;
int authenticated;
}authdata;
int get_authentication_information(authdata *); /* gets current authentication information */
int is_authorized_for_host(host *,authdata *);
int is_authorized_for_service(service *,authdata *);
int is_authorized_for_all_hosts(authdata *);
int is_authorized_for_all_services(authdata *);
int is_authorized_for_system_information(authdata *);
int is_authorized_for_system_commands(authdata *);
int is_authorized_for_host_commands(host *,authdata *);
int is_authorized_for_service_commands(service *,authdata *);
int is_authorized_for_hostgroup(hostgroup *,authdata *);
int is_authorized_for_servicegroup(servicegroup *,authdata *);
int is_authorized_for_configuration_information(authdata *);
int is_authorized_for_read_only(authdata *);
#ifdef __cplusplus
}
#endif
#endif

533
nagios/cgiutils.h Normal file
View File

@@ -0,0 +1,533 @@
/* include/cgiutils.h. Generated by configure. */
/************************************************************************
*
* CGIUTILS.H - Header file for common CGI functions
* Copyright (c) 1999-2008 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 10-15-2008
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef _CGIUTILS_H
#define _CGIUTILS_H
#include "objects.h"
#include "cgiauth.h"
#ifdef __cplusplus
extern "C" {
#endif
/* should we compile and use the statusmap CGI? */
#define USE_STATUSMAP 1
/* should we compile and use the statuswrl CGI? */
#define USE_STATUSWRL 1
/* should we compile and use the trends CGI? */
#define USE_TRENDS 1
/* should we compile and use the histogram CGI? */
#define USE_HISTOGRAM 1
/**************************** CGI REFRESH RATE ******************************/
#define DEFAULT_REFRESH_RATE 60 /* 60 second refresh rate for CGIs */
/******************************* CGI NAMES **********************************/
#define STATUS_CGI "status.cgi"
#define STATUSMAP_CGI "statusmap.cgi"
#define STATUSWORLD_CGI "statuswrl.cgi"
#define COMMAND_CGI "cmd.cgi"
#define EXTINFO_CGI "extinfo.cgi"
#define SHOWLOG_CGI "showlog.cgi"
#define NOTIFICATIONS_CGI "notifications.cgi"
#define HISTORY_CGI "history.cgi"
#define CONFIG_CGI "config.cgi"
#define OUTAGES_CGI "outages.cgi"
#define TRENDS_CGI "trends.cgi"
#define AVAIL_CGI "avail.cgi"
#define TAC_CGI "tac.cgi"
#define STATUSWML_CGI "statuswml.cgi"
#define TRACEROUTE_CGI "traceroute.cgi"
#define HISTOGRAM_CGI "histogram.cgi"
#define CHECKSANITY_CGI "checksanity.cgi"
#define MINISTATUS_CGI "ministatus.cgi"
#define SUMMARY_CGI "summary.cgi"
/**************************** STYLE SHEET NAMES ******************************/
#define COMMON_CSS "common.css"
#define SHOWLOG_CSS "showlog.css"
#define STATUS_CSS "status.css"
#define STATUSMAP_CSS "statusmap.css"
#define COMMAND_CSS "cmd.css"
#define EXTINFO_CSS "extinfo.css"
#define NOTIFICATIONS_CSS "notifications.css"
#define HISTORY_CSS "history.css"
#define CONFIG_CSS "config.css"
#define OUTAGES_CSS "outages.css"
#define TRENDS_CSS "trends.css"
#define AVAIL_CSS "avail.css"
#define TAC_CSS "tac.css"
#define HISTOGRAM_CSS "histogram.css"
#define CHECKSANITY_CSS "checksanity.css"
#define MINISTATUS_CSS "ministatus.css"
#define SUMMARY_CSS "summary.css"
/********************************* ICONS ************************************/
#define STATUS_ICON_WIDTH 20
#define STATUS_ICON_HEIGHT 20
#define INFO_ICON "info.png"
#define INFO_ICON_ALT "Informational Message"
#define START_ICON "start.gif"
#define START_ICON_ALT "Program Start"
#define STOP_ICON "stop.gif"
#define STOP_ICON_ALT "Program End"
#define RESTART_ICON "restart.gif"
#define RESTART_ICON_ALT "Program Restart"
#define OK_ICON "recovery.png"
#define OK_ICON_ALT "Service Ok"
#define CRITICAL_ICON "critical.png"
#define CRITICAL_ICON_ALT "Service Critical"
#define WARNING_ICON "warning.png"
#define WARNING_ICON_ALT "Service Warning"
#define UNKNOWN_ICON "unknown.png"
#define UNKNOWN_ICON_ALT "Service Unknown"
#define NOTIFICATION_ICON "notify.gif"
#define NOTIFICATION_ICON_ALT "Service Notification"
#define LOG_ROTATION_ICON "logrotate.png"
#define LOG_ROTATION_ICON_ALT "Log Rotation"
#define EXTERNAL_COMMAND_ICON "command.png"
#define EXTERNAL_COMMAND_ICON_ALT "External Command"
#define STATUS_DETAIL_ICON "status2.gif"
#define STATUS_OVERVIEW_ICON "status.gif"
#define STATUSMAP_ICON "status3.gif"
#define STATUSWORLD_ICON "status4.gif"
#define EXTINFO_ICON "extinfo.gif"
#define HISTORY_ICON "history.gif"
#define CONTACTGROUP_ICON "contactgroup.gif"
#define TRENDS_ICON "trends.gif"
#define DISABLED_ICON "disabled.gif"
#define ENABLED_ICON "enabled.gif"
#define PASSIVE_ONLY_ICON "passiveonly.gif"
#define NOTIFICATIONS_DISABLED_ICON "ndisabled.gif"
#define ACKNOWLEDGEMENT_ICON "ack.gif"
#define REMOVE_ACKNOWLEDGEMENT_ICON "noack.gif"
#define COMMENT_ICON "comment.gif"
#define DELETE_ICON "delete.gif"
#define DELAY_ICON "delay.gif"
#define DOWNTIME_ICON "downtime.gif"
#define PASSIVE_ICON "passiveonly.gif"
#define RIGHT_ARROW_ICON "right.gif"
#define LEFT_ARROW_ICON "left.gif"
#define UP_ARROW_ICON "up.gif"
#define DOWN_ARROW_ICON "down.gif"
#define FLAPPING_ICON "flapping.gif"
#define SCHEDULED_DOWNTIME_ICON "downtime.gif"
#define EMPTY_ICON "empty.gif"
#define ACTIVE_ICON "active.gif"
#define ACTIVE_ICON_ALT "Active Mode"
#define STANDBY_ICON "standby.gif"
#define STANDBY_ICON_ALT "Standby Mode"
#define HOST_DOWN_ICON "critical.png"
#define HOST_DOWN_ICON_ALT "Host Down"
#define HOST_UNREACHABLE_ICON "critical.png"
#define HOST_UNREACHABLE_ICON_ALT "Host Unreachable"
#define HOST_UP_ICON "recovery.png"
#define HOST_UP_ICON_ALT "Host Up"
#define HOST_NOTIFICATION_ICON "notify.gif"
#define HOST_NOTIFICATION_ICON_ALT "Host Notification"
#define SERVICE_EVENT_ICON "serviceevent.gif"
#define SERVICE_EVENT_ICON_ALT "Service Event Handler"
#define HOST_EVENT_ICON "hostevent.gif"
#define HOST_EVENT_ICON_ALT "Host Event Handler"
#define THERM_OK_IMAGE "thermok.png"
#define THERM_WARNING_IMAGE "thermwarn.png"
#define THERM_CRITICAL_IMAGE "thermcrit.png"
#define CONFIGURATION_ICON "config.gif"
#define NOTES_ICON "notes.gif"
#define ACTION_ICON "action.gif"
#define DETAIL_ICON "detail.gif"
#define PARENT_TRAVERSAL_ICON "parentup.gif"
#define TAC_DISABLED_ICON "tacdisabled.png"
#define TAC_ENABLED_ICON "tacenabled.png"
#define ZOOM1_ICON "zoom1.gif"
#define ZOOM2_ICON "zoom2.gif"
#define CONTEXT_HELP_ICON1 "contexthelp1.gif"
#define CONTEXT_HELP_ICON2 "contexthelp2.gif"
#define SPLUNK_SMALL_WHITE_ICON "splunk1.gif"
#define SPLUNK_SMALL_BLACK_ICON "splunk2.gif"
/************************** PLUGIN RETURN VALUES ****************************/
#define STATE_OK 0
#define STATE_WARNING 1
#define STATE_CRITICAL 2
#define STATE_UNKNOWN 3 /* changed from -1 on 02/24/2001 */
/********************* EXTENDED INFO CGI DISPLAY TYPES *********************/
#define DISPLAY_PROCESS_INFO 0
#define DISPLAY_HOST_INFO 1
#define DISPLAY_SERVICE_INFO 2
#define DISPLAY_COMMENTS 3
#define DISPLAY_PERFORMANCE 4
#define DISPLAY_HOSTGROUP_INFO 5
#define DISPLAY_DOWNTIME 6
#define DISPLAY_SCHEDULING_QUEUE 7
#define DISPLAY_SERVICEGROUP_INFO 8
/************************ COMMAND CGI COMMAND MODES *************************/
#define CMDMODE_NONE 0
#define CMDMODE_REQUEST 1
#define CMDMODE_COMMIT 2
/******************** HOST AND SERVICE NOTIFICATION TYPES ******************/
#define NOTIFICATION_ALL 0 /* all service and host notifications */
#define NOTIFICATION_SERVICE_ALL 1 /* all types of service notifications */
#define NOTIFICATION_HOST_ALL 2 /* all types of host notifications */
#define NOTIFICATION_SERVICE_WARNING 4
#define NOTIFICATION_SERVICE_UNKNOWN 8
#define NOTIFICATION_SERVICE_CRITICAL 16
#define NOTIFICATION_SERVICE_RECOVERY 32
#define NOTIFICATION_HOST_DOWN 64
#define NOTIFICATION_HOST_UNREACHABLE 128
#define NOTIFICATION_HOST_RECOVERY 256
#define NOTIFICATION_SERVICE_ACK 512
#define NOTIFICATION_HOST_ACK 1024
#define NOTIFICATION_SERVICE_FLAP 2048
#define NOTIFICATION_HOST_FLAP 4096
#define NOTIFICATION_SERVICE_CUSTOM 8192
#define NOTIFICATION_HOST_CUSTOM 16384
/********************** HOST AND SERVICE ALERT TYPES **********************/
#define HISTORY_ALL 0 /* all service and host alert */
#define HISTORY_SERVICE_ALL 1 /* all types of service alerts */
#define HISTORY_HOST_ALL 2 /* all types of host alerts */
#define HISTORY_SERVICE_WARNING 4
#define HISTORY_SERVICE_UNKNOWN 8
#define HISTORY_SERVICE_CRITICAL 16
#define HISTORY_SERVICE_RECOVERY 32
#define HISTORY_HOST_DOWN 64
#define HISTORY_HOST_UNREACHABLE 128
#define HISTORY_HOST_RECOVERY 256
/****************************** SORT TYPES *******************************/
#define SORT_NONE 0
#define SORT_ASCENDING 1
#define SORT_DESCENDING 2
/***************************** SORT OPTIONS ******************************/
#define SORT_NOTHING 0
#define SORT_HOSTNAME 1
#define SORT_SERVICENAME 2
#define SORT_SERVICESTATUS 3
#define SORT_LASTCHECKTIME 4
#define SORT_CURRENTATTEMPT 5
#define SORT_STATEDURATION 6
#define SORT_NEXTCHECKTIME 7
#define SORT_HOSTSTATUS 8
/****************** HOST AND SERVICE FILTER PROPERTIES *******************/
#define HOST_SCHEDULED_DOWNTIME 1
#define HOST_NO_SCHEDULED_DOWNTIME 2
#define HOST_STATE_ACKNOWLEDGED 4
#define HOST_STATE_UNACKNOWLEDGED 8
#define HOST_CHECKS_DISABLED 16
#define HOST_CHECKS_ENABLED 32
#define HOST_EVENT_HANDLER_DISABLED 64
#define HOST_EVENT_HANDLER_ENABLED 128
#define HOST_FLAP_DETECTION_DISABLED 256
#define HOST_FLAP_DETECTION_ENABLED 512
#define HOST_IS_FLAPPING 1024
#define HOST_IS_NOT_FLAPPING 2048
#define HOST_NOTIFICATIONS_DISABLED 4096
#define HOST_NOTIFICATIONS_ENABLED 8192
#define HOST_PASSIVE_CHECKS_DISABLED 16384
#define HOST_PASSIVE_CHECKS_ENABLED 32768
#define HOST_PASSIVE_CHECK 65536
#define HOST_ACTIVE_CHECK 131072
#define HOST_HARD_STATE 262144
#define HOST_SOFT_STATE 524288
#define SERVICE_SCHEDULED_DOWNTIME 1
#define SERVICE_NO_SCHEDULED_DOWNTIME 2
#define SERVICE_STATE_ACKNOWLEDGED 4
#define SERVICE_STATE_UNACKNOWLEDGED 8
#define SERVICE_CHECKS_DISABLED 16
#define SERVICE_CHECKS_ENABLED 32
#define SERVICE_EVENT_HANDLER_DISABLED 64
#define SERVICE_EVENT_HANDLER_ENABLED 128
#define SERVICE_FLAP_DETECTION_ENABLED 256
#define SERVICE_FLAP_DETECTION_DISABLED 512
#define SERVICE_IS_FLAPPING 1024
#define SERVICE_IS_NOT_FLAPPING 2048
#define SERVICE_NOTIFICATIONS_DISABLED 4096
#define SERVICE_NOTIFICATIONS_ENABLED 8192
#define SERVICE_PASSIVE_CHECKS_DISABLED 16384
#define SERVICE_PASSIVE_CHECKS_ENABLED 32768
#define SERVICE_PASSIVE_CHECK 65536
#define SERVICE_ACTIVE_CHECK 131072
#define SERVICE_HARD_STATE 262144
#define SERVICE_SOFT_STATE 524288
/****************************** SSI TYPES ********************************/
#define SSI_HEADER 0
#define SSI_FOOTER 1
/************************ CONTEXT-SENSITIVE HELP *************************/
#define CONTEXTHELP_STATUS_DETAIL "A1"
#define CONTEXTHELP_STATUS_HGOVERVIEW "A2"
#define CONTEXTHELP_STATUS_HGSUMMARY "A3"
#define CONTEXTHELP_STATUS_HGGRID "A4"
#define CONTEXTHELP_STATUS_SVCPROBLEMS "A5"
#define CONTEXTHELP_STATUS_HOST_DETAIL "A6"
#define CONTEXTHELP_STATUS_HOSTPROBLEMS "A7"
#define CONTEXTHELP_STATUS_SGOVERVIEW "A8"
#define CONTEXTHELP_STATUS_SGSUMMARY "A9"
#define CONTEXTHELP_STATUS_SGGRID "A10"
#define CONTEXTHELP_TAC "B1"
#define CONTEXTHELP_MAP "C1"
#define CONTEXTHELP_LOG "D1"
#define CONTEXTHELP_HISTORY "E1"
#define CONTEXTHELP_NOTIFICATIONS "F1"
#define CONTEXTHELP_TRENDS_MENU1 "G1"
#define CONTEXTHELP_TRENDS_MENU2 "G2"
#define CONTEXTHELP_TRENDS_MENU3 "G3"
#define CONTEXTHELP_TRENDS_MENU4 "G4"
#define CONTEXTHELP_TRENDS_HOST "G5"
#define CONTEXTHELP_TRENDS_SERVICE "G6"
#define CONTEXTHELP_AVAIL_MENU1 "H1"
#define CONTEXTHELP_AVAIL_MENU2 "H2"
#define CONTEXTHELP_AVAIL_MENU3 "H3"
#define CONTEXTHELP_AVAIL_MENU4 "H4"
#define CONTEXTHELP_AVAIL_MENU5 "H5"
#define CONTEXTHELP_AVAIL_HOSTGROUP "H6"
#define CONTEXTHELP_AVAIL_HOST "H7"
#define CONTEXTHELP_AVAIL_SERVICE "H8"
#define CONTEXTHELP_AVAIL_SERVICEGROUP "H9"
#define CONTEXTHELP_EXT_HOST "I1"
#define CONTEXTHELP_EXT_SERVICE "I2"
#define CONTEXTHELP_EXT_HOSTGROUP "I3"
#define CONTEXTHELP_EXT_PROCESS "I4"
#define CONTEXTHELP_EXT_PERFORMANCE "I5"
#define CONTEXTHELP_EXT_COMMENTS "I6"
#define CONTEXTHELP_EXT_DOWNTIME "I7"
#define CONTEXTHELP_EXT_QUEUE "I8"
#define CONTEXTHELP_EXT_SERVICEGROUP "I9"
#define CONTEXTHELP_CMD_INPUT "J1"
#define CONTEXTHELP_CMD_COMMIT "J2"
#define CONTEXTHELP_OUTAGES "K1"
#define CONTEXTHELP_CONFIG_MENU "L1"
#define CONTEXTHELP_CONFIG_HOSTS "L2"
#define CONTEXTHELP_CONFIG_HOSTDEPENDENCIES "L3"
#define CONTEXTHELP_CONFIG_HOSTESCALATIONS "L4"
#define CONTEXTHELP_CONFIG_HOSTGROUPS "L5"
#define CONTEXTHELP_CONFIG_HOSTGROUPESCALATIONS "L6"
#define CONTEXTHELP_CONFIG_SERVICES "L7"
#define CONTEXTHELP_CONFIG_SERVICEDEPENDENCIES "L8"
#define CONTEXTHELP_CONFIG_SERVICEESCALATIONS "L9"
#define CONTEXTHELP_CONFIG_CONTACTS "L10"
#define CONTEXTHELP_CONFIG_CONTACTGROUPS "L11"
#define CONTEXTHELP_CONFIG_TIMEPERIODS "L12"
#define CONTEXTHELP_CONFIG_COMMANDS "L13"
#define CONTEXTHELP_CONFIG_HOSTEXTINFO "L14"
#define CONTEXTHELP_CONFIG_SERVICEEXTINFO "L15"
#define CONTEXTHELP_CONFIG_SERVICEGROUPS "L16"
#define CONTEXTHELP_HISTOGRAM_MENU1 "M1"
#define CONTEXTHELP_HISTOGRAM_MENU2 "M2"
#define CONTEXTHELP_HISTOGRAM_MENU3 "M3"
#define CONTEXTHELP_HISTOGRAM_MENU4 "M4"
#define CONTEXTHELP_HISTOGRAM_HOST "M5"
#define CONTEXTHELP_HISTOGRAM_SERVICE "M6"
#define CONTEXTHELP_SUMMARY_MENU "N1"
#define CONTEXTHELP_SUMMARY_RECENT_ALERTS "N2"
#define CONTEXTHELP_SUMMARY_ALERT_TOTALS "N3"
#define CONTEXTHELP_SUMMARY_HOSTGROUP_ALERT_TOTALS "N4"
#define CONTEXTHELP_SUMMARY_HOST_ALERT_TOTALS "N5"
#define CONTEXTHELP_SUMMARY_SERVICE_ALERT_TOTALS "N6"
#define CONTEXTHELP_SUMMARY_ALERT_PRODUCERS "N7"
#define CONTEXTHELP_SUMMARY_SERVICEGROUP_ALERT_TOTALS "N8"
/************************** LIFO RETURN CODES ****************************/
#define LIFO_OK 0
#define LIFO_ERROR_MEMORY 1
#define LIFO_ERROR_FILE 2
#define LIFO_ERROR_DATA 3
/*************************** DATA STRUCTURES *****************************/
/* LIFO data structure */
typedef struct lifo_struct{
char *data;
struct lifo_struct *next;
}lifo;
/* MMAPFILE structure - used for reading files via mmap() */
typedef struct mmapfile_struct{
char *path;
int mode;
int fd;
unsigned long file_size;
unsigned long current_position;
unsigned long current_line;
void *mmap_buf;
}mmapfile;
/******************************** FUNCTIONS *******************************/
void reset_cgi_vars(void);
void free_cgi_vars(void);
void free_memory(void);
char * get_cgi_config_location(void); /* gets location of the CGI config file to read */
char * get_cmd_file_location(void); /* gets location of external command file to write to */
int read_cgi_config_file(char *);
int read_main_config_file(char *);
int read_all_object_configuration_data(char *,int);
int read_all_status_data(char *,int);
int hashfunc(const char *name1, const char *name2, int hashslots);
int compare_hashdata(const char *,const char *,const char *,const char *);
void strip(char *); /* strips newlines, carriage returns, and spaces from end of buffer */
char *unescape_newlines(char *);
void sanitize_plugin_output(char *); /* strips HTML and bad characters from plugin output */
void strip_html_brackets(char *); /* strips > and < from string */
int process_macros(char *,char **,int); /* processes macros in a string */
void get_time_string(time_t *,char *,int,int); /* gets a date/time string */
void get_datetime_string(time_t *,char *,int,int);
void get_interval_time_string(double,char *,int); /* gets a time string for an interval of time */
void get_expire_time_string(time_t *,char *,int); /* gets a date/time string in the format used for Expire: tags*/
char * my_strtok(char *,char *); /* replacement for strtok() function - doesn't skip multiple tokens */
char * my_strsep (char **, const char *);
#ifdef REMOVED_10182007
int my_free(void **); /* my wrapper for free() */
#endif
char * url_encode(char *); /* encodes a string in proper URL format */
char * html_encode(char *,int); /* encodes a string in HTML format (for what the user sees) */
char * escape_string(char *); /* escape string for html form usage */
void get_time_breakdown(unsigned long,int *,int *,int *,int *); /* given total seconds, get days, hours, minutes, seconds */
void get_log_archive_to_use(int,char *,int); /* determines the name of the log archive to use */
void determine_log_rotation_times(int);
int determine_archive_to_use_from_time(time_t);
void print_extra_hostgroup_url(char *,char *);
void print_extra_servicegroup_url(char *,char *);
void display_info_table(char *,int,authdata *);
void display_nav_table(char *,int);
void display_splunk_host_url(host *);
void display_splunk_service_url(service *);
void display_splunk_generic_url(char *,int);
void strip_splunk_query_terms(char *);
void include_ssi_files(char *,int); /* include user-defined SSI footers/headers */
void include_ssi_file(char *); /* include user-defined SSI footer/header */
void cgi_config_file_error(char *);
void main_config_file_error(char *);
void object_data_error(void);
void status_data_error(void);
void display_context_help(char *); /* displays context-sensitive help window */
int read_file_into_lifo(char *); /* LIFO functions */
void free_lifo_memory(void);
int push_lifo(char *);
char *pop_lifo(void);
mmapfile *mmap_fopen(char *); /* open a file read-only using mmap() */
int mmap_fclose(mmapfile *);
char *mmap_fgets(mmapfile *);
char *mmap_fgets_multiline(mmapfile *);
#ifdef __cplusplus
}
#endif
#endif

128
nagios/comments.h Normal file
View File

@@ -0,0 +1,128 @@
/*****************************************************************************
*
* COMMENTS.H - Header file for comment functions
*
* Copyright (c) 1999-2006 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 12-26-2006
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _COMMENTS_H
#define _COMMENTS_H
#include "config.h"
#include "common.h"
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
/**************************** COMMENT SOURCES ******************************/
#define COMMENTSOURCE_INTERNAL 0
#define COMMENTSOURCE_EXTERNAL 1
/***************************** COMMENT TYPES *******************************/
#define HOST_COMMENT 1
#define SERVICE_COMMENT 2
/****************************** ENTRY TYPES ********************************/
#define USER_COMMENT 1
#define DOWNTIME_COMMENT 2
#define FLAPPING_COMMENT 3
#define ACKNOWLEDGEMENT_COMMENT 4
/*************************** CHAINED HASH LIMITS ***************************/
#define COMMENT_HASHSLOTS 1024
/**************************** DATA STRUCTURES ******************************/
/* COMMENT structure */
typedef struct comment_struct{
int comment_type;
int entry_type;
unsigned long comment_id;
int source;
int persistent;
time_t entry_time;
int expires;
time_t expire_time;
char *host_name;
char *service_description;
char *author;
char *comment_data;
struct comment_struct *next;
struct comment_struct *nexthash;
}comment;
#ifdef NSCORE
int initialize_comment_data(char *); /* initializes comment data */
int cleanup_comment_data(char *); /* cleans up comment data */
int add_new_comment(int,int,char *,char *,time_t,char *,char *,int,int,int,time_t,unsigned long *); /* adds a new host or service comment */
int add_new_host_comment(int,char *,time_t,char *,char *,int,int,int,time_t,unsigned long *); /* adds a new host comment */
int add_new_service_comment(int,char *,char *,time_t,char *,char *,int,int,int,time_t,unsigned long *); /* adds a new service comment */
int delete_comment(int,unsigned long); /* deletes a host or service comment */
int delete_host_comment(unsigned long); /* deletes a host comment */
int delete_service_comment(unsigned long); /* deletes a service comment */
int delete_all_comments(int,char *,char *); /* deletes all comments for a particular host or service */
int delete_all_host_comments(char *); /* deletes all comments for a specific host */
int delete_host_acknowledgement_comments(host *); /* deletes all non-persistent ack comments for a specific host */
int delete_all_service_comments(char *,char *); /* deletes all comments for a specific service */
int delete_service_acknowledgement_comments(service *); /* deletes all non-persistent ack comments for a specific service */
int check_for_expired_comment(unsigned long); /* expires a comment */
#endif
comment *find_comment(unsigned long,int); /* finds a specific comment */
comment *find_service_comment(unsigned long); /* finds a specific service comment */
comment *find_host_comment(unsigned long); /* finds a specific host comment */
comment *get_first_comment_by_host(char *);
comment *get_next_comment_by_host(char *,comment *);
int number_of_host_comments(char *); /* returns the number of comments associated with a particular host */
int number_of_service_comments(char *, char *); /* returns the number of comments associated with a particular service */
int add_comment(int,int,char *,char *,time_t,char *,char *,unsigned long,int,int,time_t,int); /* adds a comment (host or service) */
int add_host_comment(int,char *,time_t,char *,char *,unsigned long,int,int,time_t,int); /* adds a host comment */
int add_service_comment(int,char *,char *,time_t,char *,char *,unsigned long,int,int,time_t,int); /* adds a service comment */
int add_comment_to_hashlist(comment *);
void free_comment_data(void); /* frees memory allocated to the comment list */
#ifdef __cplusplus
}
#endif
#endif

501
nagios/common.h Normal file
View File

@@ -0,0 +1,501 @@
/************************************************************************
*
* Nagios Common Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
* Last Modified: 10-22-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#define PROGRAM_VERSION "3.2.0"
#define PROGRAM_MODIFICATION_DATE "08-12-2009"
/*#define DEBUG_CHECK_IPC 1 */
/*#define DEBUG_CHECK_IPC2 1*/
/* daemon is thread safe */
#ifdef NSCORE
#ifndef _REENTRANT
#define _REENTRANT
#endif
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#endif
/* Experimental performance tweaks - use with caution */
#undef USE_MEMORY_PERFORMANCE_TWEAKS
/* my_free has been freed from bondage as a function */
#define my_free(ptr) { if(ptr) { free(ptr); ptr = NULL; } }
/***************************** COMMANDS *********************************/
#define CMD_NONE 0
#define CMD_ADD_HOST_COMMENT 1
#define CMD_DEL_HOST_COMMENT 2
#define CMD_ADD_SVC_COMMENT 3
#define CMD_DEL_SVC_COMMENT 4
#define CMD_ENABLE_SVC_CHECK 5
#define CMD_DISABLE_SVC_CHECK 6
#define CMD_SCHEDULE_SVC_CHECK 7
#define CMD_DELAY_SVC_NOTIFICATION 9
#define CMD_DELAY_HOST_NOTIFICATION 10
#define CMD_DISABLE_NOTIFICATIONS 11
#define CMD_ENABLE_NOTIFICATIONS 12
#define CMD_RESTART_PROCESS 13
#define CMD_SHUTDOWN_PROCESS 14
#define CMD_ENABLE_HOST_SVC_CHECKS 15
#define CMD_DISABLE_HOST_SVC_CHECKS 16
#define CMD_SCHEDULE_HOST_SVC_CHECKS 17
#define CMD_DELAY_HOST_SVC_NOTIFICATIONS 19 /* currently unimplemented */
#define CMD_DEL_ALL_HOST_COMMENTS 20
#define CMD_DEL_ALL_SVC_COMMENTS 21
#define CMD_ENABLE_SVC_NOTIFICATIONS 22
#define CMD_DISABLE_SVC_NOTIFICATIONS 23
#define CMD_ENABLE_HOST_NOTIFICATIONS 24
#define CMD_DISABLE_HOST_NOTIFICATIONS 25
#define CMD_ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST 26
#define CMD_DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST 27
#define CMD_ENABLE_HOST_SVC_NOTIFICATIONS 28
#define CMD_DISABLE_HOST_SVC_NOTIFICATIONS 29
#define CMD_PROCESS_SERVICE_CHECK_RESULT 30
#define CMD_SAVE_STATE_INFORMATION 31
#define CMD_READ_STATE_INFORMATION 32
#define CMD_ACKNOWLEDGE_HOST_PROBLEM 33
#define CMD_ACKNOWLEDGE_SVC_PROBLEM 34
#define CMD_START_EXECUTING_SVC_CHECKS 35
#define CMD_STOP_EXECUTING_SVC_CHECKS 36
#define CMD_START_ACCEPTING_PASSIVE_SVC_CHECKS 37
#define CMD_STOP_ACCEPTING_PASSIVE_SVC_CHECKS 38
#define CMD_ENABLE_PASSIVE_SVC_CHECKS 39
#define CMD_DISABLE_PASSIVE_SVC_CHECKS 40
#define CMD_ENABLE_EVENT_HANDLERS 41
#define CMD_DISABLE_EVENT_HANDLERS 42
#define CMD_ENABLE_HOST_EVENT_HANDLER 43
#define CMD_DISABLE_HOST_EVENT_HANDLER 44
#define CMD_ENABLE_SVC_EVENT_HANDLER 45
#define CMD_DISABLE_SVC_EVENT_HANDLER 46
#define CMD_ENABLE_HOST_CHECK 47
#define CMD_DISABLE_HOST_CHECK 48
#define CMD_START_OBSESSING_OVER_SVC_CHECKS 49
#define CMD_STOP_OBSESSING_OVER_SVC_CHECKS 50
#define CMD_REMOVE_HOST_ACKNOWLEDGEMENT 51
#define CMD_REMOVE_SVC_ACKNOWLEDGEMENT 52
#define CMD_SCHEDULE_FORCED_HOST_SVC_CHECKS 53
#define CMD_SCHEDULE_FORCED_SVC_CHECK 54
#define CMD_SCHEDULE_HOST_DOWNTIME 55
#define CMD_SCHEDULE_SVC_DOWNTIME 56
#define CMD_ENABLE_HOST_FLAP_DETECTION 57
#define CMD_DISABLE_HOST_FLAP_DETECTION 58
#define CMD_ENABLE_SVC_FLAP_DETECTION 59
#define CMD_DISABLE_SVC_FLAP_DETECTION 60
#define CMD_ENABLE_FLAP_DETECTION 61
#define CMD_DISABLE_FLAP_DETECTION 62
#define CMD_ENABLE_HOSTGROUP_SVC_NOTIFICATIONS 63
#define CMD_DISABLE_HOSTGROUP_SVC_NOTIFICATIONS 64
#define CMD_ENABLE_HOSTGROUP_HOST_NOTIFICATIONS 65
#define CMD_DISABLE_HOSTGROUP_HOST_NOTIFICATIONS 66
#define CMD_ENABLE_HOSTGROUP_SVC_CHECKS 67
#define CMD_DISABLE_HOSTGROUP_SVC_CHECKS 68
#define CMD_CANCEL_HOST_DOWNTIME 69 /* not internally implemented */
#define CMD_CANCEL_SVC_DOWNTIME 70 /* not internally implemented */
#define CMD_CANCEL_ACTIVE_HOST_DOWNTIME 71 /* old - no longer used */
#define CMD_CANCEL_PENDING_HOST_DOWNTIME 72 /* old - no longer used */
#define CMD_CANCEL_ACTIVE_SVC_DOWNTIME 73 /* old - no longer used */
#define CMD_CANCEL_PENDING_SVC_DOWNTIME 74 /* old - no longer used */
#define CMD_CANCEL_ACTIVE_HOST_SVC_DOWNTIME 75 /* unimplemented */
#define CMD_CANCEL_PENDING_HOST_SVC_DOWNTIME 76 /* unimplemented */
#define CMD_FLUSH_PENDING_COMMANDS 77
#define CMD_DEL_HOST_DOWNTIME 78
#define CMD_DEL_SVC_DOWNTIME 79
#define CMD_ENABLE_FAILURE_PREDICTION 80
#define CMD_DISABLE_FAILURE_PREDICTION 81
#define CMD_ENABLE_PERFORMANCE_DATA 82
#define CMD_DISABLE_PERFORMANCE_DATA 83
#define CMD_SCHEDULE_HOSTGROUP_HOST_DOWNTIME 84
#define CMD_SCHEDULE_HOSTGROUP_SVC_DOWNTIME 85
#define CMD_SCHEDULE_HOST_SVC_DOWNTIME 86
/* new commands in Nagios 2.x found below... */
#define CMD_PROCESS_HOST_CHECK_RESULT 87
#define CMD_START_EXECUTING_HOST_CHECKS 88
#define CMD_STOP_EXECUTING_HOST_CHECKS 89
#define CMD_START_ACCEPTING_PASSIVE_HOST_CHECKS 90
#define CMD_STOP_ACCEPTING_PASSIVE_HOST_CHECKS 91
#define CMD_ENABLE_PASSIVE_HOST_CHECKS 92
#define CMD_DISABLE_PASSIVE_HOST_CHECKS 93
#define CMD_START_OBSESSING_OVER_HOST_CHECKS 94
#define CMD_STOP_OBSESSING_OVER_HOST_CHECKS 95
#define CMD_SCHEDULE_HOST_CHECK 96
#define CMD_SCHEDULE_FORCED_HOST_CHECK 98
#define CMD_START_OBSESSING_OVER_SVC 99
#define CMD_STOP_OBSESSING_OVER_SVC 100
#define CMD_START_OBSESSING_OVER_HOST 101
#define CMD_STOP_OBSESSING_OVER_HOST 102
#define CMD_ENABLE_HOSTGROUP_HOST_CHECKS 103
#define CMD_DISABLE_HOSTGROUP_HOST_CHECKS 104
#define CMD_ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS 105
#define CMD_DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS 106
#define CMD_ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS 107
#define CMD_DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS 108
#define CMD_ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS 109
#define CMD_DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS 110
#define CMD_ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS 111
#define CMD_DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS 112
#define CMD_ENABLE_SERVICEGROUP_SVC_CHECKS 113
#define CMD_DISABLE_SERVICEGROUP_SVC_CHECKS 114
#define CMD_ENABLE_SERVICEGROUP_HOST_CHECKS 115
#define CMD_DISABLE_SERVICEGROUP_HOST_CHECKS 116
#define CMD_ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS 117
#define CMD_DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS 118
#define CMD_ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS 119
#define CMD_DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS 120
#define CMD_SCHEDULE_SERVICEGROUP_HOST_DOWNTIME 121
#define CMD_SCHEDULE_SERVICEGROUP_SVC_DOWNTIME 122
#define CMD_CHANGE_GLOBAL_HOST_EVENT_HANDLER 123
#define CMD_CHANGE_GLOBAL_SVC_EVENT_HANDLER 124
#define CMD_CHANGE_HOST_EVENT_HANDLER 125
#define CMD_CHANGE_SVC_EVENT_HANDLER 126
#define CMD_CHANGE_HOST_CHECK_COMMAND 127
#define CMD_CHANGE_SVC_CHECK_COMMAND 128
#define CMD_CHANGE_NORMAL_HOST_CHECK_INTERVAL 129
#define CMD_CHANGE_NORMAL_SVC_CHECK_INTERVAL 130
#define CMD_CHANGE_RETRY_SVC_CHECK_INTERVAL 131
#define CMD_CHANGE_MAX_HOST_CHECK_ATTEMPTS 132
#define CMD_CHANGE_MAX_SVC_CHECK_ATTEMPTS 133
#define CMD_SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME 134
#define CMD_ENABLE_HOST_AND_CHILD_NOTIFICATIONS 135
#define CMD_DISABLE_HOST_AND_CHILD_NOTIFICATIONS 136
#define CMD_SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME 137
#define CMD_ENABLE_SERVICE_FRESHNESS_CHECKS 138
#define CMD_DISABLE_SERVICE_FRESHNESS_CHECKS 139
#define CMD_ENABLE_HOST_FRESHNESS_CHECKS 140
#define CMD_DISABLE_HOST_FRESHNESS_CHECKS 141
#define CMD_SET_HOST_NOTIFICATION_NUMBER 142
#define CMD_SET_SVC_NOTIFICATION_NUMBER 143
/* new commands in Nagios 3.x found below... */
#define CMD_CHANGE_HOST_CHECK_TIMEPERIOD 144
#define CMD_CHANGE_SVC_CHECK_TIMEPERIOD 145
#define CMD_PROCESS_FILE 146
#define CMD_CHANGE_CUSTOM_HOST_VAR 147
#define CMD_CHANGE_CUSTOM_SVC_VAR 148
#define CMD_CHANGE_CUSTOM_CONTACT_VAR 149
#define CMD_ENABLE_CONTACT_HOST_NOTIFICATIONS 150
#define CMD_DISABLE_CONTACT_HOST_NOTIFICATIONS 151
#define CMD_ENABLE_CONTACT_SVC_NOTIFICATIONS 152
#define CMD_DISABLE_CONTACT_SVC_NOTIFICATIONS 153
#define CMD_ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS 154
#define CMD_DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS 155
#define CMD_ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS 156
#define CMD_DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS 157
#define CMD_CHANGE_RETRY_HOST_CHECK_INTERVAL 158
#define CMD_SEND_CUSTOM_HOST_NOTIFICATION 159
#define CMD_SEND_CUSTOM_SVC_NOTIFICATION 160
#define CMD_CHANGE_HOST_NOTIFICATION_TIMEPERIOD 161
#define CMD_CHANGE_SVC_NOTIFICATION_TIMEPERIOD 162
#define CMD_CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD 163
#define CMD_CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD 164
#define CMD_CHANGE_HOST_MODATTR 165
#define CMD_CHANGE_SVC_MODATTR 166
#define CMD_CHANGE_CONTACT_MODATTR 167
#define CMD_CHANGE_CONTACT_MODHATTR 168
#define CMD_CHANGE_CONTACT_MODSATTR 169
/* custom command introduced in Nagios 3.x */
#define CMD_CUSTOM_COMMAND 999
/************************ SERVICE CHECK TYPES ****************************/
#define SERVICE_CHECK_ACTIVE 0 /* Nagios performed the service check */
#define SERVICE_CHECK_PASSIVE 1 /* the service check result was submitted by an external source */
/************************** HOST CHECK TYPES *****************************/
#define HOST_CHECK_ACTIVE 0 /* Nagios performed the host check */
#define HOST_CHECK_PASSIVE 1 /* the host check result was submitted by an external source */
/************************ SERVICE STATE TYPES ****************************/
#define SOFT_STATE 0
#define HARD_STATE 1
/************************* SCHEDULED DOWNTIME TYPES **********************/
#define SERVICE_DOWNTIME 1 /* service downtime */
#define HOST_DOWNTIME 2 /* host downtime */
#define ANY_DOWNTIME 3 /* host or service downtime */
/************************** NOTIFICATION OPTIONS *************************/
#define NOTIFICATION_OPTION_NONE 0
#define NOTIFICATION_OPTION_BROADCAST 1
#define NOTIFICATION_OPTION_FORCED 2
#define NOTIFICATION_OPTION_INCREMENT 4
/************************** ACKNOWLEDGEMENT TYPES ************************/
#define HOST_ACKNOWLEDGEMENT 0
#define SERVICE_ACKNOWLEDGEMENT 1
#define ACKNOWLEDGEMENT_NONE 0
#define ACKNOWLEDGEMENT_NORMAL 1
#define ACKNOWLEDGEMENT_STICKY 2
/**************************** DEPENDENCY TYPES ***************************/
#define NOTIFICATION_DEPENDENCY 1
#define EXECUTION_DEPENDENCY 2
/********************** HOST/SERVICE CHECK OPTIONS ***********************/
#define CHECK_OPTION_NONE 0 /* no check options */
#define CHECK_OPTION_FORCE_EXECUTION 1 /* force execution of a check (ignores disabled services/hosts, invalid timeperiods) */
#define CHECK_OPTION_FRESHNESS_CHECK 2 /* this is a freshness check */
#define CHECK_OPTION_ORPHAN_CHECK 4 /* this is an orphan check */
/**************************** PROGRAM MODES ******************************/
#define STANDBY_MODE 0
#define ACTIVE_MODE 1
/************************** LOG ROTATION MODES ***************************/
#define LOG_ROTATION_NONE 0
#define LOG_ROTATION_HOURLY 1
#define LOG_ROTATION_DAILY 2
#define LOG_ROTATION_WEEKLY 3
#define LOG_ROTATION_MONTHLY 4
/***************************** LOG VERSIONS ******************************/
#define LOG_VERSION_1 "1.0"
#define LOG_VERSION_2 "2.0"
/*************************** CHECK STATISTICS ****************************/
#define ACTIVE_SCHEDULED_SERVICE_CHECK_STATS 0
#define ACTIVE_ONDEMAND_SERVICE_CHECK_STATS 1
#define PASSIVE_SERVICE_CHECK_STATS 2
#define ACTIVE_SCHEDULED_HOST_CHECK_STATS 3
#define ACTIVE_ONDEMAND_HOST_CHECK_STATS 4
#define PASSIVE_HOST_CHECK_STATS 5
#define ACTIVE_CACHED_HOST_CHECK_STATS 6
#define ACTIVE_CACHED_SERVICE_CHECK_STATS 7
#define EXTERNAL_COMMAND_STATS 8
#define PARALLEL_HOST_CHECK_STATS 9
#define SERIAL_HOST_CHECK_STATS 10
#define MAX_CHECK_STATS_TYPES 11
/************************* GENERAL DEFINITIONS **************************/
#define OK 0
#define ERROR -2 /* value was changed from -1 so as to not interfere with STATUS_UNKNOWN plugin result */
#ifndef TRUE
#define TRUE 1
#elif (TRUE!=1)
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#elif (FALSE!=0)
#define FALSE 0
#endif
/****************** HOST CONFIG FILE READING OPTIONS ********************/
#define READ_HOSTS 1
#define READ_HOSTGROUPS 2
#define READ_CONTACTS 4
#define READ_CONTACTGROUPS 8
#define READ_SERVICES 16
#define READ_COMMANDS 32
#define READ_TIMEPERIODS 64
#define READ_SERVICEESCALATIONS 128
#define READ_HOSTGROUPESCALATIONS 256 /* no longer implemented */
#define READ_SERVICEDEPENDENCIES 512
#define READ_HOSTDEPENDENCIES 1024
#define READ_HOSTESCALATIONS 2048
#define READ_HOSTEXTINFO 4096
#define READ_SERVICEEXTINFO 8192
#define READ_SERVICEGROUPS 16384
#define READ_ALL_OBJECT_DATA READ_HOSTS | READ_HOSTGROUPS | READ_CONTACTS | READ_CONTACTGROUPS | READ_SERVICES | READ_COMMANDS | READ_TIMEPERIODS | READ_SERVICEESCALATIONS | READ_SERVICEDEPENDENCIES | READ_HOSTDEPENDENCIES | READ_HOSTESCALATIONS | READ_HOSTEXTINFO | READ_SERVICEEXTINFO | READ_SERVICEGROUPS
/************************** DATE RANGE TYPES ****************************/
#define DATERANGE_CALENDAR_DATE 0 /* 2008-12-25 */
#define DATERANGE_MONTH_DATE 1 /* july 4 (specific month) */
#define DATERANGE_MONTH_DAY 2 /* day 21 (generic month) */
#define DATERANGE_MONTH_WEEK_DAY 3 /* 3rd thursday (specific month) */
#define DATERANGE_WEEK_DAY 4 /* 3rd thursday (generic month) */
#define DATERANGE_TYPES 5
/************************** DATE/TIME TYPES *****************************/
#define LONG_DATE_TIME 0
#define SHORT_DATE_TIME 1
#define SHORT_DATE 2
#define SHORT_TIME 3
#define HTTP_DATE_TIME 4 /* time formatted for use in HTTP headers */
/**************************** DATE FORMATS ******************************/
#define DATE_FORMAT_US 0 /* U.S. (MM-DD-YYYY HH:MM:SS) */
#define DATE_FORMAT_EURO 1 /* European (DD-MM-YYYY HH:MM:SS) */
#define DATE_FORMAT_ISO8601 2 /* ISO8601 (YYYY-MM-DD HH:MM:SS) */
#define DATE_FORMAT_STRICT_ISO8601 3 /* ISO8601 (YYYY-MM-DDTHH:MM:SS) */
/************************** MISC DEFINITIONS ****************************/
#define MAX_FILENAME_LENGTH 256 /* max length of path/filename that Nagios will process */
#define MAX_INPUT_BUFFER 1024 /* size in bytes of max. input buffer (for reading files, misc stuff) */
#define MAX_COMMAND_BUFFER 8192 /* max length of raw or processed command line */
#define MAX_EXTERNAL_COMMAND_LENGTH 8192 /* max length of an external command */
#define MAX_DATETIME_LENGTH 48
/************************* MODIFIED ATTRIBUTES **************************/
#define MODATTR_NONE 0
#define MODATTR_NOTIFICATIONS_ENABLED 1
#define MODATTR_ACTIVE_CHECKS_ENABLED 2
#define MODATTR_PASSIVE_CHECKS_ENABLED 4
#define MODATTR_EVENT_HANDLER_ENABLED 8
#define MODATTR_FLAP_DETECTION_ENABLED 16
#define MODATTR_FAILURE_PREDICTION_ENABLED 32
#define MODATTR_PERFORMANCE_DATA_ENABLED 64
#define MODATTR_OBSESSIVE_HANDLER_ENABLED 128
#define MODATTR_EVENT_HANDLER_COMMAND 256
#define MODATTR_CHECK_COMMAND 512
#define MODATTR_NORMAL_CHECK_INTERVAL 1024
#define MODATTR_RETRY_CHECK_INTERVAL 2048
#define MODATTR_MAX_CHECK_ATTEMPTS 4096
#define MODATTR_FRESHNESS_CHECKS_ENABLED 8192
#define MODATTR_CHECK_TIMEPERIOD 16384
#define MODATTR_CUSTOM_VARIABLE 32768
#define MODATTR_NOTIFICATION_TIMEPERIOD 65536

336
nagios/config.h Normal file
View File

@@ -0,0 +1,336 @@
/* include/config.h. Generated by configure. */
/************************************************************************
*
* Nagios Config Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
* Last Modified: 11-02-2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
/***** NAGIOS STUFF *****/
#define DEFAULT_NAGIOS_USER "nagios"
#define DEFAULT_NAGIOS_GROUP "nagios"
/* stop gcc from bitching about implicit asprintf declarations */
#define _GNU_SOURCE 1
/* Event broker integration */
#define USE_EVENT_BROKER 1
/* Embed a PERL interpreter into Nagios with optional cache for compiled code (contributed by Stephen Davies) */
/* #undef EMBEDDEDPERL */
/* #undef THREADEDPERL */
/* 0 = cache, 1 = do not cache */
#define DO_CLEAN "1"
/* commands used by CGIs */
#define TRACEROUTE_COMMAND "/usr/bin/traceroute"
/* #undef PING_COMMAND */
/* #undef PING_PACKETS_FIRST */
/* Debugging options */
/* function entry and exit */
/* #undef DEBUG0 */
/* general info messages */
/* #undef DEBUG1 */
/* warning messages */
/* #undef DEBUG2 */
/* service and host checks, other events */
/* #undef DEBUG3 */
/* service and host notifications */
/* #undef DEBUG4 */
/* SQL queries (defunct) */
/* #undef DEBUG5 */
/* I/O implementations */
#define USE_XSDDEFAULT 1
#define USE_XCDDEFAULT 1
#define USE_XRDDEFAULT 1
#define USE_XODTEMPLATE 1
#define USE_XPDDEFAULT 1
#define USE_XDDDEFAULT 1
/***** FUNCTION DEFINITIONS *****/
#define HAVE_SETENV 1
#define HAVE_UNSETENV 1
/* #undef HAVE_SOCKET */
#define HAVE_STRDUP 1
#define HAVE_STRSTR 1
#define HAVE_STRTOUL 1
#define HAVE_INITGROUPS 1
/* #undef HAVE_GETLOADAVG */
#define HAVE_GDIMAGECREATETRUECOLOR 1
/***** ASPRINTF() AND FRIENDS *****/
/* #undef HAVE_VSNPRINTF */
/* #undef HAVE_SNPRINTF */
/* #undef HAVE_ASPRINTF */
/* #undef HAVE_VASPRINTF */
#define HAVE_C99_VSNPRINTF 1
#define HAVE_VA_COPY 1
/* #undef HAVE___VA_COPY */
/***** MISC DEFINITIONS *****/
#define USE_NANOSLEEP 1
#define STDC_HEADERS 1
#define HAVE_TM_ZONE 1
/* #undef HAVE_TZNAME */
/* #undef USE_PROC */
#define SOCKET_SIZE_TYPE size_t
#define GETGROUPS_T gid_t
#define RETSIGTYPE void
/***** HEADER FILES *****/
#include <stdio.h>
#include <stdlib.h>
/* needed for the time_t structures we use later... */
/* this include must come before sys/resource.h or we can have problems on some OSes */
#define TIME_WITH_SYS_TIME 1
#define HAVE_SYS_TIME_H 1
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#define HAVE_SYS_RESOURCE_H 1
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#define HAVE_LIMITS_H 1
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#define HAVE_PWD_H 1
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#define HAVE_GRP_H 1
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#define HAVE_STRINGS_H 1
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#define HAVE_STRING_H 1
#ifdef HAVE_STRINGS_H
#include <string.h>
#endif
#define HAVE_UNISTD_H 1
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#define HAVE_SYSLOG_H 1
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#define HAVE_SIGNAL_H 1
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#define HAVE_SYS_STAT_H 1
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#define HAVE_SYS_MMAN_H 1
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#define HAVE_FCNTL_H 1
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#define HAVE_STDARG_H 1
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#define HAVE_SYS_TYPES_H 1
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#define HAVE_SYS_WAIT_H 1
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#define HAVE_ERRNO_H 1
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#define HAVE_SYS_TIMEB_H 1
#if HAVE_SYS_TIMEB_H
#include <sys/timeb.h>
#endif
#define HAVE_SYS_IPC_H 1
#ifdef HAVE_SYS_IPC_H
#include <sys/ipc.h>
#endif
#define HAVE_SYS_MSG_H 1
#ifdef HAVE_SYS_MSG_H
#include <sys/msg.h>
#endif
#define HAVE_MATH_H 1
#ifdef HAVE_MATH_H
#include <math.h>
#endif
#define HAVE_CTYPE_H 1
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#define HAVE_DIRENT_H 1
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#define HAVE_PTHREAD_H 1
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif
#define HAVE_REGEX_H 1
#ifdef HAVE_REGEX_H
#include <regex.h>
#define HAVE_SYS_SOCKET_H 1
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
/* #undef HAVE_SOCKET */
#ifdef HAVE_SOCKET_H
#include <socket.h>
#endif
#define HAVE_NETINET_IN_H 1
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#define HAVE_ARPA_INET_H 1
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#define HAVE_NETDB_H 1
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#define HAVE_LIBGEN_H 1
#ifdef HAVE_LIBGEN_H
#include <libgen.h>
#endif
#define HAVE_SYS_UN_H 1
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#define HAVE_SYS_POLL_H 1
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
/* #define HAVE_GETOPT_H 1 */
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
/* #undef HAVE_LINUX_MODULE_H */
#ifdef HAVE_LINUX_MODULE_H
#include <linux/module.h>
#endif
/* configure script should allow user to override ltdl choice, but this will do for now... */
/* #undef USE_LTDL */
#ifdef HAVE_LTDL_H
#define USE_LTDL
#endif
#ifdef USE_LTDL
#include <ltdl.h>
#else
/* #undef HAVE_DLFCN_H */
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif
#endif
/* moved to end to prevent AIX compiler warnings */
#ifndef RTLD_GLOBAL
#define RTLD_GLOBAL 0
#endif
#ifndef RTLD_NOW
#define RTLD_NOW 0
#endif
/***** MARO DEFINITIONS *****/
/* this needs to come after all system include files, so we don't accidentally attempt to redefine it */
#ifndef WEXITSTATUS
# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#endif
#ifndef WIFEXITED
# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
#endif
#endif

101
nagios/downtime.h Normal file
View File

@@ -0,0 +1,101 @@
/*****************************************************************************
*
* DOWNTIME.H - Header file for scheduled downtime functions
*
* Copyright (c) 2001-2005 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 11-25-2005
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _DOWNTIME_H
#define _DOWNTIME_H
#include "config.h"
#include "common.h"
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
/* SCHEDULED_DOWNTIME_ENTRY structure */
typedef struct scheduled_downtime_struct{
int type;
char *host_name;
char *service_description;
time_t entry_time;
time_t start_time;
time_t end_time;
int fixed;
unsigned long triggered_by;
unsigned long duration;
unsigned long downtime_id;
char *author;
char *comment;
#ifdef NSCORE
unsigned long comment_id;
int is_in_effect;
int start_flex_downtime;
int incremented_pending_downtime;
#endif
struct scheduled_downtime_struct *next;
}scheduled_downtime;
#ifdef NSCORE
int initialize_downtime_data(char *); /* initializes scheduled downtime data */
int cleanup_downtime_data(char *); /* cleans up scheduled downtime data */
int add_new_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *);
int add_new_host_downtime(char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *);
int add_new_service_downtime(char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *);
int delete_host_downtime(unsigned long);
int delete_service_downtime(unsigned long);
int delete_downtime(int,unsigned long);
int schedule_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *);
int unschedule_downtime(int,unsigned long);
int register_downtime(int,unsigned long);
int handle_scheduled_downtime(scheduled_downtime *);
int handle_scheduled_downtime_by_id(unsigned long);
int check_pending_flex_host_downtime(host *);
int check_pending_flex_service_downtime(service *);
int check_for_expired_downtime(void);
#endif
int add_host_downtime(char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long);
int add_service_downtime(char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long);
int add_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long);
scheduled_downtime *find_downtime(int,unsigned long);
scheduled_downtime *find_host_downtime(unsigned long);
scheduled_downtime *find_service_downtime(unsigned long);
void free_downtime_data(void); /* frees memory allocated to scheduled downtime list */
#ifdef __cplusplus
}
#endif
#endif

44
nagios/locations.h Normal file
View File

@@ -0,0 +1,44 @@
/************************************************************************
*
* Nagios Locations Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
* Last Modified: 04-30-2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#define DEFAULT_TEMP_FILE "/usr/local/nagios/var/tempfile"
#define DEFAULT_TEMP_PATH "/tmp"
#define DEFAULT_CHECK_RESULT_PATH "/usr/local/nagios/var/spool/checkresults"
#define DEFAULT_STATUS_FILE "/usr/local/nagios/var/status.dat"
#define DEFAULT_LOG_FILE "/usr/local/nagios/var/nagios.log"
#define DEFAULT_LOG_ARCHIVE_PATH "/usr/local/nagios/var/archives/"
#define DEFAULT_DEBUG_FILE "/usr/local/nagios/var/nagios.debug"
#define DEFAULT_COMMENT_FILE "/usr/local/nagios/var/comments.dat"
#define DEFAULT_DOWNTIME_FILE "/usr/local/nagios/var/downtime.dat"
#define DEFAULT_RETENTION_FILE "/usr/local/nagios/var/retention.dat"
#define DEFAULT_COMMAND_FILE "/usr/local/nagios/var/rw/nagios.cmd"
#define DEFAULT_CONFIG_FILE "/usr/local/nagios/etc/nagios.cfg"
#define DEFAULT_PHYSICAL_HTML_PATH "/usr/local/nagios/share"
#define DEFAULT_URL_HTML_PATH "/nagios"
#define DEFAULT_PHYSICAL_CGIBIN_PATH "/usr/local/nagios/sbin"
#define DEFAULT_URL_CGIBIN_PATH "/nagios/cgi-bin"
#define DEFAULT_CGI_CONFIG_FILE "/usr/local/nagios/etc/cgi.cfg"
#define DEFAULT_LOCK_FILE "/usr/local/nagios/var/nagios.lock"
#define DEFAULT_OBJECT_CACHE_FILE "/usr/local/nagios/var/objects.cache"
#define DEFAULT_PRECACHED_OBJECT_FILE "/usr/local/nagios/var/objects.precache"
#define DEFAULT_EVENT_BROKER_FILE "/usr/local/nagios/var/broker.socket"
#define DEFAULT_P1_FILE "/usr/local/nagios/bin/p1.pl" /**** EMBEDDED PERL ****/
#define DEFAULT_AUTH_FILE "" /**** EMBEDDED PERL - IS THIS USED? ****/

264
nagios/macros.h Normal file
View File

@@ -0,0 +1,264 @@
/************************************************************************
*
* MACROS.H - Common macro functions
* Written By: Ethan Galstad (egalstad@nagios.org)
* Last Modified: 10-28-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef _MACROS_H
#define _MACROS_H
#include "config.h"
#include "common.h"
#include "objects.h"
/****************** LENGTH LIMITATIONS ****************/
#define MAX_COMMAND_ARGUMENTS 32 /* maximum number of $ARGx$ macros */
/****************** MACRO DEFINITIONS *****************/
#define MACRO_ENV_VAR_PREFIX "NAGIOS_"
#define MAX_USER_MACROS 256 /* maximum number of $USERx$ macros */
#define MACRO_X_COUNT 153 /* size of macro_x[] array */
#define MACRO_HOSTNAME 0
#define MACRO_HOSTALIAS 1
#define MACRO_HOSTADDRESS 2
#define MACRO_SERVICEDESC 3
#define MACRO_SERVICESTATE 4
#define MACRO_SERVICESTATEID 5
#define MACRO_SERVICEATTEMPT 6
#define MACRO_LONGDATETIME 7
#define MACRO_SHORTDATETIME 8
#define MACRO_DATE 9
#define MACRO_TIME 10
#define MACRO_TIMET 11
#define MACRO_LASTHOSTCHECK 12
#define MACRO_LASTSERVICECHECK 13
#define MACRO_LASTHOSTSTATECHANGE 14
#define MACRO_LASTSERVICESTATECHANGE 15
#define MACRO_HOSTOUTPUT 16
#define MACRO_SERVICEOUTPUT 17
#define MACRO_HOSTPERFDATA 18
#define MACRO_SERVICEPERFDATA 19
#define MACRO_CONTACTNAME 20
#define MACRO_CONTACTALIAS 21
#define MACRO_CONTACTEMAIL 22
#define MACRO_CONTACTPAGER 23
#define MACRO_ADMINEMAIL 24
#define MACRO_ADMINPAGER 25
#define MACRO_HOSTSTATE 26
#define MACRO_HOSTSTATEID 27
#define MACRO_HOSTATTEMPT 28
#define MACRO_NOTIFICATIONTYPE 29
#define MACRO_NOTIFICATIONNUMBER 30 /* deprecated - see HOSTNOTIFICATIONNUMBER and SERVICENOTIFICATIONNUMBER macros */
#define MACRO_HOSTEXECUTIONTIME 31
#define MACRO_SERVICEEXECUTIONTIME 32
#define MACRO_HOSTLATENCY 33
#define MACRO_SERVICELATENCY 34
#define MACRO_HOSTDURATION 35
#define MACRO_SERVICEDURATION 36
#define MACRO_HOSTDURATIONSEC 37
#define MACRO_SERVICEDURATIONSEC 38
#define MACRO_HOSTDOWNTIME 39
#define MACRO_SERVICEDOWNTIME 40
#define MACRO_HOSTSTATETYPE 41
#define MACRO_SERVICESTATETYPE 42
#define MACRO_HOSTPERCENTCHANGE 43
#define MACRO_SERVICEPERCENTCHANGE 44
#define MACRO_HOSTGROUPNAME 45
#define MACRO_HOSTGROUPALIAS 46
#define MACRO_SERVICEGROUPNAME 47
#define MACRO_SERVICEGROUPALIAS 48
#define MACRO_HOSTACKAUTHOR 49
#define MACRO_HOSTACKCOMMENT 50
#define MACRO_SERVICEACKAUTHOR 51
#define MACRO_SERVICEACKCOMMENT 52
#define MACRO_LASTSERVICEOK 53
#define MACRO_LASTSERVICEWARNING 54
#define MACRO_LASTSERVICEUNKNOWN 55
#define MACRO_LASTSERVICECRITICAL 56
#define MACRO_LASTHOSTUP 57
#define MACRO_LASTHOSTDOWN 58
#define MACRO_LASTHOSTUNREACHABLE 59
#define MACRO_SERVICECHECKCOMMAND 60
#define MACRO_HOSTCHECKCOMMAND 61
#define MACRO_MAINCONFIGFILE 62
#define MACRO_STATUSDATAFILE 63
#define MACRO_HOSTDISPLAYNAME 64
#define MACRO_SERVICEDISPLAYNAME 65
#define MACRO_RETENTIONDATAFILE 66
#define MACRO_OBJECTCACHEFILE 67
#define MACRO_TEMPFILE 68
#define MACRO_LOGFILE 69
#define MACRO_RESOURCEFILE 70
#define MACRO_COMMANDFILE 71
#define MACRO_HOSTPERFDATAFILE 72
#define MACRO_SERVICEPERFDATAFILE 73
#define MACRO_HOSTACTIONURL 74
#define MACRO_HOSTNOTESURL 75
#define MACRO_HOSTNOTES 76
#define MACRO_SERVICEACTIONURL 77
#define MACRO_SERVICENOTESURL 78
#define MACRO_SERVICENOTES 79
#define MACRO_TOTALHOSTSUP 80
#define MACRO_TOTALHOSTSDOWN 81
#define MACRO_TOTALHOSTSUNREACHABLE 82
#define MACRO_TOTALHOSTSDOWNUNHANDLED 83
#define MACRO_TOTALHOSTSUNREACHABLEUNHANDLED 84
#define MACRO_TOTALHOSTPROBLEMS 85
#define MACRO_TOTALHOSTPROBLEMSUNHANDLED 86
#define MACRO_TOTALSERVICESOK 87
#define MACRO_TOTALSERVICESWARNING 88
#define MACRO_TOTALSERVICESCRITICAL 89
#define MACRO_TOTALSERVICESUNKNOWN 90
#define MACRO_TOTALSERVICESWARNINGUNHANDLED 91
#define MACRO_TOTALSERVICESCRITICALUNHANDLED 92
#define MACRO_TOTALSERVICESUNKNOWNUNHANDLED 93
#define MACRO_TOTALSERVICEPROBLEMS 94
#define MACRO_TOTALSERVICEPROBLEMSUNHANDLED 95
#define MACRO_PROCESSSTARTTIME 96
#define MACRO_HOSTCHECKTYPE 97
#define MACRO_SERVICECHECKTYPE 98
#define MACRO_LONGHOSTOUTPUT 99
#define MACRO_LONGSERVICEOUTPUT 100
#define MACRO_TEMPPATH 101
#define MACRO_HOSTNOTIFICATIONNUMBER 102
#define MACRO_SERVICENOTIFICATIONNUMBER 103
#define MACRO_HOSTNOTIFICATIONID 104
#define MACRO_SERVICENOTIFICATIONID 105
#define MACRO_HOSTEVENTID 106
#define MACRO_LASTHOSTEVENTID 107
#define MACRO_SERVICEEVENTID 108
#define MACRO_LASTSERVICEEVENTID 109
#define MACRO_HOSTGROUPNAMES 110
#define MACRO_SERVICEGROUPNAMES 111
#define MACRO_HOSTACKAUTHORNAME 112
#define MACRO_HOSTACKAUTHORALIAS 113
#define MACRO_SERVICEACKAUTHORNAME 114
#define MACRO_SERVICEACKAUTHORALIAS 115
#define MACRO_MAXHOSTATTEMPTS 116
#define MACRO_MAXSERVICEATTEMPTS 117
#define MACRO_SERVICEISVOLATILE 118
#define MACRO_TOTALHOSTSERVICES 119
#define MACRO_TOTALHOSTSERVICESOK 120
#define MACRO_TOTALHOSTSERVICESWARNING 121
#define MACRO_TOTALHOSTSERVICESUNKNOWN 122
#define MACRO_TOTALHOSTSERVICESCRITICAL 123
#define MACRO_HOSTGROUPNOTES 124
#define MACRO_HOSTGROUPNOTESURL 125
#define MACRO_HOSTGROUPACTIONURL 126
#define MACRO_SERVICEGROUPNOTES 127
#define MACRO_SERVICEGROUPNOTESURL 128
#define MACRO_SERVICEGROUPACTIONURL 129
#define MACRO_HOSTGROUPMEMBERS 130
#define MACRO_SERVICEGROUPMEMBERS 131
#define MACRO_CONTACTGROUPNAME 132
#define MACRO_CONTACTGROUPALIAS 133
#define MACRO_CONTACTGROUPMEMBERS 134
#define MACRO_CONTACTGROUPNAMES 135
#define MACRO_NOTIFICATIONRECIPIENTS 136
#define MACRO_NOTIFICATIONISESCALATED 137
#define MACRO_NOTIFICATIONAUTHOR 138
#define MACRO_NOTIFICATIONAUTHORNAME 139
#define MACRO_NOTIFICATIONAUTHORALIAS 140
#define MACRO_NOTIFICATIONCOMMENT 141
#define MACRO_EVENTSTARTTIME 142
#define MACRO_HOSTPROBLEMID 143
#define MACRO_LASTHOSTPROBLEMID 144
#define MACRO_SERVICEPROBLEMID 145
#define MACRO_LASTSERVICEPROBLEMID 146
#define MACRO_ISVALIDTIME 147
#define MACRO_NEXTVALIDTIME 148
#define MACRO_LASTHOSTSTATE 149
#define MACRO_LASTHOSTSTATEID 150
#define MACRO_LASTSERVICESTATE 151
#define MACRO_LASTSERVICESTATEID 152
/************* MACRO CLEANING OPTIONS *****************/
#define STRIP_ILLEGAL_MACRO_CHARS 1
#define ESCAPE_MACRO_CHARS 2
#define URL_ENCODE_MACRO_CHARS 4
/****************** MACRO FUNCTIONS ******************/
int process_macros(char *,char **,int); /* replace macros with their actual values */
char *clean_macro_chars(char *,int); /* cleans macros characters before insertion into output string */
int grab_service_macros(service *); /* updates the service macro data */
int grab_host_macros(host *); /* updates the host macro data */
int grab_servicegroup_macros(servicegroup *); /* updates servicegroup macros */
int grab_hostgroup_macros(hostgroup *); /* updates hostgroup macros */
int grab_contact_macros(contact *); /* updates the contact macro data */
int grab_contactgroup_macros(contactgroup *); /* updates contactgroup macros */
int grab_datetime_macros(void); /* updates date/time macros */
int grab_on_demand_macro(char *); /* fetches an on-demand macro */
char *get_url_encoded_string(char *); /* URL encode a string */
int init_macros(void);
int init_macrox_names(void);
int add_macrox_name(int,char *);
int free_macrox_names(void);
int clear_argv_macros(void);
int clear_volatile_macros(void);
int clear_host_macros(void);
int clear_service_macros(void);
int clear_hostgroup_macros(void);
int clear_servicegroup_macros(void);
int clear_contact_macros(void);
int clear_contactgroup_macros(void);
int clear_summary_macros(void);
int grab_macro_value(char *,char **,int *,int *);
int grab_macrox_value(int,char *,char *,char **,int *);
int grab_custom_macro_value(char *,char *,char *,char **);
int grab_datetime_macro(int,char *,char *,char **);
int grab_standard_host_macro(int,host *,char **,int *);
int grab_standard_hostgroup_macro(int,hostgroup *,char **);
int grab_standard_service_macro(int,service *,char **,int *);
int grab_standard_servicegroup_macro(int,servicegroup *,char **);
int grab_standard_contact_macro(int,contact *,char **);
int grab_contact_address_macro(int,contact *,char **);
int grab_standard_contactgroup_macro(int,contactgroup *,char **);
int grab_custom_object_macro(char *,customvariablesmember *,char **);
#ifdef NSCORE
int set_all_macro_environment_vars(int);
int set_macrox_environment_vars(int);
int set_argv_macro_environment_vars(int);
int set_custom_macro_environment_vars(int);
int set_contact_address_environment_vars(int);
int set_macro_environment_var(char *,char *,int);
#endif
#endif

822
nagios/nagios.h Normal file
View File

@@ -0,0 +1,822 @@
/************************************************************************
*
* Nagios Main Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
* Last Modified: 12-14-2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef _NAGIOS_H
#define _NAGIOS_H
#ifndef __GNUC__
# define __attribute__(x) /* nothing */
#endif
#include "config.h"
#include "common.h"
#include "locations.h"
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
/************* MISC LENGTH/SIZE DEFINITIONS ***********/
/*
NOTE: Plugin length is artificially capped at 8k to prevent runaway plugins from returning MBs/GBs of data
back to Nagios. If you increase the 8k cap by modifying this value, make sure you also increase the value
of MAX_EXTERNAL_COMMAND_LENGTH in common.h to allow for passive checks results received through the external
command file. EG 10/19/07
*/
#define MAX_PLUGIN_OUTPUT_LENGTH 8192 /* max length of plugin output (including perf data) */
/******************* DEFAULT VALUES *******************/
#define DEFAULT_LOG_LEVEL 1 /* log all events to main log file */
#define DEFAULT_USE_SYSLOG 1 /* log events to syslog? 1=yes, 0=no */
#define DEFAULT_SYSLOG_LEVEL 2 /* log only severe events to syslog */
#define DEFAULT_NOTIFICATION_LOGGING 1 /* log notification events? 1=yes, 0=no */
#define DEFAULT_INTER_CHECK_DELAY 5.0 /* seconds between initial service check scheduling */
#define DEFAULT_INTERLEAVE_FACTOR 1 /* default interleave to use when scheduling checks */
#define DEFAULT_SLEEP_TIME 0.5 /* seconds between event run checks */
#define DEFAULT_INTERVAL_LENGTH 60 /* seconds per interval unit for check scheduling */
#define DEFAULT_RETRY_INTERVAL 30 /* services are retried in 30 seconds if they're not OK */
#define DEFAULT_COMMAND_CHECK_INTERVAL -1 /* interval to check for external commands (default = as often as possible) */
#define DEFAULT_CHECK_REAPER_INTERVAL 10 /* interval in seconds to reap host and service check results */
#define DEFAULT_MAX_REAPER_TIME 30 /* maximum number of seconds to spend reaping service checks before we break out for a while */
#define DEFAULT_MAX_CHECK_RESULT_AGE 3600 /* maximum number of seconds that a check result file is considered to be valid */
#define DEFAULT_MAX_PARALLEL_SERVICE_CHECKS 0 /* maximum number of service checks we can have running at any given time (0=unlimited) */
#define DEFAULT_RETENTION_UPDATE_INTERVAL 60 /* minutes between auto-save of retention data */
#define DEFAULT_RETENTION_SCHEDULING_HORIZON 900 /* max seconds between program restarts that we will preserve scheduling information */
#define DEFAULT_STATUS_UPDATE_INTERVAL 60 /* seconds between aggregated status data updates */
#define DEFAULT_FRESHNESS_CHECK_INTERVAL 60 /* seconds between service result freshness checks */
#define DEFAULT_AUTO_RESCHEDULING_INTERVAL 30 /* seconds between host and service check rescheduling events */
#define DEFAULT_AUTO_RESCHEDULING_WINDOW 180 /* window of time (in seconds) for which we should reschedule host and service checks */
#define DEFAULT_ORPHAN_CHECK_INTERVAL 60 /* seconds between checks for orphaned hosts and services */
#define DEFAULT_NOTIFICATION_TIMEOUT 30 /* max time in seconds to wait for notification commands to complete */
#define DEFAULT_EVENT_HANDLER_TIMEOUT 30 /* max time in seconds to wait for event handler commands to complete */
#define DEFAULT_HOST_CHECK_TIMEOUT 30 /* max time in seconds to wait for host check commands to complete */
#define DEFAULT_SERVICE_CHECK_TIMEOUT 60 /* max time in seconds to wait for service check commands to complete */
#define DEFAULT_OCSP_TIMEOUT 15 /* max time in seconds to wait for obsessive compulsive processing commands to complete */
#define DEFAULT_OCHP_TIMEOUT 15 /* max time in seconds to wait for obsessive compulsive processing commands to complete */
#define DEFAULT_PERFDATA_TIMEOUT 5 /* max time in seconds to wait for performance data commands to complete */
#define DEFAULT_TIME_CHANGE_THRESHOLD 900 /* compensate for time changes of more than 15 minutes */
#define DEFAULT_LOG_HOST_RETRIES 0 /* don't log host retries */
#define DEFAULT_LOG_SERVICE_RETRIES 0 /* don't log service retries */
#define DEFAULT_LOG_EVENT_HANDLERS 1 /* log event handlers */
#define DEFAULT_LOG_INITIAL_STATES 0 /* don't log initial service and host states */
#define DEFAULT_LOG_EXTERNAL_COMMANDS 1 /* log external commands */
#define DEFAULT_LOG_PASSIVE_CHECKS 1 /* log passive service checks */
#define DEFAULT_DEBUG_LEVEL 0 /* don't log any debugging information */
#define DEFAULT_DEBUG_VERBOSITY 1
#define DEFAULT_MAX_DEBUG_FILE_SIZE 1000000 /* max size of debug log */
#define DEFAULT_AGGRESSIVE_HOST_CHECKING 0 /* don't use "aggressive" host checking */
#define DEFAULT_CHECK_EXTERNAL_COMMANDS 1 /* check for external commands */
#define DEFAULT_CHECK_ORPHANED_SERVICES 1 /* check for orphaned services */
#define DEFAULT_CHECK_ORPHANED_HOSTS 1 /* check for orphaned hosts */
#define DEFAULT_ENABLE_FLAP_DETECTION 0 /* don't enable flap detection */
#define DEFAULT_PROCESS_PERFORMANCE_DATA 0 /* don't process performance data */
#define DEFAULT_CHECK_SERVICE_FRESHNESS 1 /* check service result freshness */
#define DEFAULT_CHECK_HOST_FRESHNESS 0 /* don't check host result freshness */
#define DEFAULT_AUTO_RESCHEDULE_CHECKS 0 /* don't auto-reschedule host and service checks */
#define DEFAULT_TRANSLATE_PASSIVE_HOST_CHECKS 0 /* should we translate DOWN/UNREACHABLE passive host checks? */
#define DEFAULT_PASSIVE_HOST_CHECKS_SOFT 0 /* passive host checks are treated as HARD by default */
#define DEFAULT_LOW_SERVICE_FLAP_THRESHOLD 20.0 /* low threshold for detection of service flapping */
#define DEFAULT_HIGH_SERVICE_FLAP_THRESHOLD 30.0 /* high threshold for detection of service flapping */
#define DEFAULT_LOW_HOST_FLAP_THRESHOLD 20.0 /* low threshold for detection of host flapping */
#define DEFAULT_HIGH_HOST_FLAP_THRESHOLD 30.0 /* high threshold for detection of host flapping */
#define DEFAULT_HOST_CHECK_SPREAD 30 /* max minutes to schedule all initial host checks */
#define DEFAULT_SERVICE_CHECK_SPREAD 30 /* max minutes to schedule all initial service checks */
#define DEFAULT_CACHED_HOST_CHECK_HORIZON 15 /* max age in seconds that cached host checks can be used */
#define DEFAULT_CACHED_SERVICE_CHECK_HORIZON 15 /* max age in seconds that cached service checks can be used */
#define DEFAULT_ENABLE_PREDICTIVE_HOST_DEPENDENCY_CHECKS 1 /* should we use predictive host dependency checks? */
#define DEFAULT_ENABLE_PREDICTIVE_SERVICE_DEPENDENCY_CHECKS 1 /* should we use predictive service dependency checks? */
#define DEFAULT_USE_LARGE_INSTALLATION_TWEAKS 0 /* don't use tweaks for large Nagios installations */
#define DEFAULT_ENABLE_EMBEDDED_PERL 0 /* enable embedded Perl interpreter (if compiled in) */
#define DEFAULT_USE_EMBEDDED_PERL_IMPLICITLY 1 /* by default, embedded Perl is used for Perl plugins that don't explicitly disable it */
#define DEFAULT_ADDITIONAL_FRESHNESS_LATENCY 15 /* seconds to be added to freshness thresholds when automatically calculated by Nagios */
#define DEFAULT_CHECK_FOR_UPDATES 1 /* should we check for new Nagios releases? */
#define DEFAULT_BARE_UPDATE_CHECK 0 /* report current version and new installs */
#define MINIMUM_UPDATE_CHECK_INTERVAL 60*60*22 /* 22 hours minimum between checks - please be kind to our servers! */
#define BASE_UPDATE_CHECK_INTERVAL 60*60*22 /* 22 hours base interval */
#define UPDATE_CHECK_INTERVAL_WOBBLE 60*60*4 /* 4 hour wobble on top of base interval */
#define BASE_UPDATE_CHECK_RETRY_INTERVAL 60*60*1 /* 1 hour base retry interval */
#define UPDATE_CHECK_RETRY_INTERVAL_WOBBLE 60*60*3 /* 3 hour wobble on top of base retry interval */
/******************* LOGGING TYPES ********************/
#define NSLOG_RUNTIME_ERROR 1
#define NSLOG_RUNTIME_WARNING 2
#define NSLOG_VERIFICATION_ERROR 4
#define NSLOG_VERIFICATION_WARNING 8
#define NSLOG_CONFIG_ERROR 16
#define NSLOG_CONFIG_WARNING 32
#define NSLOG_PROCESS_INFO 64
#define NSLOG_EVENT_HANDLER 128
/*#define NSLOG_NOTIFICATION 256*/ /* NOT USED ANYMORE - CAN BE REUSED */
#define NSLOG_EXTERNAL_COMMAND 512
#define NSLOG_HOST_UP 1024
#define NSLOG_HOST_DOWN 2048
#define NSLOG_HOST_UNREACHABLE 4096
#define NSLOG_SERVICE_OK 8192
#define NSLOG_SERVICE_UNKNOWN 16384
#define NSLOG_SERVICE_WARNING 32768
#define NSLOG_SERVICE_CRITICAL 65536
#define NSLOG_PASSIVE_CHECK 131072
#define NSLOG_INFO_MESSAGE 262144
#define NSLOG_HOST_NOTIFICATION 524288
#define NSLOG_SERVICE_NOTIFICATION 1048576
/***************** DEBUGGING LEVELS *******************/
#define DEBUGL_ALL -1
#define DEBUGL_NONE 0
#define DEBUGL_FUNCTIONS 1
#define DEBUGL_CONFIG 2
#define DEBUGL_PROCESS 4
#define DEBUGL_STATUSDATA 4
#define DEBUGL_RETENTIONDATA 4
#define DEBUGL_EVENTS 8
#define DEBUGL_CHECKS 16
#define DEBUGL_IPC 16
#define DEBUGL_FLAPPING 16
#define DEBUGL_EVENTHANDLERS 16
#define DEBUGL_PERFDATA 16
#define DEBUGL_NOTIFICATIONS 32
#define DEBUGL_EVENTBROKER 64
#define DEBUGL_EXTERNALCOMMANDS 128
#define DEBUGL_COMMANDS 256
#define DEBUGL_DOWNTIME 512
#define DEBUGL_COMMENTS 1024
#define DEBUGL_MACROS 2048
#define DEBUGV_BASIC 0
#define DEBUGV_MORE 1
#define DEBUGV_MOST 2
/******************** HOST STATUS *********************/
#define HOST_UP 0
#define HOST_DOWN 1
#define HOST_UNREACHABLE 2
/******************* STATE LOGGING TYPES **************/
#define INITIAL_STATES 1
#define CURRENT_STATES 2
/************ SERVICE DEPENDENCY VALUES ***************/
#define DEPENDENCIES_OK 0
#define DEPENDENCIES_FAILED 1
/*********** ROUTE CHECK PROPAGATION TYPES ************/
#define PROPAGATE_TO_PARENT_HOSTS 1
#define PROPAGATE_TO_CHILD_HOSTS 2
/****************** SERVICE STATES ********************/
#define STATE_OK 0
#define STATE_WARNING 1
#define STATE_CRITICAL 2
#define STATE_UNKNOWN 3 /* changed from -1 on 02/24/2001 */
/****************** FLAPPING TYPES ********************/
#define HOST_FLAPPING 0
#define SERVICE_FLAPPING 1
/**************** NOTIFICATION TYPES ******************/
#define HOST_NOTIFICATION 0
#define SERVICE_NOTIFICATION 1
/************* NOTIFICATION REASON TYPES ***************/
#define NOTIFICATION_NORMAL 0
#define NOTIFICATION_ACKNOWLEDGEMENT 1
#define NOTIFICATION_FLAPPINGSTART 2
#define NOTIFICATION_FLAPPINGSTOP 3
#define NOTIFICATION_FLAPPINGDISABLED 4
#define NOTIFICATION_DOWNTIMESTART 5
#define NOTIFICATION_DOWNTIMEEND 6
#define NOTIFICATION_DOWNTIMECANCELLED 7
#define NOTIFICATION_CUSTOM 99
/**************** EVENT HANDLER TYPES *****************/
#define HOST_EVENTHANDLER 0
#define SERVICE_EVENTHANDLER 1
#define GLOBAL_HOST_EVENTHANDLER 2
#define GLOBAL_SERVICE_EVENTHANDLER 3
/***************** STATE CHANGE TYPES *****************/
#define HOST_STATECHANGE 0
#define SERVICE_STATECHANGE 1
/***************** OBJECT CHECK TYPES *****************/
#define SERVICE_CHECK 0
#define HOST_CHECK 1
/******************* EVENT TYPES **********************/
#define EVENT_SERVICE_CHECK 0 /* active service check */
#define EVENT_COMMAND_CHECK 1 /* external command check */
#define EVENT_LOG_ROTATION 2 /* log file rotation */
#define EVENT_PROGRAM_SHUTDOWN 3 /* program shutdown */
#define EVENT_PROGRAM_RESTART 4 /* program restart */
#define EVENT_CHECK_REAPER 5 /* reaps results from host and service checks */
#define EVENT_ORPHAN_CHECK 6 /* checks for orphaned hosts and services */
#define EVENT_RETENTION_SAVE 7 /* save (dump) retention data */
#define EVENT_STATUS_SAVE 8 /* save (dump) status data */
#define EVENT_SCHEDULED_DOWNTIME 9 /* scheduled host or service downtime */
#define EVENT_SFRESHNESS_CHECK 10 /* checks service result "freshness" */
#define EVENT_EXPIRE_DOWNTIME 11 /* checks for (and removes) expired scheduled downtime */
#define EVENT_HOST_CHECK 12 /* active host check */
#define EVENT_HFRESHNESS_CHECK 13 /* checks host result "freshness" */
#define EVENT_RESCHEDULE_CHECKS 14 /* adjust scheduling of host and service checks */
#define EVENT_EXPIRE_COMMENT 15 /* removes expired comments */
#define EVENT_CHECK_PROGRAM_UPDATE 16 /* checks for new version of Nagios */
#define EVENT_SLEEP 98 /* asynchronous sleep event that occurs when event queues are empty */
#define EVENT_USER_FUNCTION 99 /* USER-defined function (modules) */
/******* INTER-CHECK DELAY CALCULATION TYPES **********/
#define ICD_NONE 0 /* no inter-check delay */
#define ICD_DUMB 1 /* dumb delay of 1 second */
#define ICD_SMART 2 /* smart delay */
#define ICD_USER 3 /* user-specified delay */
/******* INTERLEAVE FACTOR CALCULATION TYPES **********/
#define ILF_USER 0 /* user-specified interleave factor */
#define ILF_SMART 1 /* smart interleave */
/************ SCHEDULED DOWNTIME TYPES ****************/
#define ACTIVE_DOWNTIME 0 /* active downtime - currently in effect */
#define PENDING_DOWNTIME 1 /* pending downtime - scheduled for the future */
/****************** DATA STRUCTURES *******************/
/* TIMED_EVENT structure */
typedef struct timed_event_struct{
int event_type;
time_t run_time;
int recurring;
unsigned long event_interval;
int compensate_for_time_change;
void *timing_func;
void *event_data;
void *event_args;
int event_options;
struct timed_event_struct *next;
struct timed_event_struct *prev;
}timed_event;
/* NOTIFY_LIST structure */
typedef struct notify_list_struct{
contact *this_should_be_named_other_than_contact;
struct notify_list_struct *next;
}notification;
/* CHECK_RESULT structure */
typedef struct check_result_struct{
int object_check_type; /* is this a service or a host check? */
char *host_name; /* host name */
char *service_description; /* service description */
int check_type; /* was this an active or passive service check? */
int check_options;
int scheduled_check; /* was this a scheduled or an on-demand check? */
int reschedule_check; /* should we reschedule the next check */
char *output_file; /* what file is the output stored in? */
FILE *output_file_fp;
int output_file_fd;
double latency;
struct timeval start_time; /* time the service check was initiated */
struct timeval finish_time; /* time the service check was completed */
int early_timeout; /* did the service check timeout? */
int exited_ok; /* did the plugin check return okay? */
int return_code; /* plugin return code */
char *output; /* plugin output */
struct check_result_struct *next;
}check_result;
/* SCHED_INFO structure */
typedef struct sched_info_struct{
int total_services;
int total_scheduled_services;
int total_hosts;
int total_scheduled_hosts;
double average_services_per_host;
double average_scheduled_services_per_host;
unsigned long service_check_interval_total;
unsigned long host_check_interval_total;
double average_service_execution_time;
double average_service_check_interval;
double average_host_check_interval;
double average_service_inter_check_delay;
double average_host_inter_check_delay;
double service_inter_check_delay;
double host_inter_check_delay;
int service_interleave_factor;
int max_service_check_spread;
int max_host_check_spread;
time_t first_service_check;
time_t last_service_check;
time_t first_host_check;
time_t last_host_check;
}sched_info;
/* PASSIVE_CHECK_RESULT structure */
typedef struct passive_check_result_struct{
int object_check_type;
char *host_name;
char *service_description;
int return_code;
char *output;
time_t check_time;
double latency;
struct passive_check_result_struct *next;
}passive_check_result;
/* CIRCULAR_BUFFER structure - used by worker threads */
typedef struct circular_buffer_struct{
void **buffer;
int tail;
int head;
int items;
int high; /* highest number of items that has ever been stored in buffer */
unsigned long overflow;
pthread_mutex_t buffer_lock;
}circular_buffer;
/* MMAPFILE structure - used for reading files via mmap() */
typedef struct mmapfile_struct{
char *path;
int mode;
int fd;
unsigned long file_size;
unsigned long current_position;
unsigned long current_line;
void *mmap_buf;
}mmapfile;
/* DBUF structure - dynamic string storage */
typedef struct dbuf_struct{
char *buf;
unsigned long used_size;
unsigned long allocated_size;
unsigned long chunk_size;
}dbuf;
#define CHECK_STATS_BUCKETS 15
/* used for tracking host and service check statistics */
typedef struct check_stats_struct{
int current_bucket;
int bucket[CHECK_STATS_BUCKETS];
int overflow_bucket;
int minute_stats[3];
time_t last_update;
}check_stats;
/******************* THREAD STUFF ********************/
/* slots in circular buffers */
#define DEFAULT_EXTERNAL_COMMAND_BUFFER_SLOTS 4096
/* worker threads */
#define TOTAL_WORKER_THREADS 1
#define COMMAND_WORKER_THREAD 0
/******************** FUNCTIONS **********************/
/**** Configuration Functions ****/
int read_main_config_file(char *); /* reads the main config file (nagios.cfg) */
int read_resource_file(char *); /* processes macros in resource file */
int read_all_object_data(char *); /* reads all object config data */
/**** Setup Functions ****/
int pre_flight_check(void); /* try and verify the configuration data */
int pre_flight_object_check(int *,int *); /* verify object relationships and settings */
int pre_flight_circular_check(int *,int *); /* detects circular dependencies and paths */
void init_timing_loop(void); /* setup the initial scheduling queue */
void setup_sighandler(void); /* trap signals */
void reset_sighandler(void); /* reset signals to default action */
int daemon_init(void); /* switches to daemon mode */
int drop_privileges(char *,char *); /* drops privileges before startup */
void display_scheduling_info(void); /* displays service check scheduling information */
/**** Event Queue Functions ****/
int schedule_new_event(int,int,time_t,int,unsigned long,void *,int,void *,void *,int); /* schedules a new timed event */
void reschedule_event(timed_event *,timed_event **,timed_event **); /* reschedules an event */
void add_event(timed_event *,timed_event **,timed_event **); /* adds an event to the execution queue */
void remove_event(timed_event *,timed_event **,timed_event **); /* remove an event from the execution queue */
int event_execution_loop(void); /* main monitoring/event handler loop */
int handle_timed_event(timed_event *); /* top level handler for timed events */
void adjust_check_scheduling(void); /* auto-adjusts scheduling of host and service checks */
void compensate_for_system_time_change(unsigned long,unsigned long); /* attempts to compensate for a change in the system time */
void adjust_timestamp_for_time_change(time_t,time_t,unsigned long,time_t *); /* adjusts a timestamp variable for a system time change */
void resort_event_list(timed_event **,timed_event **); /* resorts event list by event run time for system time changes */
/**** IPC Functions ****/
int move_check_result_to_queue(char *);
int process_check_result_queue(char *);
int process_check_result_file(char *);
int add_check_result_to_list(check_result *);
check_result *read_check_result(void); /* reads a host/service check result from the list in memory */
int delete_check_result_file(char *);
int free_check_result_list(void);
int init_check_result(check_result *);
int free_check_result(check_result *); /* frees memory associated with a host/service check result */
int parse_check_output(char *,char **,char **,char **,int,int);
int open_command_file(void); /* creates the external command file as a named pipe (FIFO) and opens it for reading */
int close_command_file(void); /* closes and deletes the external command file (FIFO) */
/**** Monitoring/Event Handler Functions ****/
int check_service_dependencies(service *,int); /* checks service dependencies */
int check_host_dependencies(host *,int); /* checks host dependencies */
void check_for_orphaned_services(void); /* checks for orphaned services */
void check_for_orphaned_hosts(void); /* checks for orphaned hosts */
void check_service_result_freshness(void); /* checks the "freshness" of service check results */
int is_service_result_fresh(service *,time_t,int); /* determines if a service's check results are fresh */
void check_host_result_freshness(void); /* checks the "freshness" of host check results */
int is_host_result_fresh(host *,time_t,int); /* determines if a host's check results are fresh */
int my_system(char *,int,int *,double *,char **,int); /* executes a command via popen(), but also protects against timeouts */
/**** Flap Detection Functions ****/
void check_for_service_flapping(service *,int,int); /* determines whether or not a service is "flapping" between states */
void check_for_host_flapping(host *,int,int,int); /* determines whether or not a host is "flapping" between states */
void set_service_flap(service *,double,double,double,int); /* handles a service that is flapping */
void clear_service_flap(service *,double,double,double); /* handles a service that has stopped flapping */
void set_host_flap(host *,double,double,double,int); /* handles a host that is flapping */
void clear_host_flap(host *,double,double,double); /* handles a host that has stopped flapping */
void enable_flap_detection_routines(void); /* enables flap detection on a program-wide basis */
void disable_flap_detection_routines(void); /* disables flap detection on a program-wide basis */
void enable_host_flap_detection(host *); /* enables flap detection for a particular host */
void disable_host_flap_detection(host *); /* disables flap detection for a particular host */
void enable_service_flap_detection(service *); /* enables flap detection for a particular service */
void disable_service_flap_detection(service *); /* disables flap detection for a particular service */
void handle_host_flap_detection_disabled(host *); /* handles the details when flap detection is disabled globally or on a per-host basis */
void handle_service_flap_detection_disabled(service *); /* handles the details when flap detection is disabled globally or on a per-service basis */
/**** Route/Host Check Functions ****/
int perform_on_demand_host_check(host *,int *,int,int,unsigned long);
int perform_scheduled_host_check(host *,int,double);
int check_host_check_viability_3x(host *,int,int *,time_t *);
int adjust_host_check_attempt_3x(host *,int);
int determine_host_reachability(host *);
int process_host_check_result_3x(host *,int,char *,int,int,int,unsigned long);
int perform_on_demand_host_check_3x(host *,int *,int,int,unsigned long);
int run_sync_host_check_3x(host *,int *,int,int,unsigned long);
int execute_sync_host_check_3x(host *);
int run_scheduled_host_check_3x(host *,int,double);
int run_async_host_check_3x(host *,int,double,int,int,int *,time_t *);
int handle_async_host_check_result_3x(host *,check_result *);
/**** Service Check Functions ****/
int check_service_check_viability(service *,int,int *,time_t *);
int run_scheduled_service_check(service *,int,double);
int run_async_service_check(service *,int,double,int,int,int *,time_t *);
int handle_async_service_check_result(service *,check_result *);
/**** Event Handler Functions ****/
int handle_host_state(host *); /* top level host state handler */
/**** Common Check Fucntions *****/
int reap_check_results(void);
/**** Check Statistics Functions ****/
int init_check_stats(void);
int update_check_stats(int,time_t);
int generate_check_stats(void);
/**** Event Handler Functions ****/
int obsessive_compulsive_service_check_processor(service *); /* distributed monitoring craziness... */
int obsessive_compulsive_host_check_processor(host *); /* distributed monitoring craziness... */
int handle_service_event(service *); /* top level service event logic */
int run_service_event_handler(service *); /* runs the event handler for a specific service */
int run_global_service_event_handler(service *); /* runs the global service event handler */
int handle_host_event(host *); /* top level host event logic */
int run_host_event_handler(host *); /* runs the event handler for a specific host */
int run_global_host_event_handler(host *); /* runs the global host event handler */
/**** Notification Functions ****/
int check_service_notification_viability(service *,int,int); /* checks viability of notifying all contacts about a service */
int is_valid_escalation_for_service_notification(service *,serviceescalation *,int); /* checks if an escalation entry is valid for a particular service notification */
int should_service_notification_be_escalated(service *); /* checks if a service notification should be escalated */
int service_notification(service *,int,char *,char *,int); /* notify all contacts about a service (problem or recovery) */
int check_contact_service_notification_viability(contact *,service *,int,int); /* checks viability of notifying a contact about a service */
int notify_contact_of_service(contact *,service *,int,char *,char *,int,int); /* notify a single contact about a service */
int check_host_notification_viability(host *,int,int); /* checks viability of notifying all contacts about a host */
int is_valid_escalation_for_host_notification(host *,hostescalation *,int); /* checks if an escalation entry is valid for a particular host notification */
int should_host_notification_be_escalated(host *); /* checks if a host notification should be escalated */
int host_notification(host *,int,char *,char *,int); /* notify all contacts about a host (problem or recovery) */
int check_contact_host_notification_viability(contact *,host *,int,int); /* checks viability of notifying a contact about a host */
int notify_contact_of_host(contact *,host *,int,char *,char *,int,int); /* notify a single contact about a host */
int create_notification_list_from_host(host *,int,int *); /* given a host, create list of contacts to be notified (remove duplicates) */
int create_notification_list_from_service(service *,int,int *); /* given a service, create list of contacts to be notified (remove duplicates) */
int add_notification(contact *); /* adds a notification instance */
notification *find_notification(contact *); /* finds a notification object */
time_t get_next_host_notification_time(host *,time_t); /* calculates nex acceptable re-notification time for a host */
time_t get_next_service_notification_time(service *,time_t); /* calculates nex acceptable re-notification time for a service */
/**** Logging Functions ****/
void logit(int,int,const char *, ...)
__attribute__((__format__(__printf__, 3, 4)));
int write_to_logs_and_console(char *,unsigned long,int); /* writes a string to screen and logs */
int write_to_console(char *); /* writes a string to screen */
int write_to_all_logs(char *,unsigned long); /* writes a string to main log file and syslog facility */
int write_to_all_logs_with_timestamp(char *,unsigned long,time_t *); /* writes a string to main log file and syslog facility */
int write_to_log(char *,unsigned long,time_t *); /* write a string to the main log file */
int write_to_syslog(char *,unsigned long); /* write a string to the syslog facility */
int log_service_event(service *); /* logs a service event */
int log_host_event(host *); /* logs a host event */
int log_host_states(int,time_t *); /* logs initial/current host states */
int log_service_states(int,time_t *); /* logs initial/current service states */
int rotate_log_file(time_t); /* rotates the main log file */
int write_log_file_info(time_t *); /* records log file/version info */
int open_debug_log(void);
int log_debug_info(int,int,const char *,...)
__attribute__((__format__(__printf__, 3, 4)));
int close_debug_log(void);
/**** Cleanup Functions ****/
void cleanup(void); /* cleanup after ourselves (before quitting or restarting) */
void free_memory(void); /* free memory allocated to all linked lists in memory */
int reset_variables(void); /* reset all global variables */
void free_notification_list(void); /* frees all memory allocated to the notification list */
/**** Hash Functions ****/
int hashfunc(const char *name1, const char *name2, int hashslots);
int compare_hashdata(const char *,const char *,const char *,const char *);
/**** Miscellaneous Functions ****/
void sighandler(int); /* handles signals */
void service_check_sighandler(int); /* handles timeouts when executing service checks */
void host_check_sighandler(int); /* handles timeouts when executing host checks */
void my_system_sighandler(int); /* handles timeouts when executing commands via my_system() */
void file_lock_sighandler(int); /* handles timeouts while waiting for file locks */
void strip(char *); /* strips whitespace from string */
char *my_strtok(char *,char *); /* my replacement for strtok() function (doesn't skip consecutive tokens) */
char *my_strsep(char **,const char *); /* Solaris doesn't have strsep(), so I took this from the glibc source code */
#ifdef REMOVED_10182007
int my_free(void **); /* my wrapper for free() */
#endif
char *get_next_string_from_buf(char *buf, int *start_index, int bufsize);
int compare_strings(char *,char *); /* compares two strings for equality */
char *escape_newlines(char *);
int contains_illegal_object_chars(char *); /* tests whether or not an object name (host, service, etc.) contains illegal characters */
int my_rename(char *,char *); /* renames a file - works across filesystems */
int my_fcopy(char *,char *); /* copies a file - works across filesystems */
int get_raw_command_line(command *,char *,char **,int); /* given a raw command line, determine the actual command to run */
int check_time_against_period(time_t,timeperiod *); /* check to see if a specific time is covered by a time period */
int is_daterange_single_day(daterange *);
time_t calculate_time_from_weekday_of_month(int,int,int,int); /* calculates midnight time of specific (3rd, last, etc.) weekday of a particular month */
time_t calculate_time_from_day_of_month(int,int,int); /* calculates midnight time of specific (1st, last, etc.) day of a particular month */
void get_next_valid_time(time_t, time_t *,timeperiod *); /* get the next valid time in a time period */
void get_datetime_string(time_t *,char *,int,int); /* get a date/time string for use in output */
void get_time_breakdown(unsigned long,int *,int *,int *, int *);
time_t get_next_log_rotation_time(void); /* determine the next time to schedule a log rotation */
int init_embedded_perl(char **); /* initialized embedded perl interpreter */
int deinit_embedded_perl(void); /* cleans up embedded perl */
int file_uses_embedded_perl(char *); /* tests whether or not the embedded perl interpreter should be used on a file */
int dbuf_init(dbuf *,int);
int dbuf_free(dbuf *);
int dbuf_strcat(dbuf *,char *);
int set_environment_var(char *,char *,int); /* sets/clears and environment variable */
int check_for_nagios_updates(int,int); /* checks to see if new version of Nagios are available */
int query_update_api(void); /* checks to see if new version of Nagios are available */
/**** External Command Functions ****/
int check_for_external_commands(void); /* checks for any external commands */
int process_external_command1(char *); /* top-level external command processor */
int process_external_command2(int,time_t,char *); /* process an external command */
int process_external_commands_from_file(char *,int); /* process external commands in a file */
int process_host_command(int,time_t,char *); /* process an external host command */
int process_hostgroup_command(int,time_t,char *); /* process an external hostgroup command */
int process_service_command(int,time_t,char *); /* process an external service command */
int process_servicegroup_command(int,time_t,char *); /* process an external servicegroup command */
int process_contact_command(int,time_t,char *); /* process an external contact command */
int process_contactgroup_command(int,time_t,char *); /* process an external contactgroup command */
/**** External Command Implementations ****/
int cmd_add_comment(int,time_t,char *); /* add a service or host comment */
int cmd_delete_comment(int,char *); /* delete a service or host comment */
int cmd_delete_all_comments(int,char *); /* delete all comments associated with a host or service */
int cmd_delay_notification(int,char *); /* delay a service or host notification */
int cmd_schedule_service_check(int,char *,int); /* schedule an immediate or delayed service check */
int cmd_schedule_check(int,char *); /* schedule an immediate or delayed host check */
int cmd_schedule_host_service_checks(int,char *,int); /* schedule an immediate or delayed checks of all services on a host */
int cmd_signal_process(int,char *); /* schedules a program shutdown or restart */
int cmd_process_service_check_result(int,time_t,char *); /* processes a passive service check */
int cmd_process_host_check_result(int,time_t,char *); /* processes a passive host check */
int cmd_acknowledge_problem(int,char *); /* acknowledges a host or service problem */
int cmd_remove_acknowledgement(int,char *); /* removes a host or service acknowledgement */
int cmd_schedule_downtime(int,time_t,char *); /* schedules host or service downtime */
int cmd_delete_downtime(int,char *); /* cancels active/pending host or service scheduled downtime */
int cmd_change_object_int_var(int,char *); /* changes host/svc (int) variable */
int cmd_change_object_char_var(int,char *); /* changes host/svc (char) variable */
int cmd_change_object_custom_var(int,char *); /* changes host/svc custom variable */
int cmd_process_external_commands_from_file(int,char *); /* process external commands from a file */
int process_passive_service_check(time_t,char *,char *,int,char *);
int process_passive_host_check(time_t,char *,int,char *);
/**** Internal Command Implementations ****/
void disable_service_checks(service *); /* disables a service check */
void enable_service_checks(service *); /* enables a service check */
void schedule_service_check(service *,time_t,int); /* schedules an immediate or delayed service check */
void schedule_host_check(host *,time_t,int); /* schedules an immediate or delayed host check */
void enable_all_notifications(void); /* enables notifications on a program-wide basis */
void disable_all_notifications(void); /* disables notifications on a program-wide basis */
void enable_service_notifications(service *); /* enables service notifications */
void disable_service_notifications(service *); /* disables service notifications */
void enable_host_notifications(host *); /* enables host notifications */
void disable_host_notifications(host *); /* disables host notifications */
void enable_and_propagate_notifications(host *,int,int,int,int); /* enables notifications for all hosts and services beyond a given host */
void disable_and_propagate_notifications(host *,int,int,int,int); /* disables notifications for all hosts and services beyond a given host */
void schedule_and_propagate_downtime(host *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long); /* schedules downtime for all hosts beyond a given host */
void acknowledge_host_problem(host *,char *,char *,int,int,int); /* acknowledges a host problem */
void acknowledge_service_problem(service *,char *,char *,int,int,int); /* acknowledges a service problem */
void remove_host_acknowledgement(host *); /* removes a host acknowledgement */
void remove_service_acknowledgement(service *); /* removes a service acknowledgement */
void start_executing_service_checks(void); /* starts executing service checks */
void stop_executing_service_checks(void); /* stops executing service checks */
void start_accepting_passive_service_checks(void); /* starts accepting passive service check results */
void stop_accepting_passive_service_checks(void); /* stops accepting passive service check results */
void enable_passive_service_checks(service *); /* enables passive service checks for a particular service */
void disable_passive_service_checks(service *); /* disables passive service checks for a particular service */
void start_using_event_handlers(void); /* enables event handlers on a program-wide basis */
void stop_using_event_handlers(void); /* disables event handlers on a program-wide basis */
void enable_service_event_handler(service *); /* enables the event handler for a particular service */
void disable_service_event_handler(service *); /* disables the event handler for a particular service */
void enable_host_event_handler(host *); /* enables the event handler for a particular host */
void disable_host_event_handler(host *); /* disables the event handler for a particular host */
void enable_host_checks(host *); /* enables checks of a particular host */
void disable_host_checks(host *); /* disables checks of a particular host */
void start_obsessing_over_service_checks(void); /* start obsessing about service check results */
void stop_obsessing_over_service_checks(void); /* stop obsessing about service check results */
void start_obsessing_over_host_checks(void); /* start obsessing about host check results */
void stop_obsessing_over_host_checks(void); /* stop obsessing about host check results */
void enable_service_freshness_checks(void); /* enable service freshness checks */
void disable_service_freshness_checks(void); /* disable service freshness checks */
void enable_host_freshness_checks(void); /* enable host freshness checks */
void disable_host_freshness_checks(void); /* disable host freshness checks */
void process_passive_checks(void); /* processes passive host and service check results */
void enable_all_failure_prediction(void); /* enables failure prediction on a program-wide basis */
void disable_all_failure_prediction(void); /* disables failure prediction on a program-wide basis */
void enable_performance_data(void); /* enables processing of performance data on a program-wide basis */
void disable_performance_data(void); /* disables processing of performance data on a program-wide basis */
void start_executing_host_checks(void); /* starts executing host checks */
void stop_executing_host_checks(void); /* stops executing host checks */
void start_accepting_passive_host_checks(void); /* starts accepting passive host check results */
void stop_accepting_passive_host_checks(void); /* stops accepting passive host check results */
void enable_passive_host_checks(host *); /* enables passive host checks for a particular host */
void disable_passive_host_checks(host *); /* disables passive host checks for a particular host */
void start_obsessing_over_service(service *); /* start obsessing about specific service check results */
void stop_obsessing_over_service(service *); /* stop obsessing about specific service check results */
void start_obsessing_over_host(host *); /* start obsessing about specific host check results */
void stop_obsessing_over_host(host *); /* stop obsessing about specific host check results */
void set_host_notification_number(host *,int); /* sets current notification number for a specific host */
void set_service_notification_number(service *,int); /* sets current notification number for a specific service */
void enable_contact_host_notifications(contact *); /* enables host notifications for a specific contact */
void disable_contact_host_notifications(contact *); /* disables host notifications for a specific contact */
void enable_contact_service_notifications(contact *); /* enables service notifications for a specific contact */
void disable_contact_service_notifications(contact *); /* disables service notifications for a specific contact */
int init_check_result_worker_thread(void);
int shutdown_check_result_worker_thread(void);
void * check_result_worker_thread(void *);
void cleanup_check_result_worker_thread(void *);
int init_command_file_worker_thread(void);
int shutdown_command_file_worker_thread(void);
void * command_file_worker_thread(void *);
void cleanup_command_file_worker_thread(void *);
int submit_external_command(char *,int *);
int submit_raw_external_command(char *,time_t *,int *);
char *get_program_version(void);
char *get_program_modification_date(void);
mmapfile *mmap_fopen(char *); /* open a file read-only via mmap() */
int mmap_fclose(mmapfile *);
char *mmap_fgets(mmapfile *);
char *mmap_fgets_multiline(mmapfile *);
#ifdef __cplusplus
}
#endif
#endif

89
nagios/nebcallbacks.h Normal file
View File

@@ -0,0 +1,89 @@
/*****************************************************************************
*
* NEBCALLBACKS.H - Include file for event broker modules
*
* Copyright (c) 2002-2007 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 01-06-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _NEBCALLBACKS_H
#define _NEBCALLBACKS_H
#include "config.h"
#include "nebmodules.h"
#ifdef __cplusplus
extern "C" {
#endif
/***** CALLBACK TYPES *****/
#define NEBCALLBACK_NUMITEMS 33 /* total number of callback types we have */
#define NEBCALLBACK_RESERVED0 0 /* reserved for future use */
#define NEBCALLBACK_RESERVED1 1
#define NEBCALLBACK_RESERVED2 2
#define NEBCALLBACK_RESERVED3 3
#define NEBCALLBACK_RESERVED4 4
#define NEBCALLBACK_RAW_DATA 5
#define NEBCALLBACK_NEB_DATA 6
#define NEBCALLBACK_PROCESS_DATA 7
#define NEBCALLBACK_TIMED_EVENT_DATA 8
#define NEBCALLBACK_LOG_DATA 9
#define NEBCALLBACK_SYSTEM_COMMAND_DATA 10
#define NEBCALLBACK_EVENT_HANDLER_DATA 11
#define NEBCALLBACK_NOTIFICATION_DATA 12
#define NEBCALLBACK_SERVICE_CHECK_DATA 13
#define NEBCALLBACK_HOST_CHECK_DATA 14
#define NEBCALLBACK_COMMENT_DATA 15
#define NEBCALLBACK_DOWNTIME_DATA 16
#define NEBCALLBACK_FLAPPING_DATA 17
#define NEBCALLBACK_PROGRAM_STATUS_DATA 18
#define NEBCALLBACK_HOST_STATUS_DATA 19
#define NEBCALLBACK_SERVICE_STATUS_DATA 20
#define NEBCALLBACK_ADAPTIVE_PROGRAM_DATA 21
#define NEBCALLBACK_ADAPTIVE_HOST_DATA 22
#define NEBCALLBACK_ADAPTIVE_SERVICE_DATA 23
#define NEBCALLBACK_EXTERNAL_COMMAND_DATA 24
#define NEBCALLBACK_AGGREGATED_STATUS_DATA 25
#define NEBCALLBACK_RETENTION_DATA 26
#define NEBCALLBACK_CONTACT_NOTIFICATION_DATA 27
#define NEBCALLBACK_CONTACT_NOTIFICATION_METHOD_DATA 28
#define NEBCALLBACK_ACKNOWLEDGEMENT_DATA 29
#define NEBCALLBACK_STATE_CHANGE_DATA 30
#define NEBCALLBACK_CONTACT_STATUS_DATA 31
#define NEBCALLBACK_ADAPTIVE_CONTACT_DATA 32
/***** CALLBACK FUNCTIONS *****/
int neb_register_callback(int callback_type, void *mod_handle, int priority, int (*callback_func)(int,void *));
int neb_deregister_callback(int callback_type, int (*callback_func)(int,void *));
int neb_deregister_module_callbacks(nebmodule *);
#ifdef __cplusplus
}
#endif
#endif

70
nagios/neberrors.h Normal file
View File

@@ -0,0 +1,70 @@
/*****************************************************************************
*
* NEBERRORS.H - Event broker errors
*
* Copyright (c) 2003-2006 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 12-12-2006
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _NEBERRORS_H
#define _NEBERRORS_H
/***** GENERIC DEFINES *****/
#define NEB_OK 0
#define NEB_ERROR -1
#define NEB_TRUE 1
#define NEB_FALSE 0
/***** GENERIC ERRORS *****/
#define NEBERROR_NOMEM 100 /* memory could not be allocated */
/***** CALLBACK ERRORS *****/
#define NEBERROR_NOCALLBACKFUNC 200 /* no callback function was specified */
#define NEBERROR_NOCALLBACKLIST 201 /* callback list not initialized */
#define NEBERROR_CALLBACKBOUNDS 202 /* callback type was out of bounds */
#define NEBERROR_CALLBACKNOTFOUND 203 /* the callback could not be found */
#define NEBERROR_NOMODULEHANDLE 204 /* no module handle specified */
#define NEBERROR_BADMODULEHANDLE 205 /* bad module handle */
#define NEBERROR_CALLBACKOVERRIDE 206 /* module wants to override default Nagios handling of event */
#define NEBERROR_CALLBACKCANCEL 207 /* module wants to cancel callbacks to other modules */
/***** MODULE ERRORS *****/
#define NEBERROR_NOMODULE 300 /* no module was specified */
/***** MODULE INFO ERRORS *****/
#define NEBERROR_MODINFOBOUNDS 400 /* module info index was out of bounds */
#endif

71
nagios/nebmods.h Normal file
View File

@@ -0,0 +1,71 @@
/*****************************************************************************
*
* NEBMODS.H - Include file for event broker modules
*
* Copyright (c) 2002-2005 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 11-25-2005
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _NEBMODS_H
#define _NEBMODS_H
#include "config.h"
#include "nebcallbacks.h"
#include "nebmodules.h"
#ifdef __cplusplus
extern "C" {
#endif
/***** MODULE STRUCTURES *****/
/* NEB module callback list struct */
typedef struct nebcallback_struct{
void *callback_func;
void *module_handle;
int priority;
struct nebcallback_struct *next;
}nebcallback;
/***** MODULE FUNCTIONS *****/
int neb_init_modules(void);
int neb_deinit_modules(void);
int neb_load_all_modules(void);
int neb_load_module(nebmodule *);
int neb_free_module_list(void);
int neb_unload_all_modules(int,int);
int neb_unload_module(nebmodule *,int,int);
int neb_add_module(char *,char *,int);
/***** CALLBACK FUNCTIONS *****/
int neb_init_callback_list(void);
int neb_free_callback_list(void);
int neb_make_callbacks(int,void *);
#ifdef __cplusplus
}
#endif
#endif

103
nagios/nebmodules.h Normal file
View File

@@ -0,0 +1,103 @@
/*****************************************************************************
*
* NEBMODULES.H - Include file for event broker modules
*
* Copyright (c) 2002-2006 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 02-27-2006
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _NEBMODULES_H
#define _NEBMODULES_H
#ifdef __cplusplus
extern "C" {
#endif
/***** MODULE VERSION INFORMATION *****/
#define NEB_API_VERSION(x) int __neb_api_version = x;
#define CURRENT_NEB_API_VERSION 3
/***** MODULE INFORMATION *****/
#define NEBMODULE_MODINFO_NUMITEMS 6
#define NEBMODULE_MODINFO_TITLE 0
#define NEBMODULE_MODINFO_AUTHOR 1
#define NEBMODULE_MODINFO_COPYRIGHT 2
#define NEBMODULE_MODINFO_VERSION 3
#define NEBMODULE_MODINFO_LICENSE 4
#define NEBMODULE_MODINFO_DESC 5
/***** MODULE LOAD/UNLOAD OPTIONS *****/
#define NEBMODULE_NORMAL_LOAD 0 /* module is being loaded normally */
#define NEBMODULE_REQUEST_UNLOAD 0 /* request module to unload (but don't force it) */
#define NEBMODULE_FORCE_UNLOAD 1 /* force module to unload */
/***** MODULES UNLOAD REASONS *****/
#define NEBMODULE_NEB_SHUTDOWN 1 /* event broker is shutting down */
#define NEBMODULE_NEB_RESTART 2 /* event broker is restarting */
#define NEBMODULE_ERROR_NO_INIT 3 /* _module_init() function was not found in module */
#define NEBMODULE_ERROR_BAD_INIT 4 /* _module_init() function returned a bad code */
#define NEBMODULE_ERROR_API_VERSION 5 /* module version is incompatible with current api */
/***** MODULE STRUCTURES *****/
/* NEB module structure */
typedef struct nebmodule_struct{
char *filename;
char *args;
char *info[NEBMODULE_MODINFO_NUMITEMS];
int should_be_loaded;
int is_currently_loaded;
#ifdef USE_LTDL
lt_dlhandle module_handle;
lt_ptr init_func;
lt_ptr deinit_func;
#else
void *module_handle;
void *init_func;
void *deinit_func;
#endif
#ifdef HAVE_PTHREAD_H
pthread_t thread_id;
#endif
struct nebmodule_struct *next;
}nebmodule;
/***** MODULE FUNCTIONS *****/
int neb_set_module_info(void *,int,char *);
#ifdef __cplusplus
}
#endif
#endif

533
nagios/nebstructs.h Normal file
View File

@@ -0,0 +1,533 @@
/*****************************************************************************
*
* NEBSTRUCTS.H - Event broker includes for Nagios
*
* Copyright (c) 2003-2007 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 10-28-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _NEBSTRUCTS_H
#define _NEBSTRUCTS_H
#include "config.h"
#include "objects.h"
#include "nagios.h"
#ifdef __cplusplus
extern "C" {
#endif
/****** STRUCTURES *************************/
/* process data structure */
typedef struct nebstruct_process_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
}nebstruct_process_data;
/* timed event data structure */
typedef struct nebstruct_timed_event_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int event_type;
int recurring;
time_t run_time;
void *event_data;
void *event_ptr;
}nebstruct_timed_event_data;
/* log data structure */
typedef struct nebstruct_log_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
time_t entry_time;
int data_type;
char *data;
}nebstruct_log_data;
/* system command structure */
typedef struct nebstruct_system_command_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
struct timeval start_time;
struct timeval end_time;
int timeout;
char *command_line;
int early_timeout;
double execution_time;
int return_code;
char *output;
}nebstruct_system_command_data;
/* event handler structure */
typedef struct nebstruct_event_handler_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int eventhandler_type;
char *host_name;
char *service_description;
int state_type;
int state;
int timeout;
char *command_name;
char *command_args;
char *command_line;
struct timeval start_time;
struct timeval end_time;
int early_timeout;
double execution_time;
int return_code;
char *output;
void *object_ptr;
}nebstruct_event_handler_data;
/* host check structure */
typedef struct nebstruct_host_check_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
char *host_name;
int current_attempt;
int check_type;
int max_attempts;
int state_type;
int state;
int timeout;
char *command_name;
char *command_args;
char *command_line;
struct timeval start_time;
struct timeval end_time;
int early_timeout;
double execution_time;
double latency;
int return_code;
char *output;
char *long_output;
char *perf_data;
void *object_ptr;
}nebstruct_host_check_data;
/* service check structure */
typedef struct nebstruct_service_check_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
char *host_name;
char *service_description;
int check_type;
int current_attempt;
int max_attempts;
int state_type;
int state;
int timeout;
char *command_name;
char *command_args;
char *command_line;
struct timeval start_time;
struct timeval end_time;
int early_timeout;
double execution_time;
double latency;
int return_code;
char *output;
char *long_output;
char *perf_data;
void *object_ptr;
}nebstruct_service_check_data;
/* comment data structure */
typedef struct nebstruct_comment_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int comment_type;
char *host_name;
char *service_description;
time_t entry_time;
char *author_name;
char *comment_data;
int persistent;
int source;
int entry_type;
int expires;
time_t expire_time;
unsigned long comment_id;
void *object_ptr; /* not implemented yet */
}nebstruct_comment_data;
/* downtime data structure */
typedef struct nebstruct_downtime_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int downtime_type;
char *host_name;
char *service_description;
time_t entry_time;
char *author_name;
char *comment_data;
time_t start_time;
time_t end_time;
int fixed;
unsigned long duration;
unsigned long triggered_by;
unsigned long downtime_id;
void *object_ptr; /* not implemented yet */
}nebstruct_downtime_data;
/* flapping data structure */
typedef struct nebstruct_flapping_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int flapping_type;
char *host_name;
char *service_description;
double percent_change;
double high_threshold;
double low_threshold;
unsigned long comment_id;
void *object_ptr;
}nebstruct_flapping_data;
/* program status structure */
typedef struct nebstruct_program_status_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
time_t program_start;
int pid;
int daemon_mode;
time_t last_command_check;
time_t last_log_rotation;
int notifications_enabled;
int active_service_checks_enabled;
int passive_service_checks_enabled;
int active_host_checks_enabled;
int passive_host_checks_enabled;
int event_handlers_enabled;
int flap_detection_enabled;
int failure_prediction_enabled;
int process_performance_data;
int obsess_over_hosts;
int obsess_over_services;
unsigned long modified_host_attributes;
unsigned long modified_service_attributes;
char *global_host_event_handler;
char *global_service_event_handler;
}nebstruct_program_status_data;
/* host status structure */
typedef struct nebstruct_host_status_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
void *object_ptr;
}nebstruct_host_status_data;
/* service status structure */
typedef struct nebstruct_service_status_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
void *object_ptr;
}nebstruct_service_status_data;
/* contact status structure */
typedef struct nebstruct_contact_status_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
void *object_ptr;
}nebstruct_contact_status_data;
/* notification data structure */
typedef struct nebstruct_notification_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int notification_type;
struct timeval start_time;
struct timeval end_time;
char *host_name;
char *service_description;
int reason_type;
int state;
char *output;
char *ack_author;
char *ack_data;
int escalated;
int contacts_notified;
void *object_ptr;
}nebstruct_notification_data;
/* contact notification data structure */
typedef struct nebstruct_contact_notification_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int notification_type;
struct timeval start_time;
struct timeval end_time;
char *host_name;
char *service_description;
char *contact_name;
int reason_type;
int state;
char *output;
char *ack_author;
char *ack_data;
int escalated;
void *object_ptr;
void *contact_ptr;
}nebstruct_contact_notification_data;
/* contact notification method data structure */
typedef struct nebstruct_contact_notification_method_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int notification_type;
struct timeval start_time;
struct timeval end_time;
char *host_name;
char *service_description;
char *contact_name;
char *command_name;
char *command_args;
int reason_type;
int state;
char *output;
char *ack_author;
char *ack_data;
int escalated;
void *object_ptr;
void *contact_ptr;
}nebstruct_contact_notification_method_data;
/* adaptive program data structure */
typedef struct nebstruct_adaptive_program_data_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int command_type;
unsigned long modified_host_attribute;
unsigned long modified_host_attributes;
unsigned long modified_service_attribute;
unsigned long modified_service_attributes;
}nebstruct_adaptive_program_data;
/* adaptive host data structure */
typedef struct nebstruct_adaptive_host_data_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int command_type;
unsigned long modified_attribute;
unsigned long modified_attributes;
void *object_ptr;
}nebstruct_adaptive_host_data;
/* adaptive service data structure */
typedef struct nebstruct_adaptive_service_data_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int command_type;
unsigned long modified_attribute;
unsigned long modified_attributes;
void *object_ptr;
}nebstruct_adaptive_service_data;
/* adaptive contact data structure */
typedef struct nebstruct_adaptive_contact_data_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int command_type;
unsigned long modified_attribute;
unsigned long modified_attributes;
unsigned long modified_host_attribute;
unsigned long modified_host_attributes;
unsigned long modified_service_attribute;
unsigned long modified_service_attributes;
void *object_ptr;
}nebstruct_adaptive_contact_data;
/* external command data structure */
typedef struct nebstruct_external_command_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int command_type;
time_t entry_time;
char *command_string;
char *command_args;
}nebstruct_external_command_data;
/* aggregated status data structure */
typedef struct nebstruct_aggregated_status_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
}nebstruct_aggregated_status_data;
/* retention data structure */
typedef struct nebstruct_retention_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
}nebstruct_retention_data;
/* acknowledgement structure */
typedef struct nebstruct_acknowledgement_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int acknowledgement_type;
char *host_name;
char *service_description;
int state;
char *author_name;
char *comment_data;
int is_sticky;
int persistent_comment;
int notify_contacts;
void *object_ptr;
}nebstruct_acknowledgement_data;
/* state change structure */
typedef struct nebstruct_statechange_struct{
int type;
int flags;
int attr;
struct timeval timestamp;
int statechange_type;
char *host_name;
char *service_description;
int state;
int state_type;
int current_attempt;
int max_attempts;
char *output;
void *object_ptr;
}nebstruct_statechange_data;
#ifdef __cplusplus
}
#endif
#endif

771
nagios/objects.h Normal file
View File

@@ -0,0 +1,771 @@
/*****************************************************************************
*
* OBJECTS.H - Header file for object addition/search functions
*
* Copyright (c) 1999-2007 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 11-10-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _OBJECTS_H
#define _OBJECTS_H
#include "config.h"
#include "common.h"
#ifdef __cplusplus
extern "C" {
#endif
/*************** CURRENT OBJECT REVISION **************/
#define CURRENT_OBJECT_STRUCTURE_VERSION 307 /* increment when changes are made to data structures... */
/* Nagios 3 starts at 300, Nagios 4 at 400, etc. */
/***************** OBJECT SIZE LIMITS *****************/
#define MAX_STATE_HISTORY_ENTRIES 21 /* max number of old states to keep track of for flap detection */
#define MAX_CONTACT_ADDRESSES 6 /* max number of custom addresses a contact can have */
/***************** SKIP LISTS ****************/
#define NUM_OBJECT_SKIPLISTS 12
#define HOST_SKIPLIST 0
#define SERVICE_SKIPLIST 1
#define COMMAND_SKIPLIST 2
#define TIMEPERIOD_SKIPLIST 3
#define CONTACT_SKIPLIST 4
#define CONTACTGROUP_SKIPLIST 5
#define HOSTGROUP_SKIPLIST 6
#define SERVICEGROUP_SKIPLIST 7
#define HOSTDEPENDENCY_SKIPLIST 8
#define SERVICEDEPENDENCY_SKIPLIST 9
#define HOSTESCALATION_SKIPLIST 10
#define SERVICEESCALATION_SKIPLIST 11
/****************** DATA STRUCTURES *******************/
typedef struct host_struct host;
typedef struct service_struct service;
typedef struct contact_struct contact;
/* OBJECT LIST STRUCTURE */
typedef struct objectlist_struct{
void *object_ptr;
struct objectlist_struct *next;
}objectlist;
/* TIMERANGE structure */
typedef struct timerange_struct{
unsigned long range_start;
unsigned long range_end;
struct timerange_struct *next;
}timerange;
/* DATERANGE structure */
typedef struct daterange_struct{
int type;
int syear; /* start year */
int smon; /* start month */
int smday; /* start day of month (may 3rd, last day in feb) */
int swday; /* start day of week (thursday) */
int swday_offset; /* start weekday offset (3rd thursday, last monday in jan) */
int eyear;
int emon;
int emday;
int ewday;
int ewday_offset;
int skip_interval;
timerange *times;
struct daterange_struct *next;
}daterange;
/* TIMEPERIODEXCLUSION structure */
typedef struct timeperiodexclusion_struct{
char *timeperiod_name;
struct timeperiod_struct *timeperiod_ptr;
struct timeperiodexclusion_struct *next;
}timeperiodexclusion;
/* TIMEPERIOD structure */
typedef struct timeperiod_struct{
char *name;
char *alias;
timerange *days[7];
daterange *exceptions[DATERANGE_TYPES];
timeperiodexclusion *exclusions;
struct timeperiod_struct *next;
struct timeperiod_struct *nexthash;
}timeperiod;
/* CONTACTSMEMBER structure */
typedef struct contactsmember_struct{
char *contact_name;
#ifdef NSCORE
contact *contact_ptr;
#endif
struct contactsmember_struct *next;
}contactsmember;
/* CONTACTGROUP structure */
typedef struct contactgroup_struct{
char *group_name;
char *alias;
contactsmember *members;
struct contactgroup_struct *next;
struct contactgroup_struct *nexthash;
}contactgroup;
/* CONTACTGROUPSMEMBER structure */
typedef struct contactgroupsmember_struct{
char *group_name;
#ifdef NSCORE
contactgroup *group_ptr;
#endif
struct contactgroupsmember_struct *next;
}contactgroupsmember;
/* CUSTOMVARIABLESMEMBER structure */
typedef struct customvariablesmember_struct{
char *variable_name;
char *variable_value;
int has_been_modified;
struct customvariablesmember_struct *next;
}customvariablesmember;
/* COMMAND structure */
typedef struct command_struct{
char *name;
char *command_line;
struct command_struct *next;
struct command_struct *nexthash;
}command;
/* COMMANDSMEMBER structure */
typedef struct commandsmember_struct{
char *command_dummy;
#ifdef NSCORE
command *command_ptr;
#endif
struct commandsmember_struct *next;
}commandsmember;
/* CONTACT structure */
struct contact_struct{
char *name;
char *alias;
char *email;
char *pager;
char *address[MAX_CONTACT_ADDRESSES];
commandsmember *host_notification_commands;
commandsmember *service_notification_commands;
int notify_on_service_unknown;
int notify_on_service_warning;
int notify_on_service_critical;
int notify_on_service_recovery;
int notify_on_service_flapping;
int notify_on_service_downtime;
int notify_on_host_down;
int notify_on_host_unreachable;
int notify_on_host_recovery;
int notify_on_host_flapping;
int notify_on_host_downtime;
char *host_notification_period;
char *service_notification_period;
int host_notifications_enabled;
int service_notifications_enabled;
int can_submit_commands;
int retain_status_information;
int retain_nonstatus_information;
customvariablesmember *custom_variables;
#ifdef NSCORE
time_t last_host_notification;
time_t last_service_notification;
unsigned long modified_attributes;
unsigned long modified_host_attributes;
unsigned long modified_service_attributes;
timeperiod *host_notification_period_ptr;
timeperiod *service_notification_period_ptr;
objectlist *contactgroups_ptr;
#endif
struct contact_struct *next;
struct contact_struct *nexthash;
};
/* SERVICESMEMBER structure */
typedef struct servicesmember_struct{
char *host_name;
char *service_description;
#ifdef NSCORE
service *service_ptr;
#endif
struct servicesmember_struct *next;
}servicesmember;
/* HOSTSMEMBER structure */
typedef struct hostsmember_struct{
char *host_name;
#ifdef NSCORE
host *host_ptr;
#endif
struct hostsmember_struct *next;
}hostsmember;
/* HOSTGROUP structure */
typedef struct hostgroup_struct{
char *group_name;
char *alias;
hostsmember *members;
char *notes;
char *notes_url;
char *action_url;
struct hostgroup_struct *next;
struct hostgroup_struct *nexthash;
}hostgroup;
/* HOST structure */
struct host_struct{
char *name;
char *display_name;
char *alias;
char *address;
hostsmember *parent_hosts;
hostsmember *child_hosts;
servicesmember *services;
char *host_check_command;
int initial_state;
double check_interval;
double retry_interval;
int max_attempts;
char *event_handler;
contactgroupsmember *contact_groups;
contactsmember *contacts;
double notification_interval;
double first_notification_delay;
int notify_on_down;
int notify_on_unreachable;
int notify_on_recovery;
int notify_on_flapping;
int notify_on_downtime;
char *notification_period;
char *check_period;
int flap_detection_enabled;
double low_flap_threshold;
double high_flap_threshold;
int flap_detection_on_up;
int flap_detection_on_down;
int flap_detection_on_unreachable;
int stalk_on_up;
int stalk_on_down;
int stalk_on_unreachable;
int check_freshness;
int freshness_threshold;
int process_performance_data;
int checks_enabled;
int accept_passive_host_checks;
int event_handler_enabled;
int retain_status_information;
int retain_nonstatus_information;
int failure_prediction_enabled;
char *failure_prediction_options;
int obsess_over_host;
char *notes;
char *notes_url;
char *action_url;
char *icon_image;
char *icon_image_alt;
char *vrml_image;
char *statusmap_image;
int have_2d_coords;
int x_2d;
int y_2d;
int have_3d_coords;
double x_3d;
double y_3d;
double z_3d;
int should_be_drawn;
customvariablesmember *custom_variables;
#ifdef NSCORE
int problem_has_been_acknowledged;
int acknowledgement_type;
int check_type;
int current_state;
int last_state;
int last_hard_state;
char *plugin_output;
char *long_plugin_output;
char *perf_data;
int state_type;
int current_attempt;
unsigned long current_event_id;
unsigned long last_event_id;
unsigned long current_problem_id;
unsigned long last_problem_id;
double latency;
double execution_time;
int is_executing;
int check_options;
int notifications_enabled;
time_t last_host_notification;
time_t next_host_notification;
time_t next_check;
int should_be_scheduled;
time_t last_check;
time_t last_state_change;
time_t last_hard_state_change;
time_t last_time_up;
time_t last_time_down;
time_t last_time_unreachable;
int has_been_checked;
int is_being_freshened;
int notified_on_down;
int notified_on_unreachable;
int current_notification_number;
int no_more_notifications;
unsigned long current_notification_id;
int check_flapping_recovery_notification;
int scheduled_downtime_depth;
int pending_flex_downtime;
int state_history[MAX_STATE_HISTORY_ENTRIES]; /* flap detection */
int state_history_index;
time_t last_state_history_update;
int is_flapping;
unsigned long flapping_comment_id;
double percent_state_change;
int total_services;
unsigned long total_service_check_interval;
unsigned long modified_attributes;
int circular_path_checked;
int contains_circular_path;
command *event_handler_ptr;
command *check_command_ptr;
timeperiod *check_period_ptr;
timeperiod *notification_period_ptr;
objectlist *hostgroups_ptr;
#endif
struct host_struct *next;
struct host_struct *nexthash;
};
/* SERVICEGROUP structure */
typedef struct servicegroup_struct{
char *group_name;
char *alias;
servicesmember *members;
char *notes;
char *notes_url;
char *action_url;
struct servicegroup_struct *next;
struct servicegroup_struct *nexthash;
}servicegroup;
/* SERVICE structure */
struct service_struct{
char *host_name;
char *description;
char *display_name;
char *service_check_command;
char *event_handler;
int initial_state;
double check_interval;
double retry_interval;
int max_attempts;
int parallelize;
contactgroupsmember *contact_groups;
contactsmember *contacts;
double notification_interval;
double first_notification_delay;
int notify_on_unknown;
int notify_on_warning;
int notify_on_critical;
int notify_on_recovery;
int notify_on_flapping;
int notify_on_downtime;
int stalk_on_ok;
int stalk_on_warning;
int stalk_on_unknown;
int stalk_on_critical;
int is_volatile;
char *notification_period;
char *check_period;
int flap_detection_enabled;
double low_flap_threshold;
double high_flap_threshold;
int flap_detection_on_ok;
int flap_detection_on_warning;
int flap_detection_on_unknown;
int flap_detection_on_critical;
int process_performance_data;
int check_freshness;
int freshness_threshold;
int accept_passive_service_checks;
int event_handler_enabled;
int checks_enabled;
int retain_status_information;
int retain_nonstatus_information;
int notifications_enabled;
int obsess_over_service;
int failure_prediction_enabled;
char *failure_prediction_options;
char *notes;
char *notes_url;
char *action_url;
char *icon_image;
char *icon_image_alt;
customvariablesmember *custom_variables;
#ifdef NSCORE
int problem_has_been_acknowledged;
int acknowledgement_type;
int host_problem_at_last_check;
int check_type;
int current_state;
int last_state;
int last_hard_state;
char *plugin_output;
char *long_plugin_output;
char *perf_data;
int state_type;
time_t next_check;
int should_be_scheduled;
time_t last_check;
int current_attempt;
unsigned long current_event_id;
unsigned long last_event_id;
unsigned long current_problem_id;
unsigned long last_problem_id;
time_t last_notification;
time_t next_notification;
int no_more_notifications;
int check_flapping_recovery_notification;
time_t last_state_change;
time_t last_hard_state_change;
time_t last_time_ok;
time_t last_time_warning;
time_t last_time_unknown;
time_t last_time_critical;
int has_been_checked;
int is_being_freshened;
int notified_on_unknown;
int notified_on_warning;
int notified_on_critical;
int current_notification_number;
unsigned long current_notification_id;
double latency;
double execution_time;
int is_executing;
int check_options;
int scheduled_downtime_depth;
int pending_flex_downtime;
int state_history[MAX_STATE_HISTORY_ENTRIES]; /* flap detection */
int state_history_index;
int is_flapping;
unsigned long flapping_comment_id;
double percent_state_change;
unsigned long modified_attributes;
host *host_ptr;
command *event_handler_ptr;
char *event_handler_args;
command *check_command_ptr;
char *check_command_args;
timeperiod *check_period_ptr;
timeperiod *notification_period_ptr;
objectlist *servicegroups_ptr;
#endif
struct service_struct *next;
struct service_struct *nexthash;
};
/* SERVICE ESCALATION structure */
typedef struct serviceescalation_struct{
char *host_name;
char *description;
int first_notification;
int last_notification;
double notification_interval;
char *escalation_period;
int escalate_on_recovery;
int escalate_on_warning;
int escalate_on_unknown;
int escalate_on_critical;
contactgroupsmember *contact_groups;
contactsmember *contacts;
#ifdef NSCORE
service *service_ptr;
timeperiod *escalation_period_ptr;
#endif
struct serviceescalation_struct *next;
struct serviceescalation_struct *nexthash;
}serviceescalation;
/* SERVICE DEPENDENCY structure */
typedef struct servicedependency_struct{
int dependency_type;
char *dependent_host_name;
char *dependent_service_description;
char *host_name;
char *service_description;
char *dependency_period;
int inherits_parent;
int fail_on_ok;
int fail_on_warning;
int fail_on_unknown;
int fail_on_critical;
int fail_on_pending;
#ifdef NSCORE
int circular_path_checked;
int contains_circular_path;
service *master_service_ptr;
service *dependent_service_ptr;
timeperiod *dependency_period_ptr;
#endif
struct servicedependency_struct *next;
struct servicedependency_struct *nexthash;
}servicedependency;
/* HOST ESCALATION structure */
typedef struct hostescalation_struct{
char *host_name;
int first_notification;
int last_notification;
double notification_interval;
char *escalation_period;
int escalate_on_recovery;
int escalate_on_down;
int escalate_on_unreachable;
contactgroupsmember *contact_groups;
contactsmember *contacts;
#ifdef NSCORE
host *host_ptr;
timeperiod *escalation_period_ptr;
#endif
struct hostescalation_struct *next;
struct hostescalation_struct *nexthash;
}hostescalation;
/* HOST DEPENDENCY structure */
typedef struct hostdependency_struct{
int dependency_type;
char *dependent_host_name;
char *host_name;
char *dependency_period;
int inherits_parent;
int fail_on_up;
int fail_on_down;
int fail_on_unreachable;
int fail_on_pending;
#ifdef NSCORE
int circular_path_checked;
int contains_circular_path;
host *master_host_ptr;
host *dependent_host_ptr;
timeperiod *dependency_period_ptr;
#endif
struct hostdependency_struct *next;
struct hostdependency_struct *nexthash;
}hostdependency;
/****************** HASH STRUCTURES ********************/
typedef struct host_cursor_struct{
int host_hashchain_iterator;
host *current_host_pointer;
}host_cursor;
/********************* FUNCTIONS **********************/
/**** Top-level input functions ****/
int read_object_config_data(char *,int,int,int); /* reads all external configuration data of specific types */
/**** Object Creation Functions ****/
contact *add_contact(char *,char *,char *,char *,char **,char *,char *,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int); /* adds a contact definition */
commandsmember *add_service_notification_command_to_contact(contact *,char *); /* adds a service notification command to a contact definition */
commandsmember *add_host_notification_command_to_contact(contact *,char *); /* adds a host notification command to a contact definition */
customvariablesmember *add_custom_variable_to_contact(contact *,char *,char *); /* adds a custom variable to a service definition */
host *add_host(char *,char *,char *,char *,char *,int,double,double,int,int,int,int,int,int,double,double,char *,int,char *,int,int,char *,int,int,double,double,int,int,int,int,int,int,int,int,char *,int,int,char *,char *,char *,char *,char *,char *,char *,int,int,int,double,double,double,int,int,int,int,int); /* adds a host definition */
hostsmember *add_parent_host_to_host(host *,char *); /* adds a parent host to a host definition */
hostsmember *add_child_link_to_host(host *,host *); /* adds a child host to a host definition */
contactgroupsmember *add_contactgroup_to_host(host *,char *); /* adds a contactgroup to a host definition */
contactsmember *add_contact_to_host(host *,char *); /* adds a contact to a host definition */
customvariablesmember *add_custom_variable_to_host(host *,char *,char *); /* adds a custom variable to a host definition */
timeperiod *add_timeperiod(char *,char *); /* adds a timeperiod definition */
timeperiodexclusion *add_exclusion_to_timeperiod(timeperiod *,char *); /* adds an exclusion to a timeperiod */
timerange *add_timerange_to_timeperiod(timeperiod *,int,unsigned long,unsigned long); /* adds a timerange to a timeperiod definition */
daterange *add_exception_to_timeperiod(timeperiod *,int,int,int,int,int,int,int,int,int,int,int,int);
timerange *add_timerange_to_daterange(daterange *,unsigned long,unsigned long);
hostgroup *add_hostgroup(char *,char *,char *,char *,char *); /* adds a hostgroup definition */
hostsmember *add_host_to_hostgroup(hostgroup *, char *); /* adds a host to a hostgroup definition */
servicegroup *add_servicegroup(char *,char *,char *,char *,char *); /* adds a servicegroup definition */
servicesmember *add_service_to_servicegroup(servicegroup *,char *,char *); /* adds a service to a servicegroup definition */
contactgroup *add_contactgroup(char *,char *); /* adds a contactgroup definition */
contactsmember *add_contact_to_contactgroup(contactgroup *,char *); /* adds a contact to a contact group definition */
command *add_command(char *,char *); /* adds a command definition */
service *add_service(char *,char *,char *,char *,int,int,int,int,double,double,double,double,char *,int,int,int,int,int,int,int,int,char *,int,char *,int,int,double,double,int,int,int,int,int,int,int,int,int,int,char *,int,int,char *,char *,char *,char *,char *,int,int,int); /* adds a service definition */
contactgroupsmember *add_contactgroup_to_service(service *,char *); /* adds a contact group to a service definition */
contactsmember *add_contact_to_service(service *,char *); /* adds a contact to a host definition */
serviceescalation *add_serviceescalation(char *,char *,int,int,double,char *,int,int,int,int); /* adds a service escalation definition */
contactgroupsmember *add_contactgroup_to_serviceescalation(serviceescalation *,char *); /* adds a contact group to a service escalation definition */
contactsmember *add_contact_to_serviceescalation(serviceescalation *,char *); /* adds a contact to a service escalation definition */
customvariablesmember *add_custom_variable_to_service(service *,char *,char *); /* adds a custom variable to a service definition */
servicedependency *add_service_dependency(char *,char *,char *,char *,int,int,int,int,int,int,int,char *); /* adds a service dependency definition */
hostdependency *add_host_dependency(char *,char *,int,int,int,int,int,int,char *); /* adds a host dependency definition */
hostescalation *add_hostescalation(char *,int,int,double,char *,int,int,int); /* adds a host escalation definition */
contactsmember *add_contact_to_hostescalation(hostescalation *,char *); /* adds a contact to a host escalation definition */
contactgroupsmember *add_contactgroup_to_hostescalation(hostescalation *,char *); /* adds a contact group to a host escalation definition */
contactsmember *add_contact_to_object(contactsmember **,char *); /* adds a contact to an object */
customvariablesmember *add_custom_variable_to_object(customvariablesmember **,char *,char *); /* adds a custom variable to an object */
servicesmember *add_service_link_to_host(host *,service *);
/*** Object Skiplist Functions ****/
int init_object_skiplists(void);
int free_object_skiplists(void);
int skiplist_compare_text(const char *val1a, const char *val1b, const char *val2a, const char *val2b);
int skiplist_compare_host(void *a, void *b);
int skiplist_compare_service(void *a, void *b);
int skiplist_compare_command(void *a, void *b);
int skiplist_compare_timeperiod(void *a, void *b);
int skiplist_compare_contact(void *a, void *b);
int skiplist_compare_contactgroup(void *a, void *b);
int skiplist_compare_hostgroup(void *a, void *b);
int skiplist_compare_servicegroup(void *a, void *b);
int skiplist_compare_hostescalation(void *a, void *b);
int skiplist_compare_serviceescalation(void *a, void *b);
int skiplist_compare_hostdependency(void *a, void *b);
int skiplist_compare_servicedependency(void *a, void *b);
int get_host_count(void);
int get_service_count(void);
/**** Object Hash Functions ****/
int add_servicedependency_to_hashlist(servicedependency *);
/**** Object Search Functions ****/
timeperiod * find_timeperiod(char *); /* finds a timeperiod object */
host * find_host(char *); /* finds a host object */
hostgroup * find_hostgroup(char *); /* finds a hostgroup object */
servicegroup * find_servicegroup(char *); /* finds a servicegroup object */
contact * find_contact(char *); /* finds a contact object */
contactgroup * find_contactgroup(char *); /* finds a contactgroup object */
command * find_command(char *); /* finds a command object */
service * find_service(char *,char *); /* finds a service object */
/**** Object Traversal Functions ****/
hostescalation *get_first_hostescalation_by_host(char *, void **);
hostescalation *get_next_hostescalation_by_host(char *,void **);
serviceescalation *get_first_serviceescalation_by_service(char *,char *, void **);
serviceescalation *get_next_serviceescalation_by_service(char *,char *,void **);
hostdependency *get_first_hostdependency_by_dependent_host(char *, void **);
hostdependency *get_next_hostdependency_by_dependent_host(char *, void **);
servicedependency *get_first_servicedependency_by_dependent_service(char *,char *, void **);
servicedependency *get_next_servicedependency_by_dependent_service(char *,char *,void **);
#ifdef NSCORE
int add_object_to_objectlist(objectlist **,void *);
int free_objectlist(objectlist **);
#endif
/**** Object Query Functions ****/
int is_host_immediate_child_of_host(host *,host *); /* checks if a host is an immediate child of another host */
int is_host_primary_immediate_child_of_host(host *,host *); /* checks if a host is an immediate child (and primary child) of another host */
int is_host_immediate_parent_of_host(host *,host *); /* checks if a host is an immediate child of another host */
int is_host_member_of_hostgroup(hostgroup *,host *); /* tests whether or not a host is a member of a specific hostgroup */
int is_host_member_of_servicegroup(servicegroup *,host *); /* tests whether or not a service is a member of a specific servicegroup */
int is_service_member_of_servicegroup(servicegroup *,service *); /* tests whether or not a service is a member of a specific servicegroup */
int is_contact_member_of_contactgroup(contactgroup *, contact *); /* tests whether or not a contact is a member of a specific contact group */
int is_contact_for_hostgroup(hostgroup *,contact *); /* tests whether or not a contact is a member of a specific hostgroup */
int is_contact_for_servicegroup(servicegroup *,contact *); /* tests whether or not a contact is a member of a specific servicegroup */
int is_contact_for_host(host *,contact *); /* tests whether or not a contact is a contact member for a specific host */
int is_escalated_contact_for_host(host *,contact *); /* checks whether or not a contact is an escalated contact for a specific host */
int is_contact_for_service(service *,contact *); /* tests whether or not a contact is a contact member for a specific service */
int is_escalated_contact_for_service(service *,contact *); /* checks whether or not a contact is an escalated contact for a specific service */
int is_host_immediate_parent_of_host(host *,host *); /* tests whether or not a host is an immediate parent of another host */
int number_of_immediate_child_hosts(host *); /* counts the number of immediate child hosts for a particular host */
int number_of_total_child_hosts(host *); /* counts the number of total child hosts for a particular host */
int number_of_immediate_parent_hosts(host *); /* counts the number of immediate parents hosts for a particular host */
int number_of_total_parent_hosts(host *); /* counts the number of total parents hosts for a particular host */
#ifdef NSCORE
int check_for_circular_servicedependency_path(servicedependency *,servicedependency *,int); /* checks if a circular dependency exists for a given service */
int check_for_circular_hostdependency_path(hostdependency *,hostdependency *,int); /* checks if a circular dependency exists for a given host */
#endif
/**** Object Cleanup Functions ****/
int free_object_data(void); /* frees all allocated memory for the object definitions */
#ifdef __cplusplus
}
#endif
#endif

45
nagios/perfdata.h Normal file
View File

@@ -0,0 +1,45 @@
/*****************************************************************************
*
* PERFDATA.H - Include file for performance data routines
*
* Copyright (c) 2001-2005 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 11-25-2005
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _PERFDATA_H
#define _PERFDATA_H
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
int initialize_performance_data(char *); /* initializes performance data */
int cleanup_performance_data(char *); /* cleans up performance data */
int update_host_performance_data(host *); /* updates host performance data */
int update_service_performance_data(service *); /* updates service performance data */
#ifdef __cplusplus
}
#endif
#endif

68
nagios/skiplist.h Normal file
View File

@@ -0,0 +1,68 @@
/************************************************************************
*
* SKIPLIST.H - Skiplist data structures and functions
*
* Copyright (c) 2008 Ethan Galstad
* Last Modified: 02-24-2008
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef _SKIPLIST_H
#define _SKIPLIST_H
#define SKIPLIST_OK 0
#define SKIPLIST_ERROR_ARGS 1
#define SKIPLIST_ERROR_MEMORY 2
#define SKIPLIST_ERROR_DUPLICATE 3
typedef struct skiplistnode_struct{
void *data;
struct skiplistnode_struct *forward[1]; /* this must be the last element of the struct, as we allocate # of elements during runtime*/
}skiplistnode;
typedef struct skiplist_struct{
int current_level;
int max_levels;
float level_probability;
unsigned long items;
int allow_duplicates;
int append_duplicates;
int (*compare_function)(void *,void *);
skiplistnode *head;
}skiplist;
skiplist *skiplist_new(int max_levels, float level_probability, int allow_duplicates, int append_duplicates, int (*compare_function)(void *,void *));
skiplistnode *skiplist_new_node(skiplist *list,int node_levels);
int skiplist_insert(skiplist *list, void *data);
int skiplist_random_level(skiplist *list);
int skiplist_empty(skiplist *list);
int skiplist_free(skiplist **list);
void *skiplist_peek(skiplist *);
void *skiplist_pop(skiplist *);
void *skiplist_get_first(skiplist *list, void **node_ptr);
void *skiplist_get_next(void **node_ptr);
void *skiplist_find_first(skiplist *list, void *data, void **node_ptr);
void *skiplist_find_next(skiplist *list, void *data, void **node_ptr);
int skiplist_delete(skiplist *list, void *data);
int skiplist_delete_first(skiplist *list, void *data);
int skiplist_delete_all(skiplist *list, void *data);
int skiplist_delete_node(skiplist *list, void *node_ptr);
#endif

37
nagios/sretention.h Normal file
View File

@@ -0,0 +1,37 @@
/*****************************************************************************
*
* SRETENTION.H - Header for state retention routines
*
* Copyright (c) 1999-2006 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 02-28-2006
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
int initialize_retention_data(char *);
int cleanup_retention_data(char *);
int save_state_information(int); /* saves all host and state information */
int read_initial_state_information(void); /* reads in initial host and state information */
#ifdef __cplusplus
}
#endif

202
nagios/statusdata.h Normal file
View File

@@ -0,0 +1,202 @@
/*****************************************************************************
*
* STATUSDATA.H - Header for external status data routines
*
* Copyright (c) 2000-2007 Ethan Galstad (egalstad@nagios.org)
* Last Modified: 10-19-2007
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _STATUSDATA_H
#define _STATUSDATA_H
#ifdef NSCORE
#include "objects.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef NSCGI
#define READ_PROGRAM_STATUS 1
#define READ_HOST_STATUS 2
#define READ_SERVICE_STATUS 4
#define READ_CONTACT_STATUS 8
#define READ_ALL_STATUS_DATA READ_PROGRAM_STATUS | READ_HOST_STATUS | READ_SERVICE_STATUS | READ_CONTACT_STATUS
/*************************** CHAINED HASH LIMITS ***************************/
#define SERVICESTATUS_HASHSLOTS 1024
#define HOSTSTATUS_HASHSLOTS 1024
/**************************** DATA STRUCTURES ******************************/
/* HOST STATUS structure */
typedef struct hoststatus_struct{
char *host_name;
char *plugin_output;
char *long_plugin_output;
char *perf_data;
int status;
time_t last_update;
int has_been_checked;
int should_be_scheduled;
int current_attempt;
int max_attempts;
time_t last_check;
time_t next_check;
int check_options;
int check_type;
time_t last_state_change;
time_t last_hard_state_change;
int last_hard_state;
time_t last_time_up;
time_t last_time_down;
time_t last_time_unreachable;
int state_type;
time_t last_notification;
time_t next_notification;
int no_more_notifications;
int notifications_enabled;
int problem_has_been_acknowledged;
int acknowledgement_type;
int current_notification_number;
int accept_passive_host_checks;
int event_handler_enabled;
int checks_enabled;
int flap_detection_enabled;
int is_flapping;
double percent_state_change;
double latency;
double execution_time;
int scheduled_downtime_depth;
int failure_prediction_enabled;
int process_performance_data;
int obsess_over_host;
struct hoststatus_struct *next;
struct hoststatus_struct *nexthash;
}hoststatus;
/* SERVICE STATUS structure */
typedef struct servicestatus_struct{
char *host_name;
char *description;
char *plugin_output;
char *long_plugin_output;
char *perf_data;
int max_attempts;
int current_attempt;
int status;
time_t last_update;
int has_been_checked;
int should_be_scheduled;
time_t last_check;
time_t next_check;
int check_options;
int check_type;
int checks_enabled;
time_t last_state_change;
time_t last_hard_state_change;
int last_hard_state;
time_t last_time_ok;
time_t last_time_warning;
time_t last_time_unknown;
time_t last_time_critical;
int state_type;
time_t last_notification;
time_t next_notification;
int no_more_notifications;
int notifications_enabled;
int problem_has_been_acknowledged;
int acknowledgement_type;
int current_notification_number;
int accept_passive_service_checks;
int event_handler_enabled;
int flap_detection_enabled;
int is_flapping;
double percent_state_change;
double latency;
double execution_time;
int scheduled_downtime_depth;
int failure_prediction_enabled;
int process_performance_data;
int obsess_over_service;
struct servicestatus_struct *next;
struct servicestatus_struct *nexthash;
}servicestatus;
/*************************** SERVICE STATES ***************************/
#define SERVICE_PENDING 1
#define SERVICE_OK 2
#define SERVICE_WARNING 4
#define SERVICE_UNKNOWN 8
#define SERVICE_CRITICAL 16
/**************************** HOST STATES ****************************/
#define HOST_PENDING 1
#define HOST_UP 2
#define HOST_DOWN 4
#define HOST_UNREACHABLE 8
/**************************** FUNCTIONS ******************************/
int read_status_data(char *,int); /* reads all status data */
int add_host_status(hoststatus *); /* adds a host status entry to the list in memory */
int add_service_status(servicestatus *); /* adds a service status entry to the list in memory */
int add_hoststatus_to_hashlist(hoststatus *);
int add_servicestatus_to_hashlist(servicestatus *);
servicestatus *find_servicestatus(char *,char *); /* finds status information for a specific service */
hoststatus *find_hoststatus(char *); /* finds status information for a specific host */
int get_servicestatus_count(char *,int); /* gets total number of services of a certain type for a specific host */
void free_status_data(void); /* free all memory allocated to status data */
#endif
#ifdef NSCORE
int initialize_status_data(char *); /* initializes status data at program start */
int update_all_status_data(void); /* updates all status data */
int cleanup_status_data(char *,int); /* cleans up status data at program termination */
int update_program_status(int); /* updates program status data */
int update_host_status(host *,int); /* updates host status data */
int update_service_status(service *,int); /* updates service status data */
int update_contact_status(contact *,int); /* updates contact status data */
#endif
#ifdef __cplusplus
}
#endif
#endif

1
nagios4/README Normal file
View File

@@ -0,0 +1 @@
These files are taken directly from Nagios 4.0.2.

156
nagios4/bitmap.h Normal file
View File

@@ -0,0 +1,156 @@
#ifndef LIBNAGIOS_bitmap_h__
#define LIBNAGIOS_bitmap_h__
/**
* @file bitmap.h
* @brief Bit map API
*
* The bitmap api is useful for running set operations on objects
* indexed by unsigned integers.
* @{
*/
struct bitmap;
typedef struct bitmap bitmap;
/**
* Resize a bitmap
* If the bitmap is made smaller, data will silently be lost.
*
* @param bm The bitmap to resize
* @param size The new desired size of the bitmap
* @return 0 on success, -1 on errors.
*/
extern int bitmap_resize(bitmap *bm, unsigned long size);
/**
* Create a bitmaptor of size 'size'
* @param size Desired storage capacity
* @return A bitmap pointer on success, NULL on errors
*/
extern bitmap *bitmap_create(unsigned long size);
/**
* Destroy a bitmaptor by freeing all the memory it uses
* @param bm The bitmaptor to destroy
*/
extern void bitmap_destroy(bitmap *bm);
/**
* Copy a bitmaptor
* @param bm The bitmaptor to copy
* @return Pointer to an identical bitmap on success, NULL on errors
*/
extern bitmap *bitmap_copy(const bitmap *bm);
/**
* Set a bit in the map
* @param bm The bitmaptor to operate on
* @param pos Position of the bit to set
* @return 0 on success, -1 on errors
*/
extern int bitmap_set(bitmap *bm, unsigned long pos);
/**
* Check if a particular bit is set in the map
* @param bm The bitmaptor to check
* @param pos Position of the bit to check
* @return 1 if set, otherwise 0
*/
extern int bitmap_isset(const bitmap *bm, unsigned long pos);
/**
* Unset a particular bit in the map
* @param bm The bitmaptor to operate on
* @param pos Position of the bit to unset
*/
extern int bitmap_unset(bitmap *bm, unsigned long pos);
/**
* Obtain cardinality (max number of elements) of the bitmaptor
* @param bm The bitmaptor to check
* @return The cardinality of the bitmaptor
*/
extern unsigned long bitmap_cardinality(const bitmap *bm);
#define bitmap_size bitmap_cardinality
/**
* Count set bits in map. Completed in O(n/8) time.
* @param bm The bitmaptor to count bits in
* @return The number of set bits
*/
extern unsigned long bitmap_count_set_bits(const bitmap *bm);
/**
* Count unset bits in map. Completed in O(n/8) time.
* @param bm The bitmaptor to count bits in
* @return The number of set bits
*/
extern unsigned long bitmap_count_unset_bits(const bitmap *bm);
/**
* Unset all bits in a bitmap
* @param bm The bitmap to clear
*/
extern void bitmap_clear(bitmap *bm);
/**
* Calculate intersection of two bitmaps
* The intersection is defined as all bits that are members of
* both A and B. It's equivalent to bitwise AND.
* This function completes in O(n/sizeof(long)) operations.
* @param a The first bitmaptor
* @param b The second bitmaptor
* @return NULL on errors; A newly created bitmaptor on success.
*/
extern bitmap *bitmap_intersect(const bitmap *a, const bitmap *b);
/**
* Calculate union of two bitmaps
* The union is defined as all bits that are members of
* A or B or both A and B. It's equivalent to bitwise OR.
* This function completes in O(n/sizeof(long)) operations.
* @param a The first bitmaptor
* @param b The second bitmaptor
* @return NULL on errors; A newly created bitmaptor on success.
*/
extern bitmap *bitmap_union(const bitmap *a, const bitmap *b);
/**
* Calculate union of two bitmaps and store result in one of them
* @param res The first bitmap
* @param addme The bitmap to unite to the first bitmap
* @return NULL on errors, res on success
*/
extern bitmap *bitmap_unite(bitmap *res, const bitmap *addme);
/**
* Calculate set difference between two bitmaps
* The set difference of A / B is defined as all members of A
* that isn't members of B. Note that parameter ordering matters
* for this function.
* This function completes in O(n/sizeof(long)) operations.
* @param a The first bitmaptor (numerator)
* @param b The first bitmaptor (denominator)
* @return NULL on errors; A newly created bitmaptor on success.
*/
extern bitmap *bitmap_diff(const bitmap *a, const bitmap *b);
/**
* Calculate symmetric difference between two bitmaps
* The symmetric difference between A and B is the set that
* contains all elements in either set but not in both.
* This function completes in O(n/sizeof(long)) operations.
* @param a The first bitmaptor
* @param b The second bitmaptor
*/
extern bitmap *bitmap_symdiff(const bitmap *a, const bitmap *b);
/**
* Compare two bitmaps for equality
* @param a The first bitmaptor
* @param b The other bitmaptor
* @return Similar to memcmp(), with tiebreaks determined by cardinality
*/
extern int bitmap_cmp(const bitmap *a, const bitmap *b);
/** @} */
#endif /* LIBNAGIOS_bitmap_h__ */

213
nagios4/broker.h Normal file
View File

@@ -0,0 +1,213 @@
/*****************************************************************************
*
* BROKER.H - Event broker includes for Nagios
*
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _BROKER_H
#define _BROKER_H
#include "nagios.h"
/*************** EVENT BROKER OPTIONS *****************/
#define BROKER_NOTHING 0
#define BROKER_EVERYTHING 1048575
#define BROKER_PROGRAM_STATE 1 /* DONE */
#define BROKER_TIMED_EVENTS 2 /* DONE */
#define BROKER_SERVICE_CHECKS 4 /* DONE */
#define BROKER_HOST_CHECKS 8 /* DONE */
#define BROKER_EVENT_HANDLERS 16 /* DONE */
#define BROKER_LOGGED_DATA 32 /* DONE */
#define BROKER_NOTIFICATIONS 64 /* DONE */
#define BROKER_FLAPPING_DATA 128 /* DONE */
#define BROKER_COMMENT_DATA 256 /* DONE */
#define BROKER_DOWNTIME_DATA 512 /* DONE */
#define BROKER_SYSTEM_COMMANDS 1024 /* DONE */
#define BROKER_OCP_DATA_UNUSED 2048 /* reusable */
#define BROKER_STATUS_DATA 4096 /* DONE */
#define BROKER_ADAPTIVE_DATA 8192 /* DONE */
#define BROKER_EXTERNALCOMMAND_DATA 16384 /* DONE */
#define BROKER_RETENTION_DATA 32768 /* DONE */
#define BROKER_ACKNOWLEDGEMENT_DATA 65536
#define BROKER_STATECHANGE_DATA 131072
#define BROKER_RESERVED18 262144
#define BROKER_RESERVED19 524288
/****** EVENT TYPES ************************/
#define NEBTYPE_NONE 0
#define NEBTYPE_HELLO 1
#define NEBTYPE_GOODBYE 2
#define NEBTYPE_INFO 3
#define NEBTYPE_PROCESS_START 100
#define NEBTYPE_PROCESS_DAEMONIZE 101
#define NEBTYPE_PROCESS_RESTART 102
#define NEBTYPE_PROCESS_SHUTDOWN 103
#define NEBTYPE_PROCESS_PRELAUNCH 104 /* before objects are read or verified */
#define NEBTYPE_PROCESS_EVENTLOOPSTART 105
#define NEBTYPE_PROCESS_EVENTLOOPEND 106
#define NEBTYPE_TIMEDEVENT_ADD 200
#define NEBTYPE_TIMEDEVENT_REMOVE 201
#define NEBTYPE_TIMEDEVENT_EXECUTE 202
#define NEBTYPE_TIMEDEVENT_DELAY 203 /* NOT IMPLEMENTED */
#define NEBTYPE_TIMEDEVENT_SKIP 204 /* NOT IMPLEMENTED */
#define NEBTYPE_TIMEDEVENT_SLEEP 205
#define NEBTYPE_LOG_DATA 300
#define NEBTYPE_LOG_ROTATION 301
#define NEBTYPE_SYSTEM_COMMAND_START 400
#define NEBTYPE_SYSTEM_COMMAND_END 401
#define NEBTYPE_EVENTHANDLER_START 500
#define NEBTYPE_EVENTHANDLER_END 501
#define NEBTYPE_NOTIFICATION_START 600
#define NEBTYPE_NOTIFICATION_END 601
#define NEBTYPE_CONTACTNOTIFICATION_START 602
#define NEBTYPE_CONTACTNOTIFICATION_END 603
#define NEBTYPE_CONTACTNOTIFICATIONMETHOD_START 604
#define NEBTYPE_CONTACTNOTIFICATIONMETHOD_END 605
#define NEBTYPE_SERVICECHECK_INITIATE 700
#define NEBTYPE_SERVICECHECK_PROCESSED 701
#define NEBTYPE_SERVICECHECK_RAW_START 702 /* NOT IMPLEMENTED */
#define NEBTYPE_SERVICECHECK_RAW_END 703 /* NOT IMPLEMENTED */
#define NEBTYPE_SERVICECHECK_ASYNC_PRECHECK 704
#define NEBTYPE_HOSTCHECK_INITIATE 800 /* a check of the route to the host has been initiated */
#define NEBTYPE_HOSTCHECK_PROCESSED 801 /* the processed/final result of a host check */
#define NEBTYPE_HOSTCHECK_RAW_START 802 /* the start of a "raw" host check */
#define NEBTYPE_HOSTCHECK_RAW_END 803 /* a finished "raw" host check */
#define NEBTYPE_HOSTCHECK_ASYNC_PRECHECK 804
#define NEBTYPE_HOSTCHECK_SYNC_PRECHECK 805
#define NEBTYPE_COMMENT_ADD 900
#define NEBTYPE_COMMENT_DELETE 901
#define NEBTYPE_COMMENT_LOAD 902
#define NEBTYPE_FLAPPING_START 1000
#define NEBTYPE_FLAPPING_STOP 1001
#define NEBTYPE_DOWNTIME_ADD 1100
#define NEBTYPE_DOWNTIME_DELETE 1101
#define NEBTYPE_DOWNTIME_LOAD 1102
#define NEBTYPE_DOWNTIME_START 1103
#define NEBTYPE_DOWNTIME_STOP 1104
#define NEBTYPE_PROGRAMSTATUS_UPDATE 1200
#define NEBTYPE_HOSTSTATUS_UPDATE 1201
#define NEBTYPE_SERVICESTATUS_UPDATE 1202
#define NEBTYPE_CONTACTSTATUS_UPDATE 1203
#define NEBTYPE_ADAPTIVEPROGRAM_UPDATE 1300
#define NEBTYPE_ADAPTIVEHOST_UPDATE 1301
#define NEBTYPE_ADAPTIVESERVICE_UPDATE 1302
#define NEBTYPE_ADAPTIVECONTACT_UPDATE 1303
#define NEBTYPE_EXTERNALCOMMAND_START 1400
#define NEBTYPE_EXTERNALCOMMAND_END 1401
#define NEBTYPE_AGGREGATEDSTATUS_STARTDUMP 1500
#define NEBTYPE_AGGREGATEDSTATUS_ENDDUMP 1501
#define NEBTYPE_RETENTIONDATA_STARTLOAD 1600
#define NEBTYPE_RETENTIONDATA_ENDLOAD 1601
#define NEBTYPE_RETENTIONDATA_STARTSAVE 1602
#define NEBTYPE_RETENTIONDATA_ENDSAVE 1603
#define NEBTYPE_ACKNOWLEDGEMENT_ADD 1700
#define NEBTYPE_ACKNOWLEDGEMENT_REMOVE 1701 /* NOT IMPLEMENTED */
#define NEBTYPE_ACKNOWLEDGEMENT_LOAD 1702 /* NOT IMPLEMENTED */
#define NEBTYPE_STATECHANGE_START 1800 /* NOT IMPLEMENTED */
#define NEBTYPE_STATECHANGE_END 1801
/****** EVENT FLAGS ************************/
#define NEBFLAG_NONE 0
#define NEBFLAG_PROCESS_INITIATED 1 /* event was initiated by Nagios process */
#define NEBFLAG_USER_INITIATED 2 /* event was initiated by a user request */
#define NEBFLAG_MODULE_INITIATED 3 /* event was initiated by an event broker module */
/****** EVENT ATTRIBUTES *******************/
#define NEBATTR_NONE 0
#define NEBATTR_SHUTDOWN_NORMAL 1
#define NEBATTR_SHUTDOWN_ABNORMAL 2
#define NEBATTR_RESTART_NORMAL 4
#define NEBATTR_RESTART_ABNORMAL 8
#define NEBATTR_FLAPPING_STOP_NORMAL 1
#define NEBATTR_FLAPPING_STOP_DISABLED 2 /* flapping stopped because flap detection was disabled */
#define NEBATTR_DOWNTIME_STOP_NORMAL 1
#define NEBATTR_DOWNTIME_STOP_CANCELLED 2
/****** EVENT BROKER FUNCTIONS *************/
#ifdef USE_EVENT_BROKER
NAGIOS_BEGIN_DECL
struct timeval get_broker_timestamp(struct timeval *);
void broker_program_state(int, int, int, struct timeval *);
void broker_timed_event(int, int, int, timed_event *, struct timeval *);
void broker_log_data(int, int, int, char *, unsigned long, time_t, struct timeval *);
int broker_event_handler(int, int, int, int, void *, int, int, struct timeval, struct timeval, double, int, int, int, char *, char *, char *, struct timeval *);
void broker_system_command(int, int, int, struct timeval, struct timeval, double, int, int, int, char *, char *, struct timeval *);
int broker_host_check(int, int, int, host *, int, int, int, struct timeval, struct timeval, char *, double, double, int, int, int, char *, char *, char *, char *, struct timeval *, check_result *);
int broker_service_check(int, int, int, service *, int, struct timeval, struct timeval, char *, double, double, int, int, int, char *, struct timeval *, check_result *);
void broker_comment_data(int, int, int, int, int, char *, char *, time_t, char *, char *, int, int, int, time_t, unsigned long, struct timeval *);
void broker_downtime_data(int, int, int, int, char *, char *, time_t, char *, char *, time_t, time_t, int, unsigned long, unsigned long, unsigned long, struct timeval *);
void broker_flapping_data(int, int, int, int, void *, double, double, double, struct timeval *);
void broker_program_status(int, int, int, struct timeval *);
void broker_host_status(int, int, int, host *, struct timeval *);
void broker_service_status(int, int, int, service *, struct timeval *);
void broker_contact_status(int, int, int, contact *, struct timeval *);
int broker_notification_data(int, int, int, int, int, struct timeval, struct timeval, void *, char *, char *, int, int, struct timeval *);
int broker_contact_notification_data(int, int, int, int, int, struct timeval, struct timeval, void *, contact *, char *, char *, int, struct timeval *);
int broker_contact_notification_method_data(int, int, int, int, int, struct timeval, struct timeval, void *, contact *, char *, char *, char *, int, struct timeval *);
void broker_adaptive_program_data(int, int, int, int, unsigned long, unsigned long, unsigned long, unsigned long, struct timeval *);
void broker_adaptive_host_data(int, int, int, host *, int, unsigned long, unsigned long, struct timeval *);
void broker_adaptive_service_data(int, int, int, service *, int, unsigned long, unsigned long, struct timeval *);
void broker_adaptive_contact_data(int, int, int, contact *, int, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, struct timeval *);
void broker_external_command(int, int, int, int, time_t, char *, char *, struct timeval *);
void broker_aggregated_status_data(int, int, int, struct timeval *);
void broker_retention_data(int, int, int, struct timeval *);
void broker_acknowledgement_data(int, int, int, int, void *, char *, char *, int, int, int, struct timeval *);
void broker_statechange_data(int, int, int, int, void *, int, int, int, int, struct timeval *);
NAGIOS_END_DECL
#endif
#endif

70
nagios4/cgiauth.h Normal file
View File

@@ -0,0 +1,70 @@
/*****************************************************************************
*
* CGIAUTH.H - Authorization utilities header file
*
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _AUTH_H
#define _AUTH_H
#include "common.h"
#include "objects.h"
NAGIOS_BEGIN_DECL
typedef struct authdata_struct {
char *username;
int authorized_for_all_hosts;
int authorized_for_all_host_commands;
int authorized_for_all_services;
int authorized_for_all_service_commands;
int authorized_for_system_information;
int authorized_for_system_commands;
int authorized_for_configuration_information;
int authorized_for_read_only;
int authenticated;
} authdata;
int get_authentication_information(authdata *); /* gets current authentication information */
int is_authorized_for_host(host *, authdata *);
int is_authorized_for_service(service *, authdata *);
int is_authorized_for_all_hosts(authdata *);
int is_authorized_for_all_services(authdata *);
int is_authorized_for_system_information(authdata *);
int is_authorized_for_system_commands(authdata *);
int is_authorized_for_host_commands(host *, authdata *);
int is_authorized_for_service_commands(service *, authdata *);
int is_authorized_for_hostgroup(hostgroup *, authdata *);
int is_authorized_for_servicegroup(servicegroup *, authdata *);
int is_authorized_for_hostgroup_commands(hostgroup *, authdata *);
int is_authorized_for_servicegroup_commands(servicegroup *, authdata *);
int is_authorized_for_configuration_information(authdata *);
int is_authorized_for_read_only(authdata *);
NAGIOS_END_DECL
#endif

479
nagios4/cgiutils.h Normal file
View File

@@ -0,0 +1,479 @@
/************************************************************************
*
* CGIUTILS.H - Header file for common CGI functions
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef _CGIUTILS_H
#define _CGIUTILS_H
#include "lib/libnagios.h"
#include "logging.h"
#include "objects.h"
#include "cgiauth.h"
NAGIOS_BEGIN_DECL
/**************************** CGI REFRESH RATE ******************************/
#define DEFAULT_REFRESH_RATE 60 /* 60 second refresh rate for CGIs */
/******************************* CGI NAMES **********************************/
#define STATUS_CGI "status.cgi"
#define STATUSMAP_CGI "statusmap.cgi"
#define STATUSWORLD_CGI "statuswrl.cgi"
#define COMMAND_CGI "cmd.cgi"
#define EXTINFO_CGI "extinfo.cgi"
#define SHOWLOG_CGI "showlog.cgi"
#define NOTIFICATIONS_CGI "notifications.cgi"
#define HISTORY_CGI "history.cgi"
#define CONFIG_CGI "config.cgi"
#define OUTAGES_CGI "outages.cgi"
#define TRENDS_CGI "trends.cgi"
#define AVAIL_CGI "avail.cgi"
#define TAC_CGI "tac.cgi"
#define STATUSWML_CGI "statuswml.cgi"
#define TRACEROUTE_CGI "traceroute.cgi"
#define HISTOGRAM_CGI "histogram.cgi"
#define CHECKSANITY_CGI "checksanity.cgi"
#define MINISTATUS_CGI "ministatus.cgi"
#define SUMMARY_CGI "summary.cgi"
/**************************** STYLE SHEET NAMES ******************************/
#define COMMON_CSS "common.css"
#define SHOWLOG_CSS "showlog.css"
#define STATUS_CSS "status.css"
#define STATUSMAP_CSS "statusmap.css"
#define COMMAND_CSS "cmd.css"
#define EXTINFO_CSS "extinfo.css"
#define NOTIFICATIONS_CSS "notifications.css"
#define HISTORY_CSS "history.css"
#define CONFIG_CSS "config.css"
#define OUTAGES_CSS "outages.css"
#define TRENDS_CSS "trends.css"
#define AVAIL_CSS "avail.css"
#define TAC_CSS "tac.css"
#define HISTOGRAM_CSS "histogram.css"
#define CHECKSANITY_CSS "checksanity.css"
#define MINISTATUS_CSS "ministatus.css"
#define SUMMARY_CSS "summary.css"
/********************************* JAVASCRIPT INCLUDES **********************/
#define JQUERY_JS "jquery-1.7.1.min.js"
/********************************* ICONS ************************************/
#define STATUS_ICON_WIDTH 20
#define STATUS_ICON_HEIGHT 20
#define INFO_ICON "info.png"
#define INFO_ICON_ALT "Informational Message"
#define START_ICON "start.gif"
#define START_ICON_ALT "Program Start"
#define STOP_ICON "stop.gif"
#define STOP_ICON_ALT "Program End"
#define RESTART_ICON "restart.gif"
#define RESTART_ICON_ALT "Program Restart"
#define OK_ICON "recovery.png"
#define OK_ICON_ALT "Service Ok"
#define CRITICAL_ICON "critical.png"
#define CRITICAL_ICON_ALT "Service Critical"
#define WARNING_ICON "warning.png"
#define WARNING_ICON_ALT "Service Warning"
#define UNKNOWN_ICON "unknown.png"
#define UNKNOWN_ICON_ALT "Service Unknown"
#define NOTIFICATION_ICON "notify.gif"
#define NOTIFICATION_ICON_ALT "Service Notification"
#define LOG_ROTATION_ICON "logrotate.png"
#define LOG_ROTATION_ICON_ALT "Log Rotation"
#define EXTERNAL_COMMAND_ICON "command.png"
#define EXTERNAL_COMMAND_ICON_ALT "External Command"
#define STATUS_DETAIL_ICON "status2.gif"
#define STATUS_OVERVIEW_ICON "status.gif"
#define STATUSMAP_ICON "status3.gif"
#define STATUSWORLD_ICON "status4.gif"
#define EXTINFO_ICON "extinfo.gif"
#define HISTORY_ICON "history.gif"
#define CONTACTGROUP_ICON "contactgroup.gif"
#define TRENDS_ICON "trends.gif"
#define DISABLED_ICON "disabled.gif"
#define ENABLED_ICON "enabled.gif"
#define PASSIVE_ONLY_ICON "passiveonly.gif"
#define NOTIFICATIONS_DISABLED_ICON "ndisabled.gif"
#define ACKNOWLEDGEMENT_ICON "ack.gif"
#define REMOVE_ACKNOWLEDGEMENT_ICON "noack.gif"
#define COMMENT_ICON "comment.gif"
#define DELETE_ICON "delete.gif"
#define DELAY_ICON "delay.gif"
#define DOWNTIME_ICON "downtime.gif"
#define PASSIVE_ICON "passiveonly.gif"
#define RIGHT_ARROW_ICON "right.gif"
#define LEFT_ARROW_ICON "left.gif"
#define UP_ARROW_ICON "up.gif"
#define DOWN_ARROW_ICON "down.gif"
#define FLAPPING_ICON "flapping.gif"
#define SCHEDULED_DOWNTIME_ICON "downtime.gif"
#define EMPTY_ICON "empty.gif"
#define ACTIVE_ICON "active.gif"
#define ACTIVE_ICON_ALT "Active Mode"
#define STANDBY_ICON "standby.gif"
#define STANDBY_ICON_ALT "Standby Mode"
#define HOST_DOWN_ICON "critical.png"
#define HOST_DOWN_ICON_ALT "Host Down"
#define HOST_UNREACHABLE_ICON "critical.png"
#define HOST_UNREACHABLE_ICON_ALT "Host Unreachable"
#define HOST_UP_ICON "recovery.png"
#define HOST_UP_ICON_ALT "Host Up"
#define HOST_NOTIFICATION_ICON "notify.gif"
#define HOST_NOTIFICATION_ICON_ALT "Host Notification"
#define SERVICE_EVENT_ICON "serviceevent.gif"
#define SERVICE_EVENT_ICON_ALT "Service Event Handler"
#define HOST_EVENT_ICON "hostevent.gif"
#define HOST_EVENT_ICON_ALT "Host Event Handler"
#define THERM_OK_IMAGE "thermok.png"
#define THERM_WARNING_IMAGE "thermwarn.png"
#define THERM_CRITICAL_IMAGE "thermcrit.png"
#define CONFIGURATION_ICON "config.gif"
#define NOTES_ICON "notes.gif"
#define ACTION_ICON "action.gif"
#define DETAIL_ICON "detail.gif"
#define PARENT_TRAVERSAL_ICON "parentup.gif"
#define TAC_DISABLED_ICON "tacdisabled.png"
#define TAC_ENABLED_ICON "tacenabled.png"
#define ZOOM1_ICON "zoom1.gif"
#define ZOOM2_ICON "zoom2.gif"
#define CONTEXT_HELP_ICON1 "contexthelp1.gif"
#define CONTEXT_HELP_ICON2 "contexthelp2.gif"
#define SPLUNK_SMALL_WHITE_ICON "splunk1.gif"
#define SPLUNK_SMALL_BLACK_ICON "splunk2.gif"
#define FIRST_PAGE_ICON "b_first2.png"
#define LAST_PAGE_ICON "b_last2.png"
#define NEXT_PAGE_ICON "b_next2.png"
#define PREVIOUS_PAGE_ICON "b_prev2.png"
/********************* EXTENDED INFO CGI DISPLAY TYPES *********************/
#define DISPLAY_PROCESS_INFO 0
#define DISPLAY_HOST_INFO 1
#define DISPLAY_SERVICE_INFO 2
#define DISPLAY_COMMENTS 3
#define DISPLAY_PERFORMANCE 4
#define DISPLAY_HOSTGROUP_INFO 5
#define DISPLAY_DOWNTIME 6
#define DISPLAY_SCHEDULING_QUEUE 7
#define DISPLAY_SERVICEGROUP_INFO 8
/************************ COMMAND CGI COMMAND MODES *************************/
#define CMDMODE_NONE 0
#define CMDMODE_REQUEST 1
#define CMDMODE_COMMIT 2
/******************** HOST AND SERVICE NOTIFICATION TYPES ******************/
#define NOTIFICATION_ALL 0 /* all service and host notifications */
#define NOTIFICATION_SERVICE_ALL 1 /* all types of service notifications */
#define NOTIFICATION_HOST_ALL 2 /* all types of host notifications */
#define NOTIFICATION_SERVICE_WARNING 4
#define NOTIFICATION_SERVICE_UNKNOWN 8
#define NOTIFICATION_SERVICE_CRITICAL 16
#define NOTIFICATION_SERVICE_RECOVERY 32
#define NOTIFICATION_HOST_DOWN 64
#define NOTIFICATION_HOST_UNREACHABLE 128
#define NOTIFICATION_HOST_RECOVERY 256
#define NOTIFICATION_SERVICE_ACK 512
#define NOTIFICATION_HOST_ACK 1024
#define NOTIFICATION_SERVICE_FLAP 2048
#define NOTIFICATION_HOST_FLAP 4096
#define NOTIFICATION_SERVICE_CUSTOM 8192
#define NOTIFICATION_HOST_CUSTOM 16384
/********************** HOST AND SERVICE ALERT TYPES **********************/
#define HISTORY_ALL 0 /* all service and host alert */
#define HISTORY_SERVICE_ALL 1 /* all types of service alerts */
#define HISTORY_HOST_ALL 2 /* all types of host alerts */
#define HISTORY_SERVICE_WARNING 4
#define HISTORY_SERVICE_UNKNOWN 8
#define HISTORY_SERVICE_CRITICAL 16
#define HISTORY_SERVICE_RECOVERY 32
#define HISTORY_HOST_DOWN 64
#define HISTORY_HOST_UNREACHABLE 128
#define HISTORY_HOST_RECOVERY 256
/****************************** SORT TYPES *******************************/
#define SORT_NONE 0
#define SORT_ASCENDING 1
#define SORT_DESCENDING 2
/***************************** SORT OPTIONS ******************************/
#define SORT_NOTHING 0
#define SORT_HOSTNAME 1
#define SORT_SERVICENAME 2
#define SORT_SERVICESTATUS 3
#define SORT_LASTCHECKTIME 4
#define SORT_CURRENTATTEMPT 5
#define SORT_STATEDURATION 6
#define SORT_NEXTCHECKTIME 7
#define SORT_HOSTSTATUS 8
#define SORT_HOSTURGENCY 9
/****************** HOST AND SERVICE FILTER PROPERTIES *******************/
#define HOST_SCHEDULED_DOWNTIME 1
#define HOST_NO_SCHEDULED_DOWNTIME 2
#define HOST_STATE_ACKNOWLEDGED 4
#define HOST_STATE_UNACKNOWLEDGED 8
#define HOST_CHECKS_DISABLED 16
#define HOST_CHECKS_ENABLED 32
#define HOST_EVENT_HANDLER_DISABLED 64
#define HOST_EVENT_HANDLER_ENABLED 128
#define HOST_FLAP_DETECTION_DISABLED 256
#define HOST_FLAP_DETECTION_ENABLED 512
#define HOST_IS_FLAPPING 1024
#define HOST_IS_NOT_FLAPPING 2048
#define HOST_NOTIFICATIONS_DISABLED 4096
#define HOST_NOTIFICATIONS_ENABLED 8192
#define HOST_PASSIVE_CHECKS_DISABLED 16384
#define HOST_PASSIVE_CHECKS_ENABLED 32768
#define HOST_PASSIVE_CHECK 65536
#define HOST_ACTIVE_CHECK 131072
#define HOST_HARD_STATE 262144
#define HOST_SOFT_STATE 524288
#define SERVICE_SCHEDULED_DOWNTIME 1
#define SERVICE_NO_SCHEDULED_DOWNTIME 2
#define SERVICE_STATE_ACKNOWLEDGED 4
#define SERVICE_STATE_UNACKNOWLEDGED 8
#define SERVICE_CHECKS_DISABLED 16
#define SERVICE_CHECKS_ENABLED 32
#define SERVICE_EVENT_HANDLER_DISABLED 64
#define SERVICE_EVENT_HANDLER_ENABLED 128
#define SERVICE_FLAP_DETECTION_ENABLED 256
#define SERVICE_FLAP_DETECTION_DISABLED 512
#define SERVICE_IS_FLAPPING 1024
#define SERVICE_IS_NOT_FLAPPING 2048
#define SERVICE_NOTIFICATIONS_DISABLED 4096
#define SERVICE_NOTIFICATIONS_ENABLED 8192
#define SERVICE_PASSIVE_CHECKS_DISABLED 16384
#define SERVICE_PASSIVE_CHECKS_ENABLED 32768
#define SERVICE_PASSIVE_CHECK 65536
#define SERVICE_ACTIVE_CHECK 131072
#define SERVICE_HARD_STATE 262144
#define SERVICE_SOFT_STATE 524288
/****************************** SSI TYPES ********************************/
#define SSI_HEADER 0
#define SSI_FOOTER 1
/************************ CONTEXT-SENSITIVE HELP *************************/
#define CONTEXTHELP_STATUS_DETAIL "A1"
#define CONTEXTHELP_STATUS_HGOVERVIEW "A2"
#define CONTEXTHELP_STATUS_HGSUMMARY "A3"
#define CONTEXTHELP_STATUS_HGGRID "A4"
#define CONTEXTHELP_STATUS_SVCPROBLEMS "A5"
#define CONTEXTHELP_STATUS_HOST_DETAIL "A6"
#define CONTEXTHELP_STATUS_HOSTPROBLEMS "A7"
#define CONTEXTHELP_STATUS_SGOVERVIEW "A8"
#define CONTEXTHELP_STATUS_SGSUMMARY "A9"
#define CONTEXTHELP_STATUS_SGGRID "A10"
#define CONTEXTHELP_TAC "B1"
#define CONTEXTHELP_MAP "C1"
#define CONTEXTHELP_LOG "D1"
#define CONTEXTHELP_HISTORY "E1"
#define CONTEXTHELP_NOTIFICATIONS "F1"
#define CONTEXTHELP_TRENDS_MENU1 "G1"
#define CONTEXTHELP_TRENDS_MENU2 "G2"
#define CONTEXTHELP_TRENDS_MENU3 "G3"
#define CONTEXTHELP_TRENDS_MENU4 "G4"
#define CONTEXTHELP_TRENDS_HOST "G5"
#define CONTEXTHELP_TRENDS_SERVICE "G6"
#define CONTEXTHELP_AVAIL_MENU1 "H1"
#define CONTEXTHELP_AVAIL_MENU2 "H2"
#define CONTEXTHELP_AVAIL_MENU3 "H3"
#define CONTEXTHELP_AVAIL_MENU4 "H4"
#define CONTEXTHELP_AVAIL_MENU5 "H5"
#define CONTEXTHELP_AVAIL_HOSTGROUP "H6"
#define CONTEXTHELP_AVAIL_HOST "H7"
#define CONTEXTHELP_AVAIL_SERVICE "H8"
#define CONTEXTHELP_AVAIL_SERVICEGROUP "H9"
#define CONTEXTHELP_EXT_HOST "I1"
#define CONTEXTHELP_EXT_SERVICE "I2"
#define CONTEXTHELP_EXT_HOSTGROUP "I3"
#define CONTEXTHELP_EXT_PROCESS "I4"
#define CONTEXTHELP_EXT_PERFORMANCE "I5"
#define CONTEXTHELP_EXT_COMMENTS "I6"
#define CONTEXTHELP_EXT_DOWNTIME "I7"
#define CONTEXTHELP_EXT_QUEUE "I8"
#define CONTEXTHELP_EXT_SERVICEGROUP "I9"
#define CONTEXTHELP_CMD_INPUT "J1"
#define CONTEXTHELP_CMD_COMMIT "J2"
#define CONTEXTHELP_OUTAGES "K1"
#define CONTEXTHELP_CONFIG_MENU "L1"
#define CONTEXTHELP_CONFIG_HOSTS "L2"
#define CONTEXTHELP_CONFIG_HOSTDEPENDENCIES "L3"
#define CONTEXTHELP_CONFIG_HOSTESCALATIONS "L4"
#define CONTEXTHELP_CONFIG_HOSTGROUPS "L5"
#define CONTEXTHELP_CONFIG_HOSTGROUPESCALATIONS "L6"
#define CONTEXTHELP_CONFIG_SERVICES "L7"
#define CONTEXTHELP_CONFIG_SERVICEDEPENDENCIES "L8"
#define CONTEXTHELP_CONFIG_SERVICEESCALATIONS "L9"
#define CONTEXTHELP_CONFIG_CONTACTS "L10"
#define CONTEXTHELP_CONFIG_CONTACTGROUPS "L11"
#define CONTEXTHELP_CONFIG_TIMEPERIODS "L12"
#define CONTEXTHELP_CONFIG_COMMANDS "L13"
#define CONTEXTHELP_CONFIG_HOSTEXTINFO "L14"
#define CONTEXTHELP_CONFIG_SERVICEEXTINFO "L15"
#define CONTEXTHELP_CONFIG_SERVICEGROUPS "L16"
#define CONTEXTHELP_HISTOGRAM_MENU1 "M1"
#define CONTEXTHELP_HISTOGRAM_MENU2 "M2"
#define CONTEXTHELP_HISTOGRAM_MENU3 "M3"
#define CONTEXTHELP_HISTOGRAM_MENU4 "M4"
#define CONTEXTHELP_HISTOGRAM_HOST "M5"
#define CONTEXTHELP_HISTOGRAM_SERVICE "M6"
#define CONTEXTHELP_SUMMARY_MENU "N1"
#define CONTEXTHELP_SUMMARY_RECENT_ALERTS "N2"
#define CONTEXTHELP_SUMMARY_ALERT_TOTALS "N3"
#define CONTEXTHELP_SUMMARY_HOSTGROUP_ALERT_TOTALS "N4"
#define CONTEXTHELP_SUMMARY_HOST_ALERT_TOTALS "N5"
#define CONTEXTHELP_SUMMARY_SERVICE_ALERT_TOTALS "N6"
#define CONTEXTHELP_SUMMARY_ALERT_PRODUCERS "N7"
#define CONTEXTHELP_SUMMARY_SERVICEGROUP_ALERT_TOTALS "N8"
/************************** LIFO RETURN CODES ****************************/
#define LIFO_OK 0
#define LIFO_ERROR_MEMORY 1
#define LIFO_ERROR_FILE 2
#define LIFO_ERROR_DATA 3
/*************************** DATA STRUCTURES *****************************/
/* LIFO data structure */
typedef struct lifo_struct {
char *data;
struct lifo_struct *next;
} lifo;
/******************************** FUNCTIONS *******************************/
void reset_cgi_vars(void);
void cgi_init(void (*doc_header)(int), void (*doc_footer)(void), int object_options, int status_options);
void free_memory(void);
const char *get_cgi_config_location(void); /* gets location of the CGI config file to read */
const char *get_cmd_file_location(void); /* gets location of external command file to write to */
int read_cgi_config_file(const char *);
int read_main_config_file(const char *);
int read_all_object_configuration_data(const char *, int);
int read_all_status_data(const char *, int);
char *unescape_newlines(char *);
void sanitize_plugin_output(char *); /* strips HTML and bad characters from plugin output */
void strip_html_brackets(char *); /* strips > and < from string */
void get_time_string(time_t *, char *, int, int); /* gets a date/time string */
void get_interval_time_string(double, char *, int); /* gets a time string for an interval of time */
const char *url_encode(const char *); /* encodes a string in proper URL format */
char *html_encode(char *, int); /* encodes a string in HTML format (for what the user sees) */
char *escape_string(const char *); /* escape string for html form usage */
void get_log_archive_to_use(int, char *, int); /* determines the name of the log archive to use */
void determine_log_rotation_times(int);
int determine_archive_to_use_from_time(time_t);
void print_extra_hostgroup_url(char *, char *);
void print_extra_servicegroup_url(char *, char *);
void display_info_table(const char *, int, authdata *);
void display_nav_table(char *, int);
void display_splunk_host_url(host *);
void display_splunk_service_url(service *);
void display_splunk_generic_url(char *, int);
void strip_splunk_query_terms(char *);
void include_ssi_files(const char *, int); /* include user-defined SSI footers/headers */
void include_ssi_file(const char *); /* include user-defined SSI footer/header */
void cgi_config_file_error(const char *);
void main_config_file_error(const char *);
void object_data_error(void);
void status_data_error(void);
void display_context_help(const char *); /* displays context-sensitive help window */
int read_file_into_lifo(char *); /* LIFO functions */
void free_lifo_memory(void);
int push_lifo(char *);
char *pop_lifo(void);
NAGIOS_END_DECL
#endif

118
nagios4/comments.h Normal file
View File

@@ -0,0 +1,118 @@
/*****************************************************************************
*
* COMMENTS.H - Header file for comment functions
*
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _COMMENTS_H
#define _COMMENTS_H
#include "common.h"
#include "objects.h"
/**************************** COMMENT SOURCES ******************************/
#define COMMENTSOURCE_INTERNAL 0
#define COMMENTSOURCE_EXTERNAL 1
/***************************** COMMENT TYPES *******************************/
#define HOST_COMMENT 1
#define SERVICE_COMMENT 2
/****************************** ENTRY TYPES ********************************/
#define USER_COMMENT 1
#define DOWNTIME_COMMENT 2
#define FLAPPING_COMMENT 3
#define ACKNOWLEDGEMENT_COMMENT 4
/*************************** CHAINED HASH LIMITS ***************************/
#define COMMENT_HASHSLOTS 1024
/**************************** DATA STRUCTURES ******************************/
NAGIOS_BEGIN_DECL
/* COMMENT structure */
typedef struct comment {
int comment_type;
int entry_type;
unsigned long comment_id;
int source;
int persistent;
time_t entry_time;
int expires;
time_t expire_time;
char *host_name;
char *service_description;
char *author;
char *comment_data;
struct comment *next;
struct comment *nexthash;
} comment;
extern struct comment *comment_list;
#ifndef NSCGI
int initialize_comment_data(void); /* initializes comment data */
int add_new_comment(int, int, char *, char *, time_t, char *, char *, int, int, int, time_t, unsigned long *); /* adds a new host or service comment */
int add_new_host_comment(int, char *, time_t, char *, char *, int, int, int, time_t, unsigned long *); /* adds a new host comment */
int add_new_service_comment(int, char *, char *, time_t, char *, char *, int, int, int, time_t, unsigned long *); /* adds a new service comment */
int delete_comment(int, unsigned long); /* deletes a host or service comment */
int delete_host_comment(unsigned long); /* deletes a host comment */
int delete_service_comment(unsigned long); /* deletes a service comment */
int delete_all_comments(int, char *, char *); /* deletes all comments for a particular host or service */
int delete_all_host_comments(char *); /* deletes all comments for a specific host */
int delete_host_acknowledgement_comments(struct host *); /* deletes all non-persistent ack comments for a specific host */
int delete_all_service_comments(char *, char *); /* deletes all comments for a specific service */
int delete_service_acknowledgement_comments(struct service *); /* deletes all non-persistent ack comments for a specific service */
int check_for_expired_comment(unsigned long); /* expires a comment */
#endif
struct comment *find_comment(unsigned long, int); /* finds a specific comment */
struct comment *find_service_comment(unsigned long); /* finds a specific service comment */
struct comment *find_host_comment(unsigned long); /* finds a specific host comment */
struct comment *get_first_comment_by_host(char *);
struct comment *get_next_comment_by_host(char *, struct comment *);
int number_of_host_comments(char *); /* returns the number of comments associated with a particular host */
int number_of_service_comments(char *, char *); /* returns the number of comments associated with a particular service */
int add_comment(int, int, char *, char *, time_t, char *, char *, unsigned long, int, int, time_t, int); /* adds a comment (host or service) */
int sort_comments(void);
int add_host_comment(int, char *, time_t, char *, char *, unsigned long, int, int, time_t, int); /* adds a host comment */
int add_service_comment(int, char *, char *, time_t, char *, char *, unsigned long, int, int, time_t, int); /* adds a service comment */
int add_comment_to_hashlist(struct comment *);
void free_comment_data(void); /* frees memory allocated to the comment list */
NAGIOS_BEGIN_DECL
#endif

531
nagios4/common.h Normal file
View File

@@ -0,0 +1,531 @@
/************************************************************************
*
* Nagios Common Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
#ifndef INCLUDE_COMMON_H
#define INCLUDE_COMMON_H
#include "shared.h"
#define PROGRAM_VERSION "4.0.2"
#define PROGRAM_MODIFICATION_DATE "11-25-2013"
NAGIOS_BEGIN_DECL
/*************************************************************/
/************** SHARED GLOBAL VARIABLES **********************/
/*************************************************************/
extern int date_format;
extern int interval_length;
extern char *illegal_output_chars;
extern char illegal_output_char_map[256];
extern int log_rotation_method;
extern int check_external_commands;
/* set this if you're going to add a ton of comments at once */
extern int defer_comment_sorting;
extern unsigned long next_downtime_id;
extern char *object_cache_file;
extern char *status_file;
extern time_t program_start;
extern int nagios_pid;
extern int daemon_mode;
extern time_t last_log_rotation;
extern int process_performance_data;
extern int enable_flap_detection;
extern int enable_notifications;
extern int execute_service_checks;
extern int accept_passive_service_checks;
extern int execute_host_checks;
extern int accept_passive_host_checks;
extern int enable_event_handlers;
extern int obsess_over_services;
extern int obsess_over_hosts;
extern int enable_timing_point;
extern char *config_file_dir;
#ifdef HAVE_TZNAME
#ifdef CYGWIN
extern char *_tzname[2] __declspec(dllimport);
#else
extern char *tzname[2];
#endif
#endif
NAGIOS_END_DECL
/* Experimental performance tweaks - use with caution */
#undef USE_MEMORY_PERFORMANCE_TWEAKS
/****************** OBJECT STATES ********************/
#define STATE_OK 0
#define STATE_WARNING 1
#define STATE_CRITICAL 2
#define STATE_UNKNOWN 3
#define STATE_UP 0
#define STATE_DOWN 1
#define STATE_UNREACHABLE 2
/* for legacy reasons */
#define HOST_UP STATE_UP
#define HOST_DOWN STATE_DOWN
#define HOST_UNREACHABLE STATE_UNREACHABLE
/***************************** COMMANDS *********************************/
#define CMD_NONE 0
#define CMD_ADD_HOST_COMMENT 1
#define CMD_DEL_HOST_COMMENT 2
#define CMD_ADD_SVC_COMMENT 3
#define CMD_DEL_SVC_COMMENT 4
#define CMD_ENABLE_SVC_CHECK 5
#define CMD_DISABLE_SVC_CHECK 6
#define CMD_SCHEDULE_SVC_CHECK 7
#define CMD_DELAY_SVC_NOTIFICATION 9
#define CMD_DELAY_HOST_NOTIFICATION 10
#define CMD_DISABLE_NOTIFICATIONS 11
#define CMD_ENABLE_NOTIFICATIONS 12
#define CMD_RESTART_PROCESS 13
#define CMD_SHUTDOWN_PROCESS 14
#define CMD_ENABLE_HOST_SVC_CHECKS 15
#define CMD_DISABLE_HOST_SVC_CHECKS 16
#define CMD_SCHEDULE_HOST_SVC_CHECKS 17
#define CMD_DELAY_HOST_SVC_NOTIFICATIONS 19 /* currently unimplemented */
#define CMD_DEL_ALL_HOST_COMMENTS 20
#define CMD_DEL_ALL_SVC_COMMENTS 21
#define CMD_ENABLE_SVC_NOTIFICATIONS 22
#define CMD_DISABLE_SVC_NOTIFICATIONS 23
#define CMD_ENABLE_HOST_NOTIFICATIONS 24
#define CMD_DISABLE_HOST_NOTIFICATIONS 25
#define CMD_ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST 26
#define CMD_DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST 27
#define CMD_ENABLE_HOST_SVC_NOTIFICATIONS 28
#define CMD_DISABLE_HOST_SVC_NOTIFICATIONS 29
#define CMD_PROCESS_SERVICE_CHECK_RESULT 30
#define CMD_SAVE_STATE_INFORMATION 31
#define CMD_READ_STATE_INFORMATION 32
#define CMD_ACKNOWLEDGE_HOST_PROBLEM 33
#define CMD_ACKNOWLEDGE_SVC_PROBLEM 34
#define CMD_START_EXECUTING_SVC_CHECKS 35
#define CMD_STOP_EXECUTING_SVC_CHECKS 36
#define CMD_START_ACCEPTING_PASSIVE_SVC_CHECKS 37
#define CMD_STOP_ACCEPTING_PASSIVE_SVC_CHECKS 38
#define CMD_ENABLE_PASSIVE_SVC_CHECKS 39
#define CMD_DISABLE_PASSIVE_SVC_CHECKS 40
#define CMD_ENABLE_EVENT_HANDLERS 41
#define CMD_DISABLE_EVENT_HANDLERS 42
#define CMD_ENABLE_HOST_EVENT_HANDLER 43
#define CMD_DISABLE_HOST_EVENT_HANDLER 44
#define CMD_ENABLE_SVC_EVENT_HANDLER 45
#define CMD_DISABLE_SVC_EVENT_HANDLER 46
#define CMD_ENABLE_HOST_CHECK 47
#define CMD_DISABLE_HOST_CHECK 48
#define CMD_START_OBSESSING_OVER_SVC_CHECKS 49
#define CMD_STOP_OBSESSING_OVER_SVC_CHECKS 50
#define CMD_REMOVE_HOST_ACKNOWLEDGEMENT 51
#define CMD_REMOVE_SVC_ACKNOWLEDGEMENT 52
#define CMD_SCHEDULE_FORCED_HOST_SVC_CHECKS 53
#define CMD_SCHEDULE_FORCED_SVC_CHECK 54
#define CMD_SCHEDULE_HOST_DOWNTIME 55
#define CMD_SCHEDULE_SVC_DOWNTIME 56
#define CMD_ENABLE_HOST_FLAP_DETECTION 57
#define CMD_DISABLE_HOST_FLAP_DETECTION 58
#define CMD_ENABLE_SVC_FLAP_DETECTION 59
#define CMD_DISABLE_SVC_FLAP_DETECTION 60
#define CMD_ENABLE_FLAP_DETECTION 61
#define CMD_DISABLE_FLAP_DETECTION 62
#define CMD_ENABLE_HOSTGROUP_SVC_NOTIFICATIONS 63
#define CMD_DISABLE_HOSTGROUP_SVC_NOTIFICATIONS 64
#define CMD_ENABLE_HOSTGROUP_HOST_NOTIFICATIONS 65
#define CMD_DISABLE_HOSTGROUP_HOST_NOTIFICATIONS 66
#define CMD_ENABLE_HOSTGROUP_SVC_CHECKS 67
#define CMD_DISABLE_HOSTGROUP_SVC_CHECKS 68
/* commands 69-77 are unimplemented */
#define CMD_UNIMPLEMENTED_69 69
#define CMD_UNIMPLEMENTED_70 70
#define CMD_UNIMPLEMENTED_71 71
#define CMD_UNIMPLEMENTED_72 72
#define CMD_UNIMPLEMENTED_73 73
#define CMD_UNIMPLEMENTED_74 74
#define CMD_UNIMPLEMENTED_75 75
#define CMD_UNIMPLEMENTED_76 76
#define CMD_UNIMPLEMENTED_77 77
#define CMD_DEL_HOST_DOWNTIME 78
#define CMD_DEL_SVC_DOWNTIME 79
#define CMD_ENABLE_PERFORMANCE_DATA 82
#define CMD_DISABLE_PERFORMANCE_DATA 83
#define CMD_SCHEDULE_HOSTGROUP_HOST_DOWNTIME 84
#define CMD_SCHEDULE_HOSTGROUP_SVC_DOWNTIME 85
#define CMD_SCHEDULE_HOST_SVC_DOWNTIME 86
/* new commands in Nagios 2.x found below... */
#define CMD_PROCESS_HOST_CHECK_RESULT 87
#define CMD_START_EXECUTING_HOST_CHECKS 88
#define CMD_STOP_EXECUTING_HOST_CHECKS 89
#define CMD_START_ACCEPTING_PASSIVE_HOST_CHECKS 90
#define CMD_STOP_ACCEPTING_PASSIVE_HOST_CHECKS 91
#define CMD_ENABLE_PASSIVE_HOST_CHECKS 92
#define CMD_DISABLE_PASSIVE_HOST_CHECKS 93
#define CMD_START_OBSESSING_OVER_HOST_CHECKS 94
#define CMD_STOP_OBSESSING_OVER_HOST_CHECKS 95
#define CMD_SCHEDULE_HOST_CHECK 96
#define CMD_SCHEDULE_FORCED_HOST_CHECK 98
#define CMD_START_OBSESSING_OVER_SVC 99
#define CMD_STOP_OBSESSING_OVER_SVC 100
#define CMD_START_OBSESSING_OVER_HOST 101
#define CMD_STOP_OBSESSING_OVER_HOST 102
#define CMD_ENABLE_HOSTGROUP_HOST_CHECKS 103
#define CMD_DISABLE_HOSTGROUP_HOST_CHECKS 104
#define CMD_ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS 105
#define CMD_DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS 106
#define CMD_ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS 107
#define CMD_DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS 108
#define CMD_ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS 109
#define CMD_DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS 110
#define CMD_ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS 111
#define CMD_DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS 112
#define CMD_ENABLE_SERVICEGROUP_SVC_CHECKS 113
#define CMD_DISABLE_SERVICEGROUP_SVC_CHECKS 114
#define CMD_ENABLE_SERVICEGROUP_HOST_CHECKS 115
#define CMD_DISABLE_SERVICEGROUP_HOST_CHECKS 116
#define CMD_ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS 117
#define CMD_DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS 118
#define CMD_ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS 119
#define CMD_DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS 120
#define CMD_SCHEDULE_SERVICEGROUP_HOST_DOWNTIME 121
#define CMD_SCHEDULE_SERVICEGROUP_SVC_DOWNTIME 122
#define CMD_CHANGE_GLOBAL_HOST_EVENT_HANDLER 123
#define CMD_CHANGE_GLOBAL_SVC_EVENT_HANDLER 124
#define CMD_CHANGE_HOST_EVENT_HANDLER 125
#define CMD_CHANGE_SVC_EVENT_HANDLER 126
#define CMD_CHANGE_HOST_CHECK_COMMAND 127
#define CMD_CHANGE_SVC_CHECK_COMMAND 128
#define CMD_CHANGE_NORMAL_HOST_CHECK_INTERVAL 129
#define CMD_CHANGE_NORMAL_SVC_CHECK_INTERVAL 130
#define CMD_CHANGE_RETRY_SVC_CHECK_INTERVAL 131
#define CMD_CHANGE_MAX_HOST_CHECK_ATTEMPTS 132
#define CMD_CHANGE_MAX_SVC_CHECK_ATTEMPTS 133
#define CMD_SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME 134
#define CMD_ENABLE_HOST_AND_CHILD_NOTIFICATIONS 135
#define CMD_DISABLE_HOST_AND_CHILD_NOTIFICATIONS 136
#define CMD_SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME 137
#define CMD_ENABLE_SERVICE_FRESHNESS_CHECKS 138
#define CMD_DISABLE_SERVICE_FRESHNESS_CHECKS 139
#define CMD_ENABLE_HOST_FRESHNESS_CHECKS 140
#define CMD_DISABLE_HOST_FRESHNESS_CHECKS 141
#define CMD_SET_HOST_NOTIFICATION_NUMBER 142
#define CMD_SET_SVC_NOTIFICATION_NUMBER 143
/* new commands in Nagios 3.x found below... */
#define CMD_CHANGE_HOST_CHECK_TIMEPERIOD 144
#define CMD_CHANGE_SVC_CHECK_TIMEPERIOD 145
#define CMD_PROCESS_FILE 146
#define CMD_CHANGE_CUSTOM_HOST_VAR 147
#define CMD_CHANGE_CUSTOM_SVC_VAR 148
#define CMD_CHANGE_CUSTOM_CONTACT_VAR 149
#define CMD_ENABLE_CONTACT_HOST_NOTIFICATIONS 150
#define CMD_DISABLE_CONTACT_HOST_NOTIFICATIONS 151
#define CMD_ENABLE_CONTACT_SVC_NOTIFICATIONS 152
#define CMD_DISABLE_CONTACT_SVC_NOTIFICATIONS 153
#define CMD_ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS 154
#define CMD_DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS 155
#define CMD_ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS 156
#define CMD_DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS 157
#define CMD_CHANGE_RETRY_HOST_CHECK_INTERVAL 158
#define CMD_SEND_CUSTOM_HOST_NOTIFICATION 159
#define CMD_SEND_CUSTOM_SVC_NOTIFICATION 160
#define CMD_CHANGE_HOST_NOTIFICATION_TIMEPERIOD 161
#define CMD_CHANGE_SVC_NOTIFICATION_TIMEPERIOD 162
#define CMD_CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD 163
#define CMD_CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD 164
#define CMD_CHANGE_HOST_MODATTR 165
#define CMD_CHANGE_SVC_MODATTR 166
#define CMD_CHANGE_CONTACT_MODATTR 167
#define CMD_CHANGE_CONTACT_MODHATTR 168
#define CMD_CHANGE_CONTACT_MODSATTR 169
#define CMD_DEL_DOWNTIME_BY_HOST_NAME 170
#define CMD_DEL_DOWNTIME_BY_HOSTGROUP_NAME 171
#define CMD_DEL_DOWNTIME_BY_START_TIME_COMMENT 172
/* custom command introduced in Nagios 3.x */
#define CMD_CUSTOM_COMMAND 999
/**************************** COMMAND ERRORS *****************************/
#define CMD_ERROR_OK 0 /* No errors encountered */
#define CMD_ERROR_UNKNOWN_COMMAND 1 /* Unknown/unsupported command */
#define CMD_ERROR_MALFORMED_COMMAND 2 /* Command malformed/missing timestamp? */
#define CMD_ERROR_INTERNAL_ERROR 3 /* Internal error */
#define CMD_ERROR_FAILURE 4 /* Command routine failed */
extern const char *cmd_error_strerror(int error_code);
/**************************** CHECK TYPES ********************************/
#define CHECK_TYPE_ACTIVE 0
#define CHECK_TYPE_PASSIVE 1
#define CHECK_TYPE_PARENT 2 /* (active) check for the benefit of dependent objects */
#define CHECK_TYPE_FILE 3 /* from spool files (yuck) */
#define CHECK_TYPE_OTHER 4 /* for modules to use */
/************* LEGACY (deprecated) CHECK TYPES ***************************/
#define SERVICE_CHECK_ACTIVE CHECK_TYPE_ACTIVE
#define SERVICE_CHECK_PASSIVE CHECK_TYPE_PASSIVE
#define HOST_CHECK_ACTIVE CHECK_TYPE_ACTIVE
#define HOST_CHECK_PASSIVE CHECK_TYPE_PASSIVE
/************************ SERVICE STATE TYPES ****************************/
#define SOFT_STATE 0
#define HARD_STATE 1
/************************* SCHEDULED DOWNTIME TYPES **********************/
#define SERVICE_DOWNTIME 1 /* service downtime */
#define HOST_DOWNTIME 2 /* host downtime */
#define ANY_DOWNTIME 3 /* host or service downtime */
/************************** NOTIFICATION OPTIONS *************************/
#define NOTIFICATION_OPTION_NONE 0
#define NOTIFICATION_OPTION_BROADCAST 1
#define NOTIFICATION_OPTION_FORCED 2
#define NOTIFICATION_OPTION_INCREMENT 4
/************************** ACKNOWLEDGEMENT TYPES ************************/
#define HOST_ACKNOWLEDGEMENT 0
#define SERVICE_ACKNOWLEDGEMENT 1
#define ACKNOWLEDGEMENT_NONE 0
#define ACKNOWLEDGEMENT_NORMAL 1
#define ACKNOWLEDGEMENT_STICKY 2
/**************************** DEPENDENCY TYPES ***************************/
#define NOTIFICATION_DEPENDENCY 1
#define EXECUTION_DEPENDENCY 2
/********************** HOST/SERVICE CHECK OPTIONS ***********************/
#define CHECK_OPTION_NONE 0 /* no check options */
#define CHECK_OPTION_FORCE_EXECUTION 1 /* force execution of a check (ignores disabled services/hosts, invalid timeperiods) */
#define CHECK_OPTION_FRESHNESS_CHECK 2 /* this is a freshness check */
#define CHECK_OPTION_ORPHAN_CHECK 4 /* this is an orphan check */
#define CHECK_OPTION_DEPENDENCY_CHECK 8 /* dependency check. different scheduling rules apply */
/**************************** PROGRAM MODES ******************************/
#define STANDBY_MODE 0
#define ACTIVE_MODE 1
/************************** LOG ROTATION MODES ***************************/
#define LOG_ROTATION_NONE 0
#define LOG_ROTATION_HOURLY 1
#define LOG_ROTATION_DAILY 2
#define LOG_ROTATION_WEEKLY 3
#define LOG_ROTATION_MONTHLY 4
/***************************** LOG VERSIONS ******************************/
#define LOG_VERSION_1 "1.0"
#define LOG_VERSION_2 "2.0"
/*************************** CHECK STATISTICS ****************************/
#define ACTIVE_SCHEDULED_SERVICE_CHECK_STATS 0
#define ACTIVE_ONDEMAND_SERVICE_CHECK_STATS 1
#define PASSIVE_SERVICE_CHECK_STATS 2
#define ACTIVE_SCHEDULED_HOST_CHECK_STATS 3
#define ACTIVE_ONDEMAND_HOST_CHECK_STATS 4
#define PASSIVE_HOST_CHECK_STATS 5
#define ACTIVE_CACHED_HOST_CHECK_STATS 6
#define ACTIVE_CACHED_SERVICE_CHECK_STATS 7
#define EXTERNAL_COMMAND_STATS 8
#define PARALLEL_HOST_CHECK_STATS 9
#define SERIAL_HOST_CHECK_STATS 10
#define MAX_CHECK_STATS_TYPES 11
/****************** HOST CONFIG FILE READING OPTIONS ********************/
#define READ_HOSTS 1
#define READ_HOSTGROUPS 2
#define READ_CONTACTS 4
#define READ_CONTACTGROUPS 8
#define READ_SERVICES 16
#define READ_COMMANDS 32
#define READ_TIMEPERIODS 64
#define READ_SERVICEESCALATIONS 128
#define READ_HOSTGROUPESCALATIONS 256 /* no longer implemented */
#define READ_SERVICEDEPENDENCIES 512
#define READ_HOSTDEPENDENCIES 1024
#define READ_HOSTESCALATIONS 2048
#define READ_HOSTEXTINFO 4096
#define READ_SERVICEEXTINFO 8192
#define READ_SERVICEGROUPS 16384
#define READ_ALL_OBJECT_DATA READ_HOSTS | READ_HOSTGROUPS | READ_CONTACTS | READ_CONTACTGROUPS | READ_SERVICES | READ_COMMANDS | READ_TIMEPERIODS | READ_SERVICEESCALATIONS | READ_SERVICEDEPENDENCIES | READ_HOSTDEPENDENCIES | READ_HOSTESCALATIONS | READ_HOSTEXTINFO | READ_SERVICEEXTINFO | READ_SERVICEGROUPS
/************************** DATE/TIME TYPES *****************************/
#define LONG_DATE_TIME 0
#define SHORT_DATE_TIME 1
#define SHORT_DATE 2
#define SHORT_TIME 3
#define HTTP_DATE_TIME 4 /* time formatted for use in HTTP headers */
/**************************** DATE FORMATS ******************************/
#define DATE_FORMAT_US 0 /* U.S. (MM-DD-YYYY HH:MM:SS) */
#define DATE_FORMAT_EURO 1 /* European (DD-MM-YYYY HH:MM:SS) */
#define DATE_FORMAT_ISO8601 2 /* ISO8601 (YYYY-MM-DD HH:MM:SS) */
#define DATE_FORMAT_STRICT_ISO8601 3 /* ISO8601 (YYYY-MM-DDTHH:MM:SS) */
/************************** MISC DEFINITIONS ****************************/
#define MAX_FILENAME_LENGTH 256 /* max length of path/filename that Nagios will process */
#define MAX_INPUT_BUFFER 1024 /* size in bytes of max. input buffer (for reading files, misc stuff) */
#define MAX_COMMAND_BUFFER 8192 /* max length of raw or processed command line */
#define MAX_EXTERNAL_COMMAND_LENGTH 8192 /* max length of an external command */
#define MAX_DATETIME_LENGTH 48
/************************* MODIFIED ATTRIBUTES **************************/
#define MODATTR_NONE 0
#define MODATTR_NOTIFICATIONS_ENABLED 1
#define MODATTR_ACTIVE_CHECKS_ENABLED 2
#define MODATTR_PASSIVE_CHECKS_ENABLED 4
#define MODATTR_EVENT_HANDLER_ENABLED 8
#define MODATTR_FLAP_DETECTION_ENABLED 16
#define MODATTR_FAILURE_PREDICTION_ENABLED 32
#define MODATTR_PERFORMANCE_DATA_ENABLED 64
#define MODATTR_OBSESSIVE_HANDLER_ENABLED 128
#define MODATTR_EVENT_HANDLER_COMMAND 256
#define MODATTR_CHECK_COMMAND 512
#define MODATTR_NORMAL_CHECK_INTERVAL 1024
#define MODATTR_RETRY_CHECK_INTERVAL 2048
#define MODATTR_MAX_CHECK_ATTEMPTS 4096
#define MODATTR_FRESHNESS_CHECKS_ENABLED 8192
#define MODATTR_CHECK_TIMEPERIOD 16384
#define MODATTR_CUSTOM_VARIABLE 32768
#define MODATTR_NOTIFICATION_TIMEPERIOD 65536
#endif /* INCLUDE_COMMON_H */

344
nagios4/config.h Normal file
View File

@@ -0,0 +1,344 @@
/* include/config.h. Generated from config.h.in by configure. */
/************************************************************************
*
* Nagios Config Header File
* Written By: Ethan Galstad (egalstad@nagios.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************/
/***** NAGIOS STUFF *****/
#define DEFAULT_NAGIOS_USER "nagios"
#define DEFAULT_NAGIOS_GROUP "nagios"
/* stop gcc from bitching about implicit asprintf declarations */
#define _GNU_SOURCE 1
/* Event broker integration */
#define USE_EVENT_BROKER /**/
/* commands used by CGIs */
#define TRACEROUTE_COMMAND "/usr/sbin/traceroute"
/* #undef PING_COMMAND */
/* #undef PING_PACKETS_FIRST */
/* Debugging options */
/* function entry and exit */
/* #undef DEBUG0 */
/* general info messages */
/* #undef DEBUG1 */
/* warning messages */
/* #undef DEBUG2 */
/* service and host checks, other events */
/* #undef DEBUG3 */
/* service and host notifications */
/* #undef DEBUG4 */
/* SQL queries (defunct) */
/* #undef DEBUG5 */
/* I/O implementations */
/* #undef USE_XSDDEFAULT */
/* #undef USE_XCDDEFAULT */
/* #undef USE_XRDDEFAULT */
/* #undef USE_XODTEMPLATE */
/* #undef USE_XPDDEFAULT */
/* #undef USE_XDDDEFAULT */
/***** CGI COMPILE OPTIONS *****/
/* should we compile and use the statusmap CGI? */
/* #undef USE_STATUSMAP */
/* should we compile and use the statuswrl CGI? */
#define USE_STATUSWRL /**/
/* should we compile and use the trends CGI? */
/* #undef USE_TRENDS */
/* should we compile and use the histogram CGI? */
/* #undef USE_HISTOGRAM */
/***** FUNCTION DEFINITIONS *****/
#define HAVE_SETENV 1
#define HAVE_UNSETENV 1
/* #undef HAVE_SOCKET */
#define HAVE_STRDUP 1
#define HAVE_STRSTR 1
#define HAVE_STRTOUL 1
#define HAVE_INITGROUPS 1
/* #undef HAVE_GETLOADAVG */
/* #undef HAVE_GDIMAGECREATETRUECOLOR */
/***** ASPRINTF() AND FRIENDS *****/
/* #undef HAVE_VSNPRINTF */
/* #undef HAVE_SNPRINTF */
/* #undef HAVE_ASPRINTF */
/* #undef HAVE_VASPRINTF */
#define HAVE_C99_VSNPRINTF 1
#define HAVE_VA_COPY 1
/* #undef HAVE___VA_COPY */
/***** MISC DEFINITIONS *****/
#define USE_NANOSLEEP /**/
#define STDC_HEADERS 1
#define HAVE_TM_ZONE 1
/* #undef HAVE_TZNAME */
/* #undef USE_PROC */
#define SOCKET_SIZE_TYPE size_t
#define GETGROUPS_T gid_t
#define RETSIGTYPE void
/***** HEADER FILES *****/
#include <stdio.h>
#include <stdlib.h>
/* needed for the time_t structures we use later... */
/* this include must come before sys/resource.h or we can have problems on some OSes */
#define TIME_WITH_SYS_TIME 1
#define HAVE_SYS_TIME_H 1
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#define HAVE_SYS_RESOURCE_H 1
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#define HAVE_LIMITS_H 1
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#define HAVE_PWD_H 1
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#define HAVE_GRP_H 1
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#define HAVE_STRINGS_H 1
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#define HAVE_STRING_H 1
#ifdef HAVE_STRINGS_H
#include <string.h>
#endif
#define HAVE_UNISTD_H 1
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#define HAVE_SYSLOG_H 1
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#define HAVE_SIGNAL_H 1
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#define HAVE_SYS_STAT_H 1
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#define HAVE_SYS_MMAN_H 1
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#define HAVE_FCNTL_H 1
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#define HAVE_STDARG_H 1
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#define HAVE_SYS_TYPES_H 1
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#define HAVE_SYS_WAIT_H 1
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#define HAVE_ERRNO_H 1
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#define HAVE_SYS_TIMEB_H 1
#if HAVE_SYS_TIMEB_H
#include <sys/timeb.h>
#endif
#define HAVE_SYS_IPC_H 1
#ifdef HAVE_SYS_IPC_H
#include <sys/ipc.h>
#endif
#define HAVE_SYS_MSG_H 1
#ifdef HAVE_SYS_MSG_H
#include <sys/msg.h>
#endif
#define HAVE_MATH_H 1
#ifdef HAVE_MATH_H
#include <math.h>
#endif
#define HAVE_CTYPE_H 1
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#define HAVE_DIRENT_H 1
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#define HAVE_REGEX_H 1
#ifdef HAVE_REGEX_H
#include <regex.h>
#define HAVE_SYS_SOCKET_H 1
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
/* #undef HAVE_SOCKET */
#ifdef HAVE_SOCKET_H
#include <socket.h>
#endif
#define HAVE_NETINET_IN_H 1
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#define HAVE_ARPA_INET_H 1
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#define HAVE_NETDB_H 1
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#define HAVE_LIBGEN_H 1
#ifdef HAVE_LIBGEN_H
#include <libgen.h>
#endif
#define HAVE_SYS_UN_H 1
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#define HAVE_SYS_POLL_H 1
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#define HAVE_GETOPT_H 1
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
/* #undef HAVE_LINUX_MODULE_H */
#ifdef HAVE_LINUX_MODULE_H
#include <linux/module.h>
#endif
#define HAVE_LOCALE_H 1
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#define HAVE_WCHAR_H 1
#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif
/* configure script should allow user to override ltdl choice, but this will do for now... */
/* #undef USE_LTDL */
/* #undef HAVE_LTDL_H */
#ifdef HAVE_LTDL_H
#define USE_LTDL
#endif
#ifdef USE_LTDL
#include <ltdl.h>
#else
#define HAVE_DLFCN_H /**/
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif
#endif
/* moved to end to prevent AIX compiler warnings */
#ifndef RTLD_GLOBAL
#define RTLD_GLOBAL 0
#endif
#ifndef RTLD_NOW
#define RTLD_NOW 0
#endif
/***** MARO DEFINITIONS *****/
/* this needs to come after all system include files, so we don't accidentally attempt to redefine it */
#ifndef WEXITSTATUS
# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#endif
#ifndef WIFEXITED
# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
#endif
#endif

94
nagios4/defaults.h Normal file
View File

@@ -0,0 +1,94 @@
#ifndef INCLUDE_defaults_h__
#define INCLUDE_defaults_h__
/******************* DEFAULT VALUES *******************/
#define DEFAULT_LOG_LEVEL 1 /* log all events to main log file */
#define DEFAULT_USE_SYSLOG 1 /* log events to syslog? 1=yes, 0=no */
#define DEFAULT_SYSLOG_LEVEL 2 /* log only severe events to syslog */
#define DEFAULT_NOTIFICATION_LOGGING 1 /* log notification events? 1=yes, 0=no */
#define DEFAULT_INTER_CHECK_DELAY 5.0 /* seconds between initial service check scheduling */
#define DEFAULT_INTERLEAVE_FACTOR 1 /* default interleave to use when scheduling checks */
#define DEFAULT_RETRY_INTERVAL 30 /* services are retried in 30 seconds if they're not OK */
#define DEFAULT_CHECK_REAPER_INTERVAL 10 /* interval in seconds to reap host and service check results */
#define DEFAULT_MAX_REAPER_TIME 30 /* maximum number of seconds to spend reaping service checks before we break out for a while */
#define DEFAULT_MAX_CHECK_RESULT_AGE 3600 /* maximum number of seconds that a check result file is considered to be valid */
#define DEFAULT_MAX_PARALLEL_SERVICE_CHECKS 0 /* maximum number of service checks we can have running at any given time (0=unlimited) */
#define DEFAULT_RETENTION_UPDATE_INTERVAL 60 /* minutes between auto-save of retention data */
#define DEFAULT_RETENTION_SCHEDULING_HORIZON 900 /* max seconds between program restarts that we will preserve scheduling information */
#define DEFAULT_STATUS_UPDATE_INTERVAL 60 /* seconds between aggregated status data updates */
#define DEFAULT_FRESHNESS_CHECK_INTERVAL 60 /* seconds between service result freshness checks */
#define DEFAULT_AUTO_RESCHEDULING_INTERVAL 30 /* seconds between host and service check rescheduling events */
#define DEFAULT_AUTO_RESCHEDULING_WINDOW 180 /* window of time (in seconds) for which we should reschedule host and service checks */
#define DEFAULT_ORPHAN_CHECK_INTERVAL 60 /* seconds between checks for orphaned hosts and services */
#define DEFAULT_INTERVAL_LENGTH 60 /* seconds per interval unit for check scheduling */
#define DEFAULT_NOTIFICATION_TIMEOUT 30 /* max time in seconds to wait for notification commands to complete */
#define DEFAULT_EVENT_HANDLER_TIMEOUT 30 /* max time in seconds to wait for event handler commands to complete */
#define DEFAULT_HOST_CHECK_TIMEOUT 30 /* max time in seconds to wait for host check commands to complete */
#define DEFAULT_SERVICE_CHECK_TIMEOUT 60 /* max time in seconds to wait for service check commands to complete */
#define DEFAULT_OCSP_TIMEOUT 15 /* max time in seconds to wait for obsessive compulsive processing commands to complete */
#define DEFAULT_OCHP_TIMEOUT 15 /* max time in seconds to wait for obsessive compulsive processing commands to complete */
#define DEFAULT_PERFDATA_TIMEOUT 5 /* max time in seconds to wait for performance data commands to complete */
#define DEFAULT_TIME_CHANGE_THRESHOLD 900 /* compensate for time changes of more than 15 minutes */
#define DEFAULT_LOG_HOST_RETRIES 0 /* don't log host retries */
#define DEFAULT_LOG_SERVICE_RETRIES 0 /* don't log service retries */
#define DEFAULT_LOG_EVENT_HANDLERS 1 /* log event handlers */
#define DEFAULT_LOG_INITIAL_STATES 0 /* don't log initial service and host states */
#define DEFAULT_LOG_CURRENT_STATES 1 /* log current service and host states after rotating log */
#define DEFAULT_LOG_EXTERNAL_COMMANDS 1 /* log external commands */
#define DEFAULT_LOG_PASSIVE_CHECKS 1 /* log passive service checks */
#define DEFAULT_DEBUG_LEVEL 0 /* don't log any debugging information */
#define DEFAULT_DEBUG_VERBOSITY 1
#define DEFAULT_MAX_DEBUG_FILE_SIZE 1000000 /* max size of debug log */
#define DEFAULT_AGGRESSIVE_HOST_CHECKING 0 /* don't use "aggressive" host checking */
#define DEFAULT_CHECK_EXTERNAL_COMMANDS 1 /* check for external commands */
#define DEFAULT_CHECK_ORPHANED_SERVICES 1 /* check for orphaned services */
#define DEFAULT_CHECK_ORPHANED_HOSTS 1 /* check for orphaned hosts */
#define DEFAULT_ENABLE_FLAP_DETECTION 0 /* don't enable flap detection */
#define DEFAULT_PROCESS_PERFORMANCE_DATA 0 /* don't process performance data */
#define DEFAULT_CHECK_SERVICE_FRESHNESS 1 /* check service result freshness */
#define DEFAULT_CHECK_HOST_FRESHNESS 0 /* don't check host result freshness */
#define DEFAULT_AUTO_RESCHEDULE_CHECKS 0 /* don't auto-reschedule host and service checks */
#define DEFAULT_TRANSLATE_PASSIVE_HOST_CHECKS 0 /* should we translate DOWN/UNREACHABLE passive host checks? */
#define DEFAULT_PASSIVE_HOST_CHECKS_SOFT 0 /* passive host checks are treated as HARD by default */
#define DEFAULT_LOW_SERVICE_FLAP_THRESHOLD 20.0 /* low threshold for detection of service flapping */
#define DEFAULT_HIGH_SERVICE_FLAP_THRESHOLD 30.0 /* high threshold for detection of service flapping */
#define DEFAULT_LOW_HOST_FLAP_THRESHOLD 20.0 /* low threshold for detection of host flapping */
#define DEFAULT_HIGH_HOST_FLAP_THRESHOLD 30.0 /* high threshold for detection of host flapping */
#define DEFAULT_HOST_CHECK_SPREAD 30 /* max minutes to schedule all initial host checks */
#define DEFAULT_SERVICE_CHECK_SPREAD 30 /* max minutes to schedule all initial service checks */
#define DEFAULT_CACHED_HOST_CHECK_HORIZON 15 /* max age in seconds that cached host checks can be used */
#define DEFAULT_CACHED_SERVICE_CHECK_HORIZON 15 /* max age in seconds that cached service checks can be used */
#define DEFAULT_ENABLE_PREDICTIVE_HOST_DEPENDENCY_CHECKS 1 /* should we use predictive host dependency checks? */
#define DEFAULT_ENABLE_PREDICTIVE_SERVICE_DEPENDENCY_CHECKS 1 /* should we use predictive service dependency checks? */
#define DEFAULT_USE_LARGE_INSTALLATION_TWEAKS 0 /* don't use tweaks for large Nagios installations */
#define DEFAULT_ADDITIONAL_FRESHNESS_LATENCY 15 /* seconds to be added to freshness thresholds when automatically calculated by Nagios */
#define DEFAULT_CHECK_FOR_UPDATES 1 /* should we check for new Nagios releases? */
#define DEFAULT_BARE_UPDATE_CHECK 0 /* report current version and new installs */
#define MINIMUM_UPDATE_CHECK_INTERVAL 60*60*22 /* 22 hours minimum between checks - please be kind to our servers! */
#define BASE_UPDATE_CHECK_INTERVAL 60*60*22 /* 22 hours base interval */
#define UPDATE_CHECK_INTERVAL_WOBBLE 60*60*4 /* 4 hour wobble on top of base interval */
#define BASE_UPDATE_CHECK_RETRY_INTERVAL 60*60*1 /* 1 hour base retry interval */
#define UPDATE_CHECK_RETRY_INTERVAL_WOBBLE 60*60*3 /* 3 hour wobble on top of base retry interval */
#define DEFAULT_ALLOW_EMPTY_HOSTGROUP_ASSIGNMENT 2 /* Allow assigning to empty hostgroups by default, but warn about it */
#define DEFAULT_HOST_PERFDATA_FILE_TEMPLATE "[HOSTPERFDATA]\t$TIMET$\t$HOSTNAME$\t$HOSTEXECUTIONTIME$\t$HOSTOUTPUT$\t$HOSTPERFDATA$"
#define DEFAULT_SERVICE_PERFDATA_FILE_TEMPLATE "[SERVICEPERFDATA]\t$TIMET$\t$HOSTNAME$\t$SERVICEDESC$\t$SERVICEEXECUTIONTIME$\t$SERVICELATENCY$\t$SERVICEOUTPUT$\t$SERVICEPERFDATA$"
#define DEFAULT_HOST_PERFDATA_PROCESS_EMPTY_RESULTS 1
#define DEFAULT_SERVICE_PERFDATA_PROCESS_EMPTY_RESULTS 1
#endif /* INCLUDE_defaults_h__ */

134
nagios4/dkhash.h Normal file
View File

@@ -0,0 +1,134 @@
#ifndef LIBNAGIOS_dkhash_h__
#define LIBNAGIOS_dkhash_h__
#include <errno.h>
/**
* @file dkhash.h
* @brief Dual-key hash functions for Nagios
*
* Having a dual-key hash function is pretty unusual, but since so
* much data in Nagios pertains to services (which are uniquely
* identified based on both host_name and service_description), it
* makes sense here.
*
* @{
*/
/** return flags usable from the callback function of dkhash_walk_data() */
#define DKHASH_WALK_REMOVE 1 /**< Remove the most recently visited object */
#define DKHASH_WALK_STOP 2 /**< Cause walking to stop */
/** return values for dkhash_insert() */
#define DKHASH_OK 0 /**< Success */
#define DKHASH_EDUPE (-EPERM) /**< duplicate insert attempted */
#define DKHASH_EPERM (-EPERM) /**< duplicate insert attempted */
#define DKHASH_EINVAL (-EINVAL) /**< Invalid parameters passed */
#define DKHASH_ENOMEM (-ENOMEM) /**< Memory allocation failed */
struct dkhash_table;
/** opaque type */
typedef struct dkhash_table dkhash_table;
/**
* Create a dual-keyed hash-table of the given size
* Note that it's generally useful to make the table 25-30% larger
* than the number of items you intend to store, and also note that
* the 'size' arguments gets rounded up to the nearest power of 2.
* @param size The desired size of the hash-table.
*/
extern dkhash_table *dkhash_create(unsigned int size);
/**
* Destroy a dual-keyed hash table
* @param t The table to destroy
* @return 0 on success, -1 on errors
*/
extern int dkhash_destroy(dkhash_table *t);
/**
* Fetch the data associated with a particular key
* @param t The table to get the data from
* @param k1 The first key
* @param k2 The second key
* @return The data on success, NULL on errors or if data isn't found
*/
extern void *dkhash_get(dkhash_table *t, const char *k1, const char *k2);
/**
* Insert a new entry into the hash table
* @param t The hash table
* @param k1 The first key
* @param k2 The second key (may be null)
* @param data The data to insert
* @return 0 on success, < 0 on errors
*/
extern int dkhash_insert(dkhash_table *t, const char *k1, const char *k2, void *data);
/**
* Remove data from the hash table
* Note that this does not free() the pointer to the data stored in the
* table. It just destroys containers for that data in the hash table.
* @param t The hash table
* @param k1 The first key
* @param k2 The second key
* @return The removed data on success, or NULL on errors
*/
extern void *dkhash_remove(dkhash_table *t, const char *k1, const char *k2);
/**
* Call a function once for each item in the hash-table
* The callback function can return DKHASH_WALK_{REMOVE,STOP} or any
* OR'ed combination thereof to control the walking procedure, and
* should return 0 on the normal case.
* @param t The hash table
* @param walker The callback function to send the data to
*/
extern void dkhash_walk_data(dkhash_table *t, int (*walker)(void *data));
/**
* Get number of collisions in hash table
* Many collisions is a sign of a too small hash table or
* poor hash-function.
* @param t The hash table to report on
* @return The total number of collisions (not duplicates) from inserts
*/
extern unsigned int dkhash_collisions(dkhash_table *t);
/**
* Get number of items in the hash table
* @param t The hash table
* @return Number of items currently in the hash-table
*/
extern unsigned int dkhash_num_entries(dkhash_table *t);
/**
* Get max number of items stored in the hash table
* @param t The hash table
* @return Max number of items stored in hash-table
*/
extern unsigned int dkhash_num_entries_max(dkhash_table *t);
/**
* Get number of entries added to hash table
* Note that some of them may have been removed.
* @param t The hash table
* @return The number of items added to the table
*/
extern unsigned int dkhash_num_entries_added(dkhash_table *t);
/**
* Get number of removed items from hash table
* @param t The hash table
* @return Number of items removed from hash table
*/
extern unsigned int dkhash_num_entries_removed(dkhash_table *t);
/**
* Get actual table size (in number of buckets)
* @param t The hash table
* @return Number of bucket-slots in hash table
*/
extern unsigned int dkhash_table_size(dkhash_table *t);
/** @} */
#endif /* LIBNAGIOS_dkhash_h__ */

112
nagios4/downtime.h Normal file
View File

@@ -0,0 +1,112 @@
/*****************************************************************************
*
* DOWNTIME.H - Header file for scheduled downtime functions
*
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _DOWNTIME_H
#define _DOWNTIME_H
#include "common.h"
#include "objects.h"
#ifndef NSCGI
#include "nagios.h"
#endif
NAGIOS_BEGIN_DECL
/* SCHEDULED_DOWNTIME_ENTRY structure */
typedef struct scheduled_downtime {
int type;
char *host_name;
char *service_description;
time_t entry_time;
time_t start_time;
time_t flex_downtime_start; /* Time the flexible downtime started */
time_t end_time;
int fixed;
unsigned long triggered_by;
unsigned long duration;
unsigned long downtime_id;
int is_in_effect;
int start_notification_sent;
char *author;
char *comment;
#ifndef NSCGI
unsigned long comment_id;
int start_flex_downtime;
int incremented_pending_downtime;
#endif
struct scheduled_downtime *next;
#ifndef NSCGI
struct timed_event *start_event, *stop_event;
#endif
struct scheduled_downtime *prev;
} scheduled_downtime;
extern struct scheduled_downtime *scheduled_downtime_list;
int initialize_downtime_data(void); /* initializes scheduled downtime data */
int cleanup_downtime_data(void); /* cleans up scheduled downtime data */
#ifndef NSCGI
int add_new_downtime(int, char *, char *, time_t, char *, char *, time_t, time_t, int, unsigned long, unsigned long, unsigned long *, int, int);
int add_new_host_downtime(char *, time_t, char *, char *, time_t, time_t, int, unsigned long, unsigned long, unsigned long *, int, int);
int add_new_service_downtime(char *, char *, time_t, char *, char *, time_t, time_t, int, unsigned long, unsigned long, unsigned long *, int, int);
int delete_host_downtime(unsigned long);
int delete_service_downtime(unsigned long);
int delete_downtime(int, unsigned long);
int schedule_downtime(int, char *, char *, time_t, char *, char *, time_t, time_t, int, unsigned long, unsigned long, unsigned long *);
int unschedule_downtime(int, unsigned long);
int register_downtime(int, unsigned long);
int handle_scheduled_downtime(struct scheduled_downtime *);
int handle_scheduled_downtime_by_id(unsigned long);
int check_pending_flex_host_downtime(struct host *);
int check_pending_flex_service_downtime(struct service *);
int check_for_expired_downtime(void);
#endif
int add_host_downtime(char *, time_t, char *, char *, time_t, time_t, time_t, int, unsigned long, unsigned long, unsigned long, int, int);
int add_service_downtime(char *, char *, time_t, char *, char *, time_t, time_t, time_t, int, unsigned long, unsigned long, unsigned long, int, int);
/* If you are going to be adding a lot of downtime in sequence, set
defer_downtime_sorting to 1 before you start and then call
sort_downtime afterwards. Things will go MUCH faster. */
extern int defer_downtime_sorting;
int add_downtime(int, char *, char *, time_t, char *, char *, time_t, time_t, time_t, int, unsigned long, unsigned long, unsigned long, int, int);
int sort_downtime(void);
struct scheduled_downtime *find_downtime(int, unsigned long);
struct scheduled_downtime *find_host_downtime(unsigned long);
struct scheduled_downtime *find_service_downtime(unsigned long);
void free_downtime_data(void); /* frees memory allocated to scheduled downtime list */
int delete_downtime_by_hostname_service_description_start_time_comment(char *, char *, time_t, char *);
NAGIOS_END_DECL
#endif

73
nagios4/fanout.h Normal file
View File

@@ -0,0 +1,73 @@
#ifndef LIBNAGIOS_fanout_h__
#define LIBNAGIOS_fanout_h__
#include "lnag-utils.h"
/**
* @file fanout.h
* @brief Simple fanout table implementation
*
* Fanouts are useful to hold short-lived integer-indexed data where
* the keyspan between smallest and largest key can be too large and
* change too often for it to be practical to maintain a growing array.
* If you think of it as a hash-table optimized for unsigned longs you've
* got the right idea.
*
* @{
*/
NAGIOS_BEGIN_DECL
/** Primary (opaque) type for this api */
typedef struct fanout_table fanout_table;
/**
* Create a fanout table
* @param[in] size The size of the table. Preferrably a power of 2
* @return Pointer to a newly created table
*/
extern fanout_table *fanout_create(unsigned long size);
/**
* Destroy a fanout table, with optional destructor.
* This function will iterate over all the entries in the fanout
* table and remove them, one by one. If 'destructor' is not NULL,
* it will be called on each and every object in the table. Note that
* 'free' is a valid destructor.
*
* @param[in] t The fanout table to destroy
* @param[in] destructor Function to call on data pointers in table
*/
extern void fanout_destroy(fanout_table *t, void (*destructor)(void *));
/**
* Return a pointer from the fanout table t
*
* @param[in] t table to fetch from
* @param[in] key key to fetch
* @return NULL on errors; Pointer to data on success
*/
extern void *fanout_get(fanout_table *t, unsigned long key);
/**
* Add an entry to the fanout table.
* Note that we don't check if the key is unique. If it isn't,
* fanout_remove() will remove the latest added first.
*
* @param[in] t fanout table to add to
* @param[in] key Key for this entry
* @param[in] data Data to add. Must not be NULL
* @return 0 on success, -1 on errors
*/
extern int fanout_add(fanout_table *t, unsigned long key, void *data);
/**
* Remove an entry from the fanout table and return its data.
*
* @param[in] t fanout table to look in
* @param[key] The key whose data we should locate
* @return Pointer to the data stored on success; NULL on errors
*/
extern void *fanout_remove(fanout_table *t, unsigned long key);
NAGIOS_END_DECL
/** @} */
#endif

175
nagios4/iobroker.h Normal file
View File

@@ -0,0 +1,175 @@
/* lib/iobroker.h. Generated from iobroker.h.in by configure. */
#ifndef LIBNAGIOS_iobroker_h__
#define LIBNAGIOS_iobroker_h__
/**
* @file iobroker.h
* @brief I/O broker library function declarations
*
* The I/O broker library handles multiplexing between hundreds or
* thousands of sockets with a few simple calls. It's designed to
* be as lightweight as possible so as to not cause memory bloat,
* and is therefore highly suitable for use by processes that are
* fork()-intensive.
*
* @{
*/
#define IOBROKER_USES_EPOLL 1
/* #undef IOBROKER_USES_POLL */
/* #undef IOBROKER_USES_SELECT */
#if (_POSIX_C_SOURCE - 0) >= 200112L
#include <poll.h>
# define IOBROKER_POLLIN POLLIN
# define IOBROKER_POLLPRI POLLPRI
# define IOBROKER_POLLOUT POLLOUT
# define IOBROKER_POLLERR POLLERR
# define IOBROKER_POLLHUP POLLHUP
# define IOBROKER_POLLNVAL POLLNVAL
#else
# define IOBROKER_POLLIN 0x001 /* there is data to read */
# define IOBROKER_POLLPRI 0x002 /* there is urgent data to read */
# define IOBROKER_POLLOUT 0x004 /* writing now will not block */
# define IOBROKER_POLLERR 0x008 /* error condition */
# define IOBROKER_POLLHUP 0x010 /* hung up */
# define IOBROKER_POLLNVAL 0x020 /* invalid polling request */
#endif
/** return codes */
#define IOBROKER_SUCCESS 0
#define IOBROKER_ENOSET (-1)
#define IOBROKER_ENOINIT (-2)
#define IOBROKER_ELIB (-3)
#define IOBROKER_EALREADY (-EALREADY)
#define IOBROKER_EINVAL (-EINVAL)
/** Flags for iobroker_destroy() */
#define IOBROKER_CLOSE_SOCKETS 1
/* Opaque type. Callers needn't worry about this */
struct iobroker_set;
typedef struct iobroker_set iobroker_set;
/**
* Get a string describing the error in the last iobroker call.
* The returned string must not be free()'d.
* @param error The error code
* @return A string describing the meaning of the error code
*/
extern const char *iobroker_strerror(int error);
/**
* Create a new socket set
* @return An iobroker_set on success. NULL on errors.
*/
extern iobroker_set *iobroker_create(void);
/**
* Published utility function used to determine the max number of
* file descriptors this process can keep open at any one time.
* @return Max number of filedescriptors we can keep open
*/
extern int iobroker_max_usable_fds(void);
/**
* Register a socket for input polling with the broker.
*
* @param iobs The socket set to add the socket to.
* @param sd The socket descriptor to add
* @param arg Argument passed to input handler on available input
* @param handler The callback function to call when input is available
*
* @return 0 on succes. < 0 on errors.
*/
extern int iobroker_register(iobroker_set *iobs, int sd, void *arg, int (*handler)(int, int, void *));
/**
* Register a socket for output polling with the broker
* @note There's no guarantee that *ALL* data is writable just
* because the socket won't block you completely.
*
* @param iobs The socket set to add the socket to.
* @param sd The socket descriptor to add
* @param arg Argument passed to output handler on ready-to-write
* @param handler The function to call when output won't block
*
* @return 0 on success. < 0 on errors
*/
extern int iobroker_register_out(iobroker_set *iobs, int sd, void *arg, int (*handler)(int, int, void *));
/**
* Check if a particular filedescriptor is registered with the iobroker set
* @param[in] iobs The iobroker set the filedescriptor should be member of
* @param[in] fd The filedescriptor to check for
* @return 1 if the filedescriptor is registered and 0 otherwise
*/
extern int iobroker_is_registered(iobroker_set *iobs, int fd);
/**
* Getter function for number of file descriptors registered in
* the set specified.
* @param iobs The io broker set to query
* @return Number of file descriptors registered in the set
*/
extern int iobroker_get_num_fds(iobroker_set *iobs);
/**
* Getter function for the maximum amount of file descriptors this
* set can handle.
* @param iobs The io broker set to query
* @return Max file descriptor capacity for the set
*/
extern int iobroker_get_max_fds(iobroker_set *iobs);
/**
* Unregister a socket for input polling with the broker.
*
* @param iobs The socket set to remove the socket from
* @param sd The socket descriptor to remove
* @return 0 on succes. < 0 on errors.
*/
extern int iobroker_unregister(iobroker_set *iobs, int sd);
/**
* Deregister a socket for input polling with the broker
* (this is identical to iobroker_unregister())
* @param iobs The socket set to remove the socket from
* @param sd The socket descriptor to remove
* @return 0 on success. < 0 on errors.
*/
extern int iobroker_deregister(iobroker_set *iobs, int sd);
/**
* Unregister and close(2) a socket registered for input with the
* broker. This is a convenience function which exists only to avoid
* doing multiple calls when read() returns 0, as closed sockets must
* always be removed from the socket set to avoid consuming tons of
* cpu power from iterating "too fast" over the file descriptors.
*
* @param iobs The socket set to remove the socket from
* @param sd The socket descriptor to remove and close
* @return 0 on success. < 0 on errors
*/
extern int iobroker_close(iobroker_set *iobs, int sd);
/**
* Destroy a socket set as created by iobroker_create
* @param iobs The socket set to destroy
* @param flags If set, close(2) all registered sockets
*/
extern void iobroker_destroy(iobroker_set *iobs, int flags);
/**
* Wait for input on any of the registered sockets.
* @param iobs The socket set to wait for.
* @param timeout Timeout in milliseconds. -1 is "wait indefinitely"
* @return -1 on errors, or number of filedescriptors with input
*/
extern int iobroker_poll(iobroker_set *iobs, int timeout);
#endif /* INCLUDE_iobroker_h__ */
/** @} */

181
nagios4/iocache.h Normal file
View File

@@ -0,0 +1,181 @@
#ifndef LIBNAGIOS_iocache_h__
#define LIBNAGIOS_iocache_h__
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
/**
* @file iocache.h
* @brief I/O cache function declarations
*
* The I/O cache library is useful for reading large chunks of data
* from sockets and utilizing parts of that data based on either
* size or a magic delimiter.
*
* @{
*/
/** opaque type for iocache operations */
struct iocache;
typedef struct iocache iocache;
/**
* Destroys an iocache object, freeing all memory allocated to it.
* @param ioc The iocache object to destroy
*/
extern void iocache_destroy(iocache *ioc);
/**
* Resets an iocache struct, discarding all data in it without free()'ing
* any memory.
*
* @param[in] ioc The iocache struct to reset
*/
extern void iocache_reset(iocache *ioc);
/**
* Resizes the buffer in an io cache
* @param ioc The io cache to resize
* @param new_size The new size of the io cache
* @return 0 on success, -1 on errors
*/
extern int iocache_resize(iocache *ioc, unsigned long new_size);
/**
* Grows an iocache object
* This uses iocache_resize() internally
* @param[in] ioc The iocache to grow
* @param[in] increment How much to increase it
* @return 0 on success, -1 on errors
*/
extern int iocache_grow(iocache *ioc, unsigned long increment);
/**
* Returns the total size of the io cache
* @param[in] ioc The iocache to inspect
* @return The size of the io cache. If ioc is null, 0 is returned
*/
extern unsigned long iocache_size(iocache *ioc);
/**
* Returns remaining read capacity of the io cache
* @param ioc The io cache to operate on
* @return The number of bytes available to read
*/
extern unsigned long iocache_capacity(iocache *ioc);
/**
* Return the amount of unread but stored data in the io cache
* @param ioc The io cache to operate on
* @return Number of bytes available to read
*/
extern unsigned long iocache_available(iocache *ioc);
/**
* Use a chunk of data from iocache based on size. The caller
* must take care not to write beyond the end of the requested
* buffer, or Bad Things(tm) will happen.
*
* @param ioc The io cache we should use data from
* @param size The size of the data we want returned
* @return NULL on errors (insufficient data, fe). pointer on success
*/
extern char *iocache_use_size(iocache *ioc, unsigned long size);
/**
* Use a chunk of data from iocache based on delimiter. The
* caller must take care not to write beyond the end of the
* requested buffer, if any is returned, or Bad Things(tm) will
* happen.
*
* @param ioc The io cache to use data from
* @param delim The delimiter
* @param delim_len Length of the delimiter
* @param size Length of the returned buffer
* @return NULL on errors (delimiter not found, insufficient data). pointer on success
*/
extern char *iocache_use_delim(iocache *ioc, const char *delim, size_t delim_len, unsigned long *size);
/**
* Forget that a specified number of bytes have been used.
* @param ioc The io cache that you want to un-use data in
* @param size The number of bytes you want to forget you've seen
* @return -1 if there was an error, 0 otherwise.
*/
extern int iocache_unuse_size(iocache *ioc, unsigned long size);
/**
* Creates the iocache object, initializing it with the given size
* @param size Initial size of the iocache buffer
* @return Pointer to a valid iocache object
*/
extern iocache *iocache_create(unsigned long size);
/**
* Read data into the iocache buffer
* @param ioc The io cache we should read into
* @param fd The filedescriptor we should read from
* @return The number of bytes read on success. < 0 on errors
*/
extern int iocache_read(iocache *ioc, int fd);
/**
* Add data to the iocache buffer
* The data is copied, so it can safely be taken from the stack in a
* function that returns before the data is used.
* If the io cache is too small to hold the data, -1 will be returned.
*
* @param[in] ioc The io cache to add to
* @param[in] buf Pointer to the data we should add
* @param[in] len Length (in bytes) of data pointed to by buf
* @return iocache_available(ioc) on success, -1 on errors
*/
extern int iocache_add(iocache *ioc, char *buf, unsigned int len);
/**
* Like sendto(), but sends all cached data prior to the requested
*
* @param[in] ioc The iocache to send, or cache data in
* @param[in] fd The file descriptor to send to
* @param[in] buf Pointer to the data to send
* @param[in] len Length (in bytes) of data to send
* @param[in] flags Flags passed to sendto(2)
* @param[in] dest_addr Destination address
* @param[in] addrlen size (in bytes) of dest_addr
* @return bytes sent on success, -ERRNO on errors
*/
extern int iocache_sendto(iocache *ioc, int fd, char *buf, unsigned int len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);
/**
* Like send(2), but sends all cached data prior to the requested
* This function uses iocache_sendto() internally, but can only be
* used on connected sockets or open()'ed files.
*
* @param[in] ioc The iocache to send, or cache data in
* @param[in] fd The file descriptor to send to
* @param[in] buf Pointer to the data to send
* @param[in] len Length (in bytes) of data to send
* @param[in] flags Flags passed to sendto(2)
* @return bytes sent on success, -ERRNO on errors
*/
static inline int iocache_send(iocache *ioc, int fd, char *buf, unsigned int len, int flags)
{
return iocache_sendto(ioc, fd, buf, len, flags, NULL, 0);
}
/**
* Like write(2), but sends all cached data prior to the requested
* This function uses iocache_send() internally.
*
* @param[in] ioc The iocache to send, or cache data in
* @param[in] fd The file descriptor to send to
* @param[in] buf Pointer to the data to send
* @param[in] len Length (in bytes) of data to send
* @return bytes sent on success, -ERRNO on errors
*/
static inline int iocache_write(iocache *ioc, int fd, char *buf, unsigned int len)
{
return iocache_send(ioc, fd, buf, len, 0);
}
#endif /* INCLUDE_iocache_h__ */
/** @} */

207
nagios4/kvvec.h Normal file
View File

@@ -0,0 +1,207 @@
#ifndef LIBNAGIOS_kvvec_h__
#define LIBNAGIOS_kvvec_h__
/**
* @file kvvec.h
* @brief Key/value vector library function and type declarations
*
* The kvvec library is nifty as either a configuration meta-format
* or for IPC purposes. Take a look at the buf2kvvec() and kvvec2buf()
* pair of functions for the latter.
* @{
*/
/**
* key/value pair
* One of the two major components of the kvvec api
*/
struct key_value {
char *key; /**< The key */
char *value; /**< The value */
int key_len; /**< Length of key */
int value_len; /**< Length of value */
};
/**
* key/value vector buffer. Actually just a buffer, but one that gets
* used as return value and internal tracker for kvvec2buf()
*/
struct kvvec_buf {
char *buf; /**< The buffer */
unsigned long buflen; /**< Length of buffer */
unsigned long bufsize; /**< Size of buffer (includes overalloc) */
};
/**
* key/value vector struct
* This is the main component of the kvvec library
* @note This should be made opaque, with a kvvec_foreach() using a
* callback to iterate over key/value pairs.
*/
struct kvvec {
struct key_value *kv; /**< The key/value array */
int kv_alloc; /**< Allocated size of key/value array */
int kv_pairs; /**< Number of key/value pairs */
int kvv_sorted; /**< Determines if this kvvec has been sorted */
};
/** Portable initializer for stack-allocated key/value vectors */
#define KVVEC_INITIALIZER { NULL, 0, 0, 0 }
/** Parameters for kvvec_destroy() */
#define KVVEC_FREE_KEYS 1 /**< Free keys when destroying a kv vector */
#define KVVEC_FREE_VALUES 2 /**< Free values when destroying a kv vector */
/** Free both keys and values when destroying a kv vector */
#define KVVEC_FREE_ALL (KVVEC_FREE_KEYS | KVVEC_FREE_VALUES)
#define KVVEC_ASSIGN 0 /**< Assign from buf in buf2kvvec_prealloc() */
#define KVVEC_COPY 1 /**< Copy from buf in buf2kvvec_prealloc() */
#define KVVEC_APPEND 2 /**< Don't reset kvvec in buf2kvvec_prealloc() */
/**
* Initialize a previously allocated key/value vector
*
* @param kvv The key/value vector to initialize
* @param hint Number of key/value pairs we expect to store
* @return Pointer to a struct kvvec, properly initialized
*/
extern struct kvvec *kvvec_init(struct kvvec *kvv, int hint);
/**
* Create a key/value vector
*
* @param hint Number of key/value pairs we expect to store
* @return Pointer to a struct kvvec, properly initialized
*/
extern struct kvvec *kvvec_create(int hint);
/**
* Resize a key/value vector
* Used by kvvec_grow(). If size is smaller than the current number of
* used key/value slots, -1 is returned.
*
* @param[in] kvv The key/value vector to resize
* @param[in] size The size to grow to
* @return 0 on success, < 0 on errors
*/
extern int kvvec_resize(struct kvvec *kvv, int size);
/**
* Grow a key/value vector.
* Used internally as needed by the kvvec api. If 'hint' is zero, the
* key/value capacity is increased by a third of the current capacity
* plus a small constant number. This uses kvvec_resize() internally.
*
* @param kvv The key/value vector to grow
* @param hint The amount of key/value slots we should grow by
* @return 0 on success, < 0 on errors
*/
extern int kvvec_grow(struct kvvec *kvv, int hint);
/**
* Return remaining storage capacity of key/value vector
* @param[in] kvv The key/value vector to check
* @return Number of key/value pairs that can be stored without growing
*/
extern unsigned int kvvec_capacity(struct kvvec *kvv);
/**
* Sort a key/value vector alphabetically by key name
* @param kvv The key/value vector to sort
* @return 0
*/
extern int kvvec_sort(struct kvvec *kvv);
/**
* Add a key/value pair to an existing key/value vector, with
* lengths of strings already calculated
* @param kvv The key/value vector to add this key/value pair to
* @param key The key
* @param keylen Length of the key
* @param value The value
* @param valuelen Length of the value
* @return 0 on success, < 0 on errors
*/
extern int kvvec_addkv_wlen(struct kvvec *kvv, const char *key, int keylen, const char *value, int valuelen);
/**
* Shortcut to kvvec_addkv_wlen() when lengths aren't known
* @param kvv The key/value vector to add this key/value pair to
* @param key The key
* @param value The value
* @return 0 on success, < 0 on errors
*/
#define kvvec_addkv(kvv, key, value) kvvec_addkv_wlen(kvv, key, 0, value, 0)
/**
* Walk each key/value pair in a key/value vector, sending them
* as arguments to a callback function. The callback function has
* no control over the iteration process and must not delete or
* modify the key/value vector it's operating on.
* @param kvv The key/value vector to walk
* @param arg Extra argument to the callback function
* @param callback Callback function
* @return 0 on success, < 0 on errors
*/
extern int kvvec_foreach(struct kvvec *kvv, void *arg, int (*callback)(struct key_value *, void *));
/**
* Destroy a key/value vector
* @param kvv The key/value vector to destroy
* @param flags or'ed combination of KVVEC_FREE_{KEYS,VALUES}, or KVVEC_FREE_ALL
* @return 0 on success, < 0 on errors
*/
extern int kvvec_destroy(struct kvvec *kvv, int flags);
/**
* Free key/value pairs associated with a key/value vector
* @param kvv The key/value vector to operate on
* @param flags flags or'ed combination of KVVEC_FREE_{KEYS,VALUES}, or KVVEC_FREE_ALL
*/
void kvvec_free_kvpairs(struct kvvec *kvv, int flags);
/**
* Create a linear buffer of all the key/value pairs and
* return it as a kvvec_buf. The caller must free() all
* pointers in the returned kvvec_buf
* (FIXME: add kvvec_buf_destroy(), or move this and its counterpart
* out of the kvvec api into a separate one)
*
* @param kvv The key/value vector to convert
* @param kv_sep Character separating keys and their values
* @param pair_sep Character separating key/value pairs
* @param overalloc Integer determining how much extra data we should
* allocate. The overallocated memory is filled with
* nul bytes.
* @return A pointer to a newly created kvvec_buf structure
*/
extern struct kvvec_buf *kvvec2buf(struct kvvec *kvv, char kv_sep, char pair_sep, int overalloc);
/**
* Create a key/value vector from a pre-parsed buffer. Immensely
* useful for ipc in combination with kvvec2buf().
*
* @param str The buffer to convert to a key/value vector
* @param len Length of buffer to convert
* @param kvsep Character separating key and value
* @param pair_sep Character separating key/value pairs
* @param flags bitmask. See KVVEC_{ASSIGN,COPY,APPEND} for values
* @return The created key/value vector
*/
extern struct kvvec *buf2kvvec(char *str, unsigned int len, const char kvsep, const char pair_sep, int flags);
/**
* Parse a buffer into the pre-allocated key/value vector. Immensely
* useful for ipc in combination with kvvec2buf().
*
* @param kvv A pre-allocated key/value vector to populate
* @param str The buffer to convert to a key/value vector
* @param len Length of buffer to convert
* @param kvsep Character separating key and value
* @param pair_sep Character separating key/value pairs
* @param flags bitmask. See KVVEC_{ASSIGN,COPY,APPEND} for values
* @return The number of pairs in the created key/value vector
*/
extern int buf2kvvec_prealloc(struct kvvec *kvv, char *str, unsigned int len, const char kvsep, const char pair_sep, int flags);
/** @} */
#endif /* INCLUDE_kvvec_h__ */

25
nagios4/libnagios.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef LIBNAGIOS_libnagios_h__
#define LIBNAGIOS_libnagios_h__
/**
* @file libnagios.h
*
* @brief Include this for all public parts of libnagios to be accessible
*/
#include "lnag-utils.h"
#include "fanout.h"
#include "nsutils.h"
#include "pqueue.h"
#include "squeue.h"
#include "kvvec.h"
#include "iobroker.h"
#include "iocache.h"
#include "runcmd.h"
#include "bitmap.h"
#include "dkhash.h"
#include "worker.h"
#include "skiplist.h"
#include "nsock.h"
#include "nspath.h"
#include "snprintf.h"
#endif /* LIB_libnagios_h__ */

Some files were not shown because too many files have changed in this diff Show More