diff options
Diffstat (limited to 'src/share/database/scripts')
54 files changed, 26411 insertions, 0 deletions
diff --git a/src/share/database/scripts/Makefile.am b/src/share/database/scripts/Makefile.am new file mode 100644 index 0000000..6602983 --- /dev/null +++ b/src/share/database/scripts/Makefile.am @@ -0,0 +1 @@ +SUBDIRS = mysql pgsql diff --git a/src/share/database/scripts/Makefile.in b/src/share/database/scripts/Makefile.in new file mode 100644 index 0000000..01e7f65 --- /dev/null +++ b/src/share/database/scripts/Makefile.in @@ -0,0 +1,704 @@ +# Makefile.in generated by automake 1.16.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2018 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@ +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 = src/share/database/scripts +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4macros/ax_boost_for_kea.m4 \ + $(top_srcdir)/m4macros/ax_cpp11.m4 \ + $(top_srcdir)/m4macros/ax_crypto.m4 \ + $(top_srcdir)/m4macros/ax_find_library.m4 \ + $(top_srcdir)/m4macros/ax_gssapi.m4 \ + $(top_srcdir)/m4macros/ax_gtest.m4 \ + $(top_srcdir)/m4macros/ax_isc_rpath.m4 \ + $(top_srcdir)/m4macros/ax_sysrepo.m4 \ + $(top_srcdir)/m4macros/libtool.m4 \ + $(top_srcdir)/m4macros/ltoptions.m4 \ + $(top_srcdir)/m4macros/ltsugar.m4 \ + $(top_srcdir)/m4macros/ltversion.m4 \ + $(top_srcdir)/m4macros/lt~obsolete.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/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 \ + distdir distdir-am +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# 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 +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +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" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +ASCIIDOC = @ASCIIDOC@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOOST_INCLUDES = @BOOST_INCLUDES@ +BOOST_LIBS = @BOOST_LIBS@ +BOTAN_TOOL = @BOTAN_TOOL@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CONTRIB_DIR = @CONTRIB_DIR@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CRYPTO_CFLAGS = @CRYPTO_CFLAGS@ +CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ +CRYPTO_LDFLAGS = @CRYPTO_LDFLAGS@ +CRYPTO_LIBS = @CRYPTO_LIBS@ +CRYPTO_PACKAGE = @CRYPTO_PACKAGE@ +CRYPTO_RPATH = @CRYPTO_RPATH@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DISTCHECK_BOOST_CONFIGURE_FLAG = @DISTCHECK_BOOST_CONFIGURE_FLAG@ +DISTCHECK_CONTRIB_CONFIGURE_FLAG = @DISTCHECK_CONTRIB_CONFIGURE_FLAG@ +DISTCHECK_CRYPTO_CONFIGURE_FLAG = @DISTCHECK_CRYPTO_CONFIGURE_FLAG@ +DISTCHECK_GTEST_CONFIGURE_FLAG = @DISTCHECK_GTEST_CONFIGURE_FLAG@ +DISTCHECK_KEA_SHELL_CONFIGURE_FLAG = @DISTCHECK_KEA_SHELL_CONFIGURE_FLAG@ +DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG = @DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG@ +DISTCHECK_PERFDHCP_CONFIGURE_FLAG = @DISTCHECK_PERFDHCP_CONFIGURE_FLAG@ +DISTCHECK_PREMIUM_CONFIGURE_FLAG = @DISTCHECK_PREMIUM_CONFIGURE_FLAG@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GENHTML = @GENHTML@ +GREP = @GREP@ +GSSAPI_CFLAGS = @GSSAPI_CFLAGS@ +GSSAPI_LIBS = @GSSAPI_LIBS@ +GTEST_CONFIG = @GTEST_CONFIG@ +GTEST_INCLUDES = @GTEST_INCLUDES@ +GTEST_LDADD = @GTEST_LDADD@ +GTEST_LDFLAGS = @GTEST_LDFLAGS@ +GTEST_SOURCE = @GTEST_SOURCE@ +HAVE_SYSREPO = @HAVE_SYSREPO@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +KEA_CXXFLAGS = @KEA_CXXFLAGS@ +KEA_SRCID = @KEA_SRCID@ +KRB5_CONFIG = @KRB5_CONFIG@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LOG4CPLUS_INCLUDES = @LOG4CPLUS_INCLUDES@ +LOG4CPLUS_LIBS = @LOG4CPLUS_LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MYSQL_CPPFLAGS = @MYSQL_CPPFLAGS@ +MYSQL_LIBS = @MYSQL_LIBS@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +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@ +PACKAGE_VERSION_TYPE = @PACKAGE_VERSION_TYPE@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PDFLATEX = @PDFLATEX@ +PERL = @PERL@ +PGSQL_CPPFLAGS = @PGSQL_CPPFLAGS@ +PGSQL_LIBS = @PGSQL_LIBS@ +PKGPYTHONDIR = @PKGPYTHONDIR@ +PKG_CONFIG = @PKG_CONFIG@ +PLANTUML = @PLANTUML@ +PREMIUM_DIR = @PREMIUM_DIR@ +PYTHON = @PYTHON@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +RANLIB = @RANLIB@ +SED = @SED@ +SEP = @SEP@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPHINXBUILD = @SPHINXBUILD@ +SRPD_PLUGINS_PATH = @SRPD_PLUGINS_PATH@ +SR_REPO_PATH = @SR_REPO_PATH@ +STRIP = @STRIP@ +SYSREPOCPP_VERSION = @SYSREPOCPP_VERSION@ +SYSREPO_CPPFLAGS = @SYSREPO_CPPFLAGS@ +SYSREPO_INCLUDEDIR = @SYSREPO_INCLUDEDIR@ +SYSREPO_LIBS = @SYSREPO_LIBS@ +SYSREPO_VERSION = @SYSREPO_VERSION@ +USE_LCOV = @USE_LCOV@ +VALGRIND = @VALGRIND@ +VERSION = @VERSION@ +WARNING_GCC_44_STRICT_ALIASING_CFLAG = @WARNING_GCC_44_STRICT_ALIASING_CFLAG@ +YACC = @YACC@ +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@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +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@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +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 = mysql pgsql +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/share/database/scripts/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/share/database/scripts/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# 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" +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 + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @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 +check-am: all-am +check: check-recursive +all-am: Makefile +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 clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic 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 Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-libtool \ + distclean-tags distdir 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 mostlyclean-libtool 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: diff --git a/src/share/database/scripts/mysql/Makefile.am b/src/share/database/scripts/mysql/Makefile.am new file mode 100644 index 0000000..29ba228 --- /dev/null +++ b/src/share/database/scripts/mysql/Makefile.am @@ -0,0 +1,40 @@ +SUBDIRS = . + +mysqldir = ${datarootdir}/${PACKAGE_NAME}/scripts/mysql + +# non-executable +mysql_DATA = +mysql_DATA += dhcpdb_create.mysql +mysql_DATA += dhcpdb_drop.mysql + +# executable +mysql_SCRIPTS = +mysql_SCRIPTS += upgrade_001.0_to_002.0.sh +mysql_SCRIPTS += upgrade_002.0_to_003.0.sh +mysql_SCRIPTS += upgrade_003.0_to_004.0.sh +mysql_SCRIPTS += upgrade_004.0_to_004.1.sh +mysql_SCRIPTS += upgrade_004.1_to_005.0.sh +mysql_SCRIPTS += upgrade_005.0_to_005.1.sh +mysql_SCRIPTS += upgrade_005.1_to_005.2.sh +mysql_SCRIPTS += upgrade_005.2_to_006.0.sh +mysql_SCRIPTS += upgrade_006.0_to_007.0.sh +mysql_SCRIPTS += upgrade_007.0_to_008.0.sh +mysql_SCRIPTS += upgrade_008.0_to_008.1.sh +mysql_SCRIPTS += upgrade_008.1_to_008.2.sh +mysql_SCRIPTS += upgrade_008.2_to_009.0.sh +mysql_SCRIPTS += upgrade_009.0_to_009.1.sh +mysql_SCRIPTS += upgrade_009.1_to_009.2.sh +mysql_SCRIPTS += upgrade_009.2_to_009.3.sh +mysql_SCRIPTS += upgrade_009.3_to_009.4.sh +mysql_SCRIPTS += upgrade_009.4_to_009.5.sh +mysql_SCRIPTS += upgrade_009.5_to_009.6.sh +mysql_SCRIPTS += upgrade_009.6_to_010.0.sh +mysql_SCRIPTS += upgrade_010_to_011.sh +mysql_SCRIPTS += upgrade_011_to_012.sh +mysql_SCRIPTS += upgrade_012_to_013.sh +mysql_SCRIPTS += upgrade_013_to_014.sh +mysql_SCRIPTS += wipe_data.sh + +DISTCLEANFILES = ${mysql_SCRIPTS} + +EXTRA_DIST = ${mysql_DATA} diff --git a/src/share/database/scripts/mysql/Makefile.in b/src/share/database/scripts/mysql/Makefile.in new file mode 100644 index 0000000..a85e34d --- /dev/null +++ b/src/share/database/scripts/mysql/Makefile.in @@ -0,0 +1,904 @@ +# Makefile.in generated by automake 1.16.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2018 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@ + + +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 = src/share/database/scripts/mysql +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4macros/ax_boost_for_kea.m4 \ + $(top_srcdir)/m4macros/ax_cpp11.m4 \ + $(top_srcdir)/m4macros/ax_crypto.m4 \ + $(top_srcdir)/m4macros/ax_find_library.m4 \ + $(top_srcdir)/m4macros/ax_gssapi.m4 \ + $(top_srcdir)/m4macros/ax_gtest.m4 \ + $(top_srcdir)/m4macros/ax_isc_rpath.m4 \ + $(top_srcdir)/m4macros/ax_sysrepo.m4 \ + $(top_srcdir)/m4macros/libtool.m4 \ + $(top_srcdir)/m4macros/ltoptions.m4 \ + $(top_srcdir)/m4macros/ltsugar.m4 \ + $(top_srcdir)/m4macros/ltversion.m4 \ + $(top_srcdir)/m4macros/lt~obsolete.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = upgrade_001.0_to_002.0.sh \ + upgrade_002.0_to_003.0.sh upgrade_003.0_to_004.0.sh \ + upgrade_004.0_to_004.1.sh upgrade_004.1_to_005.0.sh \ + upgrade_005.0_to_005.1.sh upgrade_005.1_to_005.2.sh \ + upgrade_005.2_to_006.0.sh upgrade_006.0_to_007.0.sh \ + upgrade_007.0_to_008.0.sh upgrade_008.0_to_008.1.sh \ + upgrade_008.1_to_008.2.sh upgrade_008.2_to_009.0.sh \ + upgrade_009.0_to_009.1.sh upgrade_009.1_to_009.2.sh \ + upgrade_009.2_to_009.3.sh upgrade_009.3_to_009.4.sh \ + upgrade_009.4_to_009.5.sh upgrade_009.5_to_009.6.sh \ + upgrade_009.6_to_010.0.sh upgrade_010_to_011.sh \ + upgrade_011_to_012.sh upgrade_012_to_013.sh \ + upgrade_013_to_014.sh wipe_data.sh +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(mysqldir)" "$(DESTDIR)$(mysqldir)" +SCRIPTS = $(mysql_SCRIPTS) +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 +DATA = $(mysql_DATA) +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 \ + distdir distdir-am +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# 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 +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in \ + $(srcdir)/upgrade_001.0_to_002.0.sh.in \ + $(srcdir)/upgrade_002.0_to_003.0.sh.in \ + $(srcdir)/upgrade_003.0_to_004.0.sh.in \ + $(srcdir)/upgrade_004.0_to_004.1.sh.in \ + $(srcdir)/upgrade_004.1_to_005.0.sh.in \ + $(srcdir)/upgrade_005.0_to_005.1.sh.in \ + $(srcdir)/upgrade_005.1_to_005.2.sh.in \ + $(srcdir)/upgrade_005.2_to_006.0.sh.in \ + $(srcdir)/upgrade_006.0_to_007.0.sh.in \ + $(srcdir)/upgrade_007.0_to_008.0.sh.in \ + $(srcdir)/upgrade_008.0_to_008.1.sh.in \ + $(srcdir)/upgrade_008.1_to_008.2.sh.in \ + $(srcdir)/upgrade_008.2_to_009.0.sh.in \ + $(srcdir)/upgrade_009.0_to_009.1.sh.in \ + $(srcdir)/upgrade_009.1_to_009.2.sh.in \ + $(srcdir)/upgrade_009.2_to_009.3.sh.in \ + $(srcdir)/upgrade_009.3_to_009.4.sh.in \ + $(srcdir)/upgrade_009.4_to_009.5.sh.in \ + $(srcdir)/upgrade_009.5_to_009.6.sh.in \ + $(srcdir)/upgrade_009.6_to_010.0.sh.in \ + $(srcdir)/upgrade_010_to_011.sh.in \ + $(srcdir)/upgrade_011_to_012.sh.in \ + $(srcdir)/upgrade_012_to_013.sh.in \ + $(srcdir)/upgrade_013_to_014.sh.in $(srcdir)/wipe_data.sh.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +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" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +ASCIIDOC = @ASCIIDOC@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOOST_INCLUDES = @BOOST_INCLUDES@ +BOOST_LIBS = @BOOST_LIBS@ +BOTAN_TOOL = @BOTAN_TOOL@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CONTRIB_DIR = @CONTRIB_DIR@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CRYPTO_CFLAGS = @CRYPTO_CFLAGS@ +CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ +CRYPTO_LDFLAGS = @CRYPTO_LDFLAGS@ +CRYPTO_LIBS = @CRYPTO_LIBS@ +CRYPTO_PACKAGE = @CRYPTO_PACKAGE@ +CRYPTO_RPATH = @CRYPTO_RPATH@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DISTCHECK_BOOST_CONFIGURE_FLAG = @DISTCHECK_BOOST_CONFIGURE_FLAG@ +DISTCHECK_CONTRIB_CONFIGURE_FLAG = @DISTCHECK_CONTRIB_CONFIGURE_FLAG@ +DISTCHECK_CRYPTO_CONFIGURE_FLAG = @DISTCHECK_CRYPTO_CONFIGURE_FLAG@ +DISTCHECK_GTEST_CONFIGURE_FLAG = @DISTCHECK_GTEST_CONFIGURE_FLAG@ +DISTCHECK_KEA_SHELL_CONFIGURE_FLAG = @DISTCHECK_KEA_SHELL_CONFIGURE_FLAG@ +DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG = @DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG@ +DISTCHECK_PERFDHCP_CONFIGURE_FLAG = @DISTCHECK_PERFDHCP_CONFIGURE_FLAG@ +DISTCHECK_PREMIUM_CONFIGURE_FLAG = @DISTCHECK_PREMIUM_CONFIGURE_FLAG@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GENHTML = @GENHTML@ +GREP = @GREP@ +GSSAPI_CFLAGS = @GSSAPI_CFLAGS@ +GSSAPI_LIBS = @GSSAPI_LIBS@ +GTEST_CONFIG = @GTEST_CONFIG@ +GTEST_INCLUDES = @GTEST_INCLUDES@ +GTEST_LDADD = @GTEST_LDADD@ +GTEST_LDFLAGS = @GTEST_LDFLAGS@ +GTEST_SOURCE = @GTEST_SOURCE@ +HAVE_SYSREPO = @HAVE_SYSREPO@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +KEA_CXXFLAGS = @KEA_CXXFLAGS@ +KEA_SRCID = @KEA_SRCID@ +KRB5_CONFIG = @KRB5_CONFIG@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LOG4CPLUS_INCLUDES = @LOG4CPLUS_INCLUDES@ +LOG4CPLUS_LIBS = @LOG4CPLUS_LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MYSQL_CPPFLAGS = @MYSQL_CPPFLAGS@ +MYSQL_LIBS = @MYSQL_LIBS@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +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@ +PACKAGE_VERSION_TYPE = @PACKAGE_VERSION_TYPE@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PDFLATEX = @PDFLATEX@ +PERL = @PERL@ +PGSQL_CPPFLAGS = @PGSQL_CPPFLAGS@ +PGSQL_LIBS = @PGSQL_LIBS@ +PKGPYTHONDIR = @PKGPYTHONDIR@ +PKG_CONFIG = @PKG_CONFIG@ +PLANTUML = @PLANTUML@ +PREMIUM_DIR = @PREMIUM_DIR@ +PYTHON = @PYTHON@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +RANLIB = @RANLIB@ +SED = @SED@ +SEP = @SEP@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPHINXBUILD = @SPHINXBUILD@ +SRPD_PLUGINS_PATH = @SRPD_PLUGINS_PATH@ +SR_REPO_PATH = @SR_REPO_PATH@ +STRIP = @STRIP@ +SYSREPOCPP_VERSION = @SYSREPOCPP_VERSION@ +SYSREPO_CPPFLAGS = @SYSREPO_CPPFLAGS@ +SYSREPO_INCLUDEDIR = @SYSREPO_INCLUDEDIR@ +SYSREPO_LIBS = @SYSREPO_LIBS@ +SYSREPO_VERSION = @SYSREPO_VERSION@ +USE_LCOV = @USE_LCOV@ +VALGRIND = @VALGRIND@ +VERSION = @VERSION@ +WARNING_GCC_44_STRICT_ALIASING_CFLAG = @WARNING_GCC_44_STRICT_ALIASING_CFLAG@ +YACC = @YACC@ +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@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +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@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +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 = . +mysqldir = ${datarootdir}/${PACKAGE_NAME}/scripts/mysql + +# non-executable +mysql_DATA = dhcpdb_create.mysql dhcpdb_drop.mysql + +# executable +mysql_SCRIPTS = upgrade_001.0_to_002.0.sh upgrade_002.0_to_003.0.sh \ + upgrade_003.0_to_004.0.sh upgrade_004.0_to_004.1.sh \ + upgrade_004.1_to_005.0.sh upgrade_005.0_to_005.1.sh \ + upgrade_005.1_to_005.2.sh upgrade_005.2_to_006.0.sh \ + upgrade_006.0_to_007.0.sh upgrade_007.0_to_008.0.sh \ + upgrade_008.0_to_008.1.sh upgrade_008.1_to_008.2.sh \ + upgrade_008.2_to_009.0.sh upgrade_009.0_to_009.1.sh \ + upgrade_009.1_to_009.2.sh upgrade_009.2_to_009.3.sh \ + upgrade_009.3_to_009.4.sh upgrade_009.4_to_009.5.sh \ + upgrade_009.5_to_009.6.sh upgrade_009.6_to_010.0.sh \ + upgrade_010_to_011.sh upgrade_011_to_012.sh \ + upgrade_012_to_013.sh upgrade_013_to_014.sh wipe_data.sh +DISTCLEANFILES = ${mysql_SCRIPTS} +EXTRA_DIST = ${mysql_DATA} +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/share/database/scripts/mysql/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/share/database/scripts/mysql/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +upgrade_001.0_to_002.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_001.0_to_002.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_002.0_to_003.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_002.0_to_003.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_003.0_to_004.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_003.0_to_004.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_004.0_to_004.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_004.0_to_004.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_004.1_to_005.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_004.1_to_005.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_005.0_to_005.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_005.0_to_005.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_005.1_to_005.2.sh: $(top_builddir)/config.status $(srcdir)/upgrade_005.1_to_005.2.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_005.2_to_006.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_005.2_to_006.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_006.0_to_007.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_006.0_to_007.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_007.0_to_008.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_007.0_to_008.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_008.0_to_008.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_008.0_to_008.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_008.1_to_008.2.sh: $(top_builddir)/config.status $(srcdir)/upgrade_008.1_to_008.2.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_008.2_to_009.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_008.2_to_009.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.0_to_009.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.0_to_009.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.1_to_009.2.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.1_to_009.2.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.2_to_009.3.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.2_to_009.3.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.3_to_009.4.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.3_to_009.4.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.4_to_009.5.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.4_to_009.5.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.5_to_009.6.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.5_to_009.6.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009.6_to_010.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009.6_to_010.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_010_to_011.sh: $(top_builddir)/config.status $(srcdir)/upgrade_010_to_011.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_011_to_012.sh: $(top_builddir)/config.status $(srcdir)/upgrade_011_to_012.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_012_to_013.sh: $(top_builddir)/config.status $(srcdir)/upgrade_012_to_013.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_013_to_014.sh: $(top_builddir)/config.status $(srcdir)/upgrade_013_to_014.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +wipe_data.sh: $(top_builddir)/config.status $(srcdir)/wipe_data.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-mysqlSCRIPTS: $(mysql_SCRIPTS) + @$(NORMAL_INSTALL) + @list='$(mysql_SCRIPTS)'; test -n "$(mysqldir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(mysqldir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(mysqldir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n' \ + -e 'h;s|.*|.|' \ + -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) { files[d] = files[d] " " $$1; \ + if (++n[d] == $(am__install_max)) { \ + print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ + else { print "f", d "/" $$4, $$1 } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(mysqldir)$$dir'"; \ + $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(mysqldir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-mysqlSCRIPTS: + @$(NORMAL_UNINSTALL) + @list='$(mysql_SCRIPTS)'; test -n "$(mysqldir)" || exit 0; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 's,.*/,,;$(transform)'`; \ + dir='$(DESTDIR)$(mysqldir)'; $(am__uninstall_files_from_dir) + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-mysqlDATA: $(mysql_DATA) + @$(NORMAL_INSTALL) + @list='$(mysql_DATA)'; test -n "$(mysqldir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(mysqldir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(mysqldir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(mysqldir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(mysqldir)" || exit $$?; \ + done + +uninstall-mysqlDATA: + @$(NORMAL_UNINSTALL) + @list='$(mysql_DATA)'; test -n "$(mysqldir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(mysqldir)'; $(am__uninstall_files_from_dir) + +# 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" +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 + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @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 +check-am: all-am +check: check-recursive +all-am: Makefile $(SCRIPTS) $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(mysqldir)" "$(DESTDIR)$(mysqldir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +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) + -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + +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 clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-mysqlDATA install-mysqlSCRIPTS + +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 Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-mysqlDATA uninstall-mysqlSCRIPTS + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-libtool \ + distclean-tags distdir 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-mysqlDATA install-mysqlSCRIPTS 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 mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-am uninstall uninstall-am uninstall-mysqlDATA \ + uninstall-mysqlSCRIPTS + +.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: diff --git a/src/share/database/scripts/mysql/dhcpdb_create.mysql b/src/share/database/scripts/mysql/dhcpdb_create.mysql new file mode 100644 index 0000000..c4b0bdc --- /dev/null +++ b/src/share/database/scripts/mysql/dhcpdb_create.mysql @@ -0,0 +1,5094 @@ +# Copyright (C) 2012-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# This is the Kea schema specification for MySQL. +# +# The schema is reasonably portable (with the exception of the engine +# specification, which is MySQL-specific). Minor changes might be needed for +# other databases. + +# To create the schema, either type the command: +# +# mysql -u <user> -p <password> <database> < dhcpdb_create.mysql +# +# ... at the command prompt, or log in to the MySQL database and at the 'mysql>' +# prompt, issue the command: +# +# source dhcpdb_create.mysql +# +# This script is also called from kea-admin, see kea-admin db-init mysql +# +# Over time, Kea database schema will evolve. Each version is marked with +# major.minor version. This file is organized sequentially, i.e. database +# is initialized to 1.0, then upgraded to 2.0 etc. This may be somewhat +# sub-optimal, but it ensues consistency with upgrade scripts. (It is much +# easier to maintain init and upgrade scripts if they look the same). +# Since initialization is done only once, it's performance is not an issue. + +# This line starts database initialization to 1.0. + +# Holds the IPv4 leases. +CREATE TABLE lease4 ( + address INT UNSIGNED PRIMARY KEY NOT NULL, # IPv4 address + hwaddr VARBINARY(20), # Hardware address + client_id VARBINARY(128), # Client ID + valid_lifetime INT UNSIGNED, # Length of the lease (seconds) + expire TIMESTAMP, # Expiration time of the lease + subnet_id INT UNSIGNED, # Subnet identification + fqdn_fwd BOOL, # Has forward DNS update been performed by a server + fqdn_rev BOOL, # Has reverse DNS update been performed by a server + hostname VARCHAR(255) # The FQDN of the client + ) ENGINE = INNODB; + + +# Create search indexes for lease4 table +# index by hwaddr and subnet_id +CREATE INDEX lease4_by_hwaddr_subnet_id ON lease4 (hwaddr, subnet_id); + +# index by client_id and subnet_id +CREATE INDEX lease4_by_client_id_subnet_id ON lease4 (client_id, subnet_id); + +# Holds the IPv6 leases. +# N.B. The use of a VARCHAR for the address is temporary for development: +# it will eventually be replaced by BINARY(16). +CREATE TABLE lease6 ( + address VARCHAR(39) PRIMARY KEY NOT NULL, # IPv6 address + duid VARBINARY(128), # DUID + valid_lifetime INT UNSIGNED, # Length of the lease (seconds) + expire TIMESTAMP, # Expiration time of the lease + subnet_id INT UNSIGNED, # Subnet identification + pref_lifetime INT UNSIGNED, # Preferred lifetime + lease_type TINYINT, # Lease type (see lease6_types + # table for possible values) + iaid INT UNSIGNED, # See Section 12 of RFC 8415 + prefix_len TINYINT UNSIGNED, # For IA_PD only + fqdn_fwd BOOL, # Has forward DNS update been performed by a server + fqdn_rev BOOL, # Has reverse DNS update been performed by a server + hostname VARCHAR(255) # The FQDN of the client + + ) ENGINE = INNODB; + +# Create search indexes for lease4 table +# index by iaid, subnet_id, and duid +CREATE INDEX lease6_by_iaid_subnet_id_duid ON lease6 (iaid, subnet_id, duid); + +# ... and a definition of lease6 types. This table is a convenience for +# users of the database - if they want to view the lease table and use the +# type names, they can join this table with the lease6 table. +# Make sure those values match Lease6::LeaseType enum (see src/bin/dhcpsrv/ +# lease_mgr.h) +CREATE TABLE lease6_types ( + lease_type TINYINT PRIMARY KEY NOT NULL, # Lease type code. + name VARCHAR(5) # Name of the lease type + ) ENGINE = INNODB; + +START TRANSACTION; +INSERT INTO lease6_types VALUES (0, 'IA_NA'); # Non-temporary v6 addresses +INSERT INTO lease6_types VALUES (1, 'IA_TA'); # Temporary v6 addresses +INSERT INTO lease6_types VALUES (2, 'IA_PD'); # Prefix delegations +COMMIT; + +# Finally, the version of the schema. We start at 1.0 during development. +# This table is only modified during schema upgrades. For historical reasons +# (related to the names of the columns in the BIND 10 DNS database file), the +# first column is called 'version' and not 'major'. +CREATE TABLE schema_version ( + version INT PRIMARY KEY NOT NULL, # Major version number + minor INT # Minor version number + ) ENGINE = INNODB; +START TRANSACTION; +INSERT INTO schema_version VALUES (1, 0); +COMMIT; + +# This line concludes database initialization to version 1.0. + +# This line starts database upgrade to version 2.0. +ALTER TABLE lease6 + ADD COLUMN hwaddr varbinary(20), # Hardware/MAC address, typically only 6 + # bytes is used, but some hardware (e.g. + # Infiniband) use up to 20. + ADD COLUMN hwtype smallint unsigned, # hardware type (16 bits) + ADD COLUMN hwaddr_source int unsigned; # Hardware source. See description + # of lease_hwaddr_source below. + +# Kea keeps track of the hardware/MAC address source, i.e. how the address +# was obtained. Depending on the technique and your network topology, it may +# be more or less trustworthy. This table is a convenience for +# users of the database - if they want to view the lease table and use the +# type names, they can join this table with the lease6 table. For details, +# see constants defined in src/lib/dhcp/dhcp/pkt.h for detailed explanation. +CREATE TABLE lease_hwaddr_source ( + hwaddr_source INT PRIMARY KEY NOT NULL, + name VARCHAR(40) +) ENGINE = INNODB; + +# Hardware address obtained from raw sockets +INSERT INTO lease_hwaddr_source VALUES (1, 'HWADDR_SOURCE_RAW'); + +# Hardware address converted from IPv6 link-local address with EUI-64 +INSERT INTO lease_hwaddr_source VALUES (2, 'HWADDR_SOURCE_IPV6_LINK_LOCAL'); + +# Hardware address extracted from client-id (duid) +INSERT INTO lease_hwaddr_source VALUES (4, 'HWADDR_SOURCE_DUID'); + +# Hardware address extracted from client address relay option (RFC6939) +INSERT INTO lease_hwaddr_source VALUES (8, 'HWADDR_SOURCE_CLIENT_ADDR_RELAY_OPTION'); + +# Hardware address extracted from remote-id option (RFC4649) +INSERT INTO lease_hwaddr_source VALUES (16, 'HWADDR_SOURCE_REMOTE_ID'); + +# Hardware address extracted from subscriber-id option (RFC4580) +INSERT INTO lease_hwaddr_source VALUES (32, 'HWADDR_SOURCE_SUBSCRIBER_ID'); + +# Hardware address extracted from docsis options +INSERT INTO lease_hwaddr_source VALUES (64, 'HWADDR_SOURCE_DOCSIS'); + +UPDATE schema_version SET version='2', minor='0'; + +# This line concludes database upgrade to version 2.0. + +# This line starts database upgrade to version 3.0. +# Upgrade extending MySQL schema with the ability to store hosts. + +CREATE TABLE IF NOT EXISTS hosts ( + host_id INT UNSIGNED NOT NULL AUTO_INCREMENT, + dhcp_identifier VARBINARY(128) NOT NULL, + dhcp_identifier_type TINYINT NOT NULL, + dhcp4_subnet_id INT UNSIGNED NULL, + dhcp6_subnet_id INT UNSIGNED NULL, + ipv4_address INT UNSIGNED NULL, + hostname VARCHAR(255) NULL, + dhcp4_client_classes VARCHAR(255) NULL, + dhcp6_client_classes VARCHAR(255) NULL, + PRIMARY KEY (host_id), + INDEX key_dhcp4_identifier_subnet_id (dhcp_identifier ASC , dhcp_identifier_type ASC), + INDEX key_dhcp6_identifier_subnet_id (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp6_subnet_id ASC) +) ENGINE=INNODB; +-- ----------------------------------------------------- +-- Table `ipv6_reservations` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS ipv6_reservations ( + reservation_id INT NOT NULL AUTO_INCREMENT, + address VARCHAR(39) NOT NULL, + prefix_len TINYINT(3) UNSIGNED NOT NULL DEFAULT 128, + type TINYINT(4) UNSIGNED NOT NULL DEFAULT 0, + dhcp6_iaid INT UNSIGNED NULL, + host_id INT UNSIGNED NOT NULL, + PRIMARY KEY (reservation_id), + INDEX fk_ipv6_reservations_host_idx (host_id ASC), + CONSTRAINT fk_ipv6_reservations_Host FOREIGN KEY (host_id) + REFERENCES hosts (host_id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=INNODB; +-- ----------------------------------------------------- +-- Table `dhcp4_options` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_options ( + option_id INT UNSIGNED NOT NULL AUTO_INCREMENT, + code TINYINT UNSIGNED NOT NULL, + value BLOB NULL, + formatted_value TEXT NULL, + space VARCHAR(128) NULL, + persistent TINYINT(1) NOT NULL DEFAULT 0, + dhcp_client_class VARCHAR(128) NULL, + dhcp4_subnet_id INT NULL, + host_id INT UNSIGNED NULL, + PRIMARY KEY (option_id), + UNIQUE INDEX option_id_UNIQUE (option_id ASC), + INDEX fk_options_host1_idx (host_id ASC), + CONSTRAINT fk_options_host1 FOREIGN KEY (host_id) + REFERENCES hosts (host_id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=INNODB; +-- ----------------------------------------------------- +-- Table `dhcp6_options` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_options ( + option_id INT UNSIGNED NOT NULL AUTO_INCREMENT, + code INT UNSIGNED NOT NULL, + value BLOB NULL, + formatted_value TEXT NULL, + space VARCHAR(128) NULL, + persistent TINYINT(1) NOT NULL DEFAULT 0, + dhcp_client_class VARCHAR(128) NULL, + dhcp6_subnet_id INT NULL, + host_id INT UNSIGNED NULL, + PRIMARY KEY (option_id), + UNIQUE INDEX option_id_UNIQUE (option_id ASC), + INDEX fk_options_host1_idx (host_id ASC), + CONSTRAINT fk_options_host10 FOREIGN KEY (host_id) + REFERENCES hosts (host_id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=INNODB; + +DELIMITER $$ +CREATE TRIGGER host_BDEL BEFORE DELETE ON hosts FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM ipv6_reservations WHERE ipv6_reservations.host_id = OLD.host_id; +END +$$ +DELIMITER ; + +UPDATE schema_version +SET version = '3', minor = '0'; +# This line concludes database upgrade to version 3.0. + +# This line starts database upgrade to version 4.0. +# Upgrade extending MySQL schema with the state columns for lease tables. + +# Add state column to the lease4 table. +ALTER TABLE lease4 + ADD COLUMN state INT UNSIGNED DEFAULT 0; + +# Add state column to the lease6 table. +ALTER TABLE lease6 + ADD COLUMN state INT UNSIGNED DEFAULT 0; + +# Create indexes for querying leases in a given state and segregated +# by the expiration time. One of the applications is to retrieve all +# expired leases. However, these indexes can be also used to retrieve +# leases in a given state regardless of the expiration time. +CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC); +CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC); + +# Create table holding mapping of the lease states to their names. +# This is not used in queries from the DHCP server but rather in +# direct queries from the lease database management tools. +CREATE TABLE IF NOT EXISTS lease_state ( + state INT UNSIGNED PRIMARY KEY NOT NULL, + name VARCHAR(64) NOT NULL +) ENGINE=INNODB; + +# Insert currently defined state names. +INSERT INTO lease_state VALUES (0, 'default'); +INSERT INTO lease_state VALUES (1, 'declined'); +INSERT INTO lease_state VALUES (2, 'expired-reclaimed'); + +# Add a constraint that any state value added to the lease4 must +# map to a value in the lease_state table. +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +# Add a constraint that any state value added to the lease6 must +# map to a value in the lease_state table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +# Add a constraint that lease type in the lease6 table must map +# to a lease type defined in the lease6_types table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type); + +# Modify the name of one of the HW address sources, and add a new one. +UPDATE lease_hwaddr_source + SET name = 'HWADDR_SOURCE_DOCSIS_CMTS' + WHERE hwaddr_source = 64; + +INSERT INTO lease_hwaddr_source VALUES (128, 'HWADDR_SOURCE_DOCSIS_MODEM'); + +# Add UNSIGNED to match with the lease6. +ALTER TABLE lease_hwaddr_source + MODIFY COLUMN hwaddr_source INT UNSIGNED NOT NULL; + +# Add a constraint that non-null hwaddr_source in the lease6 table +# must map to an entry in the lease_hwaddr_source. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_hwaddr_source FOREIGN KEY (hwaddr_source) + REFERENCES lease_hwaddr_source (hwaddr_source); + +# Procedure that returns a result set containing the column names for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease4DumpHeader() +BEGIN +SELECT 'address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state'; +END $$ +DELIMITER ; + +# Procedure that returns a result set containing the data for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN +SELECT + INET_NTOA(l.address), + IFNULL(HEX(l.hwaddr), ''), + IFNULL(HEX(l.client_id), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + s.name +FROM + lease4 l + LEFT OUTER JOIN lease_state s on (l.state = s.state) +ORDER BY l.address; +END $$ +DELIMITER ; + +# Procedure that returns a result set containing the column names for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN +SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,hwtype,hwaddr_source,state'; +END $$ +DELIMITER ; + +# Procedure that returns a result set containing the data for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN +SELECT + l.address, + IFNULL(HEX(l.duid), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + IFNULL(t.name, ''), + l.iaid, + l.prefix_len, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + IFNULL(HEX(l.hwaddr), ''), + IFNULL(l.hwtype, ''), + IFNULL(h.name, ''), + IFNULL(s.name, '') +FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) +ORDER BY l.address; +END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '4', minor = '0'; + +# This line concludes database upgrade to version 4.0. + +# In the event hardware address cannot be determined, we need to satisfy +# foreign key constraint between lease6 and lease_hardware_source +INSERT INTO lease_hwaddr_source VALUES (0, 'HWADDR_SOURCE_UNKNOWN'); + +# Update the schema version number +UPDATE schema_version +SET version = '4', minor = '1'; + +# This line concludes database upgrade to version 4.1. + +# Update index used for searching DHCPv4 reservations by identifier and subnet id. +# This index is now unique (to prevent duplicates) and includes DHCPv4 subnet +# identifier. +DROP INDEX key_dhcp4_identifier_subnet_id ON hosts; +CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id ON hosts (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp4_subnet_id ASC); + +# Update index used for searching DHCPv6 reservations by identifier and subnet id. +# This index is now unique to prevent duplicates. +DROP INDEX key_dhcp6_identifier_subnet_id ON hosts; +CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id ON hosts (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp6_subnet_id ASC); + +# Create index to search for reservations using IP address and subnet id. +# This unique index guarantees that there is only one occurrence of the +# particular IPv4 address for a given subnet. +CREATE UNIQUE INDEX key_dhcp4_ipv4_address_subnet_id ON hosts (ipv4_address ASC , dhcp4_subnet_id ASC); + +# Create index to search for reservations using address/prefix and prefix +# length. +CREATE UNIQUE INDEX key_dhcp6_address_prefix_len ON ipv6_reservations (address ASC , prefix_len ASC); + +# Create a table mapping host identifiers to their names. Values in this +# table are used as a foreign key in hosts table to guarantee that only +# identifiers present in host_identifier_type table are used in hosts +# table. +CREATE TABLE IF NOT EXISTS host_identifier_type ( + type TINYINT PRIMARY KEY NOT NULL, # Lease type code. + name VARCHAR(32) # Name of the lease type +) ENGINE = INNODB; + +START TRANSACTION; +INSERT INTO host_identifier_type VALUES (0, 'hw-address'); +INSERT INTO host_identifier_type VALUES (1, 'duid'); +INSERT INTO host_identifier_type VALUES (2, 'circuit-id'); +COMMIT; + +# Add a constraint that any identifier type value added to the hosts +# must map to a value in the host_identifier_type table. +ALTER TABLE hosts + ADD CONSTRAINT fk_host_identifier_type FOREIGN KEY (dhcp_identifier_type) + REFERENCES host_identifier_type (type); + +# Store DHCPv6 option code as 16-bit unsigned integer. +ALTER TABLE dhcp6_options MODIFY code SMALLINT UNSIGNED NOT NULL; + +# Subnet identifier is unsigned. +ALTER TABLE dhcp4_options MODIFY dhcp4_subnet_id INT UNSIGNED NULL; +ALTER TABLE dhcp6_options MODIFY dhcp6_subnet_id INT UNSIGNED NULL; + +# Scopes associate DHCP options stored in dhcp4_options and +# dhcp6_options tables with hosts, subnets, classes or indicate +# that they are global options. +CREATE TABLE IF NOT EXISTS dhcp_option_scope ( + scope_id TINYINT UNSIGNED PRIMARY KEY NOT NULL, + scope_name VARCHAR(32) +) ENGINE = INNODB; + +START TRANSACTION; +INSERT INTO dhcp_option_scope VALUES (0, 'global'); +INSERT INTO dhcp_option_scope VALUES (1, 'subnet'); +INSERT INTO dhcp_option_scope VALUES (2, 'client-class'); +INSERT INTO dhcp_option_scope VALUES (3, 'host'); +COMMIT; + +# Add scopes into table holding DHCPv4 options +ALTER TABLE dhcp4_options ADD COLUMN scope_id TINYINT UNSIGNED NOT NULL; +ALTER TABLE dhcp4_options + ADD CONSTRAINT fk_dhcp4_option_scope FOREIGN KEY (scope_id) + REFERENCES dhcp_option_scope (scope_id); + +# Add scopes into table holding DHCPv6 options +ALTER TABLE dhcp6_options ADD COLUMN scope_id TINYINT UNSIGNED NOT NULL; +ALTER TABLE dhcp6_options + ADD CONSTRAINT fk_dhcp6_option_scope FOREIGN KEY (scope_id) + REFERENCES dhcp_option_scope (scope_id); + +# Add UNSIGNED to reservation_id +ALTER TABLE ipv6_reservations + MODIFY reservation_id INT UNSIGNED NOT NULL AUTO_INCREMENT; + +# This line concludes database upgrade to version 7.0. + +# Add columns holding reservations for siaddr, sname and file fields +# carried within DHCPv4 message. +ALTER TABLE hosts ADD COLUMN dhcp4_next_server INT UNSIGNED NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_server_hostname VARCHAR(64) NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_boot_file_name VARCHAR(128) NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '0'; +# This line concludes database upgrade to version 5.0. + +# Add missing 'client-id' and new 'flex-id' host identifier types. +INSERT INTO host_identifier_type VALUES (3, 'client-id'); +INSERT INTO host_identifier_type VALUES (4, 'flex-id'); + +# Recreate the trigger removing dependent host entries. +DROP TRIGGER host_BDEL; + +DELIMITER $$ +CREATE TRIGGER host_BDEL BEFORE DELETE ON hosts FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM ipv6_reservations WHERE ipv6_reservations.host_id = OLD.host_id; +DELETE FROM dhcp4_options WHERE dhcp4_options.host_id = OLD.host_id; +DELETE FROM dhcp6_options WHERE dhcp6_options.host_id = OLD.host_id; +END +$$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '1'; +# This line concludes database upgrade to version 5.1. + +# Make subnet_id column types consistent with lease table columns +ALTER TABLE dhcp4_options MODIFY dhcp4_subnet_id INT UNSIGNED; +ALTER TABLE dhcp6_options MODIFY dhcp6_subnet_id INT UNSIGNED; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '2'; + +# This line concludes database upgrade to version 5.2. + +# Add user context into table holding hosts +ALTER TABLE hosts ADD COLUMN user_context TEXT NULL; + +# Add user contexts into tables holding DHCP options +ALTER TABLE dhcp4_options ADD COLUMN user_context TEXT NULL; +ALTER TABLE dhcp6_options ADD COLUMN user_context TEXT NULL; + +# Create index for searching leases by subnet identifier. +CREATE INDEX lease4_by_subnet_id ON lease4 (subnet_id); + +# Create for searching leases by subnet identifier and lease type. +CREATE INDEX lease6_by_subnet_id_lease_type ON lease6 (subnet_id, lease_type); + +# The index by iaid_subnet_id_duid is not the best choice because there are +# cases when we don't specify subnet identifier while searching leases. The +# index will be universal if the subnet_id is the right most column in the +# index. +DROP INDEX lease6_by_iaid_subnet_id_duid on lease6; +CREATE INDEX lease6_by_duid_iaid_subnet_id ON lease6 (duid, iaid, subnet_id); + +# Create lease4_stat table +CREATE TABLE lease4_stat ( + subnet_id INT UNSIGNED NOT NULL, + state INT UNSIGNED NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, state) +) ENGINE = INNODB; + +# Create stat_lease4_insert trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_insert AFTER INSERT ON lease4 + FOR EACH ROW + BEGIN + IF NEW.state = 0 OR NEW.state = 1 THEN + # Update the state count if it exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert the state count record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease4_update trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_update AFTER UPDATE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease4_delete trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_delete AFTER DELETE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + END $$ +DELIMITER ; + +# Create lease6_stat table +CREATE TABLE lease6_stat ( + subnet_id INT UNSIGNED NOT NULL, + lease_type INT UNSIGNED NOT NULL, + state INT UNSIGNED NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, lease_type, state) +) ENGINE = INNODB; + +# Create stat_lease6_insert trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_insert AFTER INSERT ON lease6 + FOR EACH ROW + BEGIN + IF NEW.state = 0 OR NEW.state = 1 THEN + # Update the state count if it exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE + subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert the state count record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease6_update trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_update AFTER UPDATE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease6_delete trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_delete AFTER DELETE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '6', minor = '0'; + +# This line concludes database upgrade to version 6.0. + +# Add user context into tables holding leases +ALTER TABLE lease4 ADD COLUMN user_context TEXT NULL; +ALTER TABLE lease6 ADD COLUMN user_context TEXT NULL; + +DROP PROCEDURE IF EXISTS lease4DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease4DumpHeader() +BEGIN +SELECT 'address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context'; +END $$ +DELIMITER ; + +# Procedure that returns a result set containing the data for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN +SELECT + INET_NTOA(l.address), + IFNULL(HEX(l.hwaddr), ''), + IFNULL(HEX(l.client_id), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + s.name, + IFNULL(l.user_context, '') +FROM + lease4 l + LEFT OUTER JOIN lease_state s on (l.state = s.state) +ORDER BY l.address; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN +SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,hwtype,hwaddr_source,state,user_context'; +END $$ +DELIMITER ; + +# Procedure that returns a result set containing the data for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN +SELECT + l.address, + IFNULL(HEX(l.duid), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + IFNULL(t.name, ''), + l.iaid, + l.prefix_len, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + IFNULL(HEX(l.hwaddr), ''), + IFNULL(l.hwtype, ''), + IFNULL(h.name, ''), + IFNULL(s.name, ''), + IFNULL(l.user_context, '') +FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) +ORDER BY l.address; +END $$ +DELIMITER ; + +# Create logs table (logs table is used by forensic logging hook library) +CREATE TABLE logs ( + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, # creation timestamp + address VARCHAR(43) NULL, # address or prefix + log TEXT NOT NULL # the log itself + ) ENGINE = INNODB; + +# Create search index +CREATE INDEX timestamp_index ON logs (timestamp); + +#add auth key for reconfiguration +ALTER TABLE hosts + ADD COLUMN auth_key VARCHAR(16) NULL; + + +# Add scope for shared network specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(4, "shared-network"); + +# Add scope for pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(5, "pool"); + +# Add scope for PD pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(6, "pd-pool"); + +-- ----------------------------------------------------- +-- Table `modification` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS modification ( + id TINYINT(3) NOT NULL, + modification_type VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +) ENGINE=InnoDB; + +INSERT INTO modification(id, modification_type) + VALUES(0, "create"); + +INSERT INTO modification(id, modification_type) + VALUES(1, "update"); + +INSERT INTO modification(id, modification_type) + VALUES(2, "delete"); + +-- ----------------------------------------------------- +-- Table `dhcp4_server` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_server ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + tag VARCHAR(64) NOT NULL, + description TEXT, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY dhcp4_server_tag_UNIQUE (tag), + KEY key_dhcp4_server_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Special server entry meaning "all servers". This refers to +# the configuration entries owned by all servers. +INSERT INTO dhcp4_server(id, tag, description, modification_ts) + VALUES(1, "all", "special type: all servers", NOW()); + +-- ----------------------------------------------------- +-- Table `dhcp4_audit` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_audit ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT(20) UNSIGNED NOT NULL, + modification_type TINYINT(1) NOT NULL, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + PRIMARY KEY (id), + KEY key_dhcp4_audit_by_modification_ts (modification_ts), + KEY fk_dhcp4_audit_modification_type (modification_type), + CONSTRAINT fk_dhcp4_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + + +-- ----------------------------------------------------- +-- Table `dhcp4_global_parameter` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_global_parameter ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + value LONGTEXT NOT NULL, + modification_ts timestamp NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp4_global_parameter_modification_ts (modification_ts), + KEY key_dhcp4_global_parameter_name (name) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_global_parameter_server` +-- M-to-M cross-reference between global parameters and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_global_parameter_server ( + parameter_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (parameter_id, server_id), + KEY fk_dhcp4_global_parameter_server_server_id (server_id), + KEY key_dhcp4_global_parameter_server (modification_ts), + CONSTRAINT fk_dhcp4_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp4_global_parameter (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_option_def` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_option_def ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + code SMALLINT UNSIGNED NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type TINYINT UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + is_array TINYINT(1) NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR(512) DEFAULT NULL, + user_context LONGTEXT, + PRIMARY KEY (id), + KEY key_dhcp4_option_def_modification_ts (modification_ts), + KEY key_dhcp4_option_def_code_space (code, space) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_option_def_server` +-- M-to-M cross-reference between option definitions and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_option_def_server ( + option_def_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_def_id, server_id), + KEY fk_dhcp4_option_def_server_server_id_idx (server_id), + KEY key_dhcp4_option_def_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp4_option_def (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_shared_network` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_shared_network ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id TINYINT(1) NOT NULL DEFAULT '1', + modification_ts TIMESTAMP NOT NULL, + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT DEFAULT NULL, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp4_shared_network_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_shared_network_server` +-- M-to-M cross-reference between shared networks and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_shared_network_server ( + shared_network_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (shared_network_id, server_id), + KEY key_dhcp4_shared_network_server_modification_ts (modification_ts), + KEY fk_dhcp4_shared_network_server_server_id (server_id), + CONSTRAINT fk_dhcp4_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp4_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_subnet` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_subnet ( + subnet_id INT(10) UNSIGNED NOT NULL, + subnet_prefix VARCHAR(32) NOT NULL, + 4o6_interface VARCHAR(128) DEFAULT NULL, + 4o6_interface_id VARCHAR(128) DEFAULT NULL, + 4o6_subnet VARCHAR(64) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id TINYINT(1) NOT NULL DEFAULT '1', + modification_ts TIMESTAMP NOT NULL, + next_server INT(10) UNSIGNED DEFAULT NULL, + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT DEFAULT NULL, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + server_hostname VARCHAR(512) DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (subnet_id), + UNIQUE KEY subnet4_subnet_prefix (subnet_prefix), + KEY fk_dhcp4_subnet_shared_network (shared_network_name), + KEY key_dhcp4_subnet_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_pool` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + start_address INT(10) UNSIGNED NOT NULL, + end_address INT(10) UNSIGNED NOT NULL, + subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp4_pool_modification_ts (modification_ts), + KEY fk_dhcp4_pool_subnet_id (subnet_id), + CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp4_subnet_server` +-- M-to-M cross-reference between subnets and servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_subnet_server ( + subnet_id INT(10) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (subnet_id,server_id), + KEY fk_dhcp4_subnet_server_server_id_idx (server_id), + KEY key_dhcp4_subnet_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_subnet_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + + +# Modify the primary key to BINGINT as other tables have. +ALTER TABLE dhcp4_options MODIFY option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; + +# Add configuration backend specific columns. +ALTER TABLE dhcp4_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP NOT NULL; + +-- ----------------------------------------------------- +-- Table `dhcp4_options_server` +-- M-to-M cross-reference between options and servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_options_server ( + option_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_id, server_id), + KEY fk_dhcp4_options_server_server_id (server_id), + KEY key_dhcp4_options_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp4_options (option_id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp4_pool_BDEL BEFORE DELETE ON dhcp4_pool FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM dhcp4_options WHERE scope_id = 5 AND pool_id = OLD.id; +END +$$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Table `dhcp6_server` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_server ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + tag VARCHAR(64) NOT NULL, + description TEXT, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY dhcp6_server_tag_UNIQUE (tag), + KEY key_dhcp6_server_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Special server entry meaning "all servers". This refers to +# the configuration entries owned by all servers. +INSERT INTO dhcp6_server(id, tag, description, modification_ts) + VALUES(1, "all", "special type: all servers", NOW()); + +-- ----------------------------------------------------- +-- Table `dhcp6_audit` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_audit ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT(20) UNSIGNED NOT NULL, + modification_type TINYINT(1) NOT NULL, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + PRIMARY KEY (id), + KEY key_dhcp6_audit_modification_ts (modification_ts), + KEY fk_dhcp6_audit_modification_type (modification_type), + CONSTRAINT fk_dhcp6_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_global_parameter` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_global_parameter ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + value LONGTEXT NOT NULL, + modification_ts timestamp NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp6_global_parameter_modification_ts (modification_ts), + KEY key_dhcp6_global_parameter_name (name) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_global_parameter_server` +-- M-to-M cross-reference between global parameters and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_global_parameter_server ( + parameter_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (parameter_id, server_id), + KEY fk_dhcp6_global_parameter_server_server_id (server_id), + KEY key_dhcp6_global_parameter_server (modification_ts), + CONSTRAINT fk_dhcp6_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp6_global_parameter (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_option_def` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_option_def ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + code SMALLINT UNSIGNED NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type TINYINT UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + is_array TINYINT(1) NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR(512) DEFAULT NULL, + user_context LONGTEXT, + PRIMARY KEY (id), + KEY key_dhcp6_option_def_modification_ts (modification_ts), + KEY key_dhcp6_option_def_code_space (code, space) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_option_def_server` +-- M-to-M cross-reference between option definitions and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_option_def_server ( + option_def_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_def_id, server_id), + KEY fk_dhcp6_option_def_server_server_id_idx (server_id), + KEY key_dhcp6_option_def_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp6_option_def (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_shared_network` +-- ----------------------------------------------------- +CREATE TABLE dhcp6_shared_network ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + preferred_lifetime INT(10) DEFAULT NULL, + rapid_commit TINYINT(1) NOT NULL DEFAULT '1', + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT DEFAULT NULL, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp6_shared_network_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_shared_network_server` +-- M-to-M cross-reference between shared networks and +-- servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_shared_network_server ( + shared_network_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + KEY key_dhcp6_shared_network_server_modification_ts (modification_ts), + KEY fk_dhcp6_shared_network_server_server_id_idx (server_id), + KEY fk_dhcp6_shared_network_server_shared_network_id (shared_network_id), + CONSTRAINT fk_dhcp6_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_subnet` +-- ----------------------------------------------------- +CREATE TABLE dhcp6_subnet ( + subnet_id INT(10) UNSIGNED NOT NULL, + subnet_prefix VARCHAR(64) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + preferred_lifetime INT(10) DEFAULT NULL, + rapid_commit TINYINT(1) NOT NULL DEFAULT '1', + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT DEFAULT NULL, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (subnet_id), + UNIQUE KEY subnet_prefix_UNIQUE (subnet_prefix), + KEY subnet6_subnet_prefix (subnet_prefix), + KEY fk_dhcp6_subnet_shared_network (shared_network_name), + KEY key_dhcp6_subnet_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_subnet_server` +-- M-to-M cross-reference between subnets and servers +-- ----------------------------------------------------- +CREATE TABLE dhcp6_subnet_server ( + subnet_id INT(10) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (subnet_id, server_id), + KEY fk_dhcp6_subnet_server_server_id (server_id), + KEY key_dhcp6_subnet_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_subnet_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_pd_pool` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_pd_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + prefix VARCHAR(45) NOT NULL, + prefix_length TINYINT(3) NOT NULL, + delegated_prefix_length TINYINT(3) NOT NULL, + dhcp6_subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY fk_dhcp6_pd_pool_subnet_id (dhcp6_subnet_id), + KEY key_dhcp6_pd_pool_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Table `dhcp6_pool` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + start_address VARCHAR(45) NOT NULL, + end_address VARCHAR(45) NOT NULL, + dhcp6_subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY fk_dhcp6_pool_subnet_id (dhcp6_subnet_id), + KEY key_dhcp6_pool_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +# Modify the primary key to BINGINT as other tables have. +ALTER TABLE dhcp6_options MODIFY option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; + +# Add configuration backend specific columns. +ALTER TABLE dhcp6_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN pd_pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP NOT NULL; + +-- ----------------------------------------------------- +-- Table `dhcp6_options_server` +-- M-to-M cross-reference between options and servers +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_options_server ( + option_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_id, server_id), + KEY fk_dhcp6_options_server_server_id_idx (server_id), + KEY key_dhcp6_options_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp6_pool_BDEL BEFORE DELETE ON dhcp6_pool FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM dhcp6_options WHERE scope_id = 5 AND pool_id = OLD.id; +END +$$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '7', minor = '0'; + +# This line concludes database upgrade to version 7.0. + + +ALTER TABLE dhcp4_options + MODIFY COLUMN modification_ts TIMESTAMP NOT NULL + DEFAULT CURRENT_TIMESTAMP; + +ALTER TABLE dhcp6_options + MODIFY COLUMN modification_ts TIMESTAMP NOT NULL + DEFAULT CURRENT_TIMESTAMP; + +ALTER TABLE dhcp4_subnet + ADD COLUMN authoritative TINYINT(1) DEFAULT NULL, + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + MODIFY COLUMN match_client_id TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN authoritative TINYINT(1) DEFAULT NULL, + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN boot_file_name VARCHAR(512) DEFAULT NULL, + ADD COLUMN next_server INT(10) UNSIGNED DEFAULT NULL, + ADD COLUMN server_hostname VARCHAR(512) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + MODIFY COLUMN match_client_id TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN interface_id VARBINARY(128) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + MODIFY COLUMN rapid_commit TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN interface_id VARBINARY(128) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + MODIFY COLUMN rapid_commit TINYINT(1) DEFAULT NULL; + +-- ----------------------------------------------------- +-- Make sure that constraints on the 7.0 schema tables +-- have appropriate referential actions. All tables +-- which join the configuration elements with the +-- servers should perform cascade deletion. +-- ----------------------------------------------------- + +ALTER TABLE dhcp4_global_parameter_server + DROP FOREIGN KEY fk_dhcp4_global_parameter_server_server_id; + +ALTER TABLE dhcp4_global_parameter_server + ADD CONSTRAINT fk_dhcp4_global_parameter_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_option_def_server + DROP FOREIGN KEY fk_dhcp4_option_def_server_server_id; + +ALTER TABLE dhcp4_option_def_server + ADD CONSTRAINT fk_dhcp4_option_def_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_shared_network_server + DROP FOREIGN KEY fk_dhcp4_shared_network_server_server_id; + +ALTER TABLE dhcp4_shared_network_server + ADD CONSTRAINT fk_dhcp4_shared_network_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_subnet_server + DROP FOREIGN KEY fk_dhcp4_subnet_server_server_id; + +ALTER TABLE dhcp4_subnet_server + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_options_server + DROP FOREIGN KEY fk_dhcp4_options_server_server_id; + +ALTER TABLE dhcp4_options_server + ADD CONSTRAINT fk_dhcp4_options_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_global_parameter_server + DROP FOREIGN KEY fk_dhcp6_global_parameter_server_server_id; + +ALTER TABLE dhcp6_global_parameter_server + ADD CONSTRAINT fk_dhcp6_global_parameter_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_option_def_server + DROP FOREIGN KEY fk_dhcp6_option_def_server_server_id; + +ALTER TABLE dhcp6_option_def_server + ADD CONSTRAINT fk_dhcp6_option_def_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_shared_network_server + DROP FOREIGN KEY fk_dhcp6_shared_network_server_server_id; + +ALTER TABLE dhcp6_shared_network_server + ADD CONSTRAINT fk_dhcp6_shared_network_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_subnet_server + DROP FOREIGN KEY fk_dhcp6_subnet_server_server_id; + +ALTER TABLE dhcp6_subnet_server + ADD CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_options_server + DROP FOREIGN KEY fk_dhcp6_options_server_option_id; + +ALTER TABLE dhcp6_options_server + ADD CONSTRAINT fk_dhcp6_options_server_option_id + FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +-- ----------------------------------------------------- +-- Table `dhcp4_audit_revision` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_audit_revision ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + server_id BIGINT(10) UNSIGNED, + PRIMARY KEY (id), + KEY key_dhcp4_audit_revision_by_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Drop columns from the dhcp4_audit table which now +-- belong to the dhcp4_audit_revision. +-- ----------------------------------------------------- +ALTER TABLE dhcp4_audit + DROP COLUMN modification_ts, + DROP COLUMN log_message; + +-- ----------------------------------------------------- +-- Add column revision_id and the foreign key with a +-- reference to the dhcp4_audit_revision table. +-- ----------------------------------------------------- +ALTER TABLE dhcp4_audit + ADD COLUMN revision_id BIGINT(20) UNSIGNED NOT NULL; + +ALTER TABLE dhcp4_audit + ADD CONSTRAINT fk_dhcp4_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp4_audit_revision (id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP4; +DELIMITER $$ +CREATE PROCEDURE createAuditRevisionDHCP4(IN audit_ts TIMESTAMP, + IN server_tag VARCHAR(256), + IN audit_log_message TEXT, + IN cascade_transaction TINYINT(1)) +BEGIN + DECLARE srv_id BIGINT(20); + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + SELECT id INTO srv_id FROM dhcp4_server WHERE tag = server_tag; + INSERT INTO dhcp4_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message); + SET @audit_revision_id = LAST_INSERT_ID(); + SET @cascade_transaction = cascade_transaction; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The @audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. "create", "update" or +-- "delete". +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditEntryDHCP4; +DELIMITER $$ +CREATE PROCEDURE createAuditEntryDHCP4(IN object_type_val VARCHAR(256), + IN object_id_val BIGINT(20) UNSIGNED, + IN modification_type_val VARCHAR(32)) +BEGIN + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + INSERT INTO dhcp4_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, \ + (SELECT id FROM modification WHERE modification_type = modification_type_val), \ + @audit_revision_id); + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Triggers used to create entries in the audit +-- tables upon insertion, update or deletion of the +-- configuration entries. +-- ----------------------------------------------------- + +# Create dhcp4_global_parameter insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_AINS AFTER INSERT ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_global_parameter update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_AUPD AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_global_parameter delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_ADEL AFTER DELETE ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_AINS AFTER INSERT ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_AUPD AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_ADEL AFTER DELETE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_AINS AFTER INSERT ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_AUPD AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_ADEL AFTER DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_AINS AFTER INSERT ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_AUPD AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_ADEL AFTER DELETE ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', OLD.id, "delete"); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates an audit entry for a +-- DHCPv4 option. Depending on the scope of the option +-- the audit entry can be created for various levels +-- of configuration hierarchy. If this is a global +-- option the audit entry is created for this option +-- for CREATE, UPDATE or DELETE. If the option is being +-- added for an owning option, e.g. for a subnet, the +-- audit entry is created as an UPDATE to this object. +-- From the Kea perspective such option addition will +-- be seen as a subnet update and the server will fetch +-- the whole subnet and merge it into its configuration. +-- The audit entry is not created if it was already +-- created as part of the current transaction. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP4; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP4(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20)) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp4_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp4_options' table. + CALL createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, create + # audit entry for the entire subnet, which indicates that + # it should be treated as the subnet update. + CALL createAuditEntryDHCP4('dhcp4_subnet', subnet_id, "update"); + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # create audit entry for the shared network which + # indicates that it should be treated as the shared + # network update. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + CALL createAuditEntryDHCP4('dhcp4_shared_network', snid, "update"); + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + CALL createAuditEntryDHCP4('dhcp4_subnet', sid, "update"); + END IF; + END IF; +END $$ +DELIMITER ; + +# Create dhcp4_options insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AINS AFTER INSERT ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("create", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id); + END $$ +DELIMITER ; + +# Create dhcp4_options update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AUPD AFTER UPDATE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("update", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id); + END $$ +DELIMITER ; + +# Create dhcp4_options delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_ADEL AFTER DELETE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("delete", OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Table `parameter_data_type` +-- Reflects an enum used by Kea to define supported +-- data types for the simple configuration parameters, +-- e.g. global parameters used by DHCP servers. +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS parameter_data_type ( + id TINYINT UNSIGNED NOT NULL PRIMARY KEY, + name VARCHAR(32) NOT NULL +) ENGINE = InnoDB; + +START TRANSACTION; +INSERT INTO parameter_data_type VALUES (0, 'integer'); +INSERT INTO parameter_data_type VALUES (1, 'real'); +INSERT INTO parameter_data_type VALUES (2, 'boolean'); +INSERT INTO parameter_data_type VALUES (4, 'string'); +COMMIT; + +ALTER TABLE dhcp4_global_parameter + ADD COLUMN parameter_type TINYINT UNSIGNED NOT NULL; + +ALTER TABLE dhcp4_global_parameter + ADD CONSTRAINT fk_dhcp4_global_parameter_type FOREIGN KEY (parameter_type) + REFERENCES parameter_data_type (id); + +ALTER TABLE dhcp6_global_parameter + ADD COLUMN parameter_type TINYINT UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_global_parameter + ADD CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) + REFERENCES parameter_data_type (id); + + +-- Rename dhcp6_subnet_id column of dhcp6_pool and dhcp6_pd_pool + +ALTER TABLE dhcp6_pool + DROP FOREIGN KEY fk_dhcp6_pool_subnet_id; +DROP INDEX fk_dhcp6_pool_subnet_id + ON dhcp6_pool; + +ALTER TABLE dhcp6_pd_pool + DROP FOREIGN KEY fk_dhcp6_pd_pool_subnet_id; +DROP INDEX fk_dhcp6_pd_pool_subnet_id + ON dhcp6_pd_pool; + +ALTER TABLE dhcp6_pool + CHANGE dhcp6_subnet_id subnet_id INT(10) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_pd_pool + CHANGE dhcp6_subnet_id subnet_id INT(10) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_pool + ADD CONSTRAINT fk_dhcp6_pool_subnet_id + FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_pd_pool + ADD CONSTRAINT fk_dhcp6_pd_pool_subnet_id + FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +-- align dhcp6_shared_network_server indexes on dhcp4_shared_network_server + +ALTER TABLE dhcp6_shared_network_server + ADD PRIMARY KEY (shared_network_id, server_id); + +ALTER TABLE dhcp6_shared_network_server + DROP FOREIGN KEY fk_dhcp6_shared_network_server_shared_network_id; +DROP INDEX fk_dhcp6_shared_network_server_shared_network_id + ON dhcp6_shared_network_server; +ALTER TABLE dhcp6_shared_network_server + ADD CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id + FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +-- Update dhcp4_subnet_server and dhcp6_subnet_server to allow update +-- on the prefix too by setting the CASCADE action. + +ALTER TABLE dhcp4_subnet_server + DROP FOREIGN KEY fk_dhcp4_subnet_server_subnet_id; +ALTER TABLE dhcp4_subnet_server + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_subnet_server + DROP FOREIGN KEY fk_dhcp6_subnet_server_subnet_id; +ALTER TABLE dhcp6_subnet_server + ADD CONSTRAINT fk_dhcp6_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Table `dhcp6_audit_revision` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_audit_revision ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + server_id BIGINT(10) UNSIGNED, + PRIMARY KEY (id), + KEY key_dhcp6_audit_revision_by_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Drop columns from the dhcp6_audit table which now +-- belong to the dhcp6_audit_revision. +-- ----------------------------------------------------- +ALTER TABLE dhcp6_audit + DROP COLUMN modification_ts, + DROP COLUMN log_message; + +-- ----------------------------------------------------- +-- Add column revision_id and the foreign key with a +-- reference to the dhcp6_audit_revision table. +-- ----------------------------------------------------- +ALTER TABLE dhcp6_audit + ADD COLUMN revision_id BIGINT(20) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_audit + ADD CONSTRAINT fk_dhcp6_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp6_audit_revision (id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP6; +DELIMITER $$ +CREATE PROCEDURE createAuditRevisionDHCP6(IN audit_ts TIMESTAMP, + IN server_tag VARCHAR(256), + IN audit_log_message TEXT, + IN cascade_transaction TINYINT(1)) +BEGIN + DECLARE srv_id BIGINT(20); + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + SELECT id INTO srv_id FROM dhcp6_server WHERE tag = server_tag; + INSERT INTO dhcp6_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message); + SET @audit_revision_id = LAST_INSERT_ID(); + SET @cascade_transaction = cascade_transaction; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The @audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. "create", "update" or +-- "delete". +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditEntryDHCP6; +DELIMITER $$ +CREATE PROCEDURE createAuditEntryDHCP6(IN object_type_val VARCHAR(256), + IN object_id_val BIGINT(20) UNSIGNED, + IN modification_type_val VARCHAR(32)) +BEGIN + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + INSERT INTO dhcp6_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, \ + (SELECT id FROM modification WHERE modification_type = modification_type_val), \ + @audit_revision_id); + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Triggers used to create entries in the audit +-- tables upon insertion, update or deletion of the +-- configuration entries. +-- ----------------------------------------------------- + +# Create dhcp6_global_parameter insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_AINS AFTER INSERT ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_global_parameter update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_AUPD AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_global_parameter delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_ADEL AFTER DELETE ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_AINS AFTER INSERT ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_AUPD AFTER UPDATE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_ADEL AFTER DELETE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_AINS AFTER INSERT ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_AUPD AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_ADEL AFTER DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_AINS AFTER INSERT ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_AUPD AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_ADEL AFTER DELETE ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', OLD.id, "delete"); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates an audit entry for a +-- DHCPv6 option. Depending on the scope of the option +-- the audit entry can be created for various levels +-- of configuration hierarchy. If this is a global +-- option the audit entry is created for this option +-- for CREATE, UPDATE or DELETE. If the option is being +-- added for an owning option, e.g. for a subnet, the +-- audit entry is created as an UPDATE to this object. +-- From the Kea perspective such option addition will +-- be seen as a subnet update and the server will fetch +-- the whole subnet and merge it into its configuration. +-- The audit entry is not created if it was already +-- created as part of the current transaction. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP6; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP6(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN pd_pool_id BIGINT(20)) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp6_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp6_options' table. + CALL createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, create + # audit entry for the entire subnet, which indicates that + # it should be treated as the subnet update. + CALL createAuditEntryDHCP6('dhcp6_subnet', subnet_id, "update"); + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # create audit entry for the shared network which + # indicates that it should be treated as the shared + # network update. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + CALL createAuditEntryDHCP6('dhcp6_shared_network', snid, "update"); + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + CALL createAuditEntryDHCP6('dhcp6_subnet', sid, "update"); + ELSEIF scope_id = 6 THEN + # If pd pool specific option is added or modified, create + # audit entry for the subnet which this pd pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + CALL createAuditEntryDHCP6('dhcp6_subnet', sid, "update"); + END IF; + END IF; +END $$ +DELIMITER ; + +# Create dhcp6_options insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AINS AFTER INSERT ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("create", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, NEW.pd_pool_id); + END $$ +DELIMITER ; + +# Create dhcp6_options update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AUPD AFTER UPDATE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("update", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, NEW.pd_pool_id); + END $$ +DELIMITER ; + +# Create dhcp6_options delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_ADEL AFTER DELETE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("delete", OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, OLD.pd_pool_id); + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '0'; + +# This line concludes database upgrade to version 8.0. + +# Add lifetime bounds +ALTER TABLE dhcp4_shared_network + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +# Create dhcp4_server insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_AINS AFTER INSERT ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_server update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_AUPD AFTER UPDATE ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_server delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_ADEL AFTER DELETE ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_server insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_AINS AFTER INSERT ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_server update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_AUPD AFTER UPDATE ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_server delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_ADEL AFTER DELETE ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Put the auth key in hexadecimal (double size but far more user friendly). +ALTER TABLE hosts + MODIFY COLUMN auth_key VARCHAR(32) NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '1'; + +# This line concludes database upgrade to version 8.1. + +# Drop existing trigger on the dhcp4_shared_network table. +DROP TRIGGER dhcp4_shared_network_ADEL; + +# Create new trigger which will delete options associated with the shared +# network. +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_BDEL BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +# Drop existing trigger on the dhcp4_subnet table. +DROP TRIGGER dhcp4_subnet_ADEL; + +# Create new trigger which will delete pools associated with the subnet and +# the options associated with the subnet. +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_BDEL BEFORE DELETE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, "delete"); + DELETE FROM dhcp4_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp4_options WHERE dhcp4_subnet_id = OLD.subnet_id; + END $$ +DELIMITER ; + +# Do not perform cascade deletion of the data in the dhcp4_pool because +# the cascade deletion does not execute triggers associated with the table. +# Instead we are going to use triggers on the dhcp4_subnet table. +ALTER TABLE dhcp4_pool + DROP FOREIGN KEY fk_dhcp4_pool_subnet_id; + +ALTER TABLE dhcp4_pool + ADD CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +# Drop existing trigger on the dhcp6_shared_network table. +DROP TRIGGER dhcp6_shared_network_ADEL; + +# Create new trigger which will delete options associated with the shared +# network. +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_BDEL BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +# Drop existing trigger on the dhcp6_subnet table. +DROP TRIGGER dhcp6_subnet_ADEL; + +# Create new trigger which will delete pools associated with the subnet and +# the options associated with the subnet. +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_BDEL BEFORE DELETE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, "delete"); + DELETE FROM dhcp6_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_pd_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_options WHERE dhcp6_subnet_id = OLD.subnet_id; + END $$ +DELIMITER ; + +# Do not perform cascade deletion of the data in the dhcp6_pool and dhcp6_pd_pool +# because the cascaded deletion does not execute triggers associated with the table. +# Instead we are going to use triggers on the dhcp6_subnet table. +ALTER TABLE dhcp6_pool + DROP FOREIGN KEY fk_dhcp6_pool_subnet_id; + +ALTER TABLE dhcp6_pd_pool + DROP FOREIGN KEY fk_dhcp6_pd_pool_subnet_id; + +ALTER TABLE dhcp6_pool + ADD CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE dhcp6_pd_pool + ADD CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp6_pd_pool_BDEL BEFORE DELETE ON dhcp6_pd_pool FOR EACH ROW +BEGIN +DELETE FROM dhcp6_options WHERE scope_id = 6 AND pd_pool_id = OLD.id; +END +$$ +DELIMITER ; + +# Add missing columns in pools. +ALTER TABLE dhcp4_pool + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +ALTER TABLE dhcp6_pd_pool + ADD COLUMN excluded_prefix VARCHAR(45) DEFAULT NULL, + ADD COLUMN excluded_prefix_length TINYINT(3) NOT NULL, + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +ALTER TABLE dhcp6_pool + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP4 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP4; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP4(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN modification_ts TIMESTAMP) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp4_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp4_options' table. + CALL createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, update + # the modification timestamp of this subnet to allow the + # servers to refresh the subnet information. This will + # also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = subnet_id; + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # update the modification timestamp of this shared network + # to allow the servers to refresh the shared network + # information. This will also result in creating an + # audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network AS n SET n.modification_ts = modification_ts + WHERE n.id = snid; + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, update + # the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + END IF; + END IF; +END $$ +DELIMITER ; + +# Recreate dhcp4_options_AINS trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_AINS; + +# This trigger is executed after inserting a DHCPv4 option into the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AINS AFTER INSERT ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("create", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp4_options_AUPD trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_AUPD; + +# This trigger is executed after updating a DHCPv4 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AUPD AFTER UPDATE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("update", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp4_options_ADEL trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_ADEL; + +# This trigger is executed after deleting a DHCPv4 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_ADEL AFTER DELETE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("delete", OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + NOW()); + END $$ +DELIMITER ; + + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP4 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP6; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP6(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN pd_pool_id BIGINT(20), + IN modification_ts TIMESTAMP) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp6_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp6_options' table. + CALL createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, update + # the modification timestamp of this subnet to allow the + # servers to refresh the subnet information. This will + # also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = subnet_id; + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # update the modification timestamp of this shared network + # to allow the servers to refresh the shared network + # information. This will also result in creating an + # audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network AS n SET n.modification_ts = modification_ts + WHERE n.id = snid; + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, update + # the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + ELSEIF scope_id = 6 THEN + # If pd pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + END IF; + END IF; +END $$ +DELIMITER ; + +# Recreate dhcp6_options_AINS trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_AINS; + +# This trigger is executed after inserting a DHCPv6 option into the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AINS AFTER INSERT ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("create", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp6_options_AUPD trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_AUPD; + +# This trigger is executed after updating a DHCPv6 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AUPD AFTER UPDATE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("update", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp6_options_ADEL trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_ADEL; + +# This trigger is executed after deleting a DHCPv6 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_ADEL AFTER DELETE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("delete", OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + OLD.pd_pool_id, NOW()); + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '2'; + +# This line concludes database upgrade to version 8.2. + +# Create hostname index for host reservations +CREATE INDEX hosts_by_hostname ON hosts (hostname); + +# Create hostname index for lease4 +CREATE INDEX lease4_by_hostname ON lease4 (hostname); + +# Create hostname index for lease6 +CREATE INDEX lease6_by_hostname ON lease6 (hostname); + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '0'; + +# This line concludes database upgrade to version 9.0. + +# Add new DDNS related columns to shared networks and subnets +ALTER TABLE dhcp4_shared_network + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '1'; + +# This line concludes database upgrade to version 9.1. + +# Add missing indexes (foreign keys) to the dhcp4_options table. +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_shared_network + FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network(name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_subnet + FOREIGN KEY (dhcp4_subnet_id) + REFERENCES dhcp4_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_pool + FOREIGN KEY (pool_id) + REFERENCES dhcp4_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Add missing indexes (foreign keys) to the dhcp6_options table. +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_shared_network + FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network(name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_subnet + FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_pool + FOREIGN KEY (pool_id) + REFERENCES dhcp6_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_pd_pool + FOREIGN KEY (pd_pool_id) + REFERENCES dhcp6_pd_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '2'; + +# This line concludes database upgrade to version 9.2. + +# Fix stat_lease4_update trigger +DROP TRIGGER stat_lease4_update; + +DELIMITER $$ +CREATE TRIGGER stat_lease4_update AFTER UPDATE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.subnet_id != NEW.subnet_id OR OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease4_delete trigger +DROP TRIGGER stat_lease4_delete; + +DELIMITER $$ +CREATE TRIGGER stat_lease4_delete AFTER DELETE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease6_update trigger +DROP TRIGGER stat_lease6_update; + +DELIMITER $$ +CREATE TRIGGER stat_lease6_update AFTER UPDATE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.subnet_id != NEW.subnet_id OR + OLD.lease_type != NEW.lease_type OR + OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease6_delete trigger +DROP TRIGGER stat_lease6_delete; + +DELIMITER $$ +CREATE TRIGGER stat_lease6_delete AFTER DELETE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '3'; + +# This line concludes database upgrade to version 9.3. + +# Starting from this version we allow specifying multiple IP reservations +# for the same address in certain DHCP configurations. The server may check +# uniqueness of the IP addresses on its own. This is no longer checked at +# the database level to facilitate the use cases when a single host may +# get the same reserved IP address via different interfaces. + +# Replace the unique index with non-unique index so the queries for +# hosts by IPv4 address are still efficient. +DROP INDEX key_dhcp4_ipv4_address_subnet_id ON hosts; +CREATE INDEX key_dhcp4_ipv4_address_subnet_id_identifier + ON hosts (ipv4_address ASC, dhcp4_subnet_id ASC); + +# Replace the unique index with non-unique index so the queries for +# hosts by IPv6 address are still efficient. +DROP INDEX key_dhcp6_address_prefix_len ON ipv6_reservations; +CREATE INDEX key_dhcp6_address_prefix_len + ON ipv6_reservations (address ASC, prefix_len ASC); + +# Stop using a trigger to delete entries dependent on hosts table. +# Use cascade action instead. This works better with complex delete +# statements. +DROP TRIGGER IF EXISTS host_BDEL; + +# Replace existing constraint to set cascade actions. +ALTER TABLE ipv6_reservations DROP FOREIGN KEY fk_ipv6_reservations_Host; +ALTER TABLE ipv6_reservations ADD CONSTRAINT fk_ipv6_reservations_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '4'; + +# This line concludes database upgrade to version 9.4. + +# Add new reservations flags. +ALTER TABLE dhcp4_subnet + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +# DROP reservation_mode +ALTER TABLE dhcp4_subnet DROP COLUMN reservation_mode; +ALTER TABLE dhcp4_shared_network DROP COLUMN reservation_mode; +ALTER TABLE dhcp6_subnet DROP COLUMN reservation_mode; +ALTER TABLE dhcp6_shared_network DROP COLUMN reservation_mode; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '5'; + +# This line concludes database upgrade to version 9.5. + +# Add new lease cache parameters. +ALTER TABLE dhcp4_subnet + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +# Add an auto-increment ID as primary key to support Percona. +ALTER TABLE logs + ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY; + +# Update the schema version number +UPDATE schema_version + SET version = '9', minor = '6'; + +# This line concludes database upgrade to version 9.6. + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv4 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp4_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + test TEXT, + next_server INT UNSIGNED DEFAULT NULL, + server_hostname VARCHAR(128) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + only_if_required TINYINT NOT NULL DEFAULT '0', + valid_lifetime INT DEFAULT NULL, + min_valid_lifetime INT DEFAULT NULL, + max_valid_lifetime INT DEFAULT NULL, + depend_on_known_directly TINYINT NOT NULL DEFAULT '0', + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY id_UNIQUE (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp4_client_class_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp4_client_class table has a corresponding row +-- in the dhcp4_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp4_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp4_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp4_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_order ( + class_id BIGINT UNSIGNED NOT NULL, + order_index BIGINT UNSIGNED NOT NULL, + depend_on_known_indirectly TINYINT NOT NULL DEFAULT '0', + PRIMARY KEY (class_id), + KEY key_dhcp4_client_class_order_index (order_index), + CONSTRAINT fk_dhcp4_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp4_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp4_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp4_client_class_ADEL; +DROP PROCEDURE IF EXISTS setClientClass4Order; + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE setClientClass4Order(IN id BIGINT UNSIGNED, + IN follow_class_name VARCHAR(128), + IN old_follow_class_name VARCHAR(128)) +proc_label:BEGIN + -- This variable will be optionally set if the follow_class_name + -- column value is specified. + DECLARE follow_class_index BIGINT UNSIGNED; + DECLARE msg TEXT; + + -- Remember currently used value of depend_on_known_indirectly. + SET @depend_on_known_indirectly = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order WHERE id = class_id + ); + + -- Bail if the class is updated without re-positioning. + IF( + @depend_on_known_indirectly IS NOT NULL AND + ((follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = 0 + WHERE class_id = id; + LEAVE proc_label; + END IF; + + IF follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SET follow_class_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = follow_class_name + ); + IF follow_class_index IS NULL THEN + -- The class with a name specified with follow_class_name does + -- not exist. + SET msg = CONCAT('Class ', follow_class_name, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1 + ORDER BY order_index DESC; + END IF; + ELSE + -- A caller did not specify the follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SET follow_class_index = (SELECT MAX(order_index) FROM dhcp4_client_class_order); + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + SET follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + SET msg = CONCAT('Unable to move class with id ', id, ' because it would break its dependencies'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + REPLACE INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_AINS AFTER INSERT ON dhcp4_client_class FOR EACH ROW BEGIN + CALL setClientClass4Order(NEW.id, NEW.follow_class_name, NULL); + CALL createAuditEntryDHCP4('dhcp4_client_class', NEW.id, "create"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_AUPD AFTER UPDATE ON dhcp4_client_class FOR EACH ROW BEGIN + SET @depend_on_known_directly = OLD.depend_on_known_directly; + SET @client_class_id = NEW.id; + CALL setClientClass4Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + CALL createAuditEntryDHCP4('dhcp4_client_class', NEW.id, "update"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to create dhcp4_client_class audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_ADEL AFTER DELETE ON dhcp4_client_class FOR EACH ROW BEGIN + CALL createAuditEntryDHCP4('dhcp4_client_class', OLD.id, "delete"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp4_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp4_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_dependency ( + class_id BIGINT UNSIGNED NOT NULL, + dependency_id BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (class_id,dependency_id), + KEY dhcp4_client_class_dependency_id_idx (dependency_id), + CONSTRAINT dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp4_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp4_client_class (id) +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_BINS; +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - class_id id client class, +-- - dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv4ClientClassDependency(IN class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE class_index BIGINT UNSIGNED; + DECLARE dependency_index BIGINT UNSIGNED; + DECLARE err_msg TEXT; + + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF class_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class id must not be NULL.'; + END IF; + IF dependency_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency id must not be NULL.'; + END IF; + -- Dependencies on self make no sense. + IF class_id = dependency_id THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class must not have dependency on self.'; + END IF; + -- Check position of our class in the hierarchy. + SET class_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.id = class_id); + IF class_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- Check position of the dependency. + SET dependency_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = dependency_id + ); + IF dependency_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', dependency_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' must not depend on class defined later with id ', dependency_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp4_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_server AS t1 + LEFT JOIN dhcp4_client_class_server AS t2 + ON t2.class_id = dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + SET err_msg = CONCAT('Unmet dependencies for client class with id ', class_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_check_dependency_BINS BEFORE INSERT ON dhcp4_client_class_dependency FOR EACH ROW +BEGIN + CALL checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_AINS; +DROP PROCEDURE IF EXISTS updateDHCPv4ClientClassKnownDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE updateDHCPv4ClientClassKnownDependency(IN client_class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE dependency TINYINT; + -- Check if the dependency class references KNOWN/UNKNOWN. + SET dependency = ( + SELECT depend_on_known_directly FROM dhcp4_client_class + WHERE id = dependency_id + ); + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = 0 THEN + SET dependency = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order + WHERE class_id = dependency_id + ); + END IF; + IF dependency <> 0 THEN + UPDATE dhcp4_client_class_order + SET depend_on_known_indirectly = 1 + WHERE class_id = client_class_id; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_dependency_AINS AFTER INSERT ON dhcp4_client_class_dependency FOR EACH ROW +BEGIN + CALL updateDHCPv4ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassKnownDependencyChange; + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv4 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv4ClientClassKnownDependencyChange() +BEGIN + DECLARE depended TINYINT DEFAULT 0; + DECLARE depends TINYINT DEFAULT 0; + + -- Session variables are set upon a client class update. + IF @client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency + WHERE dependency_id = @client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + IF @depend_on_known_directly <> 0 OR @depend_on_known_indirectly <> 0 THEN + SET depended = 1; + END IF; + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SET depends = ( + SELECT depend_on_known_directly FROM dhcp4_client_class + WHERE id = @client_class_id + ); + -- If it doesn't depend directly, check indirect dependencies. + IF depends = 0 THEN + SET depends = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order + WHERE class_id = @client_class_id + ); + END IF; + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'; + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv4 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_server ( + class_id bigint unsigned NOT NULL, + server_id bigint unsigned NOT NULL, + modification_ts timestamp NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + KEY fk_dhcp4_client_class_server_id (server_id), + CONSTRAINT fk_dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv4 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp4_option_def + ADD COLUMN class_id BIGINT UNSIGNED NULL DEFAULT NULL; + +ALTER TABLE dhcp4_option_def + ADD CONSTRAINT fk_dhcp4_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv6 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp6_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + test TEXT, + only_if_required TINYINT NOT NULL DEFAULT '0', + valid_lifetime INT DEFAULT NULL, + min_valid_lifetime INT DEFAULT NULL, + max_valid_lifetime INT DEFAULT NULL, + depend_on_known_directly TINYINT NOT NULL DEFAULT '0', + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY id_UNIQUE (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp6_client_class_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp6_client_class table has a corresponding row +-- in the dhcp6_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp6_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp6_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp6_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_order ( + class_id BIGINT UNSIGNED NOT NULL, + order_index BIGINT UNSIGNED NOT NULL, + depend_on_known_indirectly TINYINT NOT NULL DEFAULT '0', + PRIMARY KEY (class_id), + KEY key_dhcp6_client_class_order_index (order_index), + CONSTRAINT fk_dhcp6_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp6_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp6_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp6_client_class_ADEL; +DROP PROCEDURE IF EXISTS setClientClass6Order; + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name name of the previous class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE setClientClass6Order(IN id BIGINT UNSIGNED, + IN follow_class_name VARCHAR(128), + IN old_follow_class_name VARCHAR(128)) +proc_label:BEGIN + -- This variable will be optionally set if the follow_class_name + -- column value is specified. + DECLARE follow_class_index BIGINT UNSIGNED; + DECLARE msg TEXT; + + -- Remember currently used value of depend_on_known_indirectly. + SET @depend_on_known_indirectly = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order WHERE id = class_id + ); + + -- Bail if the class is updated without re-positioning. + IF( + @depend_on_known_indirectly IS NOT NULL AND + ((follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = 0 + WHERE class_id = id; + LEAVE proc_label; + END IF; + + IF follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SET follow_class_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = follow_class_name + ); + IF follow_class_index IS NULL THEN + -- The class with a name specified with follow_class_name does + -- not exist. + SET msg = CONCAT('Class ', follow_class_name, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1 + ORDER BY order_index DESC; + END IF; + ELSE + -- A caller did not specify the follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SET follow_class_index = (SELECT MAX(order_index) FROM dhcp6_client_class_order); + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + SET follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + SET msg = CONCAT('Unable to move class with id ', id, ' because it would break its dependencies'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + REPLACE INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_AINS AFTER INSERT ON dhcp6_client_class FOR EACH ROW BEGIN + CALL setClientClass6Order(NEW.id, NEW.follow_class_name, NULL); + CALL createAuditEntryDHCP6('dhcp6_client_class', NEW.id, "create"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_AUPD AFTER UPDATE ON dhcp6_client_class FOR EACH ROW BEGIN + SET @depend_on_known_directly = OLD.depend_on_known_directly; + SET @client_class_id = NEW.id; + CALL setClientClass6Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + CALL createAuditEntryDHCP6('dhcp6_client_class', NEW.id, "update"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to create dhcp6_client_class audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_ADEL AFTER DELETE ON dhcp6_client_class FOR EACH ROW BEGIN + CALL createAuditEntryDHCP6('dhcp6_client_class', OLD.id, "delete"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp6_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp6_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_dependency ( + class_id BIGINT UNSIGNED NOT NULL, + dependency_id BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (class_id,dependency_id), + KEY dhcp6_client_class_dependency_id_idx (dependency_id), + CONSTRAINT dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp6_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp6_client_class (id) +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_BINS; +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - class_id id client class, +-- - dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv6ClientClassDependency(IN class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE class_index BIGINT UNSIGNED; + DECLARE dependency_index BIGINT UNSIGNED; + DECLARE err_msg TEXT; + + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF class_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class id must not be NULL.'; + END IF; + IF dependency_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency id must not be NULL.'; + END IF; + -- Dependencies on self make no sense. + IF class_id = dependency_id THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class must not have dependency on self.'; + END IF; + -- Check position of our class in the hierarchy. + SET class_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.id = class_id); + IF class_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- Check position of the dependency. + SET dependency_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = dependency_id + ); + IF dependency_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', dependency_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' must not depend on class defined later with id ', dependency_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp6_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_server AS t1 + LEFT JOIN dhcp6_client_class_server AS t2 + ON t2.class_id = dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + SET err_msg = CONCAT('Unmet dependencies for client class with id ', class_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_check_dependency_BINS BEFORE INSERT ON dhcp6_client_class_dependency FOR EACH ROW +BEGIN + CALL checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_AINS; +DROP PROCEDURE IF EXISTS updateDHCPv6ClientClassKnownDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE updateDHCPv6ClientClassKnownDependency(IN client_class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE dependency TINYINT; + -- Check if the dependency class references KNOWN/UNKNOWN. + SET dependency = ( + SELECT depend_on_known_directly FROM dhcp6_client_class + WHERE id = dependency_id + ); + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = 0 THEN + SET dependency = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order + WHERE class_id = dependency_id + ); + END IF; + IF dependency <> 0 THEN + UPDATE dhcp6_client_class_order + SET depend_on_known_indirectly = 1 + WHERE class_id = client_class_id; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_dependency_AINS AFTER INSERT ON dhcp6_client_class_dependency FOR EACH ROW +BEGIN + CALL updateDHCPv6ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassKnownDependencyChange; + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv6 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv6ClientClassKnownDependencyChange() +BEGIN + DECLARE depended TINYINT DEFAULT 0; + DECLARE depends TINYINT DEFAULT 0; + + -- Session variables are set upon a client class update. + IF @client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency + WHERE dependency_id = @client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + IF @depend_on_known_directly <> 0 OR @depend_on_known_indirectly <> 0 THEN + SET depended = 1; + END IF; + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SET depends = ( + SELECT depend_on_known_directly FROM dhcp6_client_class + WHERE id = @client_class_id + ); + -- If it doesn't depend directly, check indirect dependencies. + IF depends = 0 THEN + SET depends = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order + WHERE class_id = @client_class_id + ); + END IF; + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'; + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv6 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_server ( + class_id bigint unsigned NOT NULL, + server_id bigint unsigned NOT NULL, + modification_ts timestamp NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + KEY fk_dhcp6_client_class_server_id (server_id), + CONSTRAINT fk_dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv6 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_option_def + ADD COLUMN class_id BIGINT UNSIGNED NULL DEFAULT NULL; + +ALTER TABLE dhcp6_option_def + ADD CONSTRAINT fk_dhcp6_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version + SET version = '10', minor = '0'; + +# This line concludes database upgrade to version 10. + +# Reverse index order to improve reclamation query performance +# Add a constraint that any state value added to the lease4 must +# map to a value in the lease_state table. Note we have to drop +# the foreign keys first, then add them back. +ALTER TABLE lease4 DROP FOREIGN KEY fk_lease4_state; +DROP INDEX lease4_by_state_expire ON lease4; +CREATE INDEX lease4_by_expire_state ON lease4 (expire ASC, state ASC); +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +ALTER TABLE lease6 DROP FOREIGN KEY fk_lease6_state; +CREATE INDEX lease6_by_expire_state ON lease6 (expire ASC, state ASC); +DROP INDEX lease6_by_state_expire ON lease6; +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +# Added preferred lifetime columns v6 client classes. +ALTER TABLE dhcp6_client_class + ADD COLUMN preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL; + +# Update the schema version number +UPDATE schema_version + SET version = '11', minor = '0'; + +# This line concludes database upgrade to version 11. + +# Ensure that dhcp_client_class is NULL when an option does not +# belong to any client class. Later, we will add foreign keys for +# the dhcp_client_class columns, and it requires that the columns +# are NULL when there are no corresponding client classes. +SET @disable_audit = 1; +UPDATE dhcp4_options SET dhcp_client_class = NULL + WHERE scope_id <> 2; +UPDATE dhcp6_options SET dhcp_client_class = NULL + WHERE scope_id <> 2; +SET @disable_audit = 0; + +# Add a foreign keys referencing a client classes. If an option is +# associated with a client class, the option will be deleted +# along with the deleted client class. +ALTER TABLE dhcp4_options + ADD CONSTRAINT fk_dhcp4_options_client_class + FOREIGN KEY (dhcp_client_class) + REFERENCES dhcp4_client_class (name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options + ADD CONSTRAINT fk_dhcp6_options_client_class + FOREIGN KEY (dhcp_client_class) + REFERENCES dhcp6_client_class (name) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version + SET version = '12', minor = '0'; + +-- This line concludes the schema upgrade to version 12. + +-- This line starts the schema upgrade to version 13. + +-- Create a function that separates a contiguous hexadecimal string +-- into groups of two hexadecimals separated by colons. +DROP FUNCTION IF EXISTS colonSeparatedHex; +DELIMITER $$ +CREATE FUNCTION colonSeparatedHex(hex VARCHAR(64)) +RETURNS VARCHAR(64) +DETERMINISTIC +BEGIN + -- Declarations + DECLARE i INT; + DECLARE length INT; + DECLARE output VARCHAR(64); + + -- Initializations + SET i = 3; + SET length = LENGTH(hex); + + -- Add a leading zero if the first octet has a single hexadecimal character. + IF MOD(length, 2) = 1 THEN + SET hex = CONCAT('0', hex); + SET length = length + 1; + END IF; + + -- Start with the first octet. + SET output = SUBSTR(hex, 1, 2); + + -- Add one octet at a time and a leading colon with each. + label: WHILE i < length DO + SET output = CONCAT(output, ':', SUBSTR(hex, i, 2)); + SET i = i + 2; + END WHILE label; + + -- Memfile uses lowercase hexadecimals. + SET output = LOWER(output); + + RETURN output; +END $$ +DELIMITER ; + +-- Modify the procedure to output a memfile-ready CSV file. +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN + SELECT + INET_NTOA(address), + IFNULL(colonSeparatedHex(HEX(hwaddr)), ''), + IFNULL(colonSeparatedHex(HEX(client_id)), ''), + valid_lifetime, + UNIX_TIMESTAMP(expire), + subnet_id, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + state, + REPLACE(IFNULL(user_context, ''), ',', ',') + FROM lease4 + ORDER BY address; +END $$ +DELIMITER ; + +-- hwtype and hwaddr_source need to be last to match memfile format. +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN + SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,state,user_context,hwtype,hwaddr_source'; +END $$ +DELIMITER ; + +-- Modify the procedure to output a memfile-ready CSV file. +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN + SELECT + address, + IFNULL(colonSeparatedHex(HEX(duid)), ''), + valid_lifetime, + UNIX_TIMESTAMP(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + IFNULL(colonSeparatedHex(HEX(hwaddr)), ''), + state, + REPLACE(IFNULL(user_context, ''), ',', ','), + hwtype, + hwaddr_source + FROM lease6 + ORDER BY address; +END $$ +DELIMITER ; + +-- Create a procedure that inserts a v4 lease from memfile data. +DELIMITER $$ +CREATE PROCEDURE lease4Upload( + IN address VARCHAR(15), + IN hwaddr VARCHAR(20), + IN client_id VARCHAR(128), + IN valid_lifetime INT UNSIGNED, + IN expire BIGINT UNSIGNED, + IN subnet_id INT UNSIGNED, + IN fqdn_fwd TINYINT, + IN fqdn_rev TINYINT, + IN hostname VARCHAR(255), + IN state INT UNSIGNED, + IN user_context TEXT +) +BEGIN + INSERT INTO lease4 ( + address, + hwaddr, + client_id, + valid_lifetime, + expire, + subnet_id, + fqdn_fwd, + fqdn_rev, + hostname, + state, + user_context + ) VALUES ( + INET_ATON(address), + UNHEX(REPLACE(hwaddr, ':', '')), + UNHEX(REPLACE(client_id, ':', '')), + valid_lifetime, + FROM_UNIXTIME(expire), + subnet_id, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + state, + REPLACE(user_context, ',', ',') + ); +END $$ +DELIMITER ; + +-- Create a procedure that inserts a v6 lease from memfile data. +DELIMITER $$ +CREATE PROCEDURE lease6Upload( + IN address VARCHAR(39), + IN duid VARCHAR(128), + IN valid_lifetime INT UNSIGNED, + IN expire BIGINT UNSIGNED, + IN subnet_id INT UNSIGNED, + IN pref_lifetime INT UNSIGNED, + IN lease_type TINYINT, + IN iaid INT UNSIGNED, + IN prefix_len TINYINT UNSIGNED, + IN fqdn_fwd TINYINT, + IN fqdn_rev TINYINT, + IN hostname VARCHAR(255), + IN hwaddr VARCHAR(64), + IN state INT UNSIGNED, + IN user_context TEXT, + IN hwtype SMALLINT, + IN hwaddr_source INT UNSIGNED +) +BEGIN + INSERT INTO lease6 ( + address, + duid, + valid_lifetime, + expire, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + hostname, + hwaddr, + state, + user_context, + hwtype, + hwaddr_source + ) VALUES ( + address, + UNHEX(REPLACE(duid, ':', '')), + valid_lifetime, + FROM_UNIXTIME(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + UNHEX(REPLACE(hwaddr, ':', '')), + state, + REPLACE(user_context, ',', ','), + hwtype, + hwaddr_source + ); +END $$ +DELIMITER ; + +-- Update the schema version number. +UPDATE schema_version + SET version = '13', minor = '0'; + +-- This line concludes the schema upgrade to version 13. + +-- This line starts the schema upgrade to version 14. + +-- Modify shared-network-name foreign key constraint on dhcp4_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp4_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp4_subnet + DROP FOREIGN KEY fk_dhcp4_subnet_shared_network; + +ALTER TABLE dhcp4_subnet + ADD CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger on dhcp4_shared_network to explicitly +-- update dhcp4_subnets. This ensures there are audit entries for updated +-- subnets. +DROP TRIGGER dhcp4_shared_network_BDEL; + +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_BDEL BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + -- In MySQL Foreign key constraint triggered updates will not cascade, so we explicitly + -- update subnets first which should ensure they get audit entries. + UPDATE dhcp4_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +-- Modify shared-network-name foreign key constraint on dhcp6_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp6_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp6_subnet + DROP FOREIGN KEY fk_dhcp6_subnet_shared_network; + +ALTER TABLE dhcp6_subnet + ADD CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger on dhcp6_shared_network to explicitly +-- update dhcp6_subnets. This ensures there are audit entries for updated +-- subnets. +DROP TRIGGER dhcp6_shared_network_BDEL; + +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_BDEL BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + -- In MySQL Foreign key constraint triggered updates will not cascade, so we explicitly + -- update subnets first which should ensure they get audit entries. + UPDATE dhcp6_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +-- Add user_context column to client class tables. +ALTER TABLE dhcp4_client_class ADD COLUMN user_context LONGTEXT NULL; +ALTER TABLE dhcp6_client_class ADD COLUMN user_context LONGTEXT NULL; + +-- Schema changes related to lease limiting start here. -- + +-- Recreate the triggers that update the leaseX_stat tables as stored procedures. -- + +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_AINS_lease4_stat(IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED) +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert the state count record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_AUPD_lease4_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED) +BEGIN + IF old_subnet_id != new_subnet_id OR old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert new state record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_ADEL_lease4_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED) +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists. + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND old_state = state; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_AINS_lease6_stat(IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED, + IN new_lease_type TINYINT) +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert the state count record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_AUPD_lease6_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN old_lease_type TINYINT, + IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED, + IN new_lease_type TINYINT) +BEGIN + IF old_subnet_id != new_subnet_id OR + old_lease_type != new_lease_type OR + old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_ADEL_lease6_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN old_lease_type TINYINT) +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; +END $$ +DELIMITER ; + +-- Create tables that contain the number of active leases. -- + +DROP TABLE IF EXISTS lease4_stat_by_client_class; +CREATE TABLE lease4_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL PRIMARY KEY, + leases BIGINT UNSIGNED NOT NULL +) ENGINE = InnoDB; + +DROP TABLE IF EXISTS lease6_stat_by_client_class; +CREATE TABLE lease6_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL, + lease_type TINYINT NOT NULL, + leases BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (client_class, lease_type), + CONSTRAINT fk_lease6_stat_by_client_class_lease_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type) +) ENGINE = InnoDB; + +-- Create procedures to be called for each row in after-event triggers for +-- INSERT, UPDATE and DELETE on lease tables. + +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_AINS_lease4_stat_by_client_class(IN new_state TINYINT, + IN new_user_context TEXT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + -- Iterate through all the client classes and increment the lease count for each. + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF ROW_COUNT() = 0 THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_AUPD_lease4_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN new_state TINYINT, + IN new_user_context TEXT) +BEGIN + -- Declarations + DECLARE old_client_classes TEXT; + DECLARE new_client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + SET old_client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET new_client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + + IF old_state != new_state OR old_client_classes != new_client_classes THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(old_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(old_client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class; + + SET i = i + 1; + END WHILE label; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(new_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(new_client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_ADEL_lease4_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is accounted for in lease limiting. + IF old_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_AINS_lease6_stat_by_client_class(IN new_state TINYINT, + IN new_user_context TEXT, + IN new_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_AUPD_lease6_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN old_lease_type TINYINT, + IN new_state TINYINT, + IN new_user_context TEXT, + IN new_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE old_client_classes TEXT; + DECLARE new_client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + SET old_client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET new_client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + + IF old_state != new_state OR old_client_classes != new_client_classes OR old_lease_type != new_lease_type THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(old_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(old_client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + + SET i = i + 1; + END WHILE label; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(new_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(new_client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_ADEL_lease6_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN old_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is accounted for in lease limiting. But check both states to be consistent with lease6_stat. + IF old_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +-- Recreate the after-event triggers for INSERT, UPDATE and DELETE on lease tables to call the -- +-- stored procedures above in pairs of two: for client classes and for subnets. -- + +-- Function that establishes whether JSON functions are supported. +-- They should be provided with MySQL>= 5.7, MariaDB >= 10.2.3. +DROP FUNCTION IF EXISTS isJsonSupported; +DELIMITER $$ +CREATE FUNCTION isJsonSupported() +RETURNS BOOL +DETERMINISTIC +BEGIN + DECLARE dummy BOOL; + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + RETURN false; + + SELECT JSON_EXTRACT('{ "foo": 1 }', '$.foo') INTO dummy; + RETURN true; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_insert; +DROP TRIGGER IF EXISTS lease4_AINS; +DELIMITER $$ +CREATE TRIGGER lease4_AINS AFTER INSERT ON lease4 FOR EACH ROW +BEGIN + CALL lease4_AINS_lease4_stat(NEW.state, NEW.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_AINS_lease4_stat_by_client_class(NEW.state, NEW.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_update; +DROP TRIGGER IF EXISTS lease4_AUPD; +DELIMITER $$ +CREATE TRIGGER lease4_AUPD AFTER UPDATE ON lease4 FOR EACH ROW +BEGIN + CALL lease4_AUPD_lease4_stat(OLD.state, OLD.subnet_id, NEW.state, NEW.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_AUPD_lease4_stat_by_client_class(OLD.state, OLD.user_context, NEW.state, NEW.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_delete; +DROP TRIGGER IF EXISTS lease4_ADEL; +DELIMITER $$ +CREATE TRIGGER lease4_ADEL AFTER DELETE ON lease4 FOR EACH ROW +BEGIN + CALL lease4_ADEL_lease4_stat(OLD.state, OLD.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_ADEL_lease4_stat_by_client_class(OLD.state, OLD.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_insert; +DROP TRIGGER IF EXISTS lease6_AINS; +DELIMITER $$ +CREATE TRIGGER lease6_AINS AFTER INSERT ON lease6 FOR EACH ROW +BEGIN + CALL lease6_AINS_lease6_stat(NEW.state, NEW.subnet_id, NEW.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_AINS_lease6_stat_by_client_class(NEW.state, NEW.user_context, NEW.lease_type); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_update; +DROP TRIGGER IF EXISTS lease6_AUPD; +DELIMITER $$ +CREATE TRIGGER lease6_AUPD AFTER UPDATE ON lease6 FOR EACH ROW +BEGIN + CALL lease6_AUPD_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type, NEW.state, NEW.subnet_id, NEW.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_AUPD_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type, NEW.state, NEW.user_context, NEW.lease_type); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_delete; +DROP TRIGGER IF EXISTS lease6_ADEL; +DELIMITER $$ +CREATE TRIGGER lease6_ADEL AFTER DELETE ON lease6 FOR EACH ROW +BEGIN + CALL lease6_ADEL_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_ADEL_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type); + END IF; +END $$ +DELIMITER ; + +-- Create functions that check if the lease limits set in the given user context are exceeded. +-- They return a string describing a limit that is being exceeded, or an empty +-- string if no limits are exceeded. The following format for is assumed for user_context +-- (not all nodes are mandatory and values are given only as examples): +-- { "ISC": { "limits": { "client-classes": [ { "name": "foo", "address-limit": 2, "prefix-limit": 1 } ], +-- "subnet": { "id": 1, "address-limit": 2, "prefix-limit": 1 } } } } + +DROP FUNCTION IF EXISTS checkLease4Limits; +DELIMITER $$ +CREATE FUNCTION checkLease4Limits(user_context TEXT) +RETURNS TEXT +READS SQL DATA +BEGIN + -- Declarations + DECLARE json_element TEXT; + DECLARE length INT; + DECLARE class TEXT; + DECLARE name VARCHAR(255); + DECLARE i INT; + DECLARE lease_limit INT; + DECLARE lease_count INT; + + -- Dive into client class limits. + SET json_element = JSON_EXTRACT(user_context, '$."ISC"."limits"."client-classes"'); + SET length = JSON_LENGTH(json_element); + + SET i = 0; + label: WHILE i < length DO + -- Get the lease limit for this client class. + SET class = JSON_EXTRACT(json_element, CONCAT('\$[', i, ']')); + SET name = JSON_UNQUOTE(JSON_EXTRACT(class, '$.name')); + SET lease_limit = JSON_EXTRACT(class, '$."address-limit"'); + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease4_stat_by_client_class WHERE client_class = name); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET i = i + 1; + END WHILE label; + + -- Dive into subnet limits. Reuse i as subnet ID. + SET json_element = JSON_EXTRACT(user_context, '$.ISC.limits.subnet'); + SET i = JSON_EXTRACT(json_element, '$.id'); + SET lease_limit = JSON_EXTRACT(json_element, '$."address-limit"'); + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease4_stat WHERE subnet_id = i AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END $$ +DELIMITER ; + +DROP FUNCTION IF EXISTS checkLease6Limits; +DELIMITER $$ +CREATE FUNCTION checkLease6Limits(user_context TEXT) +RETURNS TEXT +READS SQL DATA +BEGIN + -- Declarations + DECLARE json_element TEXT; + DECLARE length INT; + DECLARE class TEXT; + DECLARE name VARCHAR(255); + DECLARE i INT; + DECLARE lease_limit INT; + DECLARE lease_count INT; + + -- Dive into client class limits. + SET json_element = JSON_EXTRACT(user_context, '$."ISC"."limits"."client-classes"'); + SET length = JSON_LENGTH(json_element); + + SET i = 0; + label: WHILE i < length DO + -- Get the lease limit for this client class. + SET class = JSON_EXTRACT(json_element, CONCAT('\$[', i, ']')); + SET name = JSON_UNQUOTE(JSON_EXTRACT(class, '$.name')); + + SET lease_limit = JSON_EXTRACT(class, '$."address-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the address count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET lease_limit = JSON_EXTRACT(class, '$."prefix-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the prefix count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 2); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET i = i + 1; + END WHILE label; + + -- Dive into subnet limits. Reuse i as subnet ID. + SET json_element = JSON_EXTRACT(user_context, '$.ISC.limits.subnet'); + SET i = JSON_EXTRACT(json_element, '$.id'); + SET lease_limit = JSON_EXTRACT(json_element, '$."address-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat WHERE subnet_id = i AND lease_type = 0 AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + SET lease_limit = JSON_EXTRACT(json_element, '$."prefix-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat WHERE subnet_id = i AND lease_type = 2 AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END $$ +DELIMITER ; + +-- Update the schema version number. +UPDATE schema_version + SET version = '14', minor = '0'; + +-- This line concludes the schema upgrade to version 14. + +# Notes: +# +# Indexes +# ======= +# It is likely that additional indexes will be needed. However, the +# increase in lookup performance from these will come at the expense +# of a decrease in performance during insert operations due to the need +# to update the indexes. For this reason, the need for additional indexes +# will be determined by experiment during performance tests. +# +# The most likely additional indexes will cover the following columns: +# +# hwaddr and client_id +# For lease stability: if a client requests a new lease, try to find an +# existing or recently expired lease for it so that it can keep using the +# same IP address. +# +# Field Sizes +# =========== +# If any of the VARxxx field sizes are altered, the lengths in the MySQL +# backend source file (mysql_lease_mgr.cc) must be correspondingly changed. +# +# Portability +# =========== +# The 'ENGINE = INNODB' on some tables is not portable to another database +# and will need to be removed. +# +# Some columns contain binary data so are stored as VARBINARY instead of +# VARCHAR. This may be non-portable between databases: in this case, the +# definition should be changed to VARCHAR. diff --git a/src/share/database/scripts/mysql/dhcpdb_drop.mysql b/src/share/database/scripts/mysql/dhcpdb_drop.mysql new file mode 100644 index 0000000..0d17890 --- /dev/null +++ b/src/share/database/scripts/mysql/dhcpdb_drop.mysql @@ -0,0 +1,153 @@ +# Copyright (C) 2016-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# Turn off foreign key checks as CASCADE isn't really supported in MySQL +SET SESSION FOREIGN_KEY_CHECKS = 0; +DROP TABLE IF EXISTS lease4; +DROP TABLE IF EXISTS lease6; +DROP TABLE IF EXISTS lease6_types; +DROP TABLE IF EXISTS lease_hwaddr_source; +DROP TABLE IF EXISTS schema_version; +DROP TABLE IF EXISTS ipv6_reservations; +DROP TABLE IF EXISTS hosts; +DROP TABLE IF EXISTS dhcp4_options; +DROP TABLE IF EXISTS dhcp6_options; +DROP TABLE IF EXISTS host_identifier_type; +DROP TABLE IF EXISTS lease_state; +DROP TABLE IF EXISTS dhcp_option_scope; +DROP TRIGGER IF EXISTS host_BDEL; +DROP PROCEDURE IF EXISTS lease4DumpHeader; +DROP PROCEDURE IF EXISTS lease4DumpData; +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DROP PROCEDURE IF EXISTS lease6DumpData; +DROP TRIGGER IF EXISTS stat_lease4_insert; +DROP TRIGGER IF EXISTS stat_lease4_update; +DROP TRIGGER IF EXISTS stat_lease4_delete; +DROP TABLE IF EXISTS lease4_stat; +DROP TRIGGER IF EXISTS stat_lease6_insert; +DROP TRIGGER IF EXISTS stat_lease6_update; +DROP TRIGGER IF EXISTS stat_lease6_delete; +DROP TABLE IF EXISTS lease6_stat; +DROP TABLE IF EXISTS logs; +DROP TABLE IF EXISTS dhcp4_audit; +DROP TABLE IF EXISTS dhcp4_audit_revision; +DROP TABLE IF EXISTS dhcp4_global_parameter; +DROP TABLE IF EXISTS dhcp4_global_parameter_server; +DROP TABLE IF EXISTS dhcp4_option_def; +DROP TABLE IF EXISTS dhcp4_option_def_server; +DROP TABLE IF EXISTS dhcp4_options_server; +DROP TABLE IF EXISTS dhcp4_pool; +DROP TABLE IF EXISTS dhcp4_server; +DROP TABLE IF EXISTS dhcp4_shared_network; +DROP TABLE IF EXISTS dhcp4_shared_network_server; +DROP TABLE IF EXISTS dhcp4_subnet; +DROP TABLE IF EXISTS dhcp4_subnet_server; +DROP TABLE IF EXISTS dhcp4_client_class; +DROP TABLE IF EXISTS dhcp4_client_class_order; +DROP TABLE IF EXISTS dhcp4_client_class_dependency; +DROP TABLE IF EXISTS dhcp4_client_class_server; +DROP TABLE IF EXISTS dhcp6_audit; +DROP TABLE IF EXISTS dhcp6_global_parameter; +DROP TABLE IF EXISTS dhcp6_global_parameter_server; +DROP TABLE IF EXISTS dhcp6_option_def; +DROP TABLE IF EXISTS dhcp6_option_def_server; +DROP TABLE IF EXISTS dhcp6_options_server; +DROP TABLE IF EXISTS dhcp6_pd_pool; +DROP TABLE IF EXISTS dhcp6_pool; +DROP TABLE IF EXISTS dhcp6_server; +DROP TABLE IF EXISTS dhcp6_shared_network; +DROP TABLE IF EXISTS dhcp6_shared_network_server; +DROP TABLE IF EXISTS dhcp6_subnet; +DROP TABLE IF EXISTS dhcp6_subnet_server; +DROP TABLE IF EXISTS dhcp6_client_class; +DROP TABLE IF EXISTS dhcp6_client_class_order; +DROP TABLE IF EXISTS dhcp6_client_class_dependency; +DROP TABLE IF EXISTS dhcp6_client_class_server; +DROP TABLE IF EXISTS modification; +DROP TABLE IF EXISTS parameter_data_type; +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP4; +DROP PROCEDURE IF EXISTS createAuditEntryDHCP4; +DROP PROCEDURE IF EXISTS createOptionAuditDHCP4; +DROP PROCEDURE IF EXISTS setClientClass4Order; +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassDependency; +DROP PROCEDURE IF EXISTS updateDHCPv4ClientClassKnownDependency; +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassKnownDependencyChange; +DROP TRIGGER IF EXISTS dhcp4_global_parameter_AINS; +DROP TRIGGER IF EXISTS dhcp4_global_parameter_AUPD; +DROP TRIGGER IF EXISTS dhcp4_global_parameter_ADEL; +DROP TRIGGER IF EXISTS dhcp4_subnet_AINS; +DROP TRIGGER IF EXISTS dhcp4_subnet_AUPD; +DROP TRIGGER IF EXISTS dhcp4_subnet_ADEL; +DROP TRIGGER IF EXISTS dhcp4_shared_network_AINS; +DROP TRIGGER IF EXISTS dhcp4_shared_network_AUPD; +DROP TRIGGER IF EXISTS dhcp4_shared_network_ADEL; +DROP TRIGGER IF EXISTS dhcp4_option_def_AINS; +DROP TRIGGER IF EXISTS dhcp4_option_def_AUPD; +DROP TRIGGER IF EXISTS dhcp4_option_def_ADEL; +DROP TRIGGER IF EXISTS dhcp4_options_AINS; +DROP TRIGGER IF EXISTS dhcp4_options_AUPD; +DROP TRIGGER IF EXISTS dhcp4_options_ADEL; +DROP TRIGGER IF EXISTS dhcp4_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp4_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp4_client_class_ADEL; +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_BINS; +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_AINS; +DROP TABLE IF EXISTS dhcp6_audit_revision; +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP6; +DROP PROCEDURE IF EXISTS createAuditEntryDHCP6; +DROP PROCEDURE IF EXISTS createOptionAuditDHCP6; +DROP PROCEDURE IF EXISTS setClientClass6Order; +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassDependency; +DROP PROCEDURE IF EXISTS updateDHCPv6ClientClassKnownDependency; +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassKnownDependencyChange; +DROP TRIGGER IF EXISTS dhcp6_global_parameter_AINS; +DROP TRIGGER IF EXISTS dhcp6_global_parameter_AUPD; +DROP TRIGGER IF EXISTS dhcp6_global_parameter_ADEL; +DROP TRIGGER IF EXISTS dhcp6_subnet_AINS; +DROP TRIGGER IF EXISTS dhcp6_subnet_AUPD; +DROP TRIGGER IF EXISTS dhcp6_subnet_ADEL; +DROP TRIGGER IF EXISTS dhcp6_shared_network_AINS; +DROP TRIGGER IF EXISTS dhcp6_shared_network_AUPD; +DROP TRIGGER IF EXISTS dhcp6_shared_network_ADEL; +DROP TRIGGER IF EXISTS dhcp6_option_def_AINS; +DROP TRIGGER IF EXISTS dhcp6_option_def_AUPD; +DROP TRIGGER IF EXISTS dhcp6_option_def_ADEL; +DROP TRIGGER IF EXISTS dhcp6_options_AINS; +DROP TRIGGER IF EXISTS dhcp6_options_AUPD; +DROP TRIGGER IF EXISTS dhcp6_options_ADEL; +DROP TRIGGER IF EXISTS dhcp6_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp6_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp6_client_class_ADEL; +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_BINS; +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_AINS; +DROP FUNCTION IF EXISTS colonSeparatedHex; +DROP PROCEDURE IF EXISTS lease4Upload; +DROP PROCEDURE IF EXISTS lease6Upload; +DROP TRIGGER IF EXISTS dhcp4_shared_network_BDEL; +DROP TRIGGER IF EXISTS dhcp6_shared_network_BDEL; +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat; +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat; +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat; +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat; +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat; +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat; +DROP TABLE IF EXISTS lease4_stat_by_client_class; +DROP TABLE IF EXISTS lease6_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat_by_client_class; +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat_by_client_class; +DROP TRIGGER IF EXISTS lease4_AINS; +DROP TRIGGER IF EXISTS lease4_AUPD; +DROP TRIGGER IF EXISTS lease4_ADEL; +DROP TRIGGER IF EXISTS lease6_AINS; +DROP TRIGGER IF EXISTS lease6_AUPD; +DROP TRIGGER IF EXISTS lease6_ADEL; +DROP FUNCTION IF EXISTS checkLease4Limits; +DROP FUNCTION IF EXISTS checkLease6Limits; +DROP FUNCTION IF EXISTS isJsonSupported; diff --git a/src/share/database/scripts/mysql/upgrade_001.0_to_002.0.sh.in b/src/share/database/scripts/mysql/upgrade_001.0_to_002.0.sh.in new file mode 100644 index 0000000..efbc2c8 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_001.0_to_002.0.sh.in @@ -0,0 +1,57 @@ +#!/bin/sh + +# Copyright (C) 2016-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "1.0" ]; then + printf 'This script upgrades 1.0 to 2.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF +ALTER TABLE lease6 + ADD COLUMN hwaddr varbinary(20), + ADD COLUMN hwtype smallint unsigned, + ADD COLUMN hwaddr_source int unsigned; + +CREATE TABLE lease_hwaddr_source ( + hwaddr_source INT PRIMARY KEY NOT NULL, + name VARCHAR(40) +) ENGINE = INNODB; + +-- See src/lib/dhcp/dhcp/pkt.h for detailed explanation +INSERT INTO lease_hwaddr_source VALUES (1, 'HWADDR_SOURCE_RAW'); +INSERT INTO lease_hwaddr_source VALUES (2, 'HWADDR_SOURCE_IPV6_LINK_LOCAL'); +INSERT INTO lease_hwaddr_source VALUES (4, 'HWADDR_SOURCE_DUID'); +INSERT INTO lease_hwaddr_source VALUES (8, 'HWADDR_SOURCE_CLIENT_ADDR_RELAY_OPTION'); +INSERT INTO lease_hwaddr_source VALUES (16, 'HWADDR_SOURCE_REMOTE_ID'); +INSERT INTO lease_hwaddr_source VALUES (32, 'HWADDR_SOURCE_SUBSCRIBER_ID'); +INSERT INTO lease_hwaddr_source VALUES (64, 'HWADDR_SOURCE_DOCSIS'); + +UPDATE schema_version SET version='2', minor='0'; +EOF diff --git a/src/share/database/scripts/mysql/upgrade_002.0_to_003.0.sh.in b/src/share/database/scripts/mysql/upgrade_002.0_to_003.0.sh.in new file mode 100644 index 0000000..78af24a --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_002.0_to_003.0.sh.in @@ -0,0 +1,118 @@ +#!/bin/sh + +# Copyright (C) 2016-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "2.0" ]; then + printf 'This script upgrades 2.0 to 3.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF +CREATE TABLE IF NOT EXISTS hosts ( +host_id INT UNSIGNED NOT NULL AUTO_INCREMENT , +dhcp_identifier VARBINARY(128) NOT NULL , +dhcp_identifier_type TINYINT NOT NULL , +dhcp4_subnet_id INT UNSIGNED NULL , +dhcp6_subnet_id INT UNSIGNED NULL , +ipv4_address INT UNSIGNED NULL , +hostname VARCHAR(255) NULL , +dhcp4_client_classes VARCHAR(255) NULL , +dhcp6_client_classes VARCHAR(255) NULL , +PRIMARY KEY (host_id) , +INDEX key_dhcp4_identifier_subnet_id (dhcp_identifier ASC, dhcp_identifier_type ASC) , +INDEX key_dhcp6_identifier_subnet_id (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp6_subnet_id ASC) +) ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS ipv6_reservations ( +reservation_id INT NOT NULL AUTO_INCREMENT , +address VARCHAR(39) NOT NULL , +prefix_len TINYINT(3) UNSIGNED NOT NULL DEFAULT 128 , +type TINYINT(4) UNSIGNED NOT NULL DEFAULT 0 , +dhcp6_iaid INT UNSIGNED NULL , +host_id INT UNSIGNED NOT NULL , +PRIMARY KEY (reservation_id) , +INDEX fk_ipv6_reservations_host_idx (host_id ASC) , +CONSTRAINT fk_ipv6_reservations_Host +FOREIGN KEY (host_id ) +REFERENCES hosts (host_id ) +ON DELETE NO ACTION +ON UPDATE NO ACTION +) ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS dhcp4_options ( +option_id INT UNSIGNED NOT NULL AUTO_INCREMENT , +code TINYINT UNSIGNED NOT NULL , +value BLOB NULL , +formatted_value TEXT NULL , +space VARCHAR(128) NULL , +persistent TINYINT(1) NOT NULL DEFAULT 0 , +dhcp_client_class VARCHAR(128) NULL , +dhcp4_subnet_id INT NULL , +host_id INT UNSIGNED NULL , +PRIMARY KEY (option_id) , +UNIQUE INDEX option_id_UNIQUE (option_id ASC) , +INDEX fk_options_host1_idx (host_id ASC) , +CONSTRAINT fk_options_host1 +FOREIGN KEY (host_id ) +REFERENCES hosts (host_id ) +ON DELETE NO ACTION +ON UPDATE NO ACTION +) ENGINE = INNODB; + +CREATE TABLE IF NOT EXISTS dhcp6_options ( +option_id INT UNSIGNED NOT NULL AUTO_INCREMENT , +code INT UNSIGNED NOT NULL , +value BLOB NULL , +formatted_value TEXT NULL , +space VARCHAR(128) NULL , +persistent TINYINT(1) NOT NULL DEFAULT 0 , +dhcp_client_class VARCHAR(128) NULL , +dhcp6_subnet_id INT NULL , +host_id INT UNSIGNED NULL , +PRIMARY KEY (option_id) , +UNIQUE INDEX option_id_UNIQUE (option_id ASC) , +INDEX fk_options_host1_idx (host_id ASC) , +CONSTRAINT fk_options_host10 +FOREIGN KEY (host_id ) +REFERENCES hosts (host_id ) +ON DELETE NO ACTION +ON UPDATE NO ACTION +) ENGINE = INNODB; + +DELIMITER $$ +CREATE TRIGGER host_BDEL BEFORE DELETE ON hosts FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM ipv6_reservations WHERE ipv6_reservations.host_id = OLD.host_id; +END +$$ +DELIMITER ; + +UPDATE schema_version SET version='3', minor='0'; +EOF diff --git a/src/share/database/scripts/mysql/upgrade_003.0_to_004.0.sh.in b/src/share/database/scripts/mysql/upgrade_003.0_to_004.0.sh.in new file mode 100644 index 0000000..3affd3a --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_003.0_to_004.0.sh.in @@ -0,0 +1,173 @@ +#!/bin/sh + +# Copyright (C) 2016-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "3.0" ]; then + printf 'This script upgrades 3.0 to 4.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF +# Add state column to the lease4 table. +ALTER TABLE lease4 + ADD COLUMN state INT UNSIGNED DEFAULT 0; + +# Add state column to the lease6 table. +ALTER TABLE lease6 + ADD COLUMN state INT UNSIGNED DEFAULT 0; + +# Create indexes for querying leases in a given state and segregated +# by the expiration time. One of the applications is to retrieve all +# expired leases. However, these indexes can be also used to retrieve +# leases in a given state regardless of the expiration time. +CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC); +CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC); + +# Create table holding mapping of the lease states to their names. +# This is not used in queries from the DHCP server but rather in +# direct queries from the lease database management tools. +CREATE TABLE IF NOT EXISTS lease_state ( + state INT UNSIGNED PRIMARY KEY NOT NULL, + name VARCHAR(64) NOT NULL +) ENGINE=INNODB; + +# Insert currently defined state names. +INSERT INTO lease_state VALUES (0, 'default'); +INSERT INTO lease_state VALUES (1, 'declined'); +INSERT INTO lease_state VALUES (2, 'expired-reclaimed'); + +# Add a constraint that any state value added to the lease4 must +# map to a value in the lease_state table. +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +# Add a constraint that any state value added to the lease6 must +# map to a value in the lease_state table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +# Add a constraint that lease type in the lease6 table must map +# to a lease type defined in the lease6_types table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type); + +# Modify the name of one of the HW address sources, and add a new one. +UPDATE lease_hwaddr_source + SET name = 'HWADDR_SOURCE_DOCSIS_CMTS' + WHERE hwaddr_source = 64; + +INSERT INTO lease_hwaddr_source VALUES (128, 'HWADDR_SOURCE_DOCSIS_MODEM'); + +# Add UNSIGNED to match with the lease6. +ALTER TABLE lease_hwaddr_source + MODIFY COLUMN hwaddr_source INT UNSIGNED NOT NULL DEFAULT 0; + +# Add a constraint that non-null hwaddr_source in the lease6 table +# must map to an entry in the lease_hwaddr_source. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_hwaddr_source FOREIGN KEY (hwaddr_source) + REFERENCES lease_hwaddr_source (hwaddr_source); + +# FUNCTION that returns a result set containing the column names for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease4DumpHeader() +BEGIN +SELECT 'address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state'; +END $$ +DELIMITER ; + +# FUNCTION that returns a result set containing the data for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN +SELECT + INET_NTOA(l.address), + IFNULL(HEX(l.hwaddr), ''), + IFNULL(HEX(l.client_id), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + s.name +from + lease4 l + LEFT OUTER JOIN lease_state s on (l.state = s.state); +END $$ +DELIMITER ; + +# FUNCTION that returns a result set containing the column names for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN +SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,hwtype,hwaddr_source,state'; +END $$ +DELIMITER ; + +# FUNCTION that returns a result set containing the data for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN +SELECT + l.address, + IFNULL(HEX(l.duid), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + IFNULL(t.name, ''), + l.iaid, + l.prefix_len, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + IFNULL(HEX(l.hwaddr), ''), + IFNULL(l.hwtype, ''), + IFNULL(h.name, ''), + IFNULL(s.name, '') +FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source); +END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '4', minor = '0'; +# This line concludes database upgrade to version 4.0. +EOF diff --git a/src/share/database/scripts/mysql/upgrade_004.0_to_004.1.sh.in b/src/share/database/scripts/mysql/upgrade_004.0_to_004.1.sh.in new file mode 100644 index 0000000..65a57ed --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_004.0_to_004.1.sh.in @@ -0,0 +1,104 @@ +#!/bin/sh + +# Copyright (C) 2016-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "4.0" ]; then + printf 'This script upgrades 4.0 to 4.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# In the event hardware address cannot be determined, we need to satisfy +# foreign key constraint between lease6 and lease_hardware_source +INSERT INTO lease_hwaddr_source VALUES (0, 'HWADDR_SOURCE_UNKNOWN'); + +# +# Add order by lease address to lease4DumpData +# +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN +SELECT + INET_NTOA(l.address), + IFNULL(HEX(l.hwaddr), ''), + IFNULL(HEX(l.client_id), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + s.name +FROM + lease4 l + LEFT OUTER JOIN lease_state s on (l.state = s.state) +ORDER BY l.address; +END $$ +DELIMITER ; + +# +# Add order by lease address to lease6DumpData +# +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN +SELECT + l.address, + IFNULL(HEX(l.duid), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + IFNULL(t.name, ''), + l.iaid, + l.prefix_len, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + IFNULL(HEX(l.hwaddr), ''), + IFNULL(l.hwtype, ''), + IFNULL(h.name, ''), + IFNULL(s.name, '') +FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) +ORDER BY l.address; +END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '4', minor = '1'; +# This line concludes database upgrade to version 4.1. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_004.1_to_005.0.sh.in b/src/share/database/scripts/mysql/upgrade_004.1_to_005.0.sh.in new file mode 100644 index 0000000..cfe3489 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_004.1_to_005.0.sh.in @@ -0,0 +1,128 @@ +#!/bin/sh + +# Copyright (C) 2016-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "4.1" ]; then + printf 'This script upgrades 4.1 to 5.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Update index used for searching DHCPv4 reservations by identifier and subnet id. +# This index is now unique (to prevent duplicates) and includes DHCPv4 subnet +# identifier. +DROP INDEX key_dhcp4_identifier_subnet_id ON hosts; +CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id ON hosts (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp4_subnet_id ASC); + +# Update index used for searching DHCPv6 reservations by identifier and subnet id. +# This index is now unique to prevent duplicates. +DROP INDEX key_dhcp6_identifier_subnet_id ON hosts; +CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id ON hosts (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp6_subnet_id ASC); + +# Create index to search for reservations using IP address and subnet id. +# This unique index guarantees that there is only one occurrence of the +# particular IPv4 address for a given subnet. +CREATE UNIQUE INDEX key_dhcp4_ipv4_address_subnet_id ON hosts (ipv4_address ASC , dhcp4_subnet_id ASC); + +# Create index to search for reservations using address/prefix and prefix +# length. +CREATE UNIQUE INDEX key_dhcp6_address_prefix_len ON ipv6_reservations (address ASC , prefix_len ASC); + +# Create a table mapping host identifiers to their names. Values in this +# table are used as a foreign key in hosts table to guarantee that only +# identifiers present in host_identifier_type table are used in hosts +# table. +CREATE TABLE IF NOT EXISTS host_identifier_type ( + type TINYINT PRIMARY KEY NOT NULL, # Lease type code. + name VARCHAR(32) # Name of the lease type +) ENGINE = INNODB; + +START TRANSACTION; +INSERT INTO host_identifier_type VALUES (0, 'hw-address'); # Non-temporary v6 addresses +INSERT INTO host_identifier_type VALUES (1, 'duid'); # Temporary v6 addresses +INSERT INTO host_identifier_type VALUES (2, 'circuit-id'); # Prefix delegations +COMMIT; + +# Add a constraint that any identifier type value added to the hosts +# must map to a value in the host_identifier_type table. +ALTER TABLE hosts + ADD CONSTRAINT fk_host_identifier_type FOREIGN KEY (dhcp_identifier_type) + REFERENCES host_identifier_type (type); + +# Store DHCPv6 option code as 16-bit unsigned integer. +ALTER TABLE dhcp6_options MODIFY code SMALLINT UNSIGNED NOT NULL; + +# Subnet identifier is unsigned. +ALTER TABLE dhcp4_options MODIFY dhcp4_subnet_id INT UNSIGNED NULL; +ALTER TABLE dhcp6_options MODIFY dhcp6_subnet_id INT UNSIGNED NULL; + +# Scopes associate DHCP options stored in dhcp4_options and +# dhcp6_options tables with hosts, subnets, classes or indicate +# that they are global options. +CREATE TABLE IF NOT EXISTS dhcp_option_scope ( + scope_id TINYINT UNSIGNED PRIMARY KEY NOT NULL, + scope_name VARCHAR(32) +) ENGINE = INNODB; + +START TRANSACTION; +INSERT INTO dhcp_option_scope VALUES (0, 'global'); +INSERT INTO dhcp_option_scope VALUES (1, 'subnet'); +INSERT INTO dhcp_option_scope VALUES (2, 'client-class'); +INSERT INTO dhcp_option_scope VALUES (3, 'host'); +COMMIT; + +# Add scopes into table holding DHCPv4 options +ALTER TABLE dhcp4_options ADD COLUMN scope_id TINYINT UNSIGNED NOT NULL; +ALTER TABLE dhcp4_options + ADD CONSTRAINT fk_dhcp4_option_scope FOREIGN KEY (scope_id) + REFERENCES dhcp_option_scope (scope_id); + +# Add scopes into table holding DHCPv6 options +ALTER TABLE dhcp6_options ADD COLUMN scope_id TINYINT UNSIGNED NOT NULL; +ALTER TABLE dhcp6_options + ADD CONSTRAINT fk_dhcp6_option_scope FOREIGN KEY (scope_id) + REFERENCES dhcp_option_scope (scope_id); + +# Add UNSIGNED to reservation_id +ALTER TABLE ipv6_reservations + MODIFY reservation_id INT UNSIGNED NOT NULL AUTO_INCREMENT; + +# Add columns holding reservations for siaddr, sname and file fields +# carried within DHCPv4 message. +ALTER TABLE hosts ADD COLUMN dhcp4_next_server INT UNSIGNED NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_server_hostname VARCHAR(64) NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_boot_file_name VARCHAR(128) NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '0'; +# This line concludes database upgrade to version 5.0. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_005.0_to_005.1.sh.in b/src/share/database/scripts/mysql/upgrade_005.0_to_005.1.sh.in new file mode 100644 index 0000000..45f40b9 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_005.0_to_005.1.sh.in @@ -0,0 +1,61 @@ +#!/bin/sh + +# Copyright (C) 2017-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "5.0" ]; then + printf 'This script upgrades 5.0 to 5.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add missing 'client-id' and new 'flex-id' host identifier types. +INSERT INTO host_identifier_type VALUES (3, 'client-id'); +INSERT INTO host_identifier_type VALUES (4, 'flex-id'); + +# Recreate the trigger removing dependent host entries. +DROP TRIGGER host_BDEL; + +DELIMITER $$ +CREATE TRIGGER host_BDEL BEFORE DELETE ON hosts FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM ipv6_reservations WHERE ipv6_reservations.host_id = OLD.host_id; +DELETE FROM dhcp4_options WHERE dhcp4_options.host_id = OLD.host_id; +DELETE FROM dhcp6_options WHERE dhcp6_options.host_id = OLD.host_id; +END +$$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '1'; +# This line concludes database upgrade to version 5.1. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_005.1_to_005.2.sh.in b/src/share/database/scripts/mysql/upgrade_005.1_to_005.2.sh.in new file mode 100644 index 0000000..4987878 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_005.1_to_005.2.sh.in @@ -0,0 +1,47 @@ +#!/bin/sh + +# Copyright (C) 2018-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "5.1" ]; then + printf 'This script upgrades 5.1 to 5.2. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Make subnet_id column types consistent with lease table columns +ALTER TABLE dhcp4_options MODIFY dhcp4_subnet_id INT UNSIGNED; +ALTER TABLE dhcp6_options MODIFY dhcp6_subnet_id INT UNSIGNED; + +# Update the schema version number +UPDATE schema_version +SET version = '5', minor = '2'; +# This line concludes database upgrade to version 5.2. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_005.2_to_006.0.sh.in b/src/share/database/scripts/mysql/upgrade_005.2_to_006.0.sh.in new file mode 100644 index 0000000..63392c8 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_005.2_to_006.0.sh.in @@ -0,0 +1,216 @@ +#!/bin/sh + +# Copyright (C) 2018-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "5.2" ]; then + printf 'This script upgrades 5.2 to 6.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add user context into table holding hosts +ALTER TABLE hosts ADD COLUMN user_context TEXT NULL; + +# Add user contexts into tables holding DHCP options +ALTER TABLE dhcp4_options ADD COLUMN user_context TEXT NULL; +ALTER TABLE dhcp6_options ADD COLUMN user_context TEXT NULL; + +# Create index for searching leases by subnet identifier. +CREATE INDEX lease4_by_subnet_id ON lease4 (subnet_id); + +# Create for searching leases by subnet identifier and lease type. +CREATE INDEX lease6_by_subnet_id_lease_type ON lease6 (subnet_id, lease_type); + +# The index by iaid_subnet_id_duid is not the best choice because there are +# cases when we don't specify subnet identifier while searching leases. The +# index will be universal if the subnet_id is the right most column in the +# index. +DROP INDEX lease6_by_iaid_subnet_id_duid on lease6; +CREATE INDEX lease6_by_duid_iaid_subnet_id ON lease6 (duid, iaid, subnet_id); + +# Create lease4_stat table +CREATE TABLE lease4_stat ( + subnet_id INT UNSIGNED NOT NULL, + state INT UNSIGNED NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, state) +) ENGINE = INNODB; + +# Create stat_lease4_insert trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_insert AFTER INSERT ON lease4 + FOR EACH ROW + BEGIN + IF NEW.state = 0 OR NEW.state = 1 THEN + # Update the state count if it exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert the state count record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease4_update trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_update AFTER UPDATE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease4_delete trigger +DELIMITER $$ +CREATE TRIGGER stat_lease4_delete AFTER DELETE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + END $$ +DELIMITER ; + +# Create lease6_stat table +CREATE TABLE lease6_stat ( + subnet_id INT UNSIGNED NOT NULL, + lease_type INT UNSIGNED NOT NULL, + state INT UNSIGNED NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, lease_type, state) +) ENGINE = INNODB; + +# Create stat_lease6_insert trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_insert AFTER INSERT ON lease6 + FOR EACH ROW + BEGIN + IF NEW.state = 0 OR NEW.state = 1 THEN + # Update the state count if it exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE + subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert the state count record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease6_update trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_update AFTER UPDATE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Create stat_lease6_delete trigger +DELIMITER $$ +CREATE TRIGGER stat_lease6_delete AFTER DELETE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + END $$ +DELIMITER ; + +# Populate lease4_stat table based on existing leases +# We only care about assigned and declined states +INSERT INTO lease4_stat (subnet_id, state, leases) + SELECT subnet_id, state, count(state) + FROM lease4 WHERE state < 2 + GROUP BY subnet_id, state ORDER BY subnet_id; + +# Populate lease6_stat table based on existing leases +# We only care about assigned and declined states +INSERT INTO lease6_stat (subnet_id, lease_type, state, leases) + SELECT subnet_id, lease_type, state, count(state) + FROM lease6 WHERE state < 2 + GROUP BY subnet_id, lease_type, state + ORDER BY subnet_id; + +# Update the schema version number +UPDATE schema_version +SET version = '6', minor = '0'; +# This line concludes database upgrade to version 6.0. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_006.0_to_007.0.sh.in b/src/share/database/scripts/mysql/upgrade_006.0_to_007.0.sh.in new file mode 100644 index 0000000..5d83da5 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_006.0_to_007.0.sh.in @@ -0,0 +1,664 @@ +#!/bin/sh + +# Copyright (C) 2018-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "6.0" ]; then + printf 'This script upgrades 6.0 to 7.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add user context into tables holding leases +ALTER TABLE lease4 ADD COLUMN user_context TEXT NULL; +ALTER TABLE lease6 ADD COLUMN user_context TEXT NULL; + +DROP PROCEDURE IF EXISTS lease4DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease4DumpHeader() +BEGIN +SELECT 'address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context'; +END $$ +DELIMITER ; + +# FUNCTION that returns a result set containing the data for lease4 dumps +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN +SELECT + INET_NTOA(l.address), + IFNULL(HEX(l.hwaddr), ''), + IFNULL(HEX(l.client_id), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + s.name, + IFNULL(l.user_context, '') +FROM + lease4 l + LEFT OUTER JOIN lease_state s on (l.state = s.state) +ORDER BY l.address; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN +SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,hwtype,hwaddr_source,state,user_context'; +END $$ +DELIMITER ; + +# FUNCTION that returns a result set containing the data for lease6 dumps +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN +SELECT + l.address, + IFNULL(HEX(l.duid), ''), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + IFNULL(t.name, ''), + l.iaid, + l.prefix_len, + l.fqdn_fwd, + l.fqdn_rev, + l.hostname, + IFNULL(HEX(l.hwaddr), ''), + IFNULL(l.hwtype, ''), + IFNULL(h.name, ''), + IFNULL(s.name, ''), + IFNULL(l.user_context, '') +FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) +ORDER BY l.address; +END $$ +DELIMITER ; + +# Create logs table (logs table is used by forensic logging hook library) +CREATE TABLE logs ( + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, # creation timestamp + address VARCHAR(43) NULL, # address or prefix + log TEXT NOT NULL # the log itself + ) ENGINE = INNODB; + +# Create search index +CREATE INDEX timestamp_index ON logs (timestamp); + +#add auth key for reconfiguration +ALTER TABLE hosts + ADD COLUMN auth_key VARCHAR(16) NULL; + +# Convert subnet-id values of 0 to NULL +UPDATE hosts SET dhcp4_subnet_id = NULL WHERE dhcp4_subnet_id = 0; +UPDATE dhcp4_options SET dhcp4_subnet_id = NULL WHERE dhcp4_subnet_id = 0; +UPDATE hosts SET dhcp6_subnet_id = NULL WHERE dhcp6_subnet_id = 0; +UPDATE dhcp6_options SET dhcp6_subnet_id = NULL WHERE dhcp6_subnet_id = 0; + +# Add scope for shared network specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(4, "shared-network"); + +# Add scope for pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(5, "pool"); + +# Add scope for PD pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(6, "pd-pool"); + +# Create table modification +CREATE TABLE IF NOT EXISTS modification ( + id TINYINT(3) NOT NULL, + modification_type VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +) ENGINE=InnoDB; + +INSERT INTO modification(id, modification_type) + VALUES(0, "create"); + +INSERT INTO modification(id, modification_type) + VALUES(1, "update"); + +INSERT INTO modification(id, modification_type) + VALUES(2, "delete"); + +# Create table dhcp4_server +# +CREATE TABLE IF NOT EXISTS dhcp4_server ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + tag VARCHAR(64) NOT NULL, + description TEXT, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY dhcp4_server_tag_UNIQUE (tag), + KEY key_dhcp4_server_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Special server entry meaning "all servers". This refers to +# the configuration entries owned by all servers. +INSERT INTO dhcp4_server(id, tag, description, modification_ts) + VALUES(1, "all", "special type: all servers", NOW()); + +# Create table dhcp4_audit +# +CREATE TABLE IF NOT EXISTS dhcp4_audit ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT(2) UNSIGNED NOT NULL, + modification_type TINYINT(1) NOT NULL, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + PRIMARY KEY (id), + KEY key_dhcp4_audit_by_modification_ts (modification_ts), + KEY fk_dhcp4_audit_modification_type (modification_type), + CONSTRAINT fk_dhcp4_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp4_global_parameter +# +CREATE TABLE IF NOT EXISTS dhcp4_global_parameter ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + value LONGTEXT NOT NULL, + modification_ts timestamp NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp4_global_parameter_modification_ts (modification_ts), + KEY key_dhcp4_global_parameter_name (name) +) ENGINE=InnoDB; + +# Create table dhcp4_global_parameter_server +# M-to-M cross-reference between global parameters and servers +# +CREATE TABLE IF NOT EXISTS dhcp4_global_parameter_server ( + parameter_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (parameter_id, server_id), + KEY fk_dhcp4_global_parameter_server_server_id (server_id), + KEY key_dhcp4_global_parameter_server (modification_ts), + CONSTRAINT fk_dhcp4_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp4_global_parameter (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp4_option_def +# +CREATE TABLE IF NOT EXISTS dhcp4_option_def ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + code SMALLINT UNSIGNED NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type TINYINT UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + is_array TINYINT(1) NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR(512) DEFAULT NULL, + user_context LONGTEXT, + PRIMARY KEY (id), + KEY key_dhcp4_option_def_modification_ts (modification_ts), + KEY key_dhcp4_option_def_code_space (code, space) +) ENGINE=InnoDB; + +# Create table dhcp4_option_def_server +# M-to-M cross-reference between option definitions and servers +# +CREATE TABLE IF NOT EXISTS dhcp4_option_def_server ( + option_def_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_def_id, server_id), + KEY fk_dhcp4_option_def_server_server_id_idx (server_id), + KEY key_dhcp4_option_def_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp4_option_def (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp4_shared_network +# +CREATE TABLE IF NOT EXISTS dhcp4_shared_network ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id TINYINT(1) NOT NULL DEFAULT '1', + modification_ts TIMESTAMP NOT NULL, + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT DEFAULT NULL, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp4_shared_network_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Create table dhcp4_shared_network_server +# M-to-M cross-reference between shared networks and servers +# +CREATE TABLE IF NOT EXISTS dhcp4_shared_network_server ( + shared_network_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (shared_network_id, server_id), + KEY key_dhcp4_shared_network_server_modification_ts (modification_ts), + KEY fk_dhcp4_shared_network_server_server_id (server_id), + CONSTRAINT fk_dhcp4_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp4_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp4_subnet +# +CREATE TABLE IF NOT EXISTS dhcp4_subnet ( + subnet_id INT(10) UNSIGNED NOT NULL, + subnet_prefix VARCHAR(32) NOT NULL, + 4o6_interface VARCHAR(128) DEFAULT NULL, + 4o6_interface_id VARCHAR(128) DEFAULT NULL, + 4o6_subnet VARCHAR(64) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id TINYINT(1) NOT NULL DEFAULT '1', + modification_ts TIMESTAMP NOT NULL, + next_server INT(10) UNSIGNED DEFAULT NULL, + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT DEFAULT NULL, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + server_hostname VARCHAR(512) DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (subnet_id), + UNIQUE KEY subnet4_subnet_prefix (subnet_prefix), + KEY fk_dhcp4_subnet_shared_network (shared_network_name), + KEY key_dhcp4_subnet_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp4_pool +# +CREATE TABLE IF NOT EXISTS dhcp4_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + start_address INT(10) UNSIGNED NOT NULL, + end_address INT(10) UNSIGNED NOT NULL, + subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp4_pool_modification_ts (modification_ts), + KEY fk_dhcp4_pool_subnet_id (subnet_id), + CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +# Create table dhcp4_subnet_server +# M-to-M cross-reference between subnets and servers +# +CREATE TABLE IF NOT EXISTS dhcp4_subnet_server ( + subnet_id INT(10) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (subnet_id,server_id), + KEY fk_dhcp4_subnet_server_server_id_idx (server_id), + KEY key_dhcp4_subnet_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_subnet_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + + +# Modify the primary key to BINGINT as other tables have. +# +ALTER TABLE dhcp4_options MODIFY option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; + +# Add configuration backend specific columns. +ALTER TABLE dhcp4_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP NOT NULL; + +# Create table dhcp4_options_server +# M-to-M cross-reference between options and servers +# +CREATE TABLE IF NOT EXISTS dhcp4_options_server ( + option_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_id, server_id), + KEY fk_dhcp4_options_server_server_id (server_id), + KEY key_dhcp4_options_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp4_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp4_options (option_id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp4_pool_BDEL BEFORE DELETE ON dhcp4_pool FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM dhcp4_options WHERE scope_id = 5 AND pool_id = OLD.id; +END +$$ +DELIMITER ; + +# Create table dhcp6_server +# +CREATE TABLE IF NOT EXISTS dhcp6_server ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + tag VARCHAR(64) NOT NULL, + description TEXT, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY dhcp6_server_tag_UNIQUE (tag), + KEY key_dhcp6_server_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Special server entry meaning "all servers". This refers to +# the configuration entries owned by all servers. +INSERT INTO dhcp6_server(id, tag, description, modification_ts) + VALUES(1, "all", "special type: all servers", NOW()); + +# Create table dhcp6_audit +# +CREATE TABLE IF NOT EXISTS dhcp6_audit ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT(20) UNSIGNED NOT NULL, + modification_type TINYINT(1) NOT NULL, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + PRIMARY KEY (id), + KEY key_dhcp6_audit_modification_ts (modification_ts), + KEY fk_dhcp6_audit_modification_type (modification_type), + CONSTRAINT fk_dhcp6_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_global_parameter +# +CREATE TABLE IF NOT EXISTS dhcp6_global_parameter ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + value LONGTEXT NOT NULL, + modification_ts timestamp NOT NULL, + PRIMARY KEY (id), + KEY key_dhcp6_global_parameter_modification_ts (modification_ts), + KEY key_dhcp6_global_parameter_name (name) +) ENGINE=InnoDB; + +# Create table dhcp6_global_parameter_server +# M-to-M cross-reference between global parameters and servers +# +CREATE TABLE IF NOT EXISTS dhcp6_global_parameter_server ( + parameter_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (parameter_id, server_id), + KEY fk_dhcp6_global_parameter_server_server_id (server_id), + KEY key_dhcp6_global_parameter_server (modification_ts), + CONSTRAINT fk_dhcp6_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp6_global_parameter (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_option_def +# +CREATE TABLE IF NOT EXISTS dhcp6_option_def ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + code SMALLINT UNSIGNED NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type TINYINT UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + is_array TINYINT(1) NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR(512) DEFAULT NULL, + user_context LONGTEXT, + PRIMARY KEY (id), + KEY key_dhcp6_option_def_modification_ts (modification_ts), + KEY key_dhcp6_option_def_code_space (code, space) +) ENGINE=InnoDB; + +# Create table dhcp6_option_def_server +# M-to-M cross-reference between option definitions and servers +# +CREATE TABLE IF NOT EXISTS dhcp6_option_def_server ( + option_def_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_def_id, server_id), + KEY fk_dhcp6_option_def_server_server_id_idx (server_id), + KEY key_dhcp6_option_def_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp6_option_def (id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_shared_network +# +CREATE TABLE dhcp6_shared_network ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + preferred_lifetime INT(10) DEFAULT NULL, + rapid_commit TINYINT(1) NOT NULL DEFAULT '1', + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT DEFAULT NULL, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp6_shared_network_modification_ts (modification_ts) +) ENGINE=InnoDB; + +# Create table dhcp6_shared_network_server +# M-to-M cross-reference between shared networks and servers +# +CREATE TABLE IF NOT EXISTS dhcp6_shared_network_server ( + shared_network_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + KEY key_dhcp6_shared_network_server_modification_ts (modification_ts), + KEY fk_dhcp6_shared_network_server_server_id_idx (server_id), + KEY fk_dhcp6_shared_network_server_shared_network_id (shared_network_id), + CONSTRAINT fk_dhcp6_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_subnet +# +CREATE TABLE dhcp6_subnet ( + subnet_id int(10) UNSIGNED NOT NULL, + subnet_prefix VARCHAR(64) NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + preferred_lifetime INT(10) DEFAULT NULL, + rapid_commit TINYINT(1) NOT NULL DEFAULT '1', + rebind_timer INT(10) DEFAULT NULL, + relay LONGTEXT DEFAULT NULL, + renew_timer INT(10) DEFAULT NULL, + require_client_classes LONGTEXT, + reservation_mode TINYINT(3) NOT NULL DEFAULT '3', + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context LONGTEXT, + valid_lifetime INT(10) DEFAULT NULL, + PRIMARY KEY (subnet_id), + UNIQUE KEY subnet6_subnet_prefix (subnet_prefix), + KEY fk_dhcp6_subnet_shared_network (shared_network_name), + KEY key_dhcp6_subnet_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_subnet_server +# M-to-M cross-reference between subnets and servers +# +CREATE TABLE dhcp6_subnet_server ( + subnet_id INT(10) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (subnet_id, server_id), + KEY fk_dhcp6_subnet_server_server_id (server_id), + KEY key_dhcp6_subnet_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_subnet_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create table dhcp6_pd_pool +# +CREATE TABLE IF NOT EXISTS dhcp6_pd_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + prefix VARCHAR(45) NOT NULL, + prefix_length TINYINT(3) NOT NULL, + delegated_prefix_length TINYINT(3) NOT NULL, + dhcp6_subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY fk_dhcp6_pd_pool_subnet_id (dhcp6_subnet_id), + KEY key_dhcp6_pd_pool_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +# Create table dhcp6_pool +# +CREATE TABLE IF NOT EXISTS dhcp6_pool ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + start_address VARCHAR(45) NOT NULL, + end_address VARCHAR(45) NOT NULL, + dhcp6_subnet_id INT(10) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + KEY fk_dhcp6_pool_subnet_id (dhcp6_subnet_id), + KEY key_dhcp6_pool_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB; + +# Modify the primary key to BINGINT as other tables have. +ALTER TABLE dhcp6_options MODIFY option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; + +# Add configuration backend specific columns. +ALTER TABLE dhcp6_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN pd_pool_id BIGINT(20) UNSIGNED DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP NOT NULL; + +# Create table dhcp6_options_server +# M-to-M cross-reference between options and servers +# +CREATE TABLE IF NOT EXISTS dhcp6_options_server ( + option_id BIGINT(20) UNSIGNED NOT NULL, + server_id BIGINT(20) UNSIGNED NOT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (option_id, server_id), + KEY fk_dhcp6_options_server_server_id_idx (server_id), + KEY key_dhcp6_options_server_modification_ts (modification_ts), + CONSTRAINT fk_dhcp6_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) + ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp6_pool_BDEL BEFORE DELETE ON dhcp6_pool FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN +DELETE FROM dhcp6_options WHERE scope_id = 5 AND pool_id = OLD.id; +END +$$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '7', minor = '0'; + +# This line concludes database upgrade to version 7.0. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_007.0_to_008.0.sh.in b/src/share/database/scripts/mysql/upgrade_007.0_to_008.0.sh.in new file mode 100644 index 0000000..bba08bc --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_007.0_to_008.0.sh.in @@ -0,0 +1,996 @@ +#!/bin/sh + +# Copyright (C) 2019-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "7.0" ]; then + printf 'This script upgrades 7.0 to 8.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + + +ALTER TABLE dhcp4_options + MODIFY COLUMN modification_ts TIMESTAMP NOT NULL + DEFAULT CURRENT_TIMESTAMP; + +ALTER TABLE dhcp6_options + MODIFY COLUMN modification_ts TIMESTAMP NOT NULL + DEFAULT CURRENT_TIMESTAMP; + +ALTER TABLE dhcp4_subnet + ADD COLUMN authoritative TINYINT(1) DEFAULT NULL, + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + MODIFY COLUMN match_client_id TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN authoritative TINYINT(1) DEFAULT NULL, + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN boot_file_name VARCHAR(512) DEFAULT NULL, + ADD COLUMN next_server INT(10) UNSIGNED DEFAULT NULL, + ADD COLUMN server_hostname VARCHAR(512) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + MODIFY COLUMN match_client_id TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN interface_id VARCHAR(128) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + MODIFY COLUMN rapid_commit TINYINT(1) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN calculate_tee_times TINYINT(1) DEFAULT NULL, + ADD COLUMN t1_percent FLOAT DEFAULT NULL, + ADD COLUMN t2_percent FLOAT DEFAULT NULL, + ADD COLUMN interface_id VARCHAR(128) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + MODIFY COLUMN reservation_mode TINYINT(3) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + MODIFY COLUMN rapid_commit TINYINT(1) DEFAULT NULL; + +-- ----------------------------------------------------- +-- Make sure that constraints on the 7.0 schema tables +-- have appropriate referential actions. All tables +-- which join the configuration elements with the +-- servers should perform cascade deletion. +-- ----------------------------------------------------- + +ALTER TABLE dhcp4_global_parameter_server + DROP FOREIGN KEY fk_dhcp4_global_parameter_server_server_id; + +ALTER TABLE dhcp4_global_parameter_server + ADD CONSTRAINT fk_dhcp4_global_parameter_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_option_def_server + DROP FOREIGN KEY fk_dhcp4_option_def_server_server_id; + +ALTER TABLE dhcp4_option_def_server + ADD CONSTRAINT fk_dhcp4_option_def_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_shared_network_server + DROP FOREIGN KEY fk_dhcp4_shared_network_server_server_id; + +ALTER TABLE dhcp4_shared_network_server + ADD CONSTRAINT fk_dhcp4_shared_network_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_subnet_server + DROP FOREIGN KEY fk_dhcp4_subnet_server_server_id; + +ALTER TABLE dhcp4_subnet_server + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp4_options_server + DROP FOREIGN KEY fk_dhcp4_options_server_server_id; + +ALTER TABLE dhcp4_options_server + ADD CONSTRAINT fk_dhcp4_options_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_global_parameter_server + DROP FOREIGN KEY fk_dhcp6_global_parameter_server_server_id; + +ALTER TABLE dhcp6_global_parameter_server + ADD CONSTRAINT fk_dhcp6_global_parameter_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_option_def_server + DROP FOREIGN KEY fk_dhcp6_option_def_server_server_id; + +ALTER TABLE dhcp6_option_def_server + ADD CONSTRAINT fk_dhcp6_option_def_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_shared_network_server + DROP FOREIGN KEY fk_dhcp6_shared_network_server_server_id; + +ALTER TABLE dhcp6_shared_network_server + ADD CONSTRAINT fk_dhcp6_shared_network_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_subnet_server + DROP FOREIGN KEY fk_dhcp6_subnet_server_server_id; + +ALTER TABLE dhcp6_subnet_server + ADD CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +ALTER TABLE dhcp6_options_server + DROP FOREIGN KEY fk_dhcp6_options_server_option_id; + +ALTER TABLE dhcp6_options_server + ADD CONSTRAINT fk_dhcp6_options_server_option_id + FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +-- ----------------------------------------------------- +-- Table dhcp4_audit_revision +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_audit_revision ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + server_id BIGINT(10) UNSIGNED, + PRIMARY KEY (id), + KEY key_dhcp4_audit_revision_by_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Drop columns from the dhcp4_audit table which now +-- belong to the dhcp4_audit_revision. +-- ----------------------------------------------------- +ALTER TABLE dhcp4_audit + DROP COLUMN modification_ts, + DROP COLUMN log_message; + +-- ----------------------------------------------------- +-- Add column revision_id and the foreign key with a +-- reference to the dhcp4_audit_revision table. +-- ----------------------------------------------------- +ALTER TABLE dhcp4_audit + ADD COLUMN revision_id BIGINT(20) UNSIGNED NOT NULL; + +ALTER TABLE dhcp4_audit + ADD CONSTRAINT fk_dhcp4_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp4_audit_revision (id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP4; +DELIMITER $$ +CREATE PROCEDURE createAuditRevisionDHCP4(IN audit_ts TIMESTAMP, + IN server_tag VARCHAR(256), + IN audit_log_message TEXT, + IN cascade_transaction TINYINT(1)) +BEGIN + DECLARE srv_id BIGINT(20); + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + SELECT id INTO srv_id FROM dhcp4_server WHERE tag = server_tag; + INSERT INTO dhcp4_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message); + SET @audit_revision_id = LAST_INSERT_ID(); + SET @cascade_transaction = cascade_transaction; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The @audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. "create", "update" or +-- "delete". +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditEntryDHCP4; +DELIMITER $$ +CREATE PROCEDURE createAuditEntryDHCP4(IN object_type_val VARCHAR(256), + IN object_id_val BIGINT(20) UNSIGNED, + IN modification_type_val VARCHAR(32)) +BEGIN + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + INSERT INTO dhcp4_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, \ + (SELECT id FROM modification WHERE modification_type = modification_type_val), \ + @audit_revision_id); + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Triggers used to create entries in the audit +-- tables upon insertion, update or deletion of the +-- configuration entries. +-- ----------------------------------------------------- + +# Create dhcp4_global_parameter insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_AINS AFTER INSERT ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_global_parameter update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_AUPD AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_global_parameter delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_global_parameter_ADEL AFTER DELETE ON dhcp4_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_global_parameter', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_AINS AFTER INSERT ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_AUPD AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_subnet delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_ADEL AFTER DELETE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_AINS AFTER INSERT ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_AUPD AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_shared_network delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_ADEL AFTER DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_AINS AFTER INSERT ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_AUPD AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_option_def delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_option_def_ADEL AFTER DELETE ON dhcp4_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_option_def', OLD.id, "delete"); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates an audit entry for a +-- DHCPv4 option. Depending on the scope of the option +-- the audit entry can be created for various levels +-- of configuration hierarchy. If this is a global +-- option the audit entry is created for this option +-- for CREATE, UPDATE or DELETE. If the option is being +-- added for an owning option, e.g. for a subnet, the +-- audit entry is created as an UPDATE to this object. +-- From the Kea perspective such option addition will +-- be seen as a subnet update and the server will fetch +-- the whole subnet and merge it into its configuration. +-- The audit entry is not created if it was already +-- created as part of the current transaction. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP4; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP4(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20)) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp4_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp4_options' table. + CALL createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, create + # audit entry for the entire subnet, which indicates that + # it should be treated as the subnet update. + CALL createAuditEntryDHCP4('dhcp4_subnet', subnet_id, "update"); + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # create audit entry for the shared network which + # indicates that it should be treated as the shared + # network update. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + CALL createAuditEntryDHCP4('dhcp4_shared_network', snid, "update"); + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + CALL createAuditEntryDHCP4('dhcp4_subnet', sid, "update"); + END IF; + END IF; +END $$ +DELIMITER ; + +# Create dhcp4_options insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AINS AFTER INSERT ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("create", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id); + END $$ +DELIMITER ; + +# Create dhcp4_options update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AUPD AFTER UPDATE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("update", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id); + END $$ +DELIMITER ; + +# Create dhcp4_options delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_options_ADEL AFTER DELETE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("delete", OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Table parameter_data_type +-- Reflects an enum used by Kea to define supported +-- data types for the simple configuration parameters, +-- e.g. global parameters used by DHCP servers. +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS parameter_data_type ( + id TINYINT UNSIGNED NOT NULL PRIMARY KEY, + name VARCHAR(32) NOT NULL +) ENGINE = InnoDB; + +START TRANSACTION; +INSERT INTO parameter_data_type VALUES (0, 'integer'); +INSERT INTO parameter_data_type VALUES (1, 'real'); +INSERT INTO parameter_data_type VALUES (2, 'boolean'); +INSERT INTO parameter_data_type VALUES (4, 'string'); +COMMIT; + +ALTER TABLE dhcp4_global_parameter + ADD COLUMN parameter_type TINYINT UNSIGNED NOT NULL; + +ALTER TABLE dhcp4_global_parameter + ADD CONSTRAINT fk_dhcp4_global_parameter_type FOREIGN KEY (parameter_type) + REFERENCES parameter_data_type (id); + +ALTER TABLE dhcp6_global_parameter + ADD COLUMN parameter_type TINYINT UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_global_parameter + ADD CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) + REFERENCES parameter_data_type (id); + + +-- Rename dhcp6_subnet_id column of dhcp6_pool and dhcp6_pd_pool + +ALTER TABLE dhcp6_pool + DROP FOREIGN KEY fk_dhcp6_pool_subnet_id; +DROP INDEX fk_dhcp6_pool_subnet_id + ON dhcp6_pool; + +ALTER TABLE dhcp6_pd_pool + DROP FOREIGN KEY fk_dhcp6_pd_pool_subnet_id; +DROP INDEX fk_dhcp6_pd_pool_subnet_id + ON dhcp6_pd_pool; + +ALTER TABLE dhcp6_pool + CHANGE dhcp6_subnet_id subnet_id INT(10) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_pd_pool + CHANGE dhcp6_subnet_id subnet_id INT(10) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_pool + ADD CONSTRAINT fk_dhcp6_pool_subnet_id + FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_pd_pool + ADD CONSTRAINT fk_dhcp6_pd_pool_subnet_id + FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +-- align dhcp6_shared_network_server indexes on dhcp4_shared_network_server + +ALTER TABLE dhcp6_shared_network_server + ADD PRIMARY KEY (shared_network_id, server_id); + +ALTER TABLE dhcp6_shared_network_server + DROP FOREIGN KEY fk_dhcp6_shared_network_server_shared_network_id; +DROP INDEX fk_dhcp6_shared_network_server_shared_network_id + ON dhcp6_shared_network_server; +ALTER TABLE dhcp6_shared_network_server + ADD CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id + FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) + ON DELETE CASCADE ON UPDATE NO ACTION; + +-- Update dhcp4_subnet_server and dhcp6_subnet_server to allow update +-- on the prefix too by setting the CASCADE action. + +ALTER TABLE dhcp4_subnet_server + DROP FOREIGN KEY fk_dhcp4_subnet_server_subnet_id; +ALTER TABLE dhcp4_subnet_server + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_subnet_server + DROP FOREIGN KEY fk_dhcp6_subnet_server_subnet_id; +ALTER TABLE dhcp6_subnet_server + ADD CONSTRAINT fk_dhcp6_subnet_server_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Table dhcp6_audit_revision +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_audit_revision ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + modification_ts TIMESTAMP NOT NULL, + log_message TEXT, + server_id BIGINT(10) UNSIGNED, + PRIMARY KEY (id), + KEY key_dhcp6_audit_revision_by_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------- +-- Drop columns from the dhcp6_audit table which now +-- belong to the dhcp6_audit_revision. +-- ----------------------------------------------------- +ALTER TABLE dhcp6_audit + DROP COLUMN modification_ts, + DROP COLUMN log_message; + +-- ----------------------------------------------------- +-- Add column revision_id and the foreign key with a +-- reference to the dhcp6_audit_revision table. +-- ----------------------------------------------------- +ALTER TABLE dhcp6_audit + ADD COLUMN revision_id BIGINT(20) UNSIGNED NOT NULL; + +ALTER TABLE dhcp6_audit + ADD CONSTRAINT fk_dhcp6_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp6_audit_revision (id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditRevisionDHCP6; +DELIMITER $$ +CREATE PROCEDURE createAuditRevisionDHCP6(IN audit_ts TIMESTAMP, + IN server_tag VARCHAR(256), + IN audit_log_message TEXT, + IN cascade_transaction TINYINT(1)) +BEGIN + DECLARE srv_id BIGINT(20); + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + SELECT id INTO srv_id FROM dhcp6_server WHERE tag = server_tag; + INSERT INTO dhcp6_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message); + SET @audit_revision_id = LAST_INSERT_ID(); + SET @cascade_transaction = cascade_transaction; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The @audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. "create", "update" or +-- "delete". +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +DROP PROCEDURE IF EXISTS createAuditEntryDHCP6; +DELIMITER $$ +CREATE PROCEDURE createAuditEntryDHCP6(IN object_type_val VARCHAR(256), + IN object_id_val BIGINT(20) UNSIGNED, + IN modification_type_val VARCHAR(32)) +BEGIN + IF @disable_audit IS NULL OR @disable_audit = 0 THEN + INSERT INTO dhcp6_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, \ + (SELECT id FROM modification WHERE modification_type = modification_type_val), \ + @audit_revision_id); + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Triggers used to create entries in the audit +-- tables upon insertion, update or deletion of the +-- configuration entries. +-- ----------------------------------------------------- + +# Create dhcp6_global_parameter insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_AINS AFTER INSERT ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_global_parameter update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_AUPD AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_global_parameter delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_global_parameter_ADEL AFTER DELETE ON dhcp6_global_parameter + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_global_parameter', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_AINS AFTER INSERT ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_AUPD AFTER UPDATE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_subnet delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_ADEL AFTER DELETE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_AINS AFTER INSERT ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_AUPD AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_shared_network delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_ADEL AFTER DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_AINS AFTER INSERT ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_AUPD AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_option_def delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_option_def_ADEL AFTER DELETE ON dhcp6_option_def + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_option_def', OLD.id, "delete"); + END $$ +DELIMITER ; + +-- ----------------------------------------------------- +-- Stored procedure which creates an audit entry for a +-- DHCPv6 option. Depending on the scope of the option +-- the audit entry can be created for various levels +-- of configuration hierarchy. If this is a global +-- option the audit entry is created for this option +-- for CREATE, UPDATE or DELETE. If the option is being +-- added for an owning option, e.g. for a subnet, the +-- audit entry is created as an UPDATE to this object. +-- From the Kea perspective such option addition will +-- be seen as a subnet update and the server will fetch +-- the whole subnet and merge it into its configuration. +-- The audit entry is not created if it was already +-- created as part of the current transaction. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP6; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP6(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN pd_pool_id BIGINT(20)) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp6_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp6_options' table. + CALL createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, create + # audit entry for the entire subnet, which indicates that + # it should be treated as the subnet update. + CALL createAuditEntryDHCP6('dhcp6_subnet', subnet_id, "update"); + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # create audit entry for the shared network which + # indicates that it should be treated as the shared + # network update. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + CALL createAuditEntryDHCP6('dhcp6_shared_network', snid, "update"); + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + CALL createAuditEntryDHCP6('dhcp6_subnet', sid, "update"); + ELSEIF scope_id = 6 THEN + # If pd pool specific option is added or modified, create + # audit entry for the subnet which this pd pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + CALL createAuditEntryDHCP6('dhcp6_subnet', sid, "update"); + END IF; + END IF; +END $$ +DELIMITER ; + +# Create dhcp6_options insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AINS AFTER INSERT ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("create", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, NEW.pd_pool_id); + END $$ +DELIMITER ; + +# Create dhcp6_options update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AUPD AFTER UPDATE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("update", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, NEW.pd_pool_id); + END $$ +DELIMITER ; + +# Create dhcp6_options delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_options_ADEL AFTER DELETE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("delete", OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, OLD.pd_pool_id); + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '0'; + +# This line concludes database upgrade to version 8.0. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_008.0_to_008.1.sh.in b/src/share/database/scripts/mysql/upgrade_008.0_to_008.1.sh.in new file mode 100644 index 0000000..f2c3e49 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_008.0_to_008.1.sh.in @@ -0,0 +1,123 @@ +#!/bin/sh + +# Copyright (C) 2019-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "8.0" ]; then + printf 'This script upgrades 8.0 to 8.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add lifetime bounds +ALTER TABLE dhcp4_shared_network + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_valid_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_valid_lifetime INT(10) DEFAULT NULL; + +# Create dhcp4_server insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_AINS AFTER INSERT ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp4_server update trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_AUPD AFTER UPDATE ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp4_server delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp4_server_ADEL AFTER DELETE ON dhcp4_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_server', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Create dhcp6_server insert trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_AINS AFTER INSERT ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', NEW.id, "create"); + END $$ +DELIMITER ; + +# Create dhcp6_server update trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_AUPD AFTER UPDATE ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', NEW.id, "update"); + END $$ +DELIMITER ; + +# Create dhcp6_server delete trigger +DELIMITER $$ +CREATE TRIGGER dhcp6_server_ADEL AFTER DELETE ON dhcp6_server + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_server', OLD.id, "delete"); + END $$ +DELIMITER ; + +# Put the auth key in hexadecimal (double size but far more user friendly). +ALTER TABLE hosts + MODIFY COLUMN auth_key VARCHAR(32) NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '1'; + +# This line concludes database upgrade to version 8.1. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_008.1_to_008.2.sh.in b/src/share/database/scripts/mysql/upgrade_008.1_to_008.2.sh.in new file mode 100644 index 0000000..4ad298e --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_008.1_to_008.2.sh.in @@ -0,0 +1,500 @@ +#!/bin/sh + +# Copyright (C) 2019-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# shellcheck disable=SC2039 +# SC2039: In POSIX sh, 'local' is undefined. + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "8.1" ]; then + printf 'This script upgrades 8.1 to 8.2. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we can id the schema +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +# Save the command line args, as we use these later change_column function. + +# Function to rename a column in a table. +change_column() { + local schema="${1-}"; shift + local table="${1-}"; shift + local ocolumn="${1-}"; shift + local ncolumn="${1-}"; shift + + # First let's find out if the column name in the table actually needs updating. + sql="select count(column_name) from information_schema.columns where table_schema='$schema' and table_name = '$table' and column_name = '$ocolumn'" + if ! count=$(mysql -N -B "${@}" -e "${sql}") + then + printf 'change_column: schema query failed [%s]\n' "${sql}" + exit 255 + fi + + # If we found a match record, the column needs to be renamed + if [ "$count" -eq 1 ] + then + sql="ALTER TABLE $table CHANGE COLUMN $ocolumn $ncolumn" + if ! mysql -N -B "${@}" -e "${sql}" + then + printf 'change_column: alter query failed [%s]\n' "${sql}" + exit 255 + fi + else + printf '%s column is already correct\n' "${table}" + fi +} + +mysql "$@" <<EOF + +# Drop existing trigger on the dhcp4_shared_network table. +DROP TRIGGER dhcp4_shared_network_ADEL; + +# Create new trigger which will delete options associated with the shared +# network. +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_BDEL BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +# Drop existing trigger on the dhcp4_subnet table. +DROP TRIGGER dhcp4_subnet_ADEL; + +# Create new trigger which will delete pools associated with the subnet and +# the options associated with the subnet. +DELIMITER $$ +CREATE TRIGGER dhcp4_subnet_BDEL BEFORE DELETE ON dhcp4_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, "delete"); + DELETE FROM dhcp4_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp4_options WHERE dhcp4_subnet_id = OLD.subnet_id; + END $$ +DELIMITER ; + +# Do not perform cascade deletion of the data in the dhcp4_pool because +# the cascade deletion does not execute triggers associated with the table. +# Instead we are going to use triggers on the dhcp4_subnet table. +ALTER TABLE dhcp4_pool + DROP FOREIGN KEY fk_dhcp4_pool_subnet_id; + +ALTER TABLE dhcp4_pool + ADD CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp4_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +# Drop existing trigger on the dhcp6_shared_network table. +DROP TRIGGER dhcp6_shared_network_ADEL; + +# Create new trigger which will delete options associated with the shared +# network. +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_BDEL BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +# Drop existing trigger on the dhcp6_subnet table. +DROP TRIGGER dhcp6_subnet_ADEL; + +# Create new trigger which will delete pools associated with the subnet and +# the options associated with the subnet. +DELIMITER $$ +CREATE TRIGGER dhcp6_subnet_BDEL BEFORE DELETE ON dhcp6_subnet + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, "delete"); + DELETE FROM dhcp6_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_pd_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_options WHERE dhcp6_subnet_id = OLD.subnet_id; + END $$ +DELIMITER ; + +# Do not perform cascade deletion of the data in the dhcp6_pool and dhcp6_pd_pool +# because the cascaded deletion does not execute triggers associated with the table. +# Instead we are going to use triggers on the dhcp6_subnet table. +ALTER TABLE dhcp6_pool + DROP FOREIGN KEY fk_dhcp6_pool_subnet_id; + +ALTER TABLE dhcp6_pd_pool + DROP FOREIGN KEY fk_dhcp6_pd_pool_subnet_id; + +ALTER TABLE dhcp6_pool + ADD CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +ALTER TABLE dhcp6_pd_pool + ADD CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (subnet_id) + REFERENCES dhcp6_subnet (subnet_id) + ON DELETE NO ACTION ON UPDATE CASCADE; + +# Create trigger which removes pool specific options upon removal of +# the pool. +DELIMITER $$ +CREATE TRIGGER dhcp6_pd_pool_BDEL BEFORE DELETE ON dhcp6_pd_pool FOR EACH ROW +BEGIN +DELETE FROM dhcp6_options WHERE scope_id = 6 AND pd_pool_id = OLD.id; +END +$$ +DELIMITER ; + +# Add missing columns in pools. +ALTER TABLE dhcp4_pool + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +ALTER TABLE dhcp6_pd_pool + ADD COLUMN excluded_prefix VARCHAR(45) DEFAULT NULL, + ADD COLUMN excluded_prefix_length TINYINT(3) NOT NULL, + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +ALTER TABLE dhcp6_pool + ADD COLUMN client_class VARCHAR(128) DEFAULT NULL, + ADD COLUMN require_client_classes LONGTEXT, + ADD COLUMN user_context LONGTEXT; + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP4 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP4; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP4(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN modification_ts TIMESTAMP) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp4_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp4_options' table. + CALL createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, update + # the modification timestamp of this subnet to allow the + # servers to refresh the subnet information. This will + # also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = subnet_id; + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # update the modification timestamp of this shared network + # to allow the servers to refresh the shared network + # information. This will also result in creating an + # audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network AS n SET n.modification_ts = modification_ts + WHERE n.id = snid; + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, update + # the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + END IF; + END IF; +END $$ +DELIMITER ; + +# Recreate dhcp4_options_AINS trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_AINS; + +# This trigger is executed after inserting a DHCPv4 option into the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AINS AFTER INSERT ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("create", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp4_options_AUPD trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_AUPD; + +# This trigger is executed after updating a DHCPv4 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_AUPD AFTER UPDATE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("update", NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp4_options_ADEL trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP4. +DROP TRIGGER IF EXISTS dhcp4_options_ADEL; + +# This trigger is executed after deleting a DHCPv4 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp4_options_ADEL AFTER DELETE ON dhcp4_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP4("delete", OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + NOW()); + END $$ +DELIMITER ; + + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP4 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +DROP PROCEDURE IF EXISTS createOptionAuditDHCP6; +DELIMITER $$ +CREATE PROCEDURE createOptionAuditDHCP6(IN modification_type VARCHAR(32), + IN scope_id TINYINT(3) UNSIGNED, + IN option_id BIGINT(20) UNSIGNED, + IN subnet_id INT(10) UNSIGNED, + IN host_id INT(10) UNSIGNED, + IN network_name VARCHAR(128), + IN pool_id BIGINT(20), + IN pd_pool_id BIGINT(20), + IN modification_ts TIMESTAMP) +BEGIN + # These variables will hold shared network id and subnet id that + # we will select. + DECLARE snid VARCHAR(128); + DECLARE sid INT(10) UNSIGNED; + + # Cascade transaction flag is set to 1 to prevent creation of + # the audit entries for the options when the options are + # created as part of the parent object creation or update. + # For example: when the option is added as part of the subnet + # addition, the cascade transaction flag is equal to 1. If + # the option is added into the existing subnet the cascade + # transaction is equal to 0. Note that depending on the option + # scope the audit entry will contain the object_type value + # of the parent object to cause the server to replace the + # entire subnet. The only case when the object_type will be + # set to 'dhcp6_options' is when a global option is added. + # Global options do not have the owner. + IF @cascade_transaction IS NULL OR @cascade_transaction = 0 THEN + # todo: host manager hasn't been updated to use audit + # mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + # If a global option is added or modified, create audit + # entry for the 'dhcp6_options' table. + CALL createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + # If subnet specific option is added or modified, update + # the modification timestamp of this subnet to allow the + # servers to refresh the subnet information. This will + # also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = subnet_id; + ELSEIF scope_id = 4 THEN + # If shared network specific option is added or modified, + # update the modification timestamp of this shared network + # to allow the servers to refresh the shared network + # information. This will also result in creating an + # audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network AS n SET n.modification_ts = modification_ts + WHERE n.id = snid; + ELSEIF scope_id = 5 THEN + # If pool specific option is added or modified, update + # the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + ELSEIF scope_id = 6 THEN + # If pd pool specific option is added or modified, create + # audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + UPDATE dhcp6_subnet AS s SET s.modification_ts = modification_ts + WHERE s.subnet_id = sid; + END IF; + END IF; +END $$ +DELIMITER ; + +# Recreate dhcp6_options_AINS trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_AINS; + +# This trigger is executed after inserting a DHCPv6 option into the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AINS AFTER INSERT ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("create", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp6_options_AUPD trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_AUPD; + +# This trigger is executed after updating a DHCPv6 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_AUPD AFTER UPDATE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("update", NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + END $$ +DELIMITER ; + +# Recreate dhcp6_options_ADEL trigger to pass timestamp to the updated +# version of the createOptionAuditDHCP6. +DROP TRIGGER IF EXISTS dhcp6_options_ADEL; + +# This trigger is executed after deleting a DHCPv6 option in the +# database. It creates appropriate audit entry for this option or +# a parent object owning this option. +DELIMITER $$ +CREATE TRIGGER dhcp6_options_ADEL AFTER DELETE ON dhcp6_options + FOR EACH ROW + BEGIN + CALL createOptionAuditDHCP6("delete", OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + OLD.pd_pool_id, NOW()); + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '8', minor = '2'; + +# This line concludes database upgrade to version 8.2. + +EOF + +# We need to rename the columns in the option def tables because "array" is +# a MySQL keyword as of 8.0.17 +change_column "${schema}" dhcp4_option_def array "is_array TINYINT(1) NOT NULL" "${@}" +change_column "${schema}" dhcp6_option_def array "is_array TINYINT(1) NOT NULL" "${@}" diff --git a/src/share/database/scripts/mysql/upgrade_008.2_to_009.0.sh.in b/src/share/database/scripts/mysql/upgrade_008.2_to_009.0.sh.in new file mode 100644 index 0000000..fdbf17d --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_008.2_to_009.0.sh.in @@ -0,0 +1,61 @@ +#!/bin/sh + +# Copyright (C) 2019-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "8.2" ]; then + printf 'This script upgrades 8.2 to 9.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Create hostname index for host reservations +CREATE INDEX hosts_by_hostname ON hosts (hostname); + +# Move to lower case hostnames in lease4 table. +UPDATE lease4 SET hostname = LOWER(hostname) +WHERE BINARY LOWER(hostname) != hostname; + +# Move to lower case hostnames in lease6 table. +UPDATE lease6 SET hostname = LOWER(hostname) +WHERE BINARY LOWER(hostname) != hostname; + +# Create hostname index for lease4 +CREATE INDEX lease4_by_hostname ON lease4 (hostname); + +# Create hostname index for lease6 +CREATE INDEX lease6_by_hostname ON lease6 (hostname); + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '0'; + +# This line concludes database upgrade to version 9.0. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.0_to_009.1.sh.in b/src/share/database/scripts/mysql/upgrade_009.0_to_009.1.sh.in new file mode 100644 index 0000000..473a18f --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.0_to_009.1.sh.in @@ -0,0 +1,77 @@ +#!/bin/sh + +# Copyright (C) 2020-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "9.0" ]; then + printf 'This script upgrades 9.0 to 9.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add new DDNS related columns to shared networks and subnets +ALTER TABLE dhcp4_shared_network + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp4_subnet + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN ddns_send_updates TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_no_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_override_client_update TINYINT(1) DEFAULT NULL, + ADD COLUMN ddns_replace_client_name TINYINT(3) DEFAULT NULL, + ADD COLUMN ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ADD COLUMN ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '1'; + +# This line concludes database upgrade to version 9.1. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.1_to_009.2.sh.in b/src/share/database/scripts/mysql/upgrade_009.1_to_009.2.sh.in new file mode 100644 index 0000000..3b8cd34 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.1_to_009.2.sh.in @@ -0,0 +1,81 @@ +#!/bin/sh + +# Copyright (C) 2020-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "9.1" ]; then + printf 'This script upgrades 9.1 to 9.2. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add missing indexes (foreign keys) to the dhcp4_options table. +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_shared_network + FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network(name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_subnet + FOREIGN KEY (dhcp4_subnet_id) + REFERENCES dhcp4_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_pool + FOREIGN KEY (pool_id) + REFERENCES dhcp4_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Add missing indexes (foreign keys) to the dhcp6_options table. +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_shared_network + FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network(name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_subnet + FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_pool + FOREIGN KEY (pool_id) + REFERENCES dhcp6_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_pd_pool + FOREIGN KEY (pd_pool_id) + REFERENCES dhcp6_pd_pool(id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '2'; + +# This line concludes database upgrade to version 9.2. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.2_to_009.3.sh.in b/src/share/database/scripts/mysql/upgrade_009.2_to_009.3.sh.in new file mode 100644 index 0000000..76e8608 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.2_to_009.3.sh.in @@ -0,0 +1,140 @@ +#!/bin/sh + +# Copyright (C) 2020-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "9.2" ]; then + printf 'This script upgrades 9.2 to 9.3. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Fix stat_lease4_update trigger +DROP TRIGGER stat_lease4_update; + +DELIMITER $$ +CREATE TRIGGER stat_lease4_update AFTER UPDATE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.subnet_id != NEW.subnet_id OR OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease4_delete trigger +DROP TRIGGER stat_lease4_delete; + +DELIMITER $$ +CREATE TRIGGER stat_lease4_delete AFTER DELETE ON lease4 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease6_update trigger +DROP TRIGGER stat_lease6_update; + +DELIMITER $$ +CREATE TRIGGER stat_lease6_update AFTER UPDATE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.subnet_id != NEW.subnet_id OR + OLD.lease_type != NEW.lease_type OR + OLD.state != NEW.state THEN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the old state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state = 0 OR NEW.state = 1 THEN + # Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + # Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + END $$ +DELIMITER ; + +# Fix stat_lease6_delete trigger +DROP TRIGGER stat_lease6_delete; + +DELIMITER $$ +CREATE TRIGGER stat_lease6_delete AFTER DELETE ON lease6 + FOR EACH ROW + BEGIN + IF OLD.state = 0 OR OLD.state = 1 THEN + # Decrement the state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + END $$ +DELIMITER ; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '3'; + +# This line concludes database upgrade to version 9.3. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.3_to_009.4.sh.in b/src/share/database/scripts/mysql/upgrade_009.3_to_009.4.sh.in new file mode 100644 index 0000000..69b3f65 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.3_to_009.4.sh.in @@ -0,0 +1,84 @@ +#!/bin/sh + +# Copyright (C) 2020-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "9.3" ]; then + printf 'This script upgrades 9.3 to 9.4. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Starting from this version we allow specifying multiple IP reservations +# for the same address in certain DHCP configurations. The server may check +# uniqueness of the IP addresses on its own. This is no longer checked at +# the database level to facilitate the use cases when a single host may +# get the same reserved IP address via different interfaces. + +# Replace the unique index with non-unique index so the queries for +# hosts by IPv4 address are still efficient. +DROP INDEX key_dhcp4_ipv4_address_subnet_id ON hosts; +CREATE INDEX key_dhcp4_ipv4_address_subnet_id_identifier + ON hosts (ipv4_address ASC, dhcp4_subnet_id ASC); + +# Replace the unique index with non-unique index so the queries for +# hosts by IPv6 address are still efficient. +DROP INDEX key_dhcp6_address_prefix_len ON ipv6_reservations; +CREATE INDEX key_dhcp6_address_prefix_len + ON ipv6_reservations (address ASC, prefix_len ASC); + +# Stop using a trigger to delete entries dependent on hosts table. +# Use cascade action instead. This works better with complex delete +# statements. +DROP TRIGGER IF EXISTS host_BDEL; + +# Replace existing constraint to set cascade actions. +ALTER TABLE ipv6_reservations DROP FOREIGN KEY fk_ipv6_reservations_Host; +ALTER TABLE ipv6_reservations ADD CONSTRAINT fk_ipv6_reservations_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_Host + FOREIGN KEY (host_id) + REFERENCES hosts(host_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '4'; + +# This line concludes database upgrade to version 9.4. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.4_to_009.5.sh.in b/src/share/database/scripts/mysql/upgrade_009.4_to_009.5.sh.in new file mode 100644 index 0000000..ebf3117 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.4_to_009.5.sh.in @@ -0,0 +1,170 @@ +#!/bin/sh + +# Copyright (C) 2020-2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(mysql_version "$@") + +if [ "$VERSION" != "9.4" ]; then + printf 'This script upgrades 9.4 to 9.5. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +mysql "$@" <<EOF + +# Add new reservations flags. +ALTER TABLE dhcp4_subnet + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN reservations_global BOOL DEFAULT NULL, + ADD COLUMN reservations_in_subnet BOOL DEFAULT NULL, + ADD COLUMN reservations_out_of_pool BOOL DEFAULT NULL; + +# Disable audit in this session +SET @disable_audit = 1; + +# Translate reservation_mode to new flags. +# 0 is DISABLED +# 1 is OUT_OF_POOL +# 2 is GLOBAL +# 3 is ALL +UPDATE dhcp4_subnet + SET reservations_global = FALSE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 0; + +UPDATE dhcp4_subnet + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = TRUE + WHERE reservation_mode = 1; + +UPDATE dhcp4_subnet + SET reservations_global = TRUE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 2; + +UPDATE dhcp4_subnet + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = FALSE + WHERE reservation_mode = 3; + +UPDATE dhcp4_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 0; + +UPDATE dhcp4_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = TRUE + WHERE reservation_mode = 1; + +UPDATE dhcp4_shared_network + SET reservations_global = TRUE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 2; + +UPDATE dhcp4_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = FALSE + WHERE reservation_mode = 3; + +UPDATE dhcp6_subnet + SET reservations_global = FALSE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 0; + +UPDATE dhcp6_subnet + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = TRUE + WHERE reservation_mode = 1; + +UPDATE dhcp6_subnet + SET reservations_global = TRUE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 2; + +UPDATE dhcp6_subnet + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = FALSE + WHERE reservation_mode = 3; + +UPDATE dhcp6_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 0; + +UPDATE dhcp6_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = TRUE + WHERE reservation_mode = 1; + +UPDATE dhcp6_shared_network + SET reservations_global = TRUE, + reservations_in_subnet = FALSE + WHERE reservation_mode = 2; + +UPDATE dhcp6_shared_network + SET reservations_global = FALSE, + reservations_in_subnet = TRUE, + reservations_out_of_pool = FALSE + WHERE reservation_mode = 3; + +# DROP reservation_mode +ALTER TABLE dhcp4_subnet DROP COLUMN reservation_mode; +ALTER TABLE dhcp4_shared_network DROP COLUMN reservation_mode; +ALTER TABLE dhcp6_subnet DROP COLUMN reservation_mode; +ALTER TABLE dhcp6_shared_network DROP COLUMN reservation_mode; + +# Enable audit in this session +SET @disable_audit = 0; + +# Update the schema version number +UPDATE schema_version +SET version = '9', minor = '5'; + +# This line concludes database upgrade to version 9.5. + +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.5_to_009.6.sh.in b/src/share/database/scripts/mysql/upgrade_009.5_to_009.6.sh.in new file mode 100644 index 0000000..717730b --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.5_to_009.6.sh.in @@ -0,0 +1,70 @@ +#!/bin/sh + +# Copyright (C) 2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "9.5"; then + printf 'This script upgrades 9.5 to 9.6. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Add column only if it doesn't exist to work around the 1.9.4 leak of +# cache_threshold and cache_max_age column alters in subnet and shared network +# tables in schema version 9.5. +if ! mysql "${@}" -e 'SELECT cache_threshold FROM dhcp4_subnet LIMIT 1' &> /dev/null; then + mysql "${@}" <<EOF +# Add new lease cache parameters. +ALTER TABLE dhcp4_subnet + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp4_shared_network + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_subnet + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; + +ALTER TABLE dhcp6_shared_network + ADD COLUMN cache_threshold FLOAT DEFAULT NULL, + ADD COLUMN cache_max_age INT(10) DEFAULT NULL; +EOF +fi + +mysql "${@}" <<EOF +# Add an auto-increment ID as primary key to support Percona. +ALTER TABLE logs + ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY; + +# Update the schema version number +UPDATE schema_version + SET version = '9', minor = '6'; + +# This line concludes database upgrade to version 9.6. +EOF diff --git a/src/share/database/scripts/mysql/upgrade_009.6_to_010.0.sh.in b/src/share/database/scripts/mysql/upgrade_009.6_to_010.0.sh.in new file mode 100644 index 0000000..1b01cad --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_009.6_to_010.0.sh.in @@ -0,0 +1,1029 @@ +#!/bin/sh + +# Copyright (C) 2021-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "9.6"; then + printf 'This script upgrades 9.6 to 10.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we have the schema. +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +shrink_tag_column() { + local schema="${1-}"; shift + local table="${1-}"; shift + + # Check if the table already has a correct server tag length. + sql="SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${schema}' AND TABLE_NAME='${table}' AND COLUMN_NAME='tag'" + if ! taglen=$(mysql -N -B "${@}" -e "${sql}") + then + printf 'shrink_tag_column: schema query failed [%s]\n' "${sql}" + exit 255 + fi + + # We aim for the length of 64 characters. + if [ "$taglen" -ne 64 ] + then + # Check if any of the tags are longer than 64 characters. + sql="SELECT COUNT(*) FROM $table WHERE CHAR_LENGTH(tag) > 64 LIMIT 1" + if ! longtag=$(mysql -N -B "${@}" -e "${sql}") + then + printf 'shrink_tag_column: select query failed [%s]\n' "${sql}" + exit 255 + fi + # Report an error if there are any server tags exceeding 64 characters. + # A user should fix the tags and rerun this migration. + if [ "$longtag" -eq 1 ] + then + printf 'shrink_tag_column: failed to resize server tag column for table %s.\n' "${table}" + printf 'Ensure that no server tags are longer than 64 characters and rerun this migration.\n' + printf 'The remote-server4-set and remote-server6-set commands from the cb_cmds hooks\n' + printf 'library can be used to modify the tags.\n' + exit 255 + fi + # If there are no long server tags we can safely alter the column. + sql="ALTER TABLE $table MODIFY COLUMN tag VARCHAR(64) NOT NULL" + if ! mysql -N -B "${@}" -e "${sql}" + then + printf 'shrink_tag_column: alter query failed [%s]\n' "${sql}" + exit 255 + fi + fi +} + +shrink_tag_column "${schema}" dhcp4_server "${@}" +shrink_tag_column "${schema}" dhcp6_server "${@}" + +mysql "$@" <<EOF + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv4 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp4_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + test TEXT, + next_server INT UNSIGNED DEFAULT NULL, + server_hostname VARCHAR(128) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + only_if_required TINYINT NOT NULL DEFAULT '0', + valid_lifetime INT DEFAULT NULL, + min_valid_lifetime INT DEFAULT NULL, + max_valid_lifetime INT DEFAULT NULL, + depend_on_known_directly TINYINT NOT NULL DEFAULT '0', + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY id_UNIQUE (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp4_client_class_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp4_client_class table has a corresponding row +-- in the dhcp4_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp4_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp4_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp4_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_order ( + class_id BIGINT UNSIGNED NOT NULL, + order_index BIGINT UNSIGNED NOT NULL, + depend_on_known_indirectly TINYINT NOT NULL DEFAULT '0', + PRIMARY KEY (class_id), + KEY key_dhcp4_client_class_order_index (order_index), + CONSTRAINT fk_dhcp4_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp4_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp4_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp4_client_class_ADEL; +DROP PROCEDURE IF EXISTS setClientClass4Order; + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE setClientClass4Order(IN id BIGINT UNSIGNED, + IN follow_class_name VARCHAR(128), + IN old_follow_class_name VARCHAR(128)) +proc_label:BEGIN + -- This variable will be optionally set if the follow_class_name + -- column value is specified. + DECLARE follow_class_index BIGINT UNSIGNED; + DECLARE msg TEXT; + + -- Remember currently used value of depend_on_known_indirectly. + SET @depend_on_known_indirectly = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order WHERE id = class_id + ); + + -- Bail if the class is updated without re-positioning. + IF( + @depend_on_known_indirectly IS NOT NULL AND + ((follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = 0 + WHERE class_id = id; + LEAVE proc_label; + END IF; + + IF follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SET follow_class_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = follow_class_name + ); + IF follow_class_index IS NULL THEN + -- The class with a name specified with follow_class_name does + -- not exist. + SET msg = CONCAT('Class ', follow_class_name, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1 + ORDER BY order_index DESC; + END IF; + ELSE + -- A caller did not specify the follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SET follow_class_index = (SELECT MAX(order_index) FROM dhcp4_client_class_order); + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + SET follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + SET msg = CONCAT('Unable to move class with id ', id, ' because it would break its dependencies'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + REPLACE INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_AINS AFTER INSERT ON dhcp4_client_class FOR EACH ROW BEGIN + CALL setClientClass4Order(NEW.id, NEW.follow_class_name, NULL); + CALL createAuditEntryDHCP4('dhcp4_client_class', NEW.id, "create"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_AUPD AFTER UPDATE ON dhcp4_client_class FOR EACH ROW BEGIN + SET @depend_on_known_directly = OLD.depend_on_known_directly; + SET @client_class_id = NEW.id; + CALL setClientClass4Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + CALL createAuditEntryDHCP4('dhcp4_client_class', NEW.id, "update"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to create dhcp4_client_class audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_ADEL AFTER DELETE ON dhcp4_client_class FOR EACH ROW BEGIN + CALL createAuditEntryDHCP4('dhcp4_client_class', OLD.id, "delete"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp4_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp4_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_dependency ( + class_id BIGINT UNSIGNED NOT NULL, + dependency_id BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (class_id,dependency_id), + KEY dhcp4_client_class_dependency_id_idx (dependency_id), + CONSTRAINT dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp4_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp4_client_class (id) +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_BINS; +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - class_id id client class, +-- - dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv4ClientClassDependency(IN class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE class_index BIGINT UNSIGNED; + DECLARE dependency_index BIGINT UNSIGNED; + DECLARE err_msg TEXT; + + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF class_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class id must not be NULL.'; + END IF; + IF dependency_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency id must not be NULL.'; + END IF; + -- Dependencies on self make no sense. + IF class_id = dependency_id THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class must not have dependency on self.'; + END IF; + -- Check position of our class in the hierarchy. + SET class_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.id = class_id); + IF class_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- Check position of the dependency. + SET dependency_index = ( + SELECT o.order_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = dependency_id + ); + IF dependency_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', dependency_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' must not depend on class defined later with id ', dependency_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp4_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_server AS t1 + LEFT JOIN dhcp4_client_class_server AS t2 + ON t2.class_id = dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + SET err_msg = CONCAT('Unmet dependencies for client class with id ', class_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_check_dependency_BINS BEFORE INSERT ON dhcp4_client_class_dependency FOR EACH ROW +BEGIN + CALL checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS dhcp4_client_class_dependency_AINS; +DROP PROCEDURE IF EXISTS updateDHCPv4ClientClassKnownDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE updateDHCPv4ClientClassKnownDependency(IN client_class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE dependency TINYINT; + -- Check if the dependency class references KNOWN/UNKNOWN. + SET dependency = ( + SELECT depend_on_known_directly FROM dhcp4_client_class + WHERE id = dependency_id + ); + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = 0 THEN + SET dependency = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order + WHERE class_id = dependency_id + ); + END IF; + IF dependency <> 0 THEN + UPDATE dhcp4_client_class_order + SET depend_on_known_indirectly = 1 + WHERE class_id = client_class_id; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp4_client_class_dependency_AINS AFTER INSERT ON dhcp4_client_class_dependency FOR EACH ROW +BEGIN + CALL updateDHCPv4ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS checkDHCPv4ClientClassKnownDependencyChange; + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv4 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv4ClientClassKnownDependencyChange() +BEGIN + DECLARE depended TINYINT DEFAULT 0; + DECLARE depends TINYINT DEFAULT 0; + + -- Session variables are set upon a client class update. + IF @client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency + WHERE dependency_id = @client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + IF @depend_on_known_directly <> 0 OR @depend_on_known_indirectly <> 0 THEN + SET depended = 1; + END IF; + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SET depends = ( + SELECT depend_on_known_directly FROM dhcp4_client_class + WHERE id = @client_class_id + ); + -- If it doesn't depend directly, check indirect dependencies. + IF depends = 0 THEN + SET depends = ( + SELECT depend_on_known_indirectly FROM dhcp4_client_class_order + WHERE class_id = @client_class_id + ); + END IF; + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'; + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv4 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_server ( + class_id bigint unsigned NOT NULL, + server_id bigint unsigned NOT NULL, + modification_ts timestamp NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + KEY fk_dhcp4_client_class_server_id (server_id), + CONSTRAINT fk_dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv4 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp4_option_def + ADD COLUMN class_id BIGINT UNSIGNED NULL DEFAULT NULL; + +ALTER TABLE dhcp4_option_def + ADD CONSTRAINT fk_dhcp4_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv6 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp6_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + test TEXT, + only_if_required TINYINT NOT NULL DEFAULT '0', + valid_lifetime INT DEFAULT NULL, + min_valid_lifetime INT DEFAULT NULL, + max_valid_lifetime INT DEFAULT NULL, + depend_on_known_directly TINYINT NOT NULL DEFAULT '0', + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY id_UNIQUE (id), + UNIQUE KEY name_UNIQUE (name), + KEY key_dhcp6_client_class_modification_ts (modification_ts) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp6_client_class table has a corresponding row +-- in the dhcp6_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp6_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp6_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp6_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_order ( + class_id BIGINT UNSIGNED NOT NULL, + order_index BIGINT UNSIGNED NOT NULL, + depend_on_known_indirectly TINYINT NOT NULL DEFAULT '0', + PRIMARY KEY (class_id), + KEY key_dhcp6_client_class_order_index (order_index), + CONSTRAINT fk_dhcp6_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp6_client_class_AINS; +DROP TRIGGER IF EXISTS dhcp6_client_class_AUPD; +DROP TRIGGER IF EXISTS dhcp6_client_class_ADEL; +DROP PROCEDURE IF EXISTS setClientClass6Order; + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE setClientClass6Order(IN id BIGINT UNSIGNED, + IN follow_class_name VARCHAR(128), + IN old_follow_class_name VARCHAR(128)) +proc_label:BEGIN + -- This variable will be optionally set if the follow_class_name + -- column value is specified. + DECLARE follow_class_index BIGINT UNSIGNED; + DECLARE msg TEXT; + + -- Remember currently used value of depend_on_known_indirectly. + SET @depend_on_known_indirectly = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order WHERE id = class_id + ); + + -- Bail if the class is updated without re-positioning. + IF( + @depend_on_known_indirectly IS NOT NULL AND + ((follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = 0 + WHERE class_id = id; + LEAVE proc_label; + END IF; + + IF follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SET follow_class_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = follow_class_name + ); + IF follow_class_index IS NULL THEN + -- The class with a name specified with follow_class_name does + -- not exist. + SET msg = CONCAT('Class ', follow_class_name, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1 + ORDER BY order_index DESC; + END IF; + ELSE + -- A caller did not specify the follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SET follow_class_index = (SELECT MAX(order_index) FROM dhcp6_client_class_order); + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + SET follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + SET msg = CONCAT('Unable to move class with id ', id, ' because it would break its dependencies'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + REPLACE INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_AINS AFTER INSERT ON dhcp6_client_class FOR EACH ROW BEGIN + CALL setClientClass6Order(NEW.id, NEW.follow_class_name, NULL); + CALL createAuditEntryDHCP6('dhcp6_client_class', NEW.id, "create"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_AUPD AFTER UPDATE ON dhcp6_client_class FOR EACH ROW BEGIN + SET @depend_on_known_directly = OLD.depend_on_known_directly; + SET @client_class_id = NEW.id; + CALL setClientClass6Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + CALL createAuditEntryDHCP6('dhcp6_client_class', NEW.id, "update"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger to create dhcp6_client_class audit. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_ADEL AFTER DELETE ON dhcp6_client_class FOR EACH ROW BEGIN + CALL createAuditEntryDHCP6('dhcp6_client_class', OLD.id, "delete"); +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp6_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp6_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_dependency ( + class_id BIGINT UNSIGNED NOT NULL, + dependency_id BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (class_id,dependency_id), + KEY dhcp6_client_class_dependency_id_idx (dependency_id), + CONSTRAINT dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp6_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp6_client_class (id) +) ENGINE=InnoDB; + +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_BINS; +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - class_id id client class, +-- - dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv6ClientClassDependency(IN class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE class_index BIGINT UNSIGNED; + DECLARE dependency_index BIGINT UNSIGNED; + DECLARE err_msg TEXT; + + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF class_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class id must not be NULL.'; + END IF; + IF dependency_id IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency id must not be NULL.'; + END IF; + -- Dependencies on self make no sense. + IF class_id = dependency_id THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Client class must not have dependency on self.'; + END IF; + -- Check position of our class in the hierarchy. + SET class_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.id = class_id); + IF class_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- Check position of the dependency. + SET dependency_index = ( + SELECT o.order_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = dependency_id + ); + IF dependency_index IS NULL THEN + SET err_msg = CONCAT('Client class with id ', dependency_id, ' does not exist.'); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + SET err_msg = CONCAT('Client class with id ', class_id, ' must not depend on class defined later with id ', dependency_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp6_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_server AS t1 + LEFT JOIN dhcp6_client_class_server AS t2 + ON t2.class_id = dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + SET err_msg = CONCAT('Unmet dependencies for client class with id ', class_id); + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = err_msg; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_check_dependency_BINS BEFORE INSERT ON dhcp6_client_class_dependency FOR EACH ROW +BEGIN + CALL checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS dhcp6_client_class_dependency_AINS; +DROP PROCEDURE IF EXISTS updateDHCPv6ClientClassKnownDependency; + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE updateDHCPv6ClientClassKnownDependency(IN client_class_id BIGINT UNSIGNED, + IN dependency_id BIGINT UNSIGNED) +BEGIN + DECLARE dependency TINYINT; + -- Check if the dependency class references KNOWN/UNKNOWN. + SET dependency = ( + SELECT depend_on_known_directly FROM dhcp6_client_class + WHERE id = dependency_id + ); + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = 0 THEN + SET dependency = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order + WHERE class_id = dependency_id + ); + END IF; + IF dependency <> 0 THEN + UPDATE dhcp6_client_class_order + SET depend_on_known_indirectly = 1 + WHERE class_id = client_class_id; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE TRIGGER dhcp6_client_class_dependency_AINS AFTER INSERT ON dhcp6_client_class_dependency FOR EACH ROW +BEGIN + CALL updateDHCPv6ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS checkDHCPv6ClientClassKnownDependencyChange; + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv6 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +DELIMITER $$ +CREATE PROCEDURE checkDHCPv6ClientClassKnownDependencyChange() +BEGIN + DECLARE depended TINYINT DEFAULT 0; + DECLARE depends TINYINT DEFAULT 0; + + -- Session variables are set upon a client class update. + IF @client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency + WHERE dependency_id = @client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + IF @depend_on_known_directly <> 0 OR @depend_on_known_indirectly <> 0 THEN + SET depended = 1; + END IF; + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SET depends = ( + SELECT depend_on_known_directly FROM dhcp6_client_class + WHERE id = @client_class_id + ); + -- If it doesn't depend directly, check indirect dependencies. + IF depends = 0 THEN + SET depends = ( + SELECT depend_on_known_indirectly FROM dhcp6_client_class_order + WHERE class_id = @client_class_id + ); + END IF; + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'; + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv6 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_server ( + class_id bigint unsigned NOT NULL, + server_id bigint unsigned NOT NULL, + modification_ts timestamp NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + KEY fk_dhcp6_client_class_server_id (server_id), + CONSTRAINT fk_dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) +) ENGINE=InnoDB; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv6 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_option_def + ADD COLUMN class_id BIGINT UNSIGNED NULL DEFAULT NULL; + +ALTER TABLE dhcp6_option_def + ADD CONSTRAINT fk_dhcp6_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +# Update the schema version number +UPDATE schema_version + SET version = '10', minor = '0'; + +# This line concludes database upgrade to version 10. +EOF diff --git a/src/share/database/scripts/mysql/upgrade_010_to_011.sh.in b/src/share/database/scripts/mysql/upgrade_010_to_011.sh.in new file mode 100644 index 0000000..c5f512a --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_010_to_011.sh.in @@ -0,0 +1,85 @@ +#!/bin/sh + +# Copyright (C) 2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "10.0"; then + printf 'This script upgrades 10.0 to 11.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we have the schema. +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +mysql "$@" <<EOF + +-- Reverse index order to improve reclamation query performance +-- Add a constraint that any state value added to the lease4 must +-- map to a value in the lease_state table. Note we have to drop +-- the foreign keys first, then add them back. +ALTER TABLE lease4 DROP FOREIGN KEY fk_lease4_state; +DROP INDEX lease4_by_state_expire ON lease4; +CREATE INDEX lease4_by_expire_state ON lease4 (expire ASC, state ASC); +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +ALTER TABLE lease6 DROP FOREIGN KEY fk_lease6_state; +CREATE INDEX lease6_by_expire_state ON lease6 (expire ASC, state ASC); +DROP INDEX lease6_by_state_expire ON lease6; +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +-- Added preferred lifetime columns to v6 client classes +ALTER TABLE dhcp6_client_class + ADD COLUMN preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN min_preferred_lifetime INT(10) DEFAULT NULL, + ADD COLUMN max_preferred_lifetime INT(10) DEFAULT NULL; + +-- Update the schema version number +UPDATE schema_version + SET version = '11', minor = '0'; + +-- This line concludes database upgrade to version 11.0 +EOF diff --git a/src/share/database/scripts/mysql/upgrade_011_to_012.sh.in b/src/share/database/scripts/mysql/upgrade_011_to_012.sh.in new file mode 100644 index 0000000..c4142b2 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_011_to_012.sh.in @@ -0,0 +1,87 @@ +#!/bin/sh + +# Copyright (C) 2021 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "11.0"; then + printf 'This script upgrades 11.0 to 12.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we have the schema. +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +mysql "$@" <<EOF + +-- Ensure that dhcp_client_class is NULL when an option does not +-- belong to any client class. Later, we will add foreign keys for +-- the dhcp_client_class columns, and it requires that the columns +-- are NULL when there are no corresponding client classes. +SET @disable_audit = 1; +UPDATE dhcp4_options SET dhcp_client_class = NULL + WHERE scope_id <> 2; +UPDATE dhcp6_options SET dhcp_client_class = NULL + WHERE scope_id <> 2; +SET @disable_audit = 0; + +-- Add a foreign keys referencing a client classes. If an option is +-- associated with a client class, the option will be deleted +-- along with the deleted client class. +ALTER TABLE dhcp4_options + ADD CONSTRAINT fk_dhcp4_options_client_class + FOREIGN KEY (dhcp_client_class) + REFERENCES dhcp4_client_class (name) + ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_options + ADD CONSTRAINT fk_dhcp6_options_client_class + FOREIGN KEY (dhcp_client_class) + REFERENCES dhcp6_client_class (name) + ON DELETE CASCADE ON UPDATE CASCADE; + +-- Update the schema version number +UPDATE schema_version + SET version = '12', minor = '0'; + +-- This line concludes database upgrade to version 12. +EOF diff --git a/src/share/database/scripts/mysql/upgrade_012_to_013.sh.in b/src/share/database/scripts/mysql/upgrade_012_to_013.sh.in new file mode 100644 index 0000000..ee133d5 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_012_to_013.sh.in @@ -0,0 +1,265 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "12.0"; then + printf 'This script upgrades 12.0 to 13.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we have the schema. +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +mysql "$@" <<EOF + +-- Create a function that separates a contiguous hexadecimal string +-- into groups of two hexadecimals separated by colons. +DROP FUNCTION IF EXISTS colonSeparatedHex; +DELIMITER $$ +CREATE FUNCTION colonSeparatedHex(hex VARCHAR(64)) +RETURNS VARCHAR(64) +DETERMINISTIC +BEGIN + -- Declarations + DECLARE i INT; + DECLARE length INT; + DECLARE output VARCHAR(64); + + -- Initializations + SET i = 3; + SET length = LENGTH(hex); + + -- Add a leading zero if the first octet has a single hexadecimal character. + IF MOD(length, 2) = 1 THEN + SET hex = CONCAT('0', hex); + SET length = length + 1; + END IF; + + -- Start with the first octet. + SET output = SUBSTR(hex, 1, 2); + + -- Add one octet at a time and a leading colon with each. + label: WHILE i < length DO + SET output = CONCAT(output, ':', SUBSTR(hex, i, 2)); + SET i = i + 2; + END WHILE label; + + -- Memfile uses lowercase hexadecimals. + SET output = LOWER(output); + + RETURN output; +END $$ +DELIMITER ; + +-- Modify the procedure to output a memfile-ready CSV file. +DROP PROCEDURE IF EXISTS lease4DumpData; +DELIMITER $$ +CREATE PROCEDURE lease4DumpData() +BEGIN + SELECT + INET_NTOA(address), + IFNULL(colonSeparatedHex(HEX(hwaddr)), ''), + IFNULL(colonSeparatedHex(HEX(client_id)), ''), + valid_lifetime, + UNIX_TIMESTAMP(expire), + subnet_id, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + state, + REPLACE(IFNULL(user_context, ''), ',', ',') + FROM lease4 + ORDER BY address; +END $$ +DELIMITER ; + +-- hwtype and hwaddr_source need to be last to match memfile format. +DROP PROCEDURE IF EXISTS lease6DumpHeader; +DELIMITER $$ +CREATE PROCEDURE lease6DumpHeader() +BEGIN + SELECT 'address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,state,user_context,hwtype,hwaddr_source'; +END $$ +DELIMITER ; + +-- Modify the procedure to output a memfile-ready CSV file. +DROP PROCEDURE IF EXISTS lease6DumpData; +DELIMITER $$ +CREATE PROCEDURE lease6DumpData() +BEGIN + SELECT + address, + IFNULL(colonSeparatedHex(HEX(duid)), ''), + valid_lifetime, + UNIX_TIMESTAMP(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + IFNULL(colonSeparatedHex(HEX(hwaddr)), ''), + state, + REPLACE(IFNULL(user_context, ''), ',', ','), + hwtype, + hwaddr_source + FROM lease6 + ORDER BY address; +END $$ +DELIMITER ; + +-- Create a procedure that inserts a v4 lease from memfile data. +DELIMITER $$ +CREATE PROCEDURE lease4Upload( + IN address VARCHAR(15), + IN hwaddr VARCHAR(20), + IN client_id VARCHAR(128), + IN valid_lifetime INT UNSIGNED, + IN expire BIGINT UNSIGNED, + IN subnet_id INT UNSIGNED, + IN fqdn_fwd TINYINT, + IN fqdn_rev TINYINT, + IN hostname VARCHAR(255), + IN state INT UNSIGNED, + IN user_context TEXT +) +BEGIN + INSERT INTO lease4 ( + address, + hwaddr, + client_id, + valid_lifetime, + expire, + subnet_id, + fqdn_fwd, + fqdn_rev, + hostname, + state, + user_context + ) VALUES ( + INET_ATON(address), + UNHEX(REPLACE(hwaddr, ':', '')), + UNHEX(REPLACE(client_id, ':', '')), + valid_lifetime, + FROM_UNIXTIME(expire), + subnet_id, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + state, + REPLACE(user_context, ',', ',') + ); +END $$ +DELIMITER ; + +-- Create a procedure that inserts a v6 lease from memfile data. +DELIMITER $$ +CREATE PROCEDURE lease6Upload( + IN address VARCHAR(39), + IN duid VARCHAR(128), + IN valid_lifetime INT UNSIGNED, + IN expire BIGINT UNSIGNED, + IN subnet_id INT UNSIGNED, + IN pref_lifetime INT UNSIGNED, + IN lease_type TINYINT, + IN iaid INT UNSIGNED, + IN prefix_len TINYINT UNSIGNED, + IN fqdn_fwd TINYINT, + IN fqdn_rev TINYINT, + IN hostname VARCHAR(255), + IN hwaddr VARCHAR(64), + IN state INT UNSIGNED, + IN user_context TEXT, + IN hwtype SMALLINT, + IN hwaddr_source INT UNSIGNED +) +BEGIN + INSERT INTO lease6 ( + address, + duid, + valid_lifetime, + expire, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + hostname, + hwaddr, + state, + user_context, + hwtype, + hwaddr_source + ) VALUES ( + address, + UNHEX(REPLACE(duid, ':', '')), + valid_lifetime, + FROM_UNIXTIME(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + REPLACE(hostname, ',', ','), + UNHEX(REPLACE(hwaddr, ':', '')), + state, + REPLACE(user_context, ',', ','), + hwtype, + hwaddr_source + ); +END $$ +DELIMITER ; + +-- Update the schema version number. +UPDATE schema_version + SET version = '13', minor = '0'; + +-- This line concludes database upgrade to version 13. +EOF diff --git a/src/share/database/scripts/mysql/upgrade_013_to_014.sh.in b/src/share/database/scripts/mysql/upgrade_013_to_014.sh.in new file mode 100644 index 0000000..b442ef3 --- /dev/null +++ b/src/share/database/scripts/mysql/upgrade_013_to_014.sh.in @@ -0,0 +1,826 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# Check version. +version=$(mysql_version "${@}") +if test "${version}" != "13.0"; then + printf 'This script upgrades 13.0 to 14.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${version}" + exit 0 +fi + +# Get the schema name from database argument. We need this to +# query information_schema for the right database. +for arg in "${@}" +do + if ! printf '%s' "${arg}" | grep -Eq '^\-\-' + then + schema="$arg" + break + fi +done + +# Make sure we have the schema. +if [ -z "$schema" ] +then + printf "Could not find database schema name in cmd line args: %s\n" "${*}" + exit 255 +fi + +mysql "$@" <<EOF +-- This line starts the schema upgrade to version 14. + +-- Modify shared-network-name foreign key constraint on dhcp4_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp4_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp4_subnet + DROP FOREIGN KEY fk_dhcp4_subnet_shared_network; + +ALTER TABLE dhcp4_subnet + ADD CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger on dhcp4_shared_network to explicitly +-- update dhcp4_subnets. This ensures there are audit entries for updated +-- subnets. +DROP TRIGGER dhcp4_shared_network_BDEL; + +DELIMITER $$ +CREATE TRIGGER dhcp4_shared_network_BDEL BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, "delete"); + -- In MySQL Foreign key constraint triggered updates will not cascade, so we explicitly + -- update subnets first which should ensure they get audit entries. + UPDATE dhcp4_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +-- Modify shared-network-name foreign key constraint on dhcp6_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp6_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp6_subnet + DROP FOREIGN KEY fk_dhcp6_subnet_shared_network; + +ALTER TABLE dhcp6_subnet + ADD CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger on dhcp6_shared_network to explicitly +-- update dhcp6_subnets. This ensures there are audit entries for updated +-- subnets. +DROP TRIGGER dhcp6_shared_network_BDEL; + +DELIMITER $$ +CREATE TRIGGER dhcp6_shared_network_BDEL BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW + BEGIN + CALL createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, "delete"); + -- In MySQL Foreign key constraint triggered updates will not cascade, so we explicitly + -- update subnets first which should ensure they get audit entries. + UPDATE dhcp6_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + END $$ +DELIMITER ; + +-- Add user_context column to client class tables. +ALTER TABLE dhcp4_client_class ADD COLUMN user_context LONGTEXT NULL; +ALTER TABLE dhcp6_client_class ADD COLUMN user_context LONGTEXT NULL; + +-- Schema changes related to lease limiting start here. -- + +-- Recreate the triggers that update the leaseX_stat tables as stored procedures. -- + +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_AINS_lease4_stat(IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED) +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert the state count record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_AUPD_lease4_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED) +BEGIN + IF old_subnet_id != new_subnet_id OR old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert new state record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat; +DELIMITER $$ +CREATE PROCEDURE lease4_ADEL_lease4_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED) +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists. + UPDATE lease4_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND old_state = state; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_AINS_lease6_stat(IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED, + IN new_lease_type TINYINT) +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert the state count record if it does not exist. + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_AUPD_lease6_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN old_lease_type TINYINT, + IN new_state TINYINT, + IN new_subnet_id INT UNSIGNED, + IN new_lease_type TINYINT) +BEGIN + IF old_subnet_id != new_subnet_id OR + old_lease_type != new_lease_type OR + old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert new state record if it does not exist + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat + VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat; +DELIMITER $$ +CREATE PROCEDURE lease6_ADEL_lease6_stat(IN old_state TINYINT, + IN old_subnet_id INT UNSIGNED, + IN old_lease_type TINYINT) +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat + SET leases = IF(leases > 0, leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; +END $$ +DELIMITER ; + +-- Create tables that contain the number of active leases. -- + +DROP TABLE IF EXISTS lease4_stat_by_client_class; +CREATE TABLE lease4_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL PRIMARY KEY, + leases BIGINT UNSIGNED NOT NULL +) ENGINE = InnoDB; + +DROP TABLE IF EXISTS lease6_stat_by_client_class; +CREATE TABLE lease6_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL, + lease_type TINYINT NOT NULL, + leases BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (client_class, lease_type), + CONSTRAINT fk_lease6_stat_by_client_class_lease_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type) +) ENGINE = InnoDB; + +-- Create procedures to be called for each row in after-event triggers for +-- INSERT, UPDATE and DELETE on lease tables. + +DROP PROCEDURE IF EXISTS lease4_AINS_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_AINS_lease4_stat_by_client_class(IN new_state TINYINT, + IN new_user_context TEXT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + -- Iterate through all the client classes and increment the lease count for each. + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF ROW_COUNT() = 0 THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_AUPD_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_AUPD_lease4_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN new_state TINYINT, + IN new_user_context TEXT) +BEGIN + -- Declarations + DECLARE old_client_classes TEXT; + DECLARE new_client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + SET old_client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET new_client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + + IF old_state != new_state OR old_client_classes != new_client_classes THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(old_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(old_client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class; + + SET i = i + 1; + END WHILE label; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(new_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(new_client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease4_ADEL_lease4_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease4_ADEL_lease4_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is accounted for in lease limiting. + IF old_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AINS_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_AINS_lease6_stat_by_client_class(IN new_state TINYINT, + IN new_user_context TEXT, + IN new_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_AUPD_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_AUPD_lease6_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN old_lease_type TINYINT, + IN new_state TINYINT, + IN new_user_context TEXT, + IN new_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE old_client_classes TEXT; + DECLARE new_client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + SET old_client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET new_client_classes = JSON_EXTRACT(new_user_context, '$."ISC"."client-classes"'); + + IF old_state != new_state OR old_client_classes != new_client_classes OR old_lease_type != new_lease_type THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(old_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(old_client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + + SET i = i + 1; + END WHILE label; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + SET length = JSON_LENGTH(new_client_classes); + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(new_client_classes, CONCAT('\$[', i, ']'))); + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF ROW_COUNT() <= 0 THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + + SET i = i + 1; + END WHILE label; + END IF; + END IF; +END $$ +DELIMITER ; + +DROP PROCEDURE IF EXISTS lease6_ADEL_lease6_stat_by_client_class; +DELIMITER $$ +CREATE PROCEDURE lease6_ADEL_lease6_stat_by_client_class(IN old_state TINYINT, + IN old_user_context TEXT, + IN old_lease_type TINYINT) +BEGIN + -- Declarations + DECLARE client_classes TEXT; + DECLARE class VARCHAR(255); + DECLARE length INT; + DECLARE i INT; + + -- Ignore ERROR 3141 (22032) at line 1: Invalid JSON text in argument 1 to + -- function json_extract: "The document is empty." at position 0. + -- Ignore ERROR 4037 (HY000): Unexpected end of JSON text in argument 1 to function 'json_extract' + -- These situations are handled with a propagating NULL result from JSON_EXTRACT. + DECLARE CONTINUE HANDLER FOR 3141 BEGIN END; + DECLARE CONTINUE HANDLER FOR 4037 BEGIN END; + + -- Only state 0 is accounted for in lease limiting. But check both states to be consistent with lease6_stat. + IF old_state = 0 THEN + -- Dive into client classes. + SET client_classes = JSON_EXTRACT(old_user_context, '$."ISC"."client-classes"'); + SET length = JSON_LENGTH(client_classes); + + SET i = 0; + label: WHILE i < length DO + SET class = JSON_UNQUOTE(JSON_EXTRACT(client_classes, CONCAT('\$[', i, ']'))); + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = IF(leases > 0, leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + + SET i = i + 1; + END WHILE label; + END IF; +END $$ +DELIMITER ; + +-- Recreate the after-event triggers for INSERT, UPDATE and DELETE on lease tables to call the -- +-- stored procedures above in pairs of two: for client classes and for subnets. -- + +-- Function that establishes whether JSON functions are supported. +-- They should be provided with MySQL>= 5.7, MariaDB >= 10.2.3. +DROP FUNCTION IF EXISTS isJsonSupported; +DELIMITER $$ +CREATE FUNCTION isJsonSupported() +RETURNS BOOL +DETERMINISTIC +BEGIN + DECLARE dummy BOOL; + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + RETURN false; + + SELECT JSON_EXTRACT('{ "foo": 1 }', '$.foo') INTO dummy; + RETURN true; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_insert; +DROP TRIGGER IF EXISTS lease4_AINS; +DELIMITER $$ +CREATE TRIGGER lease4_AINS AFTER INSERT ON lease4 FOR EACH ROW +BEGIN + CALL lease4_AINS_lease4_stat(NEW.state, NEW.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_AINS_lease4_stat_by_client_class(NEW.state, NEW.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_update; +DROP TRIGGER IF EXISTS lease4_AUPD; +DELIMITER $$ +CREATE TRIGGER lease4_AUPD AFTER UPDATE ON lease4 FOR EACH ROW +BEGIN + CALL lease4_AUPD_lease4_stat(OLD.state, OLD.subnet_id, NEW.state, NEW.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_AUPD_lease4_stat_by_client_class(OLD.state, OLD.user_context, NEW.state, NEW.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease4_delete; +DROP TRIGGER IF EXISTS lease4_ADEL; +DELIMITER $$ +CREATE TRIGGER lease4_ADEL AFTER DELETE ON lease4 FOR EACH ROW +BEGIN + CALL lease4_ADEL_lease4_stat(OLD.state, OLD.subnet_id); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease4_ADEL_lease4_stat_by_client_class(OLD.state, OLD.user_context); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_insert; +DROP TRIGGER IF EXISTS lease6_AINS; +DELIMITER $$ +CREATE TRIGGER lease6_AINS AFTER INSERT ON lease6 FOR EACH ROW +BEGIN + CALL lease6_AINS_lease6_stat(NEW.state, NEW.subnet_id, NEW.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_AINS_lease6_stat_by_client_class(NEW.state, NEW.user_context, NEW.lease_type); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_update; +DROP TRIGGER IF EXISTS lease6_AUPD; +DELIMITER $$ +CREATE TRIGGER lease6_AUPD AFTER UPDATE ON lease6 FOR EACH ROW +BEGIN + CALL lease6_AUPD_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type, NEW.state, NEW.subnet_id, NEW.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_AUPD_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type, NEW.state, NEW.user_context, NEW.lease_type); + END IF; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS stat_lease6_delete; +DROP TRIGGER IF EXISTS lease6_ADEL; +DELIMITER $$ +CREATE TRIGGER lease6_ADEL AFTER DELETE ON lease6 FOR EACH ROW +BEGIN + CALL lease6_ADEL_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type); + IF @json_supported IS NULL THEN + SELECT isJsonSupported() INTO @json_supported; + END IF; + IF @json_supported = 1 THEN + CALL lease6_ADEL_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type); + END IF; +END $$ +DELIMITER ; + +-- Create functions that check if the lease limits set in the given user context are exceeded. +-- They return a string describing a limit that is being exceeded, or an empty +-- string if no limits are exceeded. The following format for is assumed for user_context +-- (not all nodes are mandatory and values are given only as examples): +-- { "ISC": { "limits": { "client-classes": [ { "name": "foo", "address-limit": 2, "prefix-limit": 1 } ], +-- "subnet": { "id": 1, "address-limit": 2, "prefix-limit": 1 } } } } + +DROP FUNCTION IF EXISTS checkLease4Limits; +DELIMITER $$ +CREATE FUNCTION checkLease4Limits(user_context TEXT) +RETURNS TEXT +READS SQL DATA +BEGIN + -- Declarations + DECLARE json_element TEXT; + DECLARE length INT; + DECLARE class TEXT; + DECLARE name VARCHAR(255); + DECLARE i INT; + DECLARE lease_limit INT; + DECLARE lease_count INT; + + -- Dive into client class limits. + SET json_element = JSON_EXTRACT(user_context, '$."ISC"."limits"."client-classes"'); + SET length = JSON_LENGTH(json_element); + + SET i = 0; + label: WHILE i < length DO + -- Get the lease limit for this client class. + SET class = JSON_EXTRACT(json_element, CONCAT('\$[', i, ']')); + SET name = JSON_UNQUOTE(JSON_EXTRACT(class, '$.name')); + SET lease_limit = JSON_EXTRACT(class, '$."address-limit"'); + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease4_stat_by_client_class WHERE client_class = name); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET i = i + 1; + END WHILE label; + + -- Dive into subnet limits. Reuse i as subnet ID. + SET json_element = JSON_EXTRACT(user_context, '$.ISC.limits.subnet'); + SET i = JSON_EXTRACT(json_element, '$.id'); + SET lease_limit = JSON_EXTRACT(json_element, '$."address-limit"'); + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease4_stat WHERE subnet_id = i AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END $$ +DELIMITER ; + +DROP FUNCTION IF EXISTS checkLease6Limits; +DELIMITER $$ +CREATE FUNCTION checkLease6Limits(user_context TEXT) +RETURNS TEXT +READS SQL DATA +BEGIN + -- Declarations + DECLARE json_element TEXT; + DECLARE length INT; + DECLARE class TEXT; + DECLARE name VARCHAR(255); + DECLARE i INT; + DECLARE lease_limit INT; + DECLARE lease_count INT; + + -- Dive into client class limits. + SET json_element = JSON_EXTRACT(user_context, '$."ISC"."limits"."client-classes"'); + SET length = JSON_LENGTH(json_element); + + SET i = 0; + label: WHILE i < length DO + -- Get the lease limit for this client class. + SET class = JSON_EXTRACT(json_element, CONCAT('\$[', i, ']')); + SET name = JSON_UNQUOTE(JSON_EXTRACT(class, '$.name')); + + SET lease_limit = JSON_EXTRACT(class, '$."address-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the address count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET lease_limit = JSON_EXTRACT(class, '$."prefix-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the prefix count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 2); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SET i = i + 1; + END WHILE label; + + -- Dive into subnet limits. Reuse i as subnet ID. + SET json_element = JSON_EXTRACT(user_context, '$.ISC.limits.subnet'); + SET i = JSON_EXTRACT(json_element, '$.id'); + SET lease_limit = JSON_EXTRACT(json_element, '$."address-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat WHERE subnet_id = i AND lease_type = 0 AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + SET lease_limit = JSON_EXTRACT(json_element, '$."prefix-limit"'); + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SET lease_count = (SELECT leases FROM lease6_stat WHERE subnet_id = i AND lease_type = 2 AND state = 0); + IF lease_count IS NULL THEN + SET lease_count = 0; + END IF; + + -- Compare. Return immediately if the limit is exceeded. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for subnet ID ', i, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END $$ +DELIMITER ; + +-- Update the schema version number. +UPDATE schema_version + SET version = '14', minor = '0'; + +-- This line concludes the schema upgrade to version 14. +EOF diff --git a/src/share/database/scripts/mysql/wipe_data.sh.in b/src/share/database/scripts/mysql/wipe_data.sh.in new file mode 100644 index 0000000..83a6f3f --- /dev/null +++ b/src/share/database/scripts/mysql/wipe_data.sh.in @@ -0,0 +1,118 @@ +#!/bin/sh + +# Copyright (C) 2019-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# This script is primarily used for MySQL unit tests, which need to +# ensure an empty, but schema correct database for each test. It +# deletes ALL transient data from an existing Kea MySQL schema, +# including leases, reservations, etc... Use at your own peril. +# Reference tables will be left in-tact. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# First argument must be the expected schema version <major>.<minor> +# Check if it's passed at all. +if [ "$#" -lt "1" ]; then + printf "Required at least one parameter: schema version number, e.g. 7.0\n" + exit 1 +fi +exp_version="$1" +shift + +# Remaining arguments are used as mysql command line arguments + +# If the existing schema doesn't match, the fail +VERSION=$(mysql_version "$@") +if [ "$VERSION" = "" ]; then + printf "Cannot wipe data, schema version could not be detected.\n" + exit 1 +fi + +if [ "$VERSION" != "$exp_version" ]; then + printf 'Cannot wipe data, wrong schema version. ' + printf 'Expected version %s, found %s.\n' "$exp_version" "$VERSION" + exit 1 +fi + +# Delete transient data from tables. Per MySQL documentation TRUNCATE +# destroys and there recreates tables. As schema updates are typically +# very slow, we're use deletes here. We turn off foreign key checks to +# worrying about table order. We also set the session variable +# disable_audit to turn off Back audit procedures, to avoid attempting +# to create entries for deleted records. +mysql "$@" <<EOF +START TRANSACTION; +SET SESSION FOREIGN_KEY_CHECKS = 0; +SET @disable_audit = 1; + +DELETE FROM dhcp4_global_parameter; +DELETE FROM dhcp4_global_parameter_server; +DELETE FROM dhcp4_option_def; +DELETE FROM dhcp4_option_def_server; +DELETE FROM dhcp4_options; +DELETE FROM dhcp4_options_server; +DELETE FROM dhcp4_pool; +# preserve special server "all" +DELETE FROM dhcp4_server WHERE tag != "all"; +DELETE FROM dhcp4_shared_network; +DELETE FROM dhcp4_shared_network_server; +DELETE FROM dhcp4_subnet; +DELETE FROM dhcp4_subnet_server; +DELETE FROM dhcp4_audit_revision; +DELETE FROM dhcp4_audit; +DELETE FROM dhcp4_client_class; +DELETE FROM dhcp4_client_class_order; +DELETE FROM dhcp4_client_class_dependency; +DELETE FROM dhcp4_client_class_server; +DELETE FROM dhcp6_global_parameter; +DELETE FROM dhcp6_global_parameter_server; +DELETE FROM dhcp6_option_def; +DELETE FROM dhcp6_option_def_server; +DELETE FROM dhcp6_options; +DELETE FROM dhcp6_options_server; +DELETE FROM dhcp6_pd_pool; +DELETE FROM dhcp6_pool; +# preserve special server "all" +DELETE FROM dhcp6_server WHERE tag != "all"; +DELETE FROM dhcp6_shared_network; +DELETE FROM dhcp6_shared_network_server; +DELETE FROM dhcp6_subnet; +DELETE FROM dhcp6_subnet_server; +DELETE FROM dhcp6_audit; +DELETE FROM dhcp6_audit_revision; +DELETE FROM dhcp6_client_class; +DELETE FROM dhcp6_client_class_order; +DELETE FROM dhcp6_client_class_dependency; +DELETE FROM dhcp6_client_class_server; +DELETE FROM hosts; +DELETE FROM ipv6_reservations; +DELETE FROM lease4; +DELETE FROM lease4_stat; +DELETE FROM lease6; +DELETE FROM lease6_stat; +DELETE FROM logs; +DELETE FROM lease4_stat_by_client_class; +DELETE FROM lease6_stat_by_client_class; +COMMIT; +EOF diff --git a/src/share/database/scripts/pgsql/Makefile.am b/src/share/database/scripts/pgsql/Makefile.am new file mode 100644 index 0000000..f9c2096 --- /dev/null +++ b/src/share/database/scripts/pgsql/Makefile.am @@ -0,0 +1,34 @@ +SUBDIRS = . + +pgsqldir = ${datarootdir}/${PACKAGE_NAME}/scripts/pgsql + +# non-executable +pgsql_DATA = +pgsql_DATA += dhcpdb_create.pgsql +pgsql_DATA += dhcpdb_drop.pgsql + +# executable +pgsql_SCRIPTS = +pgsql_SCRIPTS += upgrade_001.0_to_002.0.sh +pgsql_SCRIPTS += upgrade_002.0_to_003.0.sh +pgsql_SCRIPTS += upgrade_003.0_to_003.1.sh +pgsql_SCRIPTS += upgrade_003.1_to_003.2.sh +pgsql_SCRIPTS += upgrade_003.2_to_003.3.sh +pgsql_SCRIPTS += upgrade_003.3_to_004.0.sh +pgsql_SCRIPTS += upgrade_004.0_to_005.0.sh +pgsql_SCRIPTS += upgrade_005.0_to_005.1.sh +pgsql_SCRIPTS += upgrade_005.1_to_006.0.sh +pgsql_SCRIPTS += upgrade_006.0_to_006.1.sh +pgsql_SCRIPTS += upgrade_006.1_to_006.2.sh +pgsql_SCRIPTS += upgrade_006.2_to_007.0.sh +pgsql_SCRIPTS += upgrade_007_to_008.sh +pgsql_SCRIPTS += upgrade_008_to_009.sh +pgsql_SCRIPTS += upgrade_009_to_010.sh +pgsql_SCRIPTS += upgrade_010_to_011.sh +pgsql_SCRIPTS += upgrade_011_to_012.sh +pgsql_SCRIPTS += upgrade_012_to_013.sh +pgsql_SCRIPTS += wipe_data.sh + +DISTCLEANFILES = ${pgsql_SCRIPTS} + +EXTRA_DIST = ${pgsql_DATA} diff --git a/src/share/database/scripts/pgsql/Makefile.in b/src/share/database/scripts/pgsql/Makefile.in new file mode 100644 index 0000000..781bb42 --- /dev/null +++ b/src/share/database/scripts/pgsql/Makefile.in @@ -0,0 +1,880 @@ +# Makefile.in generated by automake 1.16.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2018 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@ + + +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 = src/share/database/scripts/pgsql +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4macros/ax_boost_for_kea.m4 \ + $(top_srcdir)/m4macros/ax_cpp11.m4 \ + $(top_srcdir)/m4macros/ax_crypto.m4 \ + $(top_srcdir)/m4macros/ax_find_library.m4 \ + $(top_srcdir)/m4macros/ax_gssapi.m4 \ + $(top_srcdir)/m4macros/ax_gtest.m4 \ + $(top_srcdir)/m4macros/ax_isc_rpath.m4 \ + $(top_srcdir)/m4macros/ax_sysrepo.m4 \ + $(top_srcdir)/m4macros/libtool.m4 \ + $(top_srcdir)/m4macros/ltoptions.m4 \ + $(top_srcdir)/m4macros/ltsugar.m4 \ + $(top_srcdir)/m4macros/ltversion.m4 \ + $(top_srcdir)/m4macros/lt~obsolete.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = upgrade_001.0_to_002.0.sh \ + upgrade_002.0_to_003.0.sh upgrade_003.0_to_003.1.sh \ + upgrade_003.1_to_003.2.sh upgrade_003.2_to_003.3.sh \ + upgrade_003.3_to_004.0.sh upgrade_004.0_to_005.0.sh \ + upgrade_005.0_to_005.1.sh upgrade_005.1_to_006.0.sh \ + upgrade_006.0_to_006.1.sh upgrade_006.1_to_006.2.sh \ + upgrade_006.2_to_007.0.sh upgrade_007_to_008.sh \ + upgrade_008_to_009.sh upgrade_009_to_010.sh \ + upgrade_010_to_011.sh upgrade_011_to_012.sh \ + upgrade_012_to_013.sh wipe_data.sh +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(pgsqldir)" "$(DESTDIR)$(pgsqldir)" +SCRIPTS = $(pgsql_SCRIPTS) +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 +DATA = $(pgsql_DATA) +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 \ + distdir distdir-am +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# 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 +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in \ + $(srcdir)/upgrade_001.0_to_002.0.sh.in \ + $(srcdir)/upgrade_002.0_to_003.0.sh.in \ + $(srcdir)/upgrade_003.0_to_003.1.sh.in \ + $(srcdir)/upgrade_003.1_to_003.2.sh.in \ + $(srcdir)/upgrade_003.2_to_003.3.sh.in \ + $(srcdir)/upgrade_003.3_to_004.0.sh.in \ + $(srcdir)/upgrade_004.0_to_005.0.sh.in \ + $(srcdir)/upgrade_005.0_to_005.1.sh.in \ + $(srcdir)/upgrade_005.1_to_006.0.sh.in \ + $(srcdir)/upgrade_006.0_to_006.1.sh.in \ + $(srcdir)/upgrade_006.1_to_006.2.sh.in \ + $(srcdir)/upgrade_006.2_to_007.0.sh.in \ + $(srcdir)/upgrade_007_to_008.sh.in \ + $(srcdir)/upgrade_008_to_009.sh.in \ + $(srcdir)/upgrade_009_to_010.sh.in \ + $(srcdir)/upgrade_010_to_011.sh.in \ + $(srcdir)/upgrade_011_to_012.sh.in \ + $(srcdir)/upgrade_012_to_013.sh.in $(srcdir)/wipe_data.sh.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +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" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +ASCIIDOC = @ASCIIDOC@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOOST_INCLUDES = @BOOST_INCLUDES@ +BOOST_LIBS = @BOOST_LIBS@ +BOTAN_TOOL = @BOTAN_TOOL@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CONTRIB_DIR = @CONTRIB_DIR@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CRYPTO_CFLAGS = @CRYPTO_CFLAGS@ +CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ +CRYPTO_LDFLAGS = @CRYPTO_LDFLAGS@ +CRYPTO_LIBS = @CRYPTO_LIBS@ +CRYPTO_PACKAGE = @CRYPTO_PACKAGE@ +CRYPTO_RPATH = @CRYPTO_RPATH@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DISTCHECK_BOOST_CONFIGURE_FLAG = @DISTCHECK_BOOST_CONFIGURE_FLAG@ +DISTCHECK_CONTRIB_CONFIGURE_FLAG = @DISTCHECK_CONTRIB_CONFIGURE_FLAG@ +DISTCHECK_CRYPTO_CONFIGURE_FLAG = @DISTCHECK_CRYPTO_CONFIGURE_FLAG@ +DISTCHECK_GTEST_CONFIGURE_FLAG = @DISTCHECK_GTEST_CONFIGURE_FLAG@ +DISTCHECK_KEA_SHELL_CONFIGURE_FLAG = @DISTCHECK_KEA_SHELL_CONFIGURE_FLAG@ +DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG = @DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG@ +DISTCHECK_PERFDHCP_CONFIGURE_FLAG = @DISTCHECK_PERFDHCP_CONFIGURE_FLAG@ +DISTCHECK_PREMIUM_CONFIGURE_FLAG = @DISTCHECK_PREMIUM_CONFIGURE_FLAG@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GENHTML = @GENHTML@ +GREP = @GREP@ +GSSAPI_CFLAGS = @GSSAPI_CFLAGS@ +GSSAPI_LIBS = @GSSAPI_LIBS@ +GTEST_CONFIG = @GTEST_CONFIG@ +GTEST_INCLUDES = @GTEST_INCLUDES@ +GTEST_LDADD = @GTEST_LDADD@ +GTEST_LDFLAGS = @GTEST_LDFLAGS@ +GTEST_SOURCE = @GTEST_SOURCE@ +HAVE_SYSREPO = @HAVE_SYSREPO@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +KEA_CXXFLAGS = @KEA_CXXFLAGS@ +KEA_SRCID = @KEA_SRCID@ +KRB5_CONFIG = @KRB5_CONFIG@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LOG4CPLUS_INCLUDES = @LOG4CPLUS_INCLUDES@ +LOG4CPLUS_LIBS = @LOG4CPLUS_LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MYSQL_CPPFLAGS = @MYSQL_CPPFLAGS@ +MYSQL_LIBS = @MYSQL_LIBS@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +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@ +PACKAGE_VERSION_TYPE = @PACKAGE_VERSION_TYPE@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PDFLATEX = @PDFLATEX@ +PERL = @PERL@ +PGSQL_CPPFLAGS = @PGSQL_CPPFLAGS@ +PGSQL_LIBS = @PGSQL_LIBS@ +PKGPYTHONDIR = @PKGPYTHONDIR@ +PKG_CONFIG = @PKG_CONFIG@ +PLANTUML = @PLANTUML@ +PREMIUM_DIR = @PREMIUM_DIR@ +PYTHON = @PYTHON@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +RANLIB = @RANLIB@ +SED = @SED@ +SEP = @SEP@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPHINXBUILD = @SPHINXBUILD@ +SRPD_PLUGINS_PATH = @SRPD_PLUGINS_PATH@ +SR_REPO_PATH = @SR_REPO_PATH@ +STRIP = @STRIP@ +SYSREPOCPP_VERSION = @SYSREPOCPP_VERSION@ +SYSREPO_CPPFLAGS = @SYSREPO_CPPFLAGS@ +SYSREPO_INCLUDEDIR = @SYSREPO_INCLUDEDIR@ +SYSREPO_LIBS = @SYSREPO_LIBS@ +SYSREPO_VERSION = @SYSREPO_VERSION@ +USE_LCOV = @USE_LCOV@ +VALGRIND = @VALGRIND@ +VERSION = @VERSION@ +WARNING_GCC_44_STRICT_ALIASING_CFLAG = @WARNING_GCC_44_STRICT_ALIASING_CFLAG@ +YACC = @YACC@ +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@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +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@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +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 = . +pgsqldir = ${datarootdir}/${PACKAGE_NAME}/scripts/pgsql + +# non-executable +pgsql_DATA = dhcpdb_create.pgsql dhcpdb_drop.pgsql + +# executable +pgsql_SCRIPTS = upgrade_001.0_to_002.0.sh upgrade_002.0_to_003.0.sh \ + upgrade_003.0_to_003.1.sh upgrade_003.1_to_003.2.sh \ + upgrade_003.2_to_003.3.sh upgrade_003.3_to_004.0.sh \ + upgrade_004.0_to_005.0.sh upgrade_005.0_to_005.1.sh \ + upgrade_005.1_to_006.0.sh upgrade_006.0_to_006.1.sh \ + upgrade_006.1_to_006.2.sh upgrade_006.2_to_007.0.sh \ + upgrade_007_to_008.sh upgrade_008_to_009.sh \ + upgrade_009_to_010.sh upgrade_010_to_011.sh \ + upgrade_011_to_012.sh upgrade_012_to_013.sh wipe_data.sh +DISTCLEANFILES = ${pgsql_SCRIPTS} +EXTRA_DIST = ${pgsql_DATA} +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/share/database/scripts/pgsql/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/share/database/scripts/pgsql/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +upgrade_001.0_to_002.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_001.0_to_002.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_002.0_to_003.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_002.0_to_003.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_003.0_to_003.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_003.0_to_003.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_003.1_to_003.2.sh: $(top_builddir)/config.status $(srcdir)/upgrade_003.1_to_003.2.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_003.2_to_003.3.sh: $(top_builddir)/config.status $(srcdir)/upgrade_003.2_to_003.3.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_003.3_to_004.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_003.3_to_004.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_004.0_to_005.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_004.0_to_005.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_005.0_to_005.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_005.0_to_005.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_005.1_to_006.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_005.1_to_006.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_006.0_to_006.1.sh: $(top_builddir)/config.status $(srcdir)/upgrade_006.0_to_006.1.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_006.1_to_006.2.sh: $(top_builddir)/config.status $(srcdir)/upgrade_006.1_to_006.2.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_006.2_to_007.0.sh: $(top_builddir)/config.status $(srcdir)/upgrade_006.2_to_007.0.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_007_to_008.sh: $(top_builddir)/config.status $(srcdir)/upgrade_007_to_008.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_008_to_009.sh: $(top_builddir)/config.status $(srcdir)/upgrade_008_to_009.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_009_to_010.sh: $(top_builddir)/config.status $(srcdir)/upgrade_009_to_010.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_010_to_011.sh: $(top_builddir)/config.status $(srcdir)/upgrade_010_to_011.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_011_to_012.sh: $(top_builddir)/config.status $(srcdir)/upgrade_011_to_012.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +upgrade_012_to_013.sh: $(top_builddir)/config.status $(srcdir)/upgrade_012_to_013.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +wipe_data.sh: $(top_builddir)/config.status $(srcdir)/wipe_data.sh.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-pgsqlSCRIPTS: $(pgsql_SCRIPTS) + @$(NORMAL_INSTALL) + @list='$(pgsql_SCRIPTS)'; test -n "$(pgsqldir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pgsqldir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pgsqldir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n' \ + -e 'h;s|.*|.|' \ + -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) { files[d] = files[d] " " $$1; \ + if (++n[d] == $(am__install_max)) { \ + print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ + else { print "f", d "/" $$4, $$1 } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(pgsqldir)$$dir'"; \ + $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(pgsqldir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-pgsqlSCRIPTS: + @$(NORMAL_UNINSTALL) + @list='$(pgsql_SCRIPTS)'; test -n "$(pgsqldir)" || exit 0; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 's,.*/,,;$(transform)'`; \ + dir='$(DESTDIR)$(pgsqldir)'; $(am__uninstall_files_from_dir) + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pgsqlDATA: $(pgsql_DATA) + @$(NORMAL_INSTALL) + @list='$(pgsql_DATA)'; test -n "$(pgsqldir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pgsqldir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pgsqldir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pgsqldir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(pgsqldir)" || exit $$?; \ + done + +uninstall-pgsqlDATA: + @$(NORMAL_UNINSTALL) + @list='$(pgsql_DATA)'; test -n "$(pgsqldir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pgsqldir)'; $(am__uninstall_files_from_dir) + +# 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" +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 + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @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 +check-am: all-am +check: check-recursive +all-am: Makefile $(SCRIPTS) $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(pgsqldir)" "$(DESTDIR)$(pgsqldir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +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) + -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + +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 clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-pgsqlDATA install-pgsqlSCRIPTS + +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 Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-pgsqlDATA uninstall-pgsqlSCRIPTS + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-libtool cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-libtool \ + distclean-tags distdir 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-pgsqlDATA \ + install-pgsqlSCRIPTS install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-am uninstall uninstall-am uninstall-pgsqlDATA \ + uninstall-pgsqlSCRIPTS + +.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: diff --git a/src/share/database/scripts/pgsql/dhcpdb_create.pgsql b/src/share/database/scripts/pgsql/dhcpdb_create.pgsql new file mode 100644 index 0000000..f24e086 --- /dev/null +++ b/src/share/database/scripts/pgsql/dhcpdb_create.pgsql @@ -0,0 +1,5658 @@ +-- Copyright (C) 2012-2022 Internet Systems Consortium, Inc. ("ISC") + +-- This Source Code Form is subject to the terms of the Mozilla Public +-- License, v. 2.0. If a copy of the MPL was not distributed with this +-- file, You can obtain one at http://mozilla.org/MPL/2.0/. + +-- This is the Kea DHCP schema specification for PostgreSQL. + +-- The schema is reasonably portable (with the exception of some field types +-- specification, which are PostgreSQL-specific). Minor changes might be needed +-- for other databases. + +-- To create the schema, either type the command: + +-- psql -U <user> -W <password> <database> < dhcpdb_create.pgsql + +-- ... at the command prompt, or log in to the PostgreSQL database and at the "postgres=#" +-- prompt, issue the command: + +-- @dhcpdb_create.pgsql + +-- Start a single transaction for the Entire script +START TRANSACTION; + +-- Holds the IPv4 leases. +CREATE TABLE lease4 ( + address BIGINT PRIMARY KEY NOT NULL, -- IPv4 address + hwaddr BYTEA, -- Hardware address + client_id BYTEA, -- Client ID + valid_lifetime BIGINT, -- Length of the lease (seconds) + expire TIMESTAMP WITH TIME ZONE, -- Expiration time of the lease + subnet_id BIGINT, -- Subnet identification + fqdn_fwd BOOLEAN, -- Has forward DNS update been performed by a server + fqdn_rev BOOLEAN, -- Has reverse DNS update been performed by a server + hostname VARCHAR(255) -- The FQDN of the client + ); + +-- Create search indexes for lease4 table +-- index by hwaddr and subnet_id +CREATE INDEX lease4_by_hwaddr_subnet_id ON lease4 (hwaddr, subnet_id); + +-- index by client_id and subnet_id +CREATE INDEX lease4_by_client_id_subnet_id ON lease4 (client_id, subnet_id); + +-- Holds the IPv6 leases. +-- N.B. The use of a VARCHAR for the address is temporary for development: +-- it will eventually be replaced by BINARY(16). +CREATE TABLE lease6 ( + address VARCHAR(39) PRIMARY KEY NOT NULL, -- IPv6 address + duid BYTEA, -- DUID + valid_lifetime BIGINT, -- Length of the lease (seconds) + expire TIMESTAMP WITH TIME ZONE, -- Expiration time of the lease + subnet_id BIGINT, -- Subnet identification + pref_lifetime BIGINT, -- Preferred lifetime + lease_type SMALLINT, -- Lease type (see lease6_types + -- table for possible values) + iaid INT, -- See Section 12 of RFC 8415 + prefix_len SMALLINT, -- For IA_PD only + fqdn_fwd BOOLEAN, -- Has forward DNS update been performed by a server + fqdn_rev BOOLEAN, -- Has reverse DNS update been performed by a server + hostname VARCHAR(255) -- The FQDN of the client + ); + +-- Create search indexes for lease6 table +-- index by iaid, subnet_id, and duid +CREATE INDEX lease6_by_iaid_subnet_id_duid ON lease6 (iaid, subnet_id, duid); + +-- ... and a definition of lease6 types. This table is a convenience for +-- users of the database - if they want to view the lease table and use the +-- type names, they can join this table with the lease6 table +CREATE TABLE lease6_types ( + lease_type SMALLINT PRIMARY KEY NOT NULL, -- Lease type code. + name VARCHAR(5) -- Name of the lease type + ); + +INSERT INTO lease6_types VALUES (0, 'IA_NA'); -- Non-temporary v6 addresses +INSERT INTO lease6_types VALUES (1, 'IA_TA'); -- Temporary v6 addresses +INSERT INTO lease6_types VALUES (2, 'IA_PD'); -- Prefix delegations + +-- Finally, the version of the schema. We start at 0.1 during development. +-- This table is only modified during schema upgrades. For historical reasons +-- (related to the names of the columns in the BIND 10 DNS database file), the +-- first column is called "version" and not "major". +CREATE TABLE schema_version ( + version INT PRIMARY KEY NOT NULL, -- Major version number + minor INT -- Minor version number + ); + +INSERT INTO schema_version VALUES (1, 0); + +-- +-- Schema 2.0 specification starts here. +-- + +-- Add state column to the lease4 table. +ALTER TABLE lease4 + ADD COLUMN state INT8 DEFAULT 0; + +-- Add state column to the lease6 table. +ALTER TABLE lease6 + ADD COLUMN state INT8 DEFAULT 0; + +-- Create indexes for querying leases in a given state and segregated +-- by the expiration time. One of the applications is to retrieve all +-- expired leases. However, these indexes can be also used to retrieve +-- leases in a given state regardless of the expiration time. +CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC); +CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC); + +-- Create table holding mapping of the lease states to their names. +-- This is not used in queries from the DHCP server but rather in +-- direct queries from the lease database management tools. +CREATE TABLE lease_state ( + state INT8 PRIMARY KEY NOT NULL, + name VARCHAR(64) NOT NULL); + +-- Insert currently defined state names. +INSERT INTO lease_state VALUES (0, 'default'); +INSERT INTO lease_state VALUES (1, 'declined'); +INSERT INTO lease_state VALUES (2, 'expired-reclaimed'); + +-- Add a constraint that any state value added to the lease4 must +-- map to a value in the lease_state table. +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +-- Add a constraint that any state value added to the lease6 must +-- map to a value in the lease_state table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +-- Add a constraint that lease type in the lease6 table must map +-- to a lease type defined in the lease6_types table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type); + +-- +-- FUNCTION that returns a result set containing the column names for lease4 dumps. +DROP FUNCTION IF EXISTS lease4DumpHeader(); +CREATE OR REPLACE FUNCTION lease4DumpHeader() RETURNS text AS $$ + select cast('address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state' as text) as result; +$$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease4 dumps. +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE OR REPLACE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) as $$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name + FROM lease4 l + left outer join lease_state s on (l.state = s.state); +$$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the column names for lease6 dumps. +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE OR REPLACE FUNCTION lease6DumpHeader() RETURNS text AS $$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state' as text) as result; +$$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease6 dumps. +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE OR REPLACE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) AS $$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state); +$$ LANGUAGE SQL; +-- + +-- Set 2.0 schema version. +UPDATE schema_version + SET version = '2', minor = '0'; + +-- Schema 2.0 specification ends here. + +-- Upgrade to schema 3.0 begins here: + +-- +-- Table structure for table host_identifier_type. +-- + +CREATE TABLE host_identifier_type ( + type SMALLINT PRIMARY KEY NOT NULL, + name VARCHAR(32) DEFAULT NULL +); + +INSERT INTO host_identifier_type VALUES (0, 'hw-address'); +INSERT INTO host_identifier_type VALUES (1, 'duid'); +INSERT INTO host_identifier_type VALUES (2, 'circuit-id'); +INSERT INTO host_identifier_type VALUES (3, 'client-id'); + +-- +-- Table structure for table dhcp_option_scope. +-- + +CREATE TABLE dhcp_option_scope ( + scope_id SMALLINT PRIMARY KEY NOT NULL, + scope_name VARCHAR(32) DEFAULT NULL +); + +INSERT INTO dhcp_option_scope VALUES (0, 'global'); +INSERT INTO dhcp_option_scope VALUES (1, 'subnet'); +INSERT INTO dhcp_option_scope VALUES (2, 'client-class'); +INSERT INTO dhcp_option_scope VALUES (3, 'host'); + +-- +-- Table structure for table hosts. +-- +-- Primary key and unique constraints automatically create indexes, +-- foreign key constraints do not. +CREATE TABLE hosts ( + host_id SERIAL PRIMARY KEY NOT NULL, + dhcp_identifier BYTEA NOT NULL, + dhcp_identifier_type SMALLINT NOT NULL, + dhcp4_subnet_id INT DEFAULT NULL, + dhcp6_subnet_id INT DEFAULT NULL, + ipv4_address BIGINT DEFAULT NULL, + hostname VARCHAR(255) DEFAULT NULL, + dhcp4_client_classes VARCHAR(255) DEFAULT NULL, + dhcp6_client_classes VARCHAR(255) DEFAULT NULL, + CONSTRAINT key_dhcp4_ipv4_address_subnet_id UNIQUE (ipv4_address, dhcp4_subnet_id), + CONSTRAINT key_dhcp4_identifier_subnet_id UNIQUE (dhcp_identifier, dhcp_identifier_type, dhcp4_subnet_id), + CONSTRAINT key_dhcp6_identifier_subnet_id UNIQUE (dhcp_identifier, dhcp_identifier_type, dhcp6_subnet_id), + CONSTRAINT fk_host_identifier_type FOREIGN KEY (dhcp_identifier_type) REFERENCES host_identifier_type (type) + ON DELETE CASCADE +); + +CREATE INDEX fk_host_identifier_type ON hosts (dhcp_identifier_type); + +-- +-- Table structure for table dhcp4_options. +-- + +CREATE TABLE dhcp4_options ( + option_id SERIAL PRIMARY KEY NOT NULL, + code SMALLINT NOT NULL, + value BYTEA, + formatted_value TEXT, + space VARCHAR(128) DEFAULT NULL, + persistent BOOLEAN NOT NULL DEFAULT 'f', + dhcp_client_class VARCHAR(128) DEFAULT NULL, + dhcp4_subnet_id BIGINT DEFAULT NULL, + host_id INT DEFAULT NULL, + scope_id SMALLINT NOT NULL, + CONSTRAINT fk_options_host1 FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_option_scode FOREIGN KEY (scope_id) REFERENCES dhcp_option_scope (scope_id) ON DELETE CASCADE +); + +CREATE INDEX fk_dhcp4_options_host1_idx ON dhcp4_options (host_id); +CREATE INDEX fk_dhcp4_options_scope_idx ON dhcp4_options (scope_id); + +-- +-- Table structure for table dhcp6_options. +-- + +CREATE TABLE dhcp6_options ( + option_id SERIAL PRIMARY KEY NOT NULL, + code INT NOT NULL, + value BYTEA, + formatted_value TEXT, + space VARCHAR(128) DEFAULT NULL, + persistent BOOLEAN NOT NULL DEFAULT 'f', + dhcp_client_class VARCHAR(128) DEFAULT NULL, + dhcp6_subnet_id BIGINT DEFAULT NULL, + host_id INT DEFAULT NULL, + scope_id SMALLINT NOT NULL, + CONSTRAINT fk_options_host10 FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_option_scode FOREIGN KEY (scope_id) REFERENCES dhcp_option_scope (scope_id) ON DELETE CASCADE +); + +CREATE INDEX fk_dhcp6_options_host1_idx ON dhcp6_options (host_id); +CREATE INDEX fk_dhcp6_options_scope_idx ON dhcp6_options (scope_id); + +-- +-- Table structure for table ipv6_reservations. +-- + +CREATE TABLE ipv6_reservations ( + reservation_id SERIAL PRIMARY KEY NOT NULL, + address VARCHAR(39) NOT NULL, + prefix_len SMALLINT NOT NULL DEFAULT '128', + type SMALLINT NOT NULL DEFAULT '0', + dhcp6_iaid INT DEFAULT NULL, + host_id INT NOT NULL, + CONSTRAINT key_dhcp6_address_prefix_len UNIQUE (address, prefix_len), + CONSTRAINT fk_ipv6_reservations_host FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE +); + +CREATE INDEX fk_ipv6_reservations_host_idx ON ipv6_reservations (host_id); + +-- +-- Table structure for table lease_hwaddr_source. +-- + +CREATE TABLE lease_hwaddr_source ( + hwaddr_source INT PRIMARY KEY NOT NULL, + name VARCHAR(40) DEFAULT NULL +); + +-- In the event hardware address cannot be determined, we need to satisfy +-- foreign key constraint between lease6 and lease_hardware_source. +INSERT INTO lease_hwaddr_source VALUES (0, 'HWADDR_SOURCE_UNKNOWN'); + +-- Hardware address obtained from raw sockets. +INSERT INTO lease_hwaddr_source VALUES (1, 'HWADDR_SOURCE_RAW'); + +-- Hardware address converted from IPv6 link-local address with EUI-64. +INSERT INTO lease_hwaddr_source VALUES (2, 'HWADDR_SOURCE_IPV6_LINK_LOCAL'); + +-- Hardware address extracted from client-id (duid). +INSERT INTO lease_hwaddr_source VALUES (4, 'HWADDR_SOURCE_DUID'); + +-- Hardware address extracted from client address relay option (RFC6939). +INSERT INTO lease_hwaddr_source VALUES (8, 'HWADDR_SOURCE_CLIENT_ADDR_RELAY_OPTION'); + +-- Hardware address extracted from remote-id option (RFC4649). +INSERT INTO lease_hwaddr_source VALUES (16, 'HWADDR_SOURCE_REMOTE_ID'); + +-- Hardware address extracted from subscriber-id option (RFC4580). +INSERT INTO lease_hwaddr_source VALUES (32, 'HWADDR_SOURCE_SUBSCRIBER_ID'); + +-- Hardware address extracted from docsis options. +INSERT INTO lease_hwaddr_source VALUES (64, 'HWADDR_SOURCE_DOCSIS_CMTS'); + +INSERT INTO lease_hwaddr_source VALUES (128, 'HWADDR_SOURCE_DOCSIS_MODEM'); + +-- Adding ORDER BY clause to sort by lease address. +-- +-- FUNCTION that returns a result set containing the data for lease4 dumps. +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE OR REPLACE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) as $$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name + FROM lease4 l + left outer join lease_state s on (l.state = s.state) + ORDER BY l.address; +$$ LANGUAGE SQL; +-- + +-- Add new columns to lease6. +ALTER TABLE lease6 + ADD COLUMN hwaddr BYTEA DEFAULT NULL, + ADD COLUMN hwtype SMALLINT DEFAULT NULL, + ADD COLUMN hwaddr_source SMALLINT DEFAULT NULL; + +-- +-- FUNCTION that returns a result set containing the column names for lease6 dumps. +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE OR REPLACE FUNCTION lease6DumpHeader() RETURNS text AS $$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state,hwaddr,hwtype,hwaddr_source' as text) as result; +$$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease6 dumps. +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE OR REPLACE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + hwaddr text, + hwtype smallint, + hwaddr_source text + ) AS $$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + encode(l.hwaddr,'hex'), + l.hwtype, + h.name + ) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) + ORDER BY l.address; +$$ LANGUAGE SQL; + +-- Add columns holding reservations for siaddr, sname and file fields +-- carried within DHCPv4 message. +ALTER TABLE hosts ADD COLUMN dhcp4_next_server BIGINT DEFAULT NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_server_hostname VARCHAR(64) DEFAULT NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_boot_file_name VARCHAR(128) DEFAULT NULL; + +-- Set 3.0 schema version. +UPDATE schema_version + SET version = '3', minor = '0'; + +-- Schema 3.0 specification ends here. + +-- Upgrade to schema 3.1 begins here: + +-- This is a placeholder for the changes between 3.0 and 3.1. We have added a +-- missing 'client-id' host reservation type entry that had been accidentally +-- omitted when the 2.0 -> 3.0 upgrade script was created. +-- Also, new flexible identifier has been added. +INSERT INTO host_identifier_type VALUES (4, 'flex-id'); + +-- Set 3.1 schema version. +UPDATE schema_version + SET version = '3', minor = '1'; + +-- Schema 3.1 specification ends here. + +-- Upgrade to schema 3.2 begins here: + +-- Remove constraints which perform too restrictive checks on the inserted +-- host reservations. We want to be able to insert host reservations which +-- include no specific IPv4 address or those that have repeating subnet +-- identifiers, e.g. IPv4 reservations would typically include 0 (or null) +-- IPv6 subnet identifiers. +ALTER TABLE hosts DROP CONSTRAINT key_dhcp4_ipv4_address_subnet_id; +ALTER TABLE hosts DROP CONSTRAINT key_dhcp4_identifier_subnet_id; +ALTER TABLE hosts DROP CONSTRAINT key_dhcp6_identifier_subnet_id; + +-- Create partial indexes instead of the constraints that we have removed. + +-- IPv4 address/IPv4 subnet identifier pair is unique if subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX key_dhcp4_ipv4_address_subnet_id ON hosts + (ipv4_address ASC, dhcp4_subnet_id ASC) + WHERE ipv4_address IS NOT NULL AND ipv4_address <> 0; + +-- Client identifier is unique within an IPv4 subnet when subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp4_subnet_id ASC) + WHERE (dhcp4_subnet_id IS NOT NULL AND dhcp4_subnet_id <> 0); + +-- Client identifier is unique within an IPv6 subnet when subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp6_subnet_id ASC) + WHERE (dhcp6_subnet_id IS NOT NULL AND dhcp6_subnet_id <> 0); + +-- Set 3.2 schema version. +UPDATE schema_version + SET version = '3', minor = '2'; + +-- Schema 3.2 specification ends here. + +-- Upgrade to schema 3.3 begins here: + +-- Change subnet ID columns type to BIGINT to match lease4/6 tables +ALTER TABLE hosts ALTER COLUMN dhcp4_subnet_id TYPE BIGINT; +ALTER TABLE hosts ALTER COLUMN dhcp6_subnet_id TYPE BIGINT; + +ALTER TABLE dhcp4_options ALTER COLUMN dhcp4_subnet_id TYPE BIGINT; +ALTER TABLE dhcp6_options ALTER COLUMN dhcp6_subnet_id TYPE BIGINT; + +-- Set 3.3 schema version. +UPDATE schema_version + SET version = '3', minor = '3'; + +-- Schema 3.3 specification ends here. + +-- Upgrade to schema 4.0 begins here: + +-- Add a column holding hosts for user context. +ALTER TABLE hosts ADD COLUMN user_context TEXT; + +-- Add a column holding DHCP options for user context. +ALTER TABLE dhcp4_options ADD COLUMN user_context TEXT; +ALTER TABLE dhcp6_options ADD COLUMN user_context TEXT; + +-- Create index for searching leases by subnet identifier. +CREATE INDEX lease4_by_subnet_id ON lease4 (subnet_id); + +-- Create for searching leases by subnet identifier and lease type. +CREATE INDEX lease6_by_subnet_id_lease_type ON lease6 (subnet_id, lease_type); + +-- The index by iaid_subnet_id_duid is not the best choice because there are +-- cases when we don't specify subnet identifier while searching leases. The +-- index will be universal if the subnet_id is the right most column in the +-- index. +DROP INDEX lease6_by_iaid_subnet_id_duid; +CREATE INDEX lease6_by_duid_iaid_subnet_id ON lease6 (duid, iaid, subnet_id); + +-- Create v4 lease statistics table +CREATE TABLE lease4_stat ( + subnet_id BIGINT NOT NULL, + state INT8 NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, state) +); + +-- +-- Create v4 insert trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_insert() RETURNS trigger AS $stat_lease4_insert$ +BEGIN + IF NEW.state < 2 THEN + UPDATE lease4_stat + SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new.subnet_id, new.state, 1); + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease4_insert$ LANGUAGE plpgsql; + +-- Create v4 insert trigger procedure +CREATE TRIGGER stat_lease4_insert +AFTER INSERT ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_insert(); + +-- +-- Create v4 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_update() RETURNS trigger AS $stat_lease4_update$ +BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease4_update$ LANGUAGE plpgsql; + +-- Create v4 update trigger +CREATE TRIGGER stat_lease4_update +AFTER UPDATE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_update(); + + +-- +-- Create the v4 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_delete() RETURNS trigger AS $stat_lease4_delete$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease4_delete$ LANGUAGE plpgsql; + +-- Create the v4 delete trigger +CREATE TRIGGER stat_lease4_delete +AFTER DELETE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_delete(); + +-- Create v6 lease statistics table +CREATE TABLE lease6_stat ( + subnet_id BIGINT NOT NULL, + lease_type SMALLINT NOT NULL, + state INT8 NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, lease_type, state) +); + +-- +-- Create v6 insert trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_insert() RETURNS trigger AS $stat_lease6_insert$ +BEGIN + IF NEW.state < 2 THEN + UPDATE lease6_stat + SET leases = leases + 1 + WHERE + subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + IF NOT FOUND THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease6_insert$ LANGUAGE plpgsql; + +-- Create v6 insert trigger procedure +CREATE TRIGGER stat_lease6_insert +AFTER INSERT ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_insert(); + +-- +-- Create v6 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_update() RETURNS trigger AS $stat_lease6_update$ +BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease6_update$ LANGUAGE plpgsql; + +-- Create v6 update trigger +CREATE TRIGGER stat_lease6_update +AFTER UPDATE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_update(); + +-- +-- Create the v6 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_delete() RETURNS trigger AS $stat_lease6_delete$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease6_delete$ LANGUAGE plpgsql; + +-- Create the v6 delete trigger +CREATE TRIGGER stat_lease6_delete +AFTER DELETE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_delete(); + +-- Set 4.0 schema version. +UPDATE schema_version + SET version = '4', minor = '0'; + +-- Schema 4.0 specification ends here. + +-- Upgrade to schema 5.0 begins here: + +-- Add a column holding leases for user context. +ALTER TABLE lease4 ADD COLUMN user_context TEXT; +ALTER TABLE lease6 ADD COLUMN user_context TEXT; + +-- +DROP FUNCTION IF EXISTS lease4DumpHeader(); +CREATE OR REPLACE FUNCTION lease4DumpHeader() RETURNS text AS $$ + select cast('address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context' as text) as result; +$$ LANGUAGE SQL; +-- + +-- +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE OR REPLACE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + user_context text + ) as $$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + l.user_context + FROM lease4 l + left outer join lease_state s on (l.state = s.state) + ORDER BY l.address; +$$ LANGUAGE SQL; +-- + +-- +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE OR REPLACE FUNCTION lease6DumpHeader() RETURNS text AS $$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state,hwaddr,hwtype,hwaddr_source,user_context' as text) as result; +$$ LANGUAGE SQL; +-- + +-- +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE OR REPLACE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire TIMESTAMP WITH TIME ZONE, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + hwaddr text, + hwtype smallint, + hwaddr_source text, + user_context text + ) AS $$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + encode(l.hwaddr,'hex'), + l.hwtype, + h.name, + l.user_context + + ) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) + ORDER BY l.address; +$$ LANGUAGE SQL; +-- + +-- Create logs table (logs table is used by forensic logging hook library) +CREATE TABLE logs ( + timestamp TIMESTAMP WITH TIME ZONE + DEFAULT CURRENT_TIMESTAMP, -- creation timestamp + address VARCHAR(43) NULL, -- address or prefix + log TEXT NOT NULL -- the log itself + ); + +-- Create search indexes +CREATE INDEX timestamp_id ON logs (timestamp); +CREATE INDEX address_id ON logs (address); + +-- Create auth_key in hosts table for storing keys for DHCPv6 reconfigure. +ALTER TABLE hosts ADD COLUMN auth_key VARCHAR(16) DEFAULT NULL; + +-- Set schema 5.0 version +UPDATE schema_version + SET version = '5', minor = '0'; + +-- Schema 5.0 specification ends here. + +-- Upgrade to schema 5.1 begins here: + +-- Put the auth key in hexadecimal (double size but far more user friendly). +ALTER TABLE hosts ALTER COLUMN auth_key TYPE VARCHAR(32); + +-- Set schema 5.1 version +UPDATE schema_version + SET version = '5', minor = '1'; + +-- Schema 5.1 specification ends here. + +-- Upgrade to schema 6.0 begins here: + +-- Create a lower case hostname index for hosts. +CREATE INDEX hosts_by_hostname ON hosts (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Create a hostname index for lease4. +CREATE INDEX lease4_by_hostname ON lease4 (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Create a hostname index for lease6. +CREATE INDEX lease6_by_hostname ON lease6 (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Set 6.0 schema version. +UPDATE schema_version + SET version = '6', minor = '0'; + +-- Schema 6.0 specification ends here. + +-- Upgrade to schema 6.1 begins here: + +-- Fix v4 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_update() RETURNS trigger AS $stat_lease4_update$ +BEGIN + IF OLD.subnet_id != NEW.subnet_id OR OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease4_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease4_update$ LANGUAGE plpgsql; + +-- +-- Fix the v4 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_delete() RETURNS trigger AS $stat_lease4_delete$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease4_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease4_delete$ LANGUAGE plpgsql; + +-- +-- Fix v6 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_update() RETURNS trigger AS $stat_lease6_update$ +BEGIN + IF OLD.subnet_id != NEW.subnet_id OR + OLD.lease_type != NEW.lease_type OR + OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease6_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease6_update$ LANGUAGE plpgsql; + +-- +-- Fix the v6 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_delete() RETURNS trigger AS $stat_lease6_delete$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +$stat_lease6_delete$ LANGUAGE plpgsql; + +-- Set 6.1 schema version. +UPDATE schema_version + SET version = '6', minor = '1'; + +-- Schema 6.1 specification ends here. + +-- Starting from this version we allow specifying multiple IP reservations +-- for the same address in certain DHCP configurations. The server may check +-- uniqueness of the IP addresses on its own. This is no longer checked at +-- the database level to facilitate the use cases when a single host may +-- get the same reserved IP address via different interfaces. + +-- Replace the unique index with non-unique index so the queries for +-- hosts by IPv4 address are still efficient. +DROP INDEX IF EXISTS key_dhcp4_ipv4_address_subnet_id; +CREATE INDEX key_dhcp4_ipv4_address_subnet_id + ON hosts (ipv4_address ASC, dhcp4_subnet_id ASC); + +-- Replace the unique index with non-unique index so the queries for +-- hosts by IPv6 address are still efficient. +ALTER TABLE ipv6_reservations DROP CONSTRAINT IF EXISTS key_dhcp6_address_prefix_len; +CREATE INDEX key_dhcp6_address_prefix_len + ON ipv6_reservations (address ASC, prefix_len ASC); + +-- Update the schema version number +UPDATE schema_version + SET version = '6', minor = '2'; + +-- Schema 6.2 specification ends here. + +-- This starts schema update to 7.0. It adds a lot (20+) of tables for the config backend. + + +-- Adding on update trigger in MySQL is as easy as using this column definition in CREATE TABLE: +-- modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, +-- Sadly, Postgres has its own convoluted way of doing this. Luckily, the update pattern is +-- the same in many tables, so we can define the trigger function once and the use it everywhere. + +-- First, we need to define a function that will do the actual job. +-- This is used in many, many tables. +CREATE OR REPLACE FUNCTION modification_ts_update() + RETURNS trigger AS $modification_ts_update$ + BEGIN + new.modification_ts = CURRENT_TIMESTAMP; + RETURN NULL; + END; + +-- Second, we need to specify which language it was written in. +$modification_ts_update$ LANGUAGE plpgsql; + + +-- Create table modification and insert values for modification types. +CREATE TABLE modification ( + id smallint NOT NULL, + modification_type VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +); +INSERT INTO modification VALUES (0,'create'), (1,'update'), (2,'delete'); + + + +-- Now create the table that holds different parameter data types. +CREATE TABLE parameter_data_type ( + id smallint NOT NULL, + name VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +); +INSERT INTO parameter_data_type VALUES + (0,'integer'), + (1,'real'), + (2,'boolean'), + (4,'string'); + + + +-- This table doesn't exist in MySQL. However, it's nice to have an enum that explains what the values +-- in ddns_replace_client_name field in the dhcp{4,6}_shared_network table means. +CREATE TABLE ddns_replace_client_name_types ( + type INT8 PRIMARY KEY NOT NULL, + name VARCHAR(32) +); +-- See enum ReplaceClientNameMode in src/lib/dhcpsrv/d2_client_cfg.h +INSERT INTO ddns_replace_client_name_types (type, name) VALUES + (0, 'RCM_NEVER'), + (1, 'RCM_ALWAYS'), + (2, 'RCM_WHEN_PRESENT'), + (3, 'RCM_WHEN_NOT_PRESENT'); + + + +-- Create table for DHCPv6 servers +CREATE TABLE dhcp6_server ( + id SERIAL PRIMARY KEY NOT NULL, + tag VARCHAR(64) NOT NULL, + description TEXT DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(tag) +); +CREATE INDEX dhcp6_server_idx1 ON dhcp6_server (modification_ts); +CREATE UNIQUE INDEX dhcp6_server_idx2 ON dhcp6_server(tag); +CREATE TRIGGER dhcp6_server_modification_ts_update + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +INSERT INTO dhcp6_server (tag, description) VALUES ('all','special type: all servers'); + +-- Create a table for storing IPv6 shared networks +CREATE TABLE dhcp6_shared_network ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + preferred_lifetime BIGINT DEFAULT NULL, + rapid_commit BOOLEAN DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + interface_id BYTEA DEFAULT NULL, -- 128 bytes + min_preferred_lifetime BIGINT DEFAULT NULL, + max_preferred_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); +CREATE INDEX dhcp6_shared_network_idx1 ON dhcp6_shared_network (name); + +CREATE TRIGGER dhcp6_shared_network_modification_ts_update + AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now we need to create a relationship between defined shared networks and the servers +CREATE TABLE dhcp6_shared_network_server ( + shared_network_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (shared_network_id, server_id), + CONSTRAINT fk_dhcp6_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp6_shared_network_server_idx1 ON dhcp6_shared_network_server (modification_ts); +CREATE INDEX dhcp6_shared_network_server_idx2 ON dhcp6_shared_network_server (server_id); + +-- Create a list of IPv6 subnets +CREATE TABLE dhcp6_subnet ( + subnet_id BIGINT PRIMARY KEY NOT NULL, + subnet_prefix VARCHAR(64) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + preferred_lifetime BIGINT DEFAULT NULL, + rapid_commit BOOLEAN DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + interface_id BYTEA DEFAULT NULL, + min_preferred_lifetime BIGINT DEFAULT NULL, + max_preferred_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE TRIGGER dhcp6_subnet_modification_ts_update + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +CREATE INDEX dhcp6_subnet_idx1 ON dhcp6_subnet (modification_ts); +CREATE INDEX dhcp6_subnet_idx2 ON dhcp6_subnet (shared_network_name); + + + +-- Create a table that holds all address pools in IPv6. +CREATE TABLE dhcp6_pool ( + id SERIAL PRIMARY KEY NOT NULL, + start_address inet NOT NULL, + end_address inet NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) +); +CREATE INDEX dhcp6_pool_idx1 ON dhcp6_pool (modification_ts); +CREATE INDEX dhcp6_pool_idx2 ON dhcp6_pool (subnet_id); + +CREATE TRIGGER dhcp6_pool_modification_ts_update + AFTER UPDATE ON dhcp6_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- And now the same, but for PD pools. +CREATE TABLE dhcp6_pd_pool ( + id SERIAL PRIMARY KEY NOT NULL, + prefix VARCHAR(45) NOT NULL, + prefix_length SMALLINT NOT NULL, + delegated_prefix_length SMALLINT NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + excluded_prefix VARCHAR(45) DEFAULT NULL, + excluded_prefix_length SMALLINT NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet(subnet_id) +); + +CREATE INDEX dhcp6_pd_pool_idx1 ON dhcp6_pd_pool (modification_ts); +CREATE INDEX dhcp6_pd_pool_idx2 ON dhcp6_pd_pool (subnet_id); +CREATE TRIGGER dhcp6_pd_pool_modification_ts_update + AFTER UPDATE ON dhcp6_pd_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +CREATE TABLE dhcp6_subnet_server ( + subnet_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (subnet_id, server_id), + CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION, + UNIQUE (subnet_id, server_id) +); +CREATE INDEX dhcp6_subnet_server_idx1 ON dhcp6_subnet_server(server_id); +CREATE INDEX dhcp6_subnet_server_idx2 ON dhcp6_subnet_server(modification_ts); +CREATE TRIGGER dhcp6_subnet_server_modification_ts_update + AFTER UPDATE ON dhcp6_subnet_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Create table for storing global DHCPv6 parameters. +CREATE TABLE dhcp6_global_parameter ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) NOT NULL, + value TEXT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + parameter_type SMALLINT NOT NULL, + CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id) +); + +CREATE INDEX key_dhcp6_global_parameter_idx1 ON dhcp6_global_parameter(modification_ts); +CREATE INDEX key_dhcp6_global_parameter_idx2 ON dhcp6_global_parameter(name); + +CREATE TRIGGER dhcp6_global_parameter_modification_ts_update + AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +CREATE TABLE dhcp6_global_parameter_server ( + parameter_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (parameter_id, server_id), + CONSTRAINT fk_dhcp6_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp6_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server(id) ON DELETE CASCADE ON UPDATE NO ACTION +); + +CREATE INDEX key_dhcp6_global_parameter_server_idx1 ON dhcp6_global_parameter_server(modification_ts); +CREATE TRIGGER dhcp6_global_parameter_server_modification_ts_update + AFTER UPDATE ON dhcp6_global_parameter_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Alter table for storing DHCPv6 options. +ALTER TABLE dhcp6_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT DEFAULT NULL, + ADD COLUMN pd_pool_id BIGINT DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD CONSTRAINT fk_dhcp6_options_pd_pool FOREIGN KEY (pd_pool_id) + REFERENCES dhcp6_pd_pool(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp6_options_pool FOREIGN KEY (pool_id) + REFERENCES dhcp6_pool (id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp6_options_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE TRIGGER dhcp6_options_modification_ts_update + AFTER UPDATE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +-- Now create a table for associating defined options with servers. +CREATE TABLE dhcp6_options_server ( + option_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_id, server_id), + CONSTRAINT fk_dhcp6_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp6_options_server_idx1 ON dhcp6_options_server(server_id); +CREATE INDEX dhcp6_options_server_idx2 ON dhcp6_options_server(modification_ts); +CREATE TRIGGER dhcp6_options_server_modification_ts_update + AFTER UPDATE ON dhcp6_options_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- This table is for storing IPv6 option definitions +CREATE TABLE dhcp6_option_def ( + id SERIAL PRIMARY KEY UNIQUE NOT NULL, + code SMALLINT NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type SMALLINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + is_array BOOLEAN NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR DEFAULT NULL, + user_context JSON DEFAULT NULL +); +CREATE INDEX dhcp6_option_def_idx1 ON dhcp6_option_def(modification_ts); +CREATE INDEX dhcp6_option_def_idx2 ON dhcp6_option_def(code, space); +CREATE TRIGGER dhcp6_option_def_modification_ts_update + AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- and another table for storing relationship between option definitions and servers. +CREATE TABLE dhcp6_option_def_server ( + option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + server_id BIGINT NOT NULL REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_def_id, server_id) +); +CREATE TRIGGER dhcp6_option_def_server_modification_ts_update + AFTER UPDATE ON dhcp6_option_def_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Now create two tables for audit revisions... +CREATE TABLE dhcp6_audit_revision ( + id SERIAL PRIMARY KEY NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + log_message TEXT DEFAULT NULL, + server_id BIGINT DEFAULT NULL +); +CREATE TRIGGER dhcp6_audit_revision_modification_ts_update + AFTER UPDATE ON dhcp6_audit_revision + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- ... and the DHCPv6 audit itself. +CREATE TABLE dhcp6_audit ( + id SERIAL UNIQUE NOT NULL, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT NOT NULL, + modification_type SMALLINT NOT NULL, + revision_id BIGINT NOT NULL, + CONSTRAINT fk_dhcp6_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp6_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE +); +CREATE TRIGGER dhcp6_audit_modification_ts_update + AFTER UPDATE ON dhcp6_audit + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); +CREATE INDEX dhcp6_audit_idx1 ON dhcp6_audit (modification_type); +CREATE INDEX dhcp6_audit_idx2 ON dhcp6_audit (revision_id); + + +-- Create table for DHCPv4 servers +CREATE TABLE dhcp4_server ( + id SERIAL PRIMARY KEY NOT NULL, + tag VARCHAR(64) NOT NULL, + description TEXT DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(tag) +); +CREATE INDEX dhcp4_server_modification_ts ON dhcp6_server (modification_ts); +CREATE TRIGGER dhcp4_server_modification_ts_update + AFTER UPDATE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +INSERT INTO dhcp4_server (tag, description) VALUES ('all','special type: all servers'); + +-- Create table for storing global DHCPv4 parameters. +CREATE TABLE dhcp4_global_parameter ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) NOT NULL, + value TEXT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + parameter_type SMALLINT NOT NULL, + CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id) +); +CREATE INDEX dhcp4_global_parameter_idx1 ON dhcp4_global_parameter(modification_ts); +CREATE INDEX dhcp4_global_parameter_idx2 ON dhcp4_global_parameter(name); + +CREATE TRIGGER dhcp4_global_parameter_modification_ts_update + AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +-- and create mapping for the global DHCPv4 parameters mapping to servers +CREATE TABLE dhcp4_global_parameter_server ( + parameter_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (parameter_id, server_id), + CONSTRAINT fk_dhcp4_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp4_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server(id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX key_dhcp4_global_parameter_idx1 ON dhcp4_global_parameter_server(modification_ts); +CREATE TRIGGER dhcp4_global_parameter_server_modification_ts_update + AFTER UPDATE ON dhcp4_global_parameter_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Create a table for storing IPv4 shared networks +CREATE TABLE dhcp4_shared_network ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id BOOLEAN DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + authoritative BOOLEAN DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + boot_file_name VARCHAR(128) DEFAULT NULL, + next_server inet DEFAULT NULL, -- let's use type inet + server_hostname VARCHAR(64) DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE UNIQUE INDEX dhcp4_shared_network_idx1 ON dhcp4_shared_network (name); +CREATE INDEX dhcp4_shared_network_idx2 ON dhcp4_shared_network (modification_ts); + +CREATE TRIGGER dhcp4_shared_network_modification_ts_update + AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now we need to create a relationship between defined shared networks and the servers +CREATE TABLE dhcp4_shared_network_server ( + shared_network_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (shared_network_id, server_id), + CONSTRAINT fk_dhcp4_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp4_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp4_shared_network_server_idx1 ON dhcp4_shared_network_server (modification_ts); +CREATE INDEX dhcp4_shared_network_server_idx2 ON dhcp4_shared_network_server (server_id); + + + +-- Create a list of IPv4 subnets +CREATE TABLE dhcp4_subnet ( + subnet_id BIGINT PRIMARY KEY NOT NULL, + subnet_prefix VARCHAR(64) UNIQUE NOT NULL, + interface_4o6 VARCHAR(128) DEFAULT NULL, + interface_id_4o6 VARCHAR(128) DEFAULT NULL, + subnet_4o6 VARCHAR(64) DEFAULT NULL, + boot_file_name VARCHAR(128) DEFAULT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id BOOLEAN DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + next_server inet DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + server_hostname VARCHAR(64) DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + authoritative BOOLEAN DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE TRIGGER dhcp4_subnet_modification_ts_update + AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +CREATE INDEX dhcp4_subnet_idx1 ON dhcp4_subnet (modification_ts); +CREATE INDEX dhcp4_subnet_idx2 ON dhcp4_subnet (shared_network_name); + + + +CREATE TABLE dhcp4_subnet_server ( + subnet_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (subnet_id, server_id), + CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION, + UNIQUE (subnet_id, server_id) +); +CREATE INDEX dhcp4_subnet_server_idx1 ON dhcp4_subnet_server(server_id); +CREATE INDEX dhcp4_subnet_server_idx2 ON dhcp4_subnet_server(modification_ts); +CREATE TRIGGER dhcp4_subnet_server_modification_ts_update + AFTER UPDATE ON dhcp4_subnet_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Create a table that holds all address pools in IPv4. +CREATE TABLE dhcp4_pool ( + id SERIAL PRIMARY KEY NOT NULL, + start_address inet NOT NULL, + end_address inet NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) +); +CREATE INDEX dhcp4_pool_idx1 ON dhcp4_pool (modification_ts); +CREATE INDEX dhcp4_pool_idx2 ON dhcp4_pool (subnet_id); + +CREATE TRIGGER dhcp4_pool_modification_ts_update + AFTER UPDATE ON dhcp4_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- ALTER table for storing DHCPv4 options. +ALTER TABLE dhcp4_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD CONSTRAINT fk_dhcp4_options_pool FOREIGN KEY (pool_id) + REFERENCES dhcp4_pool (id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp4_options_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE TRIGGER dhcp4_options_modification_ts_update + AFTER UPDATE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now create a table for associating defined v4 options with servers. +CREATE TABLE dhcp4_options_server ( + option_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_id, server_id), + CONSTRAINT fk_dhcp4_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp4_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp4_options_server_idx1 ON dhcp4_options_server(server_id); +CREATE INDEX dhcp4_options_server_idx2 ON dhcp4_options_server(modification_ts); +CREATE TRIGGER dhcp4_options_server_modification_ts_update + AFTER UPDATE ON dhcp4_options_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- This table is for storing IPv4 option definitions +CREATE TABLE dhcp4_option_def ( + id SERIAL PRIMARY KEY UNIQUE NOT NULL, + code SMALLINT NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type SMALLINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + is_array BOOLEAN NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR DEFAULT NULL, + user_context JSON DEFAULT NULL +); +CREATE INDEX dhcp4_option_def_idx1 ON dhcp4_option_def(modification_ts); +CREATE INDEX dhcp4_option_def_idx2 ON dhcp4_option_def(code, space); +CREATE TRIGGER dhcp4_option_def_modification_ts_update + AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- and another table for storing relationship between option definitions and servers. +CREATE TABLE dhcp4_option_def_server ( + option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + server_id BIGINT NOT NULL REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_def_id, server_id) +); +CREATE TRIGGER dhcp4_option_def_server_modification_ts_update + AFTER UPDATE ON dhcp4_option_def_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now create two tables for audit revisions... +CREATE TABLE dhcp4_audit_revision ( + id SERIAL PRIMARY KEY NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + log_message TEXT DEFAULT NULL, + server_id BIGINT DEFAULT NULL +); +CREATE TRIGGER dhcp4_audit_revision_modification_ts_update + AFTER UPDATE ON dhcp4_audit_revision + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- ... and the DHCPv4 audit itself. +CREATE TABLE dhcp4_audit ( + id SERIAL UNIQUE NOT NULL, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT NOT NULL, + modification_type SMALLINT NOT NULL, + revision_id BIGINT NOT NULL, + CONSTRAINT fk_dhcp4_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp4_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE +); +CREATE TRIGGER dhcp4_audit_modification_ts_update + AFTER UPDATE ON dhcp4_audit + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); +CREATE INDEX dhcp4_audit_idx1 ON dhcp4_audit (modification_type); +CREATE INDEX dhcp4_audit_idx2 ON dhcp4_audit (revision_id); + + +-- Stores a TEXT value to a session variable +-- name name of session variable to set +-- value TEXT value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value TEXT) +RETURNS VOID +AS $$ +DECLARE +BEGIN + PERFORM set_config(name, value, false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;$$ +LANGUAGE plpgsql; + +-- Stores a BIGINT value to a session variable +-- Note the value converted to TEXT and then stored as Postgresql does +-- not support any other data type in session variables. +-- name name of session variable to set +-- value BIGINT value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value BIGINT) +RETURNS VOID +AS $$ +BEGIN + PERFORM set_config(name, cast(value as text), false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;$$ +LANGUAGE plpgsql; + +-- Stores a BOOLEAN value to a session variable +-- Note the value converted to TEXT and then stored as Postgresql does +-- not support any other data type in session variables. +-- name name of session variable to set +-- value BOOLEAN value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value BOOLEAN) +RETURNS VOID +AS $$ +BEGIN + PERFORM set_config(name, cast(value as text), false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;$$ +LANGUAGE plpgsql; + + +-- Fetches a text value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns NULL. +-- Postgresql allows you to store custom session values +-- but throws an exception if they have not first been +-- set. This allows us to be a bit more graceful. +CREATE OR REPLACE FUNCTION get_session_value(name TEXT) +RETURNS TEXT +AS $$ +DECLARE + text_value TEXT := ''; +BEGIN + text_value = current_setting(name); + RETURN(text_value); + + EXCEPTION + WHEN undefined_object THEN + -- Variable has not been initialized so return NULL + RETURN NULL; + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_value(%, TEXT) failed, sqlstate: %', name, sqlstate; +END;$$ +LANGUAGE plpgsql; + +-- Fetches an BIGINT value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns zero. +CREATE OR REPLACE FUNCTION get_session_big_int(name text) +RETURNS BIGINT +AS $$ +DECLARE + int_value BIGINT := 0; + text_value TEXT := ''; +BEGIN + text_value = get_session_value(name); + IF text_value is NULL or text_value = '' THEN + RETURN(0); + END IF; + + int_value = cast(text_value as BIGINT); + RETURN(int_value); + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_big_int(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate; + +END;$$ +LANGUAGE plpgsql; + +-- Fetches an BOOLEAN value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns zero. +CREATE OR REPLACE FUNCTION get_session_boolean(name text) +RETURNS BOOLEAN +AS $$ +DECLARE + bool_value BOOLEAN := false; + text_value TEXT := ''; +BEGIN + text_value = get_session_value(name); + IF text_value is NULL or text_value = '' THEN + RETURN(false); + END IF; + + bool_value = cast(text_value as BOOLEAN); + RETURN(bool_value); + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_boolean(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate; + +END;$$ +LANGUAGE plpgsql; + + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditRevisionDHCP4(audit_ts TIMESTAMP WITH TIME ZONE, + server_tag VARCHAR(64), + audit_log_message TEXT, + cascade_transaction BOOLEAN) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + disable_audit BOOLEAN := false; + audit_revision_id BIGINT; + srv_id BIGINT; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + SELECT id INTO srv_id FROM dhcp4_server WHERE tag = server_tag; + INSERT INTO dhcp4_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id; + + -- Update pertinent session variables. + PERFORM set_session_value('kea.audit_revision_id', audit_revision_id); + PERFORM set_session_value('kea.cascade_transaction', cascade_transaction); + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. 'create', 'update' or +-- 'delete'. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditEntryDHCP4(object_type_val VARCHAR(256), + object_id_val BIGINT, + modification_type_val VARCHAR(32)) +RETURNS VOID +LANGUAGE plpgsql +as $$ +DECLARE + audit_revision_id BIGINT; + disable_audit BOOLEAN := false; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + + IF disable_audit IS NULL OR disable_audit = false THEN + -- Fetch session value most recently created audit_revision_id. + audit_revision_id := get_session_big_int('kea.audit_revision_id'); + INSERT INTO dhcp4_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, + (SELECT id FROM modification WHERE modification_type = modification_type_val), + audit_revision_id); + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv4 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp4_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + test TEXT, + next_server INET DEFAULT NULL, + server_hostname VARCHAR(128) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + only_if_required BOOLEAN NOT NULL DEFAULT false, + valid_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + depend_on_known_directly BOOLEAN NOT NULL DEFAULT false, + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX key_dhcp4_client_class_modification_ts on dhcp4_client_class (modification_ts); + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp4_client_class table has a corresponding row +-- in the dhcp4_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp4_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp4_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp4_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_order ( + class_id BIGINT PRIMARY KEY NOT NULL, + order_index BIGINT NOT NULL, + depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false, + CONSTRAINT fk_dhcp4_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE +); + +CREATE INDEX key_dhcp4_client_class_order_index on dhcp4_client_class_order (order_index); + + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass4Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BIGINT := 0; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp4_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp4_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- ON CONFLICT required 9.5 or later + UPDATE dhcp4_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Trigger procedure to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AINS() RETURNS trigger AS $dhcp4_client_class_AINS$ +BEGIN + PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, NULL); + PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp4_client_class_AINS$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class insert trigger +CREATE TRIGGER dhcp4_client_class_AINS + AFTER INSERT ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AINS(); + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AUPD() RETURNS trigger AS $dhcp4_client_class_AUPD$ +BEGIN + PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly); + PERFORM set_session_value('kea.client_class_id', NEW.id); + PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp4_client_class_AUPD$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class update insert trigger +CREATE TRIGGER dhcp4_client_class_AUPD + AFTER UPDATE ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AUPD(); + +-- ----------------------------------------------------------------------- +-- Trigger procedure to create the audit entry for client class delete. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_ADEL() RETURNS trigger AS $dhcp4_client_class_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_client_class', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp4_client_class_ADEL$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class delete trigger +CREATE TRIGGER dhcp4_client_class_ADEL + AFTER DELETE ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_ADEL(); + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp4_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp4_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_dependency ( + class_id BIGINT PRIMARY KEY NOT NULL, + dependency_id BIGINT NOT NULL, + + CONSTRAINT dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp4_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp4_client_class (id) +); + +CREATE INDEX dhcp4_client_class_dependency_id_idx on dhcp4_client_class_dependency (dependency_id); + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - p_class_id id client class, +-- - p_dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassDependency(p_class_id BIGINT, + p_dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + class_index BIGINT; + dependency_index BIGINT; +BEGIN + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF p_class_id IS NULL THEN + RAISE EXCEPTION 'Client class id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + IF p_dependency_id IS NULL THEN + RAISE EXCEPTION 'Class dependency id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Dependencies on self make no sense. + IF p_class_id = p_dependency_id THEN + RAISE EXCEPTION 'Client class must not have dependency on self.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of our class in the hierarchy. + SELECT o.order_index INTO class_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_class_id; + + IF class_index IS NULL THEN + RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of the dependency. + SELECT o.order_index INTO dependency_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_dependency_id; + + IF dependency_index IS NULL THEN + RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + RAISE EXCEPTION + 'Client class with id % must not depend on class defined later with id %', + p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp4_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_server AS t1 + LEFT JOIN dhcp4_client_class_server AS t2 + ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = p_class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unmet dependencies for client class with id %', class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + RETURN; +END;$$; + + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_check_dependency_BINS() + RETURNS trigger AS $dhcp4_client_class_check_dependency_BINS$ +BEGIN + PERFORM checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +$dhcp4_client_class_check_dependency_BINS$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class_check_dependency_BINS before insert trigger. +CREATE TRIGGER dhcp4_client_class_check_dependency_BINS + BEFORE INSERT ON dhcp4_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_check_dependency_BINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION updateDHCPv4ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + dependency BOOLEAN; +BEGIN + -- Check if the dependency class references KNOWN/UNKNOWN. + SELECT depend_on_known_directly INTO dependency FROM dhcp4_client_class + WHERE id = dependency_id; + + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = false THEN + SELECT depend_on_known_indirectly INTO dependency FROM dhcp4_client_class_order + WHERE class_id = dependency_id; + END IF; + + IF dependency = true THEN + UPDATE dhcp4_client_class_order + SET depend_on_known_indirectly = true + WHERE class_id = client_class_id; + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_dependency_AINS() + RETURNS TRIGGER AS $dhcp4_client_class_dependency_AINS$ +BEGIN + PERFORM updateDHCPv4ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +$dhcp4_client_class_dependency_AINS$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class_check_dependency_AINS after insert trigger. +CREATE TRIGGER dhcp4_client_class_dependency_AINS + AFTER INSERT ON dhcp4_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_dependency_AINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv4 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassKnownDependencyChange() +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + depended BOOLEAN := false; + depends BOOLEAN := false; + client_class_id BIGINT; + depend_on_known_directly BOOLEAN; + depend_on_known_indirectly BOOLEAN; +BEGIN + + -- Session variables are set upon a client class update. + client_class_id := get_session_big_int('kea.client_class_id'); + IF client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency + WHERE dependency_id = client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly'); + depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly'); + IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN + SET depended = true; + END IF; + + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SELECT depend_on_known_directly INTO depends FROM dhcp4_client_class + WHERE id = client_class_id; + + -- If it doesn't depend directly, check indirect dependencies. + IF depends = false THEN + SELECT depend_on_known_indirectly INTO depends FROM dhcp4_client_class_order + WHERE class_id = client_class_id; + END IF; + + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + END IF; + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv4 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_server ( + class_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + CONSTRAINT fk_dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) +); + +CREATE INDEX fk_dhcp4_client_class_server_id ON dhcp4_client_class_server (server_id); + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditRevisionDHCP6(audit_ts TIMESTAMP WITH TIME ZONE, + server_tag VARCHAR(64), + audit_log_message TEXT, + cascade_transaction BOOLEAN) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + disable_audit BOOLEAN := false; + audit_revision_id BIGINT; + srv_id BIGINT; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + SELECT id INTO srv_id FROM dhcp6_server WHERE tag = server_tag; + INSERT INTO dhcp6_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id; + + -- Update pertinent session variables. + PERFORM set_session_value('kea.audit_revision_id', audit_revision_id); + PERFORM set_session_value('kea.cascade_transaction', cascade_transaction); + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. 'create', 'update' or +-- 'delete'. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditEntryDHCP6(object_type_val VARCHAR(256), + object_id_val BIGINT, + modification_type_val VARCHAR(32)) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + audit_revision_id BIGINT; + disable_audit BOOLEAN := false; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + -- Fetch session value most recently created audit_revision_id. + audit_revision_id := get_session_big_int('kea.audit_revision_id'); + INSERT INTO dhcp6_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, + (SELECT id FROM modification WHERE modification_type = modification_type_val), + audit_revision_id); + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv6 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp6_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + test TEXT, + only_if_required BOOLEAN NOT NULL DEFAULT false, + valid_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + depend_on_known_directly BOOLEAN NOT NULL DEFAULT false, + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX key_dhcp6_client_class_modification_ts on dhcp6_client_class (modification_ts); + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp6_client_class table has a corresponding row +-- in the dhcp6_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp6_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp6_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp6_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_order ( + class_id BIGINT PRIMARY KEY NOT NULL, + order_index BIGINT NOT NULL, + depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false, + CONSTRAINT fk_dhcp6_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE +); + +CREATE INDEX key_dhcp6_client_class_order_index on dhcp6_client_class_order (order_index); + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass6Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BIGINT := 0; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp6_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp6_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp6_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Trigger procedure to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AINS() RETURNS trigger AS $dhcp6_client_class_AINS$ +BEGIN + PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, NULL); + PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp6_client_class_AINS$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class insert trigger +CREATE TRIGGER dhcp6_client_class_AINS + AFTER INSERT ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AINS(); + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AUPD() RETURNS trigger AS $dhcp6_client_class_AUPD$ +BEGIN + PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly); + PERFORM set_session_value('kea.client_class_id', NEW.id); + PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp6_client_class_AUPD$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class update insert trigger +CREATE TRIGGER dhcp6_client_class_AUPD + AFTER UPDATE ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AUPD(); + +-- ----------------------------------------------------------------------- +-- Trigger procedure to create the audit entry for client class delete. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_ADEL() RETURNS trigger AS $dhcp6_client_class_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_client_class', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp6_client_class_ADEL$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class delete trigger +CREATE TRIGGER dhcp6_client_class_ADEL + AFTER DELETE ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_ADEL(); + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp6_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp6_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_dependency ( + class_id BIGINT PRIMARY KEY NOT NULL, + dependency_id BIGINT NOT NULL, + + CONSTRAINT dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp6_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp6_client_class (id) +); + +CREATE INDEX dhcp6_client_class_dependency_id_idx on dhcp6_client_class_dependency (dependency_id); + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - p_class_id id client class, +-- - p_dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassDependency(p_class_id BIGINT, + p_dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + class_index BIGINT; + dependency_index BIGINT; +BEGIN + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF p_class_id IS NULL THEN + RAISE EXCEPTION 'Client class id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + IF p_dependency_id IS NULL THEN + RAISE EXCEPTION 'Class dependency id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Dependencies on self make no sense. + IF p_class_id = p_dependency_id THEN + RAISE EXCEPTION 'Client class must not have dependency on self.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of our class in the hierarchy. + SELECT o.order_index INTO class_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_class_id; + + IF class_index IS NULL THEN + RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of the dependency. + SELECT o.order_index INTO dependency_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_dependency_id; + + IF dependency_index IS NULL THEN + RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + RAISE EXCEPTION + 'Client class with id % must not depend on class defined later with id %', + p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp6_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_server AS t1 + LEFT JOIN dhcp6_client_class_server AS t2 + ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = p_class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unmet dependencies for client class with id %', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + RETURN; +END;$$; + + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_check_dependency_BINS() + RETURNS trigger AS $dhcp6_client_class_check_dependency_BINS$ +BEGIN + PERFORM checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +$dhcp6_client_class_check_dependency_BINS$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class_check_dependency_BINS before insert trigger. +CREATE TRIGGER dhcp6_client_class_check_dependency_BINS + BEFORE INSERT ON dhcp6_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_check_dependency_BINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION updateDHCPv6ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + dependency BOOLEAN; +BEGIN + -- Check if the dependency class references KNOWN/UNKNOWN. + SELECT depend_on_known_directly INTO dependency FROM dhcp6_client_class + WHERE id = dependency_id; + + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = false THEN + SELECT depend_on_known_indirectly INTO dependency FROM dhcp6_client_class_order + WHERE class_id = dependency_id; + END IF; + + IF dependency = true THEN + UPDATE dhcp6_client_class_order + SET depend_on_known_indirectly = true + WHERE class_id = client_class_id; + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_dependency_AINS() + RETURNS TRIGGER AS $dhcp6_client_class_dependency_AINS$ +BEGIN + PERFORM updateDHCPv6ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +$dhcp6_client_class_dependency_AINS$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class_check_dependency_AINS after insert trigger. +CREATE TRIGGER dhcp6_client_class_dependency_AINS + AFTER INSERT ON dhcp6_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_dependency_AINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv6 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassKnownDependencyChange() +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + depended BOOLEAN := false; + depends BOOLEAN := false; + client_class_id BIGINT; + depend_on_known_directly BOOLEAN; + depend_on_known_indirectly BOOLEAN; +BEGIN + + -- Session variables are set upon a client class update. + client_class_id := get_session_big_int('kea.client_class_id'); + IF client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency + WHERE dependency_id = client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly'); + depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly'); + IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN + SET depended = true; + END IF; + + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SELECT depend_on_known_directly INTO depends FROM dhcp6_client_class + WHERE id = client_class_id; + + -- If it doesn't depend directly, check indirect dependencies. + IF depends = false THEN + SELECT depend_on_known_indirectly INTO depends FROM dhcp6_client_class_order + WHERE class_id = client_class_id; + END IF; + + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + END IF; + END IF; + RETURN; +END;$$; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv6 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_server ( + class_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + CONSTRAINT fk_dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) +); + +CREATE INDEX fk_dhcp6_client_class_server_id ON dhcp6_client_class_server (server_id); + +-- Trigger function for dhcp4_pool_BDEL called BEFORE DELETE on dhcp4_pool +-- It removes pool specific options upon removal of the pool. +CREATE OR REPLACE FUNCTION func_dhcp4_pool_BDEL() RETURNS TRIGGER AS $dhcp4_pool_BDEL$ +BEGIN + DELETE FROM dhcp4_options WHERE scope_id = 5 AND pool_id = OLD.id; + RETURN OLD; +END; +$dhcp4_pool_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_pool_BDEL + BEFORE DELETE ON dhcp4_pool + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_pool_BDEL(); + +-- Trigger function for dhcp6_pool_BDEL called BEFORE DELETE on dhcp6_pool +-- It removes pool specific options upon removal of the pool. +CREATE OR REPLACE FUNCTION func_dhcp6_pool_BDEL() RETURNS TRIGGER AS $dhcp6_pool_BDEL$ +BEGIN + DELETE FROM dhcp6_options WHERE scope_id = 5 AND pool_id = OLD.id; + RETURN OLD; +END; +$dhcp6_pool_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_pool_BDEL + BEFORE DELETE ON dhcp6_pool + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_pool_BDEL(); + +-- Trigger function for dhcp4_global_parameter_AINS called AFTER INSERT on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AINS() RETURNS TRIGGER AS $dhcp4_global_parameter_AINS$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp4_global_parameter_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_AINS + AFTER INSERT ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AINS(); + + +-- Trigger function for dhcp4_global_parameter_AUPD called AFTER UPDATE on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AUPD() RETURNS TRIGGER AS $dhcp4_global_parameter_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp4_global_parameter_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_AUPD + AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AUPD(); + + +-- Trigger function for dhcp4_global_parameter_ADEL called AFTER DELETE on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_ADEL() RETURNS TRIGGER AS $dhcp4_global_parameter_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp4_global_parameter_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_ADEL + AFTER DELETE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_ADEL(); + +-- Trigger function for dhcp4_subnet_AINS called AFTER INSERT on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AINS() RETURNS TRIGGER AS $dhcp4_subnet_AINS$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'create'); + RETURN NULL; +END; +$dhcp4_subnet_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_AINS + AFTER INSERT ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AINS(); + + +-- Trigger function for dhcp4_subnet_AUPD called AFTER UPDATE on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AUPD() RETURNS TRIGGER AS $dhcp4_subnet_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'update'); + RETURN NULL; +END; +$dhcp4_subnet_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_AUPD + AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AUPD(); + + +-- Trigger function for dhcp4_shared_network_AINS called AFTER INSERT on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AINS() RETURNS TRIGGER AS $dhcp4_shared_network_AINS$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp4_shared_network_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_AINS + AFTER INSERT ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AINS(); + +-- Trigger function for dhcp4_shared_network_AUPD called AFTER UPDATE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AUPD() RETURNS TRIGGER AS $dhcp4_shared_network_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp4_shared_network_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_AUPD + AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AUPD(); + +-- Trigger function for dhcp4_shared_network_ADEL called AFTER DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_ADEL() RETURNS TRIGGER AS $dhcp4_shared_network_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp4_shared_network_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_ADEL + AFTER DELETE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_ADEL(); + +-- Trigger function for dhcp4_option_def_AINS called AFTER INSERT on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AINS() RETURNS TRIGGER AS $dhcp4_option_def_AINS$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp4_option_def_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_AINS + AFTER INSERT ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AINS(); + +-- Trigger function for dhcp4_option_def_AUPD called AFTER UPDATE on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AUPD() RETURNS TRIGGER AS $dhcp4_option_def_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp4_option_def_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_AUPD + AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AUPD(); + +-- Trigger function for dhcp4_option_def_ADEL called AFTER DELETE on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_ADEL() RETURNS TRIGGER AS $dhcp4_option_def_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp4_option_def_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_ADEL + AFTER DELETE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_ADEL(); + +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: 'create', 'update' or 'delete' +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP4(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := true; + ct TEXT; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp4_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp4_options' table. + PERFORM createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;$$; + +-- Trigger function for dhcp4_options_AINS called AFTER INSERT on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_AINS() RETURNS TRIGGER AS $dhcp4_options_AINS$ +BEGIN + PERFORM createOptionAuditDHCP4('create', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + RETURN NULL; +END; +$dhcp4_options_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_AINS + AFTER INSERT ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AINS(); + + +-- Trigger function for dhcp4_options_AUPD called AFTER UPDATE on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_AUPD() RETURNS TRIGGER AS $dhcp4_options_AUPD$ +BEGIN + PERFORM createOptionAuditDHCP4('update', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + RETURN NULL; +END; +$dhcp4_options_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_AUPD + AFTER UPDATE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AUPD(); + +-- Trigger function for dhcp4_options_ADEL called AFTER DELETE on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_ADEL() RETURNS TRIGGER AS $dhcp4_options_ADEL$ +BEGIN + PERFORM createOptionAuditDHCP4('delete', OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + NOW()); + RETURN NULL; +END; +$dhcp4_options_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_ADEL + AFTER DELETE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_ADEL(); + +-- Trigger function for dhcp6_global_parameter_AINS called AFTER INSERT on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AINS() RETURNS TRIGGER AS $dhcp6_global_parameter_AINS$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp6_global_parameter_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_AINS + AFTER INSERT ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AINS(); + +-- Trigger function for dhcp6_global_parameter_AUPD called AFTER UPDATE on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AUPD() RETURNS TRIGGER AS $dhcp6_global_parameter_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp6_global_parameter_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_AUPD + AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AUPD(); + +-- Trigger function for dhcp6_global_parameter_ADEL called AFTER DELETE on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_ADEL() RETURNS TRIGGER AS $dhcp6_global_parameter_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp6_global_parameter_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_ADEL + AFTER DELETE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_ADEL(); + +-- Trigger function for dhcp6_subnet_AINS called AFTER INSERT on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AINS() RETURNS TRIGGER AS $dhcp6_subnet_AINS$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'create'); + RETURN NULL; +END; +$dhcp6_subnet_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_AINS + AFTER INSERT ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AINS(); + +-- Trigger function for dhcp6_subnet_AUPD called AFTER UPDATE on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AUPD() RETURNS TRIGGER AS $dhcp6_subnet_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'update'); + RETURN NULL; +END; +$dhcp6_subnet_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_AUPD + AFTER UPDATE ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AUPD(); + +-- Trigger function for dhcp6_shared_network_AINS called AFTER INSERT on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AINS() RETURNS TRIGGER AS $dhcp6_shared_network_AINS$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp6_shared_network_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_AINS + AFTER INSERT ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AINS(); + +-- Trigger function for dhcp6_shared_network_AUPD called AFTER UPDATE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AUPD() RETURNS TRIGGER AS $dhcp6_shared_network_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp6_shared_network_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_AUPD + AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AUPD(); + +-- Trigger function for dhcp6_shared_network_ADEL called AFTER DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_ADEL() RETURNS TRIGGER AS $dhcp6_shared_network_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp6_shared_network_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_ADEL + AFTER DELETE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_ADEL(); + +-- Trigger function for dhcp6_option_def_AINS called AFTER INSERT on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AINS() RETURNS TRIGGER AS $dhcp6_option_def_AINS$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp6_option_def_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_AINS + AFTER INSERT ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AINS(); + +-- Trigger function for dhcp6_option_def_AUPD called AFTER UPDATE on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AUPD() RETURNS TRIGGER AS $dhcp6_option_def_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp6_option_def_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_AUPD + AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AUPD(); + +-- Trigger function for dhcp6_option_def_ADEL called AFTER DELETE on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_ADEL() RETURNS TRIGGER AS $dhcp6_option_def_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp6_option_def_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_ADEL + AFTER DELETE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_ADEL(); + +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, + option_id INT, + subnet_id BIGINT, + host_id INT, + network_name VARCHAR(128), + pool_id BIGINT, + pd_pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := false; + +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, create + -- audit entry for the entire subnet, which indicates that + -- it should be treated as the subnet update. + PERFORM createAuditEntryDHCP6('dhcp6_subnet', subnet_id, 'update'); + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- create audit entry for the shared network which + -- indicates that it should be treated as the shared + -- network update. + SELECT id INTO snid FROM dhcp6_shared_network + WHERE name = network_name LIMIT 1; + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', snid, 'update'); + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update'); + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pd pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool + WHERE id = pd_pool_id; + PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update'); + END IF; + END IF; + RETURN; +END;$$; + +-- Trigger function for dhcp6_options_AINS called AFTER INSERT on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_AINS() RETURNS TRIGGER AS $dhcp6_options_AINS$ +BEGIN + PERFORM createOptionAuditDHCP6('create', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + RETURN NULL; +END; +$dhcp6_options_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_AINS + AFTER INSERT ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AINS(); + +-- Trigger function for dhcp6_options_AUPD called AFTER UPDATE on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_AUPD() RETURNS TRIGGER AS $dhcp6_options_AUPD$ +BEGIN + PERFORM createOptionAuditDHCP6('update', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + RETURN NULL; +END; +$dhcp6_options_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_AUPD + AFTER UPDATE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AUPD(); + + +-- Trigger function for dhcp6_options_ADEL called AFTER DELETE on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_ADEL() RETURNS TRIGGER AS $dhcp6_options_ADEL$ +BEGIN + PERFORM createOptionAuditDHCP6('delete', OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + OLD.pd_pool_id, NOW()); + RETURN NULL; +END; +$dhcp6_options_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_ADEL + AFTER DELETE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_ADEL(); + + +-- Trigger function for dhcp4_server_AINS called AFTER INSERT on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_AINS() RETURNS TRIGGER AS $dhcp4_server_AINS$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp4_server_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_AINS + AFTER INSERT ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AINS(); + + +-- Trigger function for dhcp4_server_AUPD called AFTER UPDATE on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_AUPD() RETURNS TRIGGER AS $dhcp4_server_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp4_server_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_AUPD + AFTER UPDATE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AUPD(); + + +-- Trigger function for dhcp4_server_ADEL called AFTER DELETE on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_ADEL() RETURNS TRIGGER AS $dhcp4_server_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp4_server_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_ADEL + AFTER DELETE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_ADEL(); + + +-- Trigger function for dhcp6_server_AINS called AFTER INSERT on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_AINS() RETURNS TRIGGER AS $dhcp6_server_AINS$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'create'); + RETURN NULL; +END; +$dhcp6_server_AINS$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_AINS + AFTER INSERT ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AINS(); + + +-- Trigger function for dhcp6_server_AUPD called AFTER UPDATE on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_AUPD() RETURNS TRIGGER AS $dhcp6_server_AUPD$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'update'); + RETURN NULL; +END; +$dhcp6_server_AUPD$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_AUPD + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AUPD(); + +-- Trigger function for dhcp6_server_ADEL called AFTER DELETE on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_ADEL() RETURNS TRIGGER AS $dhcp6_server_ADEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', OLD.id, 'delete'); + RETURN NULL; +END; +$dhcp6_server_ADEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_ADEL + AFTER DELETE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_ADEL(); + +-- Trigger function for dhcp4_shared_network_BDEL called BEFORE DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_BDEL() RETURNS TRIGGER AS $dhcp4_shared_network_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +$dhcp4_shared_network_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_BDEL + BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_BDEL(); + +-- Trigger function for dhcp4_subnet_BDEL called BEFORE DELETE on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_BDEL() RETURNS TRIGGER AS $dhcp4_subnet_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, 'delete'); + DELETE FROM dhcp4_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp4_options WHERE dhcp4_subnet_id = OLD.subnet_id; + RETURN OLD; +END; +$dhcp4_subnet_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_BDEL + BEFORE DELETE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_BDEL(); + +-- Trigger function for dhcp6_shared_network_BDEL called BEFORE DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_BDEL() RETURNS TRIGGER AS $dhcp6_shared_network_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +$dhcp6_shared_network_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_BDEL + BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_BDEL(); + +-- Trigger function for dhcp6_subnet_BDEL called BEFORE DELETE on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_BDEL() RETURNS TRIGGER AS $dhcp6_subnet_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, 'delete'); + DELETE FROM dhcp6_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_pd_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_options WHERE dhcp6_subnet_id = OLD.subnet_id; + RETURN OLD; +END; +$dhcp6_subnet_BDEL$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_BDEL + BEFORE DELETE ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_BDEL(); +-- Trigger function for dhcp6_pd_pool_BDEL called BEFORE DELETE on dhcp6_pd_pool +CREATE OR REPLACE FUNCTION func_dhcp6_pd_pool_BDEL() RETURNS TRIGGER AS $dhcp6_pd_pool_BDEL$ +BEGIN + DELETE FROM dhcp6_options WHERE scope_id = 6 AND pd_pool_id = OLD.id; + RETURN OLD; +END; +$dhcp6_pd_pool_BDEL$ +LANGUAGE plpgsql; + +-- Update the schema version number +UPDATE schema_version + SET version = '7', minor = '0'; + +-- Schema 7.0 specification ends here. + +-- This starts schema update to 8.0. It adds a few missing elements for CB and +-- functions for kea-admin's lease-dump and lease-upload commands. + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv4 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp4_option_def + ADD COLUMN class_id BIGINT NULL DEFAULT NULL; + +ALTER TABLE dhcp4_option_def + ADD CONSTRAINT fk_dhcp4_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv6 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_option_def + ADD COLUMN class_id BIGINT NULL DEFAULT NULL; + +ALTER TABLE dhcp6_option_def + ADD CONSTRAINT fk_dhcp6_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Add missing preferred_lifetime columns to dhcp6_client_class table. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_client_class + ADD COLUMN preferred_lifetime BIGINT DEFAULT NULL, + ADD COLUMN min_preferred_lifetime BIGINT DEFAULT NULL, + ADD COLUMN max_preferred_lifetime BIGINT DEFAULT NULL; + +-- ----------------------------------------------------------------------- +-- Add option scopes +-- ----------------------------------------------------------------------- +-- Add scope for shared network specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(4, 'shared-network'); + +-- Add scope for pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(5, 'pool'); + +-- Add scope for PD pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(6, 'pd-pool'); + +-- Drop the existing function, createOptionAuditDHCP6 so we can replace it +-- with one that has slightly different arguments. +DROP FUNCTION IF EXISTS createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, option_id INT, subnet_id BIGINT, + host_id INT, network_name VARCHAR(128), + pool_id BIGINT, pd_pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE); + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP6 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR(128), + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := false; + +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;$$; + +-- Fix mangled constraints on dhcp4_subnet_server table. +ALTER TABLE dhcp4_subnet_server + DROP CONSTRAINT fk_dhcp6_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + DROP CONSTRAINT fk_dhcp6_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION; + +-- Add missing foreign key indexes. PostgreSQL does not automatically create indexes for +-- foreign key constraints. These have been added using the basic guideline: +-- +-- If the constraint does not reference a static table (e.g. parameter_data_type), +-- and the referencing column is not the primary key or the first +-- column in the primary key, and does not already have an index, then an index +-- should be added to the table for the referencing column. +-- +-- dhcp6_global_parameter_server +CREATE INDEX fk_dhcp6_global_parameter_server_server_id ON dhcp6_global_parameter_server (server_id); + +-- dhcp6_options +-- Missing foreign key constraint and indexes +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_subnet + FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE INDEX fk_dhcp6_options_subnet ON dhcp6_options (dhcp6_subnet_id); +CREATE INDEX fk_dhcp6_options_pd_pool ON dhcp6_options (pd_pool_id); +CREATE INDEX fk_dhcp6_options_pool ON dhcp6_options (pool_id); +CREATE INDEX fk_dhcp6_options_shared_network ON dhcp6_options (shared_network_name); + +-- dhcp6_option_def_server +-- Missing foreign key constraints and index +ALTER TABLE dhcp6_option_def_server + ADD CONSTRAINT fk_dhcp6_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + ADD CONSTRAINT fk_dhcp6_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION; + +CREATE INDEX fk_dhcp6_option_def_server_server_id ON dhcp6_option_def_server (server_id); + +-- dhcp6_option_def +CREATE INDEX fk_dhcp6_option_def_client_class_id ON dhcp6_option_def (class_id); + +-- dhcp4_global_parameter_server +CREATE INDEX fk_dhcp4_global_parameter_server_server_id ON dhcp4_global_parameter_server (server_id); + +-- dhcp4_options +-- Missing foreign key constraint and indexes +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_subnet + FOREIGN KEY (dhcp4_subnet_id) + REFERENCES dhcp4_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE INDEX fk_dhcp4_options_subnet ON dhcp4_options (dhcp4_subnet_id); +CREATE INDEX fk_dhcp4_options_pool ON dhcp4_options (pool_id); +CREATE INDEX fk_dhcp4_options_shared_network ON dhcp4_options (shared_network_name); + +-- dhcp4_option_def_server +-- Missing foreign key constraints and index +ALTER TABLE dhcp4_option_def_server + ADD CONSTRAINT fk_dhcp4_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp4_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + ADD CONSTRAINT fk_dhcp4_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION; + +CREATE INDEX fk_dhcp4_option_def_server_server_id ON dhcp4_option_def_server (server_id); + +-- dhcp4_option_def +CREATE INDEX fk_dhcp4_option_def_client_class_id ON dhcp4_option_def (class_id); + +-- Create a function that separates groups of two hexadecimals +-- with colons. +CREATE OR REPLACE FUNCTION colonSeparatedHex(hex TEXT) +RETURNS TEXT +AS $$ +DECLARE + i INT := 3; + length INT := LENGTH(hex); + output TEXT; +BEGIN + -- Add a leading zero if the first octet has a single hexadecimal character. + IF MOD(length, 2) = 1 THEN + hex := CONCAT('0', hex); + length := length + 1; + END IF; + + -- Start with the first octet. + output := SUBSTR(hex, 1, 2); + + -- Add one octet at a time and a leading colon with each. + WHILE i < length LOOP + output := CONCAT(output, ':', SUBSTR(hex, i, 2)); + i := i + 2; + END LOOP; + + -- Memfile uses lowercase hexadecimals. + output := LOWER(output); + + RETURN output; +END +$$ LANGUAGE plpgsql; + +-- Modify the function to output a memfile-ready CSV file. +-- Some columns that are SMALLINT in the lease4 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE OR REPLACE FUNCTION lease4DumpData() +RETURNS TABLE ( + address INET, + hwaddr VARCHAR, + client_id VARCHAR, + valid_lifetime BIGINT, + expire BIGINT, + subnet_id BIGINT, + fqdn_fwd INT, + fqdn_rev INT, + hostname VARCHAR, + state INT8, + user_context VARCHAR +) AS $$ + SELECT + ('0.0.0.0'::inet + address), + colonSeparatedHex(encode(hwaddr, 'hex')), + colonSeparatedHex(encode(client_id, 'hex')), + valid_lifetime, + extract(epoch from expire)::bigint, + subnet_id, + fqdn_fwd::int, + fqdn_rev::int, + replace(hostname, ',', ','), + state, + replace(user_context, ',', ',') + FROM lease4 + ORDER BY address; +$$ LANGUAGE SQL; + +-- hwtype and hwaddr_source need to be last to match memfile format. +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE OR REPLACE FUNCTION lease6DumpHeader() +RETURNS TEXT AS $$ + SELECT CAST('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,state,user_context,hwtype,hwaddr_source' AS TEXT) AS result; +$$ LANGUAGE SQL; + +-- Modify the function to output a memfile-ready CSV file. +-- Some columns that are SMALLINT in the lease6 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE OR REPLACE FUNCTION lease6DumpData() +RETURNS TABLE ( + address VARCHAR, + duid VARCHAR, + valid_lifetime BIGINT, + expire BIGINT, + subnet_id BIGINT, + pref_lifetime BIGINT, + lease_type SMALLINT, + iaid INT, + prefix_len SMALLINT, + fqdn_fwd INT, + fqdn_rev INT, + hostname VARCHAR, + hwaddr VARCHAR, + state INT8, + user_context VARCHAR, + hwtype SMALLINT, + hwaddr_source SMALLINT +) AS $$ + SELECT + address, + colonSeparatedHex(encode(duid, 'hex')), + valid_lifetime, + extract(epoch from expire)::bigint, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd::int, + fqdn_rev::int, + replace(hostname, ',', ','), + colonSeparatedHex(encode(hwaddr, 'hex')), + state, + replace(user_context, ',', ','), + hwtype, + hwaddr_source + FROM lease6 + ORDER BY address; +$$ LANGUAGE SQL; + +-- Create a procedure that inserts a v4 lease from memfile data. +-- Some columns that are SMALLINT in the lease4 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +CREATE OR REPLACE FUNCTION lease4Upload( + IN address VARCHAR, + IN hwaddr VARCHAR, + IN client_id VARCHAR, + IN valid_lifetime BIGINT, + IN expire BIGINT, + IN subnet_id BIGINT, + IN fqdn_fwd INT, + IN fqdn_rev INT, + IN hostname VARCHAR, + IN state INT8, + IN user_context VARCHAR +) RETURNS VOID AS $$ +BEGIN + INSERT INTO lease4 ( + address, + hwaddr, + client_id, + valid_lifetime, + expire, + subnet_id, + fqdn_fwd, + fqdn_rev, + hostname, + state, + user_context + ) VALUES ( + address::inet - '0.0.0.0'::inet, + decode(replace(hwaddr, ':', ''), 'hex'), + decode(replace(client_id, ':', ''), 'hex'), + valid_lifetime, + to_timestamp(expire), + subnet_id, + fqdn_fwd::int::boolean, + fqdn_rev::int::boolean, + replace(hostname, ',', ','), + state, + replace(user_context, ',', ',') + ); +END +$$ LANGUAGE plpgsql; + +-- Create a procedure that inserts a v6 lease from memfile data. +-- Some columns that are SMALLINT in the lease6 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +CREATE OR REPLACE FUNCTION lease6Upload( + IN address VARCHAR, + IN duid VARCHAR, + IN valid_lifetime BIGINT, + IN expire BIGINT, + IN subnet_id BIGINT, + IN pref_lifetime BIGINT, + IN lease_type INT, + IN iaid INT, + IN prefix_len INT, + IN fqdn_fwd INT, + IN fqdn_rev INT, + IN hostname VARCHAR, + IN hwaddr VARCHAR, + IN state INT8, + IN user_context VARCHAR, + IN hwtype INT, + IN hwaddr_source INT +) RETURNS VOID AS $$ +BEGIN + INSERT INTO lease6 ( + address, + duid, + valid_lifetime, + expire, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + hostname, + hwaddr, + state, + user_context, + hwtype, + hwaddr_source + ) VALUES ( + address, + decode(replace(duid, ':', ''), 'hex'), + valid_lifetime, + to_timestamp(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd::int::boolean, + fqdn_rev::int::boolean, + replace(hostname, ',', ','), + decode(replace(hwaddr, ':', ''), 'hex'), + state, + replace(user_context, ',', ','), + hwtype, + hwaddr_source + ); +END +$$ LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '8', minor = '0'; + +-- Schema 8.0 specification ends here. + +-- This starts schema update to 9.0. + +-- Add missing cascade to constraint on dhcp4/6_subnet_server tables. +ALTER TABLE dhcp4_subnet_server + DROP CONSTRAINT fk_dhcp4_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE CASCADE, + DROP CONSTRAINT fk_dhcp4_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_subnet_server + DROP CONSTRAINT fk_dhcp6_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE CASCADE, + DROP CONSTRAINT fk_dhcp6_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE; + +-- Fix constraint typo on dhcp4_option_def_server +ALTER TABLE dhcp4_option_def_server + DROP CONSTRAINT dhcp4_option_def_server_option_def_id_fkey, + ADD CONSTRAINT dhcp4_option_def_server_option_def_id_fkey + FOREIGN KEY (option_def_id) REFERENCES dhcp4_option_def(id) ON DELETE CASCADE; + +-- DROP shared-network ADEL triggers that should not exist. +DROP TRIGGER IF EXISTS dhcp4_shared_network_ADEL on dhcp4_shared_network CASCADE; +DROP TRIGGER IF EXISTS dhcp6_shared_network_ADEL on dhcp6_shared_network CASCADE; + +-- Replace createOptionAuditDHCP4() with a version that has local variable +-- snid correctly declared as a BIGINT. +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP4(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp4_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp4_options' table. + PERFORM createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;$$; + +-- Replace createOptionAuditDHCP6() with a version that has local variable +-- snid correctly declared as a BIGINT. +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;$$; + +-- Returns the epoch GMT time in second from a timestamp with time zone +-- +-- param input_ts timestamp value to convert +-- return a BIGINT containing the number of seconds since the epoch in GMT. +CREATE OR REPLACE FUNCTION gmt_epoch(input_ts TIMESTAMP WITH TIME ZONE) +RETURNS BIGINT +AS $$ +DECLARE + gmt_epoch BIGINT; +BEGIN + SELECT (extract(epoch from input_ts) + extract(timezone from input_ts))::BIGINT INTO gmt_epoch; + RETURN gmt_epoch; + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'gmt_epoch(%) : failed, sqlstate: %', input_ts, sqlstate; +END;$$ +LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '9', minor = '0'; + +-- Schema 9.0 specification ends here. + +-- This starts schema update to 10.0. +-- It adds corrections for client classes for CB + +-- Replace setClientClass4Order(): +-- 1. l_depend_on_known_indirectly needs to be BOOL +-- 2. follow_class_index needs to be BIGINT + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass4Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BOOL := false; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp4_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp4_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp4_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, false); + RETURN; +END;$$; + +-- Replace setClientClass6Order(): +-- 1. l_depend_on_known_indirectly needs to be BOOL +-- 2. follow_class_index needs to be BIGINT + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass6Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BOOL := false; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp6_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp6_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp6_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, false); + RETURN; +END;$$; + +-- Change primary key to composite, dependency table can have multiple rows +-- per class id. +ALTER TABLE dhcp4_client_class_dependency DROP CONSTRAINT dhcp4_client_class_dependency_pkey; +ALTER TABLE dhcp4_client_class_dependency ADD PRIMARY KEY(class_id, dependency_id); + +ALTER TABLE dhcp6_client_class_dependency DROP CONSTRAINT dhcp6_client_class_dependency_pkey; +ALTER TABLE dhcp6_client_class_dependency ADD PRIMARY KEY(class_id, dependency_id); + +-- Replace triggers that verify class dependency. +-- Because they are BEFORE INSERT triggers they need to return NEW not NULL. +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_check_dependency_BINS() + RETURNS trigger AS $dhcp4_client_class_check_dependency_BINS$ +BEGIN + PERFORM checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NEW; +END; +$dhcp4_client_class_check_dependency_BINS$ +LANGUAGE plpgsql; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_check_dependency_BINS() + RETURNS trigger AS $dhcp6_client_class_check_dependency_BINS$ +BEGIN + PERFORM checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NEW; +END; +$dhcp6_client_class_check_dependency_BINS$ +LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '10', minor = '0'; + +-- Schema 10.0 specification ends here. + +-- This starts schema update to 11.0. + +-- Replace createOptionAuditDHCP6() with a version corrected +-- where clause when scope is 6 (i.e. PD pool) +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;$$; + +-- Update the schema version number. +UPDATE schema_version + SET version = '11', minor = '0'; + +-- Schema 11.0 specification ends here. + +-- This line starts the schema upgrade to version 12. + +-- Modify shared-network-name foreign key constraint on dhcp4_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp4_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp4_subnet + DROP CONSTRAINT fk_dhcp4_subnet_shared_network, + ADD CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger function on dhcp4_shared_network to explicitly +-- update dhcp4_subnets. This ensures there are audit entries for updated +-- subnets. +-- Trigger function for dhcp4_shared_network_BDEL called BEFORE DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_BDEL() RETURNS TRIGGER AS $dhcp4_shared_network_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + -- Explicitly update subnets now rather than via foreign key constraint, this ensures the + -- audit entries for subnets will preceded that of the shared-network, keeping the order + -- of the entries the same as they are for MySQL. + UPDATE dhcp4_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +$dhcp4_shared_network_BDEL$ +LANGUAGE plpgsql; + +-- Modify shared-network-name foreign key constraint on dhcp6_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp6_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp6_subnet + DROP CONSTRAINT fk_dhcp6_subnet_shared_network, + ADD CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger function on dhcp6_shared_network to explicitly +-- update dhcp6_subnets. This ensures there are audit entries for updated +-- subnets. +-- Trigger function for dhcp6_shared_network_BDEL called BEFORE DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_BDEL() RETURNS TRIGGER AS $dhcp6_shared_network_BDEL$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + -- Explicitly update subnets now rather than via foreign key constraint, this ensures the + -- audit entries for subnets will preceded that of the shared-network, keeping the order + -- of the entries the same as they are for MySQL. + UPDATE dhcp6_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +$dhcp6_shared_network_BDEL$ +LANGUAGE plpgsql; + +-- Add user_context column to client class tables. +ALTER TABLE dhcp4_client_class ADD COLUMN user_context JSON DEFAULT NULL; +ALTER TABLE dhcp6_client_class ADD COLUMN user_context JSON DEFAULT NULL; + +-- Update the schema version number. +UPDATE schema_version + SET version = '12', minor = '0'; + +-- This line concludes the schema upgrade to version 12. + +-- This line starts the schema upgrade to version 13. + +-- JSON functions -- + +-- Helper function that avoids a casting error when the string +-- presumed to be in JSON format, is empty. +CREATE OR REPLACE FUNCTION json_cast(IN json_candidate TEXT) +RETURNS JSON +AS $$ +BEGIN + IF LENGTH(json_candidate) = 0 THEN + RETURN '{}'::json; + END IF; + RETURN json_candidate::json; +END; +$$ LANGUAGE plpgsql; + +-- Function that establishes whether JSON functions are supported. +-- They should be provided with PostgreSQL >= 9.4. +CREATE OR REPLACE FUNCTION isJsonSupported() +RETURNS BOOLEAN +AS $$ +BEGIN + IF get_session_value('json_supported') IS NULL THEN + IF (SELECT proname FROM pg_proc WHERE proname = 'json_extract_path') = 'json_extract_path' THEN + PERFORM set_session_value('kea.json_supported', true); + ELSE + PERFORM set_session_value('kea.json_supported', false); + END IF; + END IF; + RETURN get_session_value('kea.json_supported'); +END +$$ LANGUAGE plpgsql; + +-- Schema changes related to lease limiting start here. -- + +-- Recreate the triggers that update the leaseX_stat tables as stored procedures. -- + +CREATE OR REPLACE FUNCTION lease4_AINS_lease4_stat(IN new_state BIGINT, + IN new_subnet_id BIGINT) +RETURNS VOID +AS $$ +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert the state count record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_AUPD_lease4_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN new_state BIGINT, + IN new_subnet_id BIGINT) +RETURNS VOID +AS $$ +BEGIN + IF old_subnet_id != new_subnet_id OR old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease4_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert new state record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_ADEL_lease4_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT) +RETURNS VOID +AS $$ +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists. + UPDATE lease4_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND old_state = state; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AINS_lease6_stat(IN new_state BIGINT, + IN new_subnet_id BIGINT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS $$ +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert the state count record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AUPD_lease6_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN old_lease_type SMALLINT, + IN new_state BIGINT, + IN new_subnet_id BIGINT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS $$ +BEGIN + IF old_subnet_id != new_subnet_id OR + old_lease_type != new_lease_type OR + old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease6_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat + VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_ADEL_lease6_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN old_lease_type SMALLINT) +RETURNS VOID +AS $$ +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; +END; +$$ LANGUAGE plpgsql; + +-- Create tables that contain the number of active leases. -- + +CREATE TABLE lease4_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL PRIMARY KEY, + leases BIGINT NOT NULL +); + +CREATE TABLE lease6_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL, + lease_type SMALLINT NOT NULL, + leases BIGINT NOT NULL, + PRIMARY KEY (client_class, lease_type), + CONSTRAINT fk_lease6_stat_by_client_class_lease_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type) +); + +-- Create procedures to be called for each row in after-event triggers for +-- INSERT, UPDATE and DELETE on lease tables. + +CREATE OR REPLACE FUNCTION lease4_AINS_lease4_stat_by_client_class(IN new_state BIGINT, + IN new_user_context TEXT) +RETURNS VOID +AS $$ +DECLARE + class VARCHAR(128); +BEGIN + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF NOT FOUND THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + END LOOP; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_AUPD_lease4_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN new_state BIGINT, + IN new_user_context TEXT) +RETURNS VOID +AS $$ +DECLARE + old_client_classes TEXT; + new_client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + SELECT json_cast(old_user_context)->'ISC'->'client-classes' INTO old_client_classes; + SELECT json_cast(new_user_context)->'ISC'->'client-classes' INTO new_client_classes; + + IF old_state != new_state OR old_client_classes != new_client_classes THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class; + END LOOP; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF NOT FOUND THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + END LOOP; + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_ADEL_lease4_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT) +RETURNS VOID +AS $$ +DECLARE + class VARCHAR(128); +BEGIN + -- Only state 0 is accounted for in lease limiting. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class; + END LOOP; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AINS_lease6_stat_by_client_class(IN new_state BIGINT, + IN new_user_context TEXT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS $$ +DECLARE + client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF NOT FOUND THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + END LOOP; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AUPD_lease6_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN old_lease_type SMALLINT, + IN new_state BIGINT, + IN new_user_context TEXT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS $$ +DECLARE + old_client_classes TEXT; + new_client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + SELECT json_cast(old_user_context)->'ISC'->'client-classes' INTO old_client_classes; + SELECT json_cast(new_user_context)->'ISC'->'client-classes' INTO new_client_classes; + + IF old_state != new_state OR old_client_classes != new_client_classes OR old_lease_type != new_lease_type THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + END LOOP; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF NOT FOUND THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + END LOOP; + END IF; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_ADEL_lease6_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN old_lease_type SMALLINT) +RETURNS VOID +AS $$ +DECLARE + client_classes VARCHAR(1024); + class VARCHAR(128); + length INT; + i INT; +BEGIN + -- Only state 0 is accounted for in lease limiting. But check both states to be consistent with lease6_stat. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + END LOOP; + END IF; +END; +$$ LANGUAGE plpgsql; + +-- Recreate the after-event triggers for INSERT, UPDATE and DELETE on lease tables to call the -- +-- stored procedures above in pairs of two: for client classes and for subnets. -- + +DROP TRIGGER IF EXISTS stat_lease4_insert ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_AINS() +RETURNS trigger AS $lease4_AINS$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_AINS_lease4_stat_by_client_class(NEW.state, NEW.user_context); + END IF; + PERFORM lease4_AINS_lease4_stat(NEW.state, NEW.subnet_id); + RETURN NULL; +END; +$lease4_AINS$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_AINS AFTER INSERT ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_AINS(); + +DROP TRIGGER IF EXISTS stat_lease4_update ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_AUPD() +RETURNS trigger AS $lease4_AUPD$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_AUPD_lease4_stat_by_client_class(OLD.state, OLD.user_context, NEW.state, NEW.user_context); + END IF; + PERFORM lease4_AUPD_lease4_stat(OLD.state, OLD.subnet_id, NEW.state, NEW.subnet_id); + RETURN NULL; +END; +$lease4_AUPD$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_AUPD AFTER UPDATE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_AUPD(); + +DROP TRIGGER IF EXISTS stat_lease4_delete ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_ADEL() +RETURNS trigger AS $lease4_ADEL$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_ADEL_lease4_stat_by_client_class(OLD.state, OLD.user_context); + END IF; + PERFORM lease4_ADEL_lease4_stat(OLD.state, OLD.subnet_id); + RETURN NULL; +END; +$lease4_ADEL$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_ADEL AFTER DELETE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_ADEL(); + +DROP TRIGGER IF EXISTS stat_lease6_insert ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_AINS() +RETURNS trigger AS $lease6_AINS$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_AINS_lease6_stat_by_client_class(NEW.state, NEW.user_context, NEW.lease_type); + END IF; + PERFORM lease6_AINS_lease6_stat(NEW.state, NEW.subnet_id, NEW.lease_type); + RETURN NULL; +END; +$lease6_AINS$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_AINS AFTER INSERT ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_AINS(); + +DROP TRIGGER IF EXISTS stat_lease6_update ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_AUPD() +RETURNS trigger AS $lease6_AUPD$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_AUPD_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type, NEW.state, NEW.user_context, NEW.lease_type); + END IF; + PERFORM lease6_AUPD_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type, NEW.state, NEW.subnet_id, NEW.lease_type); + RETURN NULL; +END; +$lease6_AUPD$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_AUPD AFTER UPDATE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_AUPD(); + +DROP TRIGGER IF EXISTS stat_lease6_delete ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_ADEL() +RETURNS trigger AS $lease6_ADEL$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_ADEL_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type); + END IF; + PERFORM lease6_ADEL_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type); + RETURN NULL; +END; +$lease6_ADEL$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_ADEL AFTER DELETE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_ADEL(); + +-- Create functions that return an empty TEXT if all limits allow for more leases, or otherwise a +-- TEXT in one of the following JSON formats detailing the limit that was reached: +-- { "limit-type": "client-class", "name": foo, "lease-type": "address", "limit": 2, "count": 2 } +-- { "limit-type": "subnet", "id": 1, "lease-type": "IA_PD", "limit": 2, "count": 2 } +-- The following format for user_context is assumed: +-- { "ISC": { "limits": { "client-classes": [ { "name": "foo", "address-limit": 2, "prefix-limit": 1 } ], +-- "subnet": { "id": 1, "address-limit": 2, "prefix-limit": 1 } } } } + +CREATE OR REPLACE FUNCTION checkLease4Limits(user_context TEXT) +RETURNS TEXT +AS $$ +DECLARE + class TEXT; + name VARCHAR(255); + sid INT; + lease_limit INT; + lease_count INT; +BEGIN + -- Dive into client class limits. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(user_context)->'ISC'->'limits'->'client-classes') LOOP + SELECT TRIM('"' FROM (json_cast(class)->'name')::text) INTO name; + SELECT json_cast(class)->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease4_stat_by_client_class INTO lease_count WHERE client_class = name; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + END LOOP; + + -- Dive into subnet limits. + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'id' INTO sid; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease4_stat WHERE subnet_id = sid AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION checkLease6Limits(user_context TEXT) +RETURNS TEXT +AS $$ +DECLARE + class TEXT; + name VARCHAR(255); + sid INT; + lease_limit INT; + lease_count INT; +BEGIN + -- Dive into client class limits. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(user_context)->'ISC'->'limits'->'client-classes') LOOP + SELECT TRIM('"' FROM (json_cast(class)->'name')::text) INTO name; + SELECT json_cast(class)->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the address count for this client class. + SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SELECT json_cast(class)->'prefix-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the prefix count for this client class. + SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 2 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + END LOOP; + + -- Dive into subnet limits. + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'id' INTO sid; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'address-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this subnet. + SELECT leases FROM lease6_stat WHERE subnet_id = sid AND lease_type = 0 AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'prefix-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease6_stat WHERE subnet_id = sid AND lease_type = 2 AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END; +$$ LANGUAGE plpgsql; + +-- Improve hosts indexes for better performance of global reservations +-- Create new index that uses only dhcp_identifier. +CREATE INDEX key_dhcp_identifier on hosts (dhcp_identifier, dhcp_identifier_type); + +-- Modify existing indexes to include subnet_id values of 0, so index is also used +-- for global reservations. +DROP INDEX IF EXISTS key_dhcp4_identifier_subnet_id; +CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp4_subnet_id ASC) + WHERE (dhcp4_subnet_id IS NOT NULL); + +DROP INDEX IF EXISTS key_dhcp6_identifier_subnet_id; +CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp6_subnet_id ASC) + WHERE (dhcp6_subnet_id IS NOT NULL); + +-- Update the schema version number. +UPDATE schema_version + SET version = '13', minor = '0'; + +-- This line concludes the schema upgrade to version 13. + +-- Commit the script transaction. +COMMIT; + +-- Notes: + +-- Indexes +-- ======= +-- It is likely that additional indexes will be needed. However, the +-- increase in lookup performance from these will come at the expense +-- of a decrease in performance during insert operations due to the need +-- to update the indexes. For this reason, the need for additional indexes +-- will be determined by experiment during performance tests. + +-- The most likely additional indexes will cover the following columns: + +-- hwaddr and client_id +-- For lease stability: if a client requests a new lease, try to find an +-- existing or recently expired lease for it so that it can keep using the +-- same IP address. + +-- Field Sizes +-- =========== +-- If any of the VARxxx field sizes are altered, the lengths in the PgSQL +-- backend source file (pgsql_lease_mgr.cc) must be correspondingly changed. + +-- Portability +-- =========== +-- Some columns contain binary data so are stored as BYTEA instead of +-- VARCHAR. This may be non-portable between databases: in this case, the +-- definition should be changed to VARCHAR. diff --git a/src/share/database/scripts/pgsql/dhcpdb_drop.pgsql b/src/share/database/scripts/pgsql/dhcpdb_drop.pgsql new file mode 100644 index 0000000..1e88ab9 --- /dev/null +++ b/src/share/database/scripts/pgsql/dhcpdb_drop.pgsql @@ -0,0 +1,228 @@ +-- Copyright (C) 2016-2022 Internet Systems Consortium. + +-- This Source Code Form is subject to the terms of the Mozilla Public +-- License, v. 2.0. If a copy of the MPL was not distributed with this +-- file, You can obtain one at http://mozilla.org/MPL/2.0/. + +DROP TABLE IF EXISTS lease4 CASCADE; +DROP TABLE IF EXISTS lease6 CASCADE; +DROP TABLE IF EXISTS lease6_types CASCADE; +DROP TABLE IF EXISTS schema_version CASCADE; +DROP TABLE IF EXISTS lease_state CASCADE; +DROP TABLE IF EXISTS dhcp4_options CASCADE; +DROP TABLE IF EXISTS dhcp6_options CASCADE; +DROP TABLE IF EXISTS ipv6_reservations CASCADE; +DROP TABLE IF EXISTS lease_hwaddr_source CASCADE; +DROP TABLE IF EXISTS host_identifier_type CASCADE; +DROP TABLE IF EXISTS dhcp_option_scope CASCADE; +DROP TABLE IF EXISTS hosts CASCADE; +DROP FUNCTION IF EXISTS lease4DumpHeader(); +DROP FUNCTION IF EXISTS lease4DumpData(); +DROP FUNCTION IF EXISTS lease6DumpHeader(); +DROP FUNCTION IF EXISTS lease6DumpData(); +DROP TABLE IF EXISTS lease4_stat CASCADE; +DROP FUNCTION IF EXISTS proc_stat_lease4_insert (); +DROP FUNCTION IF EXISTS proc_stat_lease4_update (); +DROP FUNCTION IF EXISTS proc_stat_lease4_delete (); +DROP TABLE IF EXISTS lease6_stat CASCADE; +DROP FUNCTION IF EXISTS proc_stat_lease6_insert (); +DROP FUNCTION IF EXISTS proc_stat_lease6_update (); +DROP FUNCTION IF EXISTS proc_stat_lease6_delete (); +DROP TABLE IF EXISTS logs CASCADE; + +-- config backend procedures for DHCPv6 +DROP FUNCTION IF EXISTS createAuditRevisionDHCP6(audit_ts TIMESTAMP WITH TIME ZONE, server_tag VARCHAR(64), + audit_log_message TEXT, cascade_transaction BOOLEAN); +DROP FUNCTION IF EXISTS createAuditEntryDHCP6(object_type_val VARCHAR(256), object_id_val BIGINT, + modification_type_val VARCHAR(32)); +DROP FUNCTION IF EXISTS createOptionAuditDHCP6(modification_type VARCHAR, scope_id SMALLINT, + option_id INT, subnet_id BIGINT, host_id INT, + network_name VARCHAR, pool_id BIGINT, pd_pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE); +DROP FUNCTION IF EXISTS createOptionAuditDHCP6(modification_type VARCHAR, scope_id SMALLINT, + option_id INT, p_subnet_id BIGINT, host_id INT, + network_name VARCHAR, pool_id BIGINT, pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE); +DROP FUNCTION IF EXISTS setClientClass6Order(id BIGINT, follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)); +DROP FUNCTION IF EXISTS checkDHCPv6ClientClassDependency(class_id BIGINT, dependency_id BIGINT); +DROP FUNCTION IF EXISTS updateDHCPv6ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT); +DROP FUNCTION IF EXISTS checkDHCPv6ClientClassKnownDependencyChange(); + +-- config backend tables for DHCPv6 +DROP TABLE IF EXISTS dhcp6_audit CASCADE; +DROP TABLE IF EXISTS dhcp6_option_def_server CASCADE; +DROP TABLE IF EXISTS dhcp6_option_def CASCADE; +DROP TABLE IF EXISTS dhcp6_options_server CASCADE; +DROP TABLE IF EXISTS dhcp6_pool CASCADE; +DROP TABLE IF EXISTS dhcp6_pd_pool CASCADE; +DROP TABLE IF EXISTS dhcp6_subnet_server CASCADE; +DROP TABLE IF EXISTS dhcp6_subnet CASCADE; +DROP TABLE IF EXISTS dhcp6_shared_network_server CASCADE; +DROP TABLE IF EXISTS dhcp6_shared_network CASCADE; +DROP TABLE IF EXISTS dhcp6_global_parameter_server CASCADE; +DROP TABLE IF EXISTS dhcp6_global_parameter CASCADE; +DROP TABLE IF EXISTS dhcp6_server CASCADE; +DROP TABLE IF EXISTS dhcp6_audit_revision CASCADE; +DROP TABLE IF EXISTS dhcp6_client_class_server CASCADE; +DROP TABLE IF EXISTS dhcp6_client_class_dependency CASCADE; +DROP TABLE IF EXISTS dhcp6_client_class_order CASCADE; +DROP TABLE IF EXISTS dhcp6_client_class CASCADE; + +-- drop trigger functions for DHCPv6 +DROP FUNCTION IF EXISTS func_dhcp6_client_class_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_client_class_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_client_class_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_client_class_check_dependency_BINS(); +DROP FUNCTION IF EXISTS func_dhcp6_client_class_dependency_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_pool_BDEL(); +DROP FUNCTION IF EXISTS func_dhcp6_global_parameter_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_global_parameter_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_global_parameter_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_subnet_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_subnet_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_shared_network_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_shared_network_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_shared_network_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_option_def_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_option_def_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_option_def_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_options_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_options_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_options_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_server_AINS(); +DROP FUNCTION IF EXISTS func_dhcp6_server_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp6_server_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp6_shared_network_BDEL(); +DROP FUNCTION IF EXISTS func_dhcp6_subnet_BDEL(); +DROP FUNCTION IF EXISTS func_dhcp6_pd_pool_BDEL(); + +-- config backend procedures for DHCPv4 +DROP FUNCTION IF EXISTS createAuditRevisionDHCP4(audit_ts TIMESTAMP WITH TIME ZONE, server_tag VARCHAR(64), + audit_log_message TEXT, cascade_transaction BOOLEAN); +DROP FUNCTION IF EXISTS createAuditEntryDHCP4(object_type_val VARCHAR(256), object_id_val BIGINT, + modification_type_val VARCHAR(32)); +DROP FUNCTION IF EXISTS createOptionAuditDHCP4(modification_type VARCHAR, scope_id SMALLINT, + option_id INT, subnet_id BIGINT, host_id INT, + network_name VARCHAR, pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE); +DROP FUNCTION IF EXISTS setClientClass4Order(id BIGINT, follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)); +DROP FUNCTION IF EXISTS checkDHCPv4ClientClassDependency(class_id BIGINT, dependency_id BIGINT); +DROP FUNCTION IF EXISTS updateDHCPv4ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT); +DROP FUNCTION IF EXISTS checkDHCPv4ClientClassKnownDependencyChange(); + +-- config backend tables for DHCPv4 +DROP TABLE IF EXISTS dhcp4_audit CASCADE; +DROP TABLE IF EXISTS dhcp4_option_def_server CASCADE; +DROP TABLE IF EXISTS dhcp4_option_def CASCADE; +DROP TABLE IF EXISTS dhcp4_options_server CASCADE; +DROP TABLE IF EXISTS dhcp4_pool CASCADE; +DROP TABLE IF EXISTS dhcp4_pd_pool CASCADE; +DROP TABLE IF EXISTS dhcp4_subnet_server CASCADE; +DROP TABLE IF EXISTS dhcp4_subnet CASCADE; +DROP TABLE IF EXISTS dhcp4_shared_network_server CASCADE; +DROP TABLE IF EXISTS dhcp4_shared_network CASCADE; +DROP TABLE IF EXISTS dhcp4_global_parameter_server CASCADE; +DROP TABLE IF EXISTS dhcp4_global_parameter CASCADE; +DROP TABLE IF EXISTS dhcp4_server CASCADE; +DROP TABLE IF EXISTS dhcp4_audit_revision CASCADE; +DROP TABLE IF EXISTS dhcp4_client_class_server CASCADE; +DROP TABLE IF EXISTS dhcp4_client_class_dependency CASCADE; +DROP TABLE IF EXISTS dhcp4_client_class_order CASCADE; +DROP TABLE IF EXISTS dhcp4_client_class CASCADE; + +-- drop trigger functions for DHCPv4 +DROP FUNCTION IF EXISTS func_dhcp4_client_class_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_client_class_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_client_class_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_client_class_check_dependency_BINS(); +DROP FUNCTION IF EXISTS func_dhcp4_client_class_dependency_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_pool_BDEL(); +DROP FUNCTION IF EXISTS func_dhcp4_global_parameter_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_global_parameter_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_global_parameter_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_subnet_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_subnet_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_shared_network_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_shared_network_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_shared_network_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_option_def_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_option_def_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_option_def_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_options_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_options_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_options_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_server_AINS(); +DROP FUNCTION IF EXISTS func_dhcp4_server_AUPD(); +DROP FUNCTION IF EXISTS func_dhcp4_server_ADEL(); +DROP FUNCTION IF EXISTS func_dhcp4_shared_network_BDEL(); +DROP FUNCTION IF EXISTS func_dhcp4_subnet_BDEL(); + +-- common tables for config backend +DROP TABLE IF EXISTS modification CASCADE; +DROP TABLE IF EXISTS parameter_data_type CASCADE; +DROP TABLE IF EXISTS ddns_replace_client_name_types CASCADE; +DROP FUNCTION IF EXISTS modification_ts_update(); +DROP FUNCTION IF EXISTS get_session_boolean(name text); +DROP FUNCTION IF EXISTS get_session_big_int(name text); +DROP FUNCTION IF EXISTS get_session_value(name text); +DROP FUNCTION IF EXISTS set_session_value(name text, value TEXT); +DROP FUNCTION IF EXISTS set_session_value(name text, value BIGINT); +DROP FUNCTION IF EXISTS set_session_value(name text, value BOOLEAN); + +DROP FUNCTION IF EXISTS lease4Upload(address VARCHAR, hwaddr VARCHAR, + client_id VARCHAR, valid_lifetime BIGINT, expire BIGINT, subnet_id BIGINT, + fqdn_fwd INT, fqdn_rev INT, hostname VARCHAR, state INT8, + user_context VARCHAR); +DROP FUNCTION IF EXISTS lease6Upload(address VARCHAR, duid VARCHAR, + valid_lifetime BIGINT, expire BIGINT, subnet_id BIGINT, + pref_lifetime BIGINT, lease_type INT, iaid INT, prefix_len INT, + fqdn_fwd INT, fqdn_rev INT, hostname VARCHAR, hwaddr VARCHAR, + state INT8, user_context VARCHAR, hwtype INT, hwaddr_source INT); +DROP FUNCTION IF EXISTS colonSeparatedHex(TEXT); + +DROP FUNCTION IF EXISTS gmt_epoch(input_time TIMESTAMP WITH TIME ZONE); + +-- lease limiting tables and functions +DROP TABLE IF EXISTS lease4_stat_by_client_class; +DROP TABLE IF EXISTS lease6_stat_by_client_class; +DROP FUNCTION IF EXISTS lease4_AINS_lease4_stat(new_state BIGINT, + new_subnet_id BIGINT); +DROP FUNCTION IF EXISTS lease4_AUPD_lease4_stat(old_state BIGINT, + old_subnet_id BIGINT, new_state BIGINT, new_subnet_id BIGINT); +DROP FUNCTION IF EXISTS lease4_ADEL_lease4_stat(old_state BIGINT, + old_subnet_id BIGINT); +DROP FUNCTION IF EXISTS lease6_AINS_lease6_stat(new_state BIGINT, + new_subnet_id BIGINT, new_lease_type SMALLINT); +DROP FUNCTION IF EXISTS lease6_AUPD_lease6_stat(old_state BIGINT, + old_subnet_id BIGINT, old_lease_type SMALLINT, new_state BIGINT, + new_subnet_id BIGINT, new_lease_type SMALLINT); +DROP FUNCTION IF EXISTS lease6_ADEL_lease6_stat(old_state BIGINT, + old_subnet_id BIGINT, old_lease_type SMALLINT); +DROP FUNCTION IF EXISTS lease4_AINS_lease4_stat_by_client_class( + new_state BIGINT, new_user_context TEXT); +DROP FUNCTION IF EXISTS lease4_AUPD_lease4_stat_by_client_class( + old_state BIGINT, old_user_context TEXT, + new_state BIGINT, new_user_context TEXT); +DROP FUNCTION IF EXISTS lease4_ADEL_lease4_stat_by_client_class( + old_state BIGINT, old_user_context TEXT); +DROP FUNCTION IF EXISTS lease6_AINS_lease6_stat_by_client_class( + new_state BIGINT, new_user_context TEXT, new_lease_type SMALLINT); +DROP FUNCTION IF EXISTS lease6_AUPD_lease6_stat_by_client_class( + old_state BIGINT, old_user_context TEXT, old_lease_type SMALLINT, + new_state BIGINT, new_user_context TEXT, new_lease_type SMALLINT); +DROP FUNCTION IF EXISTS lease6_ADEL_lease6_stat_by_client_class( + old_state BIGINT, old_user_context TEXT, old_lease_type SMALLINT); +DROP FUNCTION IF EXISTS func_lease4_AINS(); +DROP FUNCTION IF EXISTS func_lease4_AUPD(); +DROP FUNCTION IF EXISTS func_lease4_ADEL(); +DROP FUNCTION IF EXISTS func_lease6_AINS(); +DROP FUNCTION IF EXISTS func_lease6_AUPD(); +DROP FUNCTION IF EXISTS func_lease6_ADEL(); +DROP FUNCTION IF EXISTS checkLease4Limits(user_context TEXT); +DROP FUNCTION IF EXISTS checkLease6Limits(user_context TEXT); +DROP FUNCTION IF EXISTS isJsonSupported(); +DROP FUNCTION IF EXISTS json_cast(json_candidate TEXT); diff --git a/src/share/database/scripts/pgsql/upgrade_001.0_to_002.0.sh.in b/src/share/database/scripts/pgsql/upgrade_001.0_to_002.0.sh.in new file mode 100644 index 0000000..658c92e --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_001.0_to_002.0.sh.in @@ -0,0 +1,173 @@ +#!/bin/sh + +# Copyright (C) 2016-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "1.0" ]; then + printf 'This script upgrades 1.0 to 2.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +-- Add state column to the lease4 table. +ALTER TABLE lease4 + ADD COLUMN state INT8 DEFAULT 0; + +-- Add state column to the lease6 table. +ALTER TABLE lease6 + ADD COLUMN state INT8 DEFAULT 0; + +-- Create indexes for querying leases in a given state and segregated +-- by the expiration time. One of the applications is to retrieve all +-- expired leases. However, these indexes can be also used to retrieve +-- leases in a given state regardless of the expiration time. +CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC); +CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC); + +-- Create table holding mapping of the lease states to their names. +-- This is not used in queries from the DHCP server but rather in +-- direct queries from the lease database management tools. +CREATE TABLE lease_state ( + state INT8 PRIMARY KEY NOT NULL, + name VARCHAR(64) NOT NULL); + +-- Insert currently defined state names. +START TRANSACTION; +INSERT INTO lease_state VALUES (0, 'default'); +INSERT INTO lease_state VALUES (1, 'declined'); +INSERT INTO lease_state VALUES (2, 'expired-reclaimed'); +COMMIT; + +-- Add a constraint that any state value added to the lease4 must +-- map to a value in the lease_state table. +ALTER TABLE lease4 + ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +-- Add a constraint that any state value added to the lease6 must +-- map to a value in the lease_state table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) + REFERENCES lease_state (state); + +-- Add a constraint that lease type in the lease6 table must map +-- to a lease type defined in the lease6_types table. +ALTER TABLE lease6 + ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type); + +-- +-- FUNCTION that returns a result set containing the column names for lease4 dumps +DROP FUNCTION IF EXISTS lease4DumpHeader(); +CREATE FUNCTION lease4DumpHeader() RETURNS text AS \$\$ + select cast('address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state' as text) as result; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease4 dumps +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) as \$\$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name + FROM lease4 l + left outer join lease_state s on (l.state = s.state); +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the column names for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE FUNCTION lease6DumpHeader() RETURNS text AS \$\$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state' as text) as result; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) AS \$\$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state); +\$\$ LANGUAGE SQL; +-- + +-- Set 2.0 schema version. +START TRANSACTION; +UPDATE schema_version + SET version = '2', minor = '0'; +COMMIT; +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_002.0_to_003.0.sh.in b/src/share/database/scripts/pgsql/upgrade_002.0_to_003.0.sh.in new file mode 100644 index 0000000..bf79353 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_002.0_to_003.0.sh.in @@ -0,0 +1,293 @@ +#!/bin/sh + +# Copyright (C) 2016-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "2.0" ]; then + printf 'This script upgrades 2.0 to 3.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Upgrade to schema 3.0 begins here: + +-- +-- Table structure for table host_identifier_type +-- + +CREATE TABLE host_identifier_type ( + type SMALLINT PRIMARY KEY NOT NULL, + name VARCHAR(32) DEFAULT NULL +); + +INSERT INTO host_identifier_type VALUES (0, 'hw-address'); +INSERT INTO host_identifier_type VALUES (1, 'duid'); +INSERT INTO host_identifier_type VALUES (2, 'circuit-id'); + +CREATE TABLE dhcp_option_scope ( + scope_id SMALLINT PRIMARY KEY NOT NULL, + scope_name varchar(32) DEFAULT NULL +); + +INSERT INTO dhcp_option_scope VALUES (0, 'global'); +INSERT INTO dhcp_option_scope VALUES (1, 'subnet'); +INSERT INTO dhcp_option_scope VALUES (2, 'client-class'); +INSERT INTO dhcp_option_scope VALUES (3, 'host'); + +-- +-- Table structure for table hosts +-- +-- Primary key and unique constraints automatically create indexes +-- foreign key constraints do not +CREATE TABLE hosts ( + host_id SERIAL PRIMARY KEY NOT NULL, + dhcp_identifier BYTEA NOT NULL, + dhcp_identifier_type SMALLINT NOT NULL, + dhcp4_subnet_id INT DEFAULT NULL, + dhcp6_subnet_id INT DEFAULT NULL, + ipv4_address BIGINT DEFAULT NULL, + hostname VARCHAR(255) DEFAULT NULL, + dhcp4_client_classes VARCHAR(255) DEFAULT NULL, + dhcp6_client_classes VARCHAR(255) DEFAULT NULL, + CONSTRAINT key_dhcp4_ipv4_address_subnet_id UNIQUE (ipv4_address, dhcp4_subnet_id), + CONSTRAINT key_dhcp4_identifier_subnet_id UNIQUE (dhcp_identifier, dhcp_identifier_type, dhcp4_subnet_id), + CONSTRAINT key_dhcp6_identifier_subnet_id UNIQUE (dhcp_identifier, dhcp_identifier_type, dhcp6_subnet_id), + CONSTRAINT fk_host_identifier_type FOREIGN KEY (dhcp_identifier_type) REFERENCES host_identifier_type (type) + ON DELETE CASCADE +); + +CREATE INDEX fk_host_identifier_type ON hosts (dhcp_identifier_type); + +-- +-- Table structure for table dhcp4_options +-- + +CREATE TABLE dhcp4_options ( + option_id SERIAL PRIMARY KEY NOT NULL, + code SMALLINT NOT NULL, + value BYTEA, + formatted_value TEXT, + space VARCHAR(128) DEFAULT NULL, + persistent BOOLEAN NOT NULL DEFAULT 'f', + dhcp_client_class VARCHAR(128) DEFAULT NULL, + dhcp4_subnet_id INT DEFAULT NULL, + host_id INT DEFAULT NULL, + scope_id SMALLINT NOT NULL, + CONSTRAINT fk_options_host1 FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_option_scode FOREIGN KEY (scope_id) REFERENCES dhcp_option_scope (scope_id) ON DELETE CASCADE +); + +CREATE INDEX fk_dhcp4_options_host1_idx ON dhcp4_options (host_id); +CREATE INDEX fk_dhcp4_options_scope_idx ON dhcp4_options (scope_id); + +-- +-- Table structure for table dhcp6_options +-- + +CREATE TABLE dhcp6_options ( + option_id SERIAL PRIMARY KEY NOT NULL, + code INT NOT NULL, + value BYTEA, + formatted_value TEXT, + space VARCHAR(128) DEFAULT NULL, + persistent BOOLEAN NOT NULL DEFAULT 'f', + dhcp_client_class VARCHAR(128) DEFAULT NULL, + dhcp6_subnet_id INT DEFAULT NULL, + host_id INT DEFAULT NULL, + scope_id SMALLINT NOT NULL, + CONSTRAINT fk_options_host10 FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_option_scode FOREIGN KEY (scope_id) REFERENCES dhcp_option_scope (scope_id) ON DELETE CASCADE +); + +CREATE INDEX fk_dhcp6_options_host1_idx ON dhcp6_options (host_id); +CREATE INDEX fk_dhcp6_options_scope_idx ON dhcp6_options (scope_id); + +-- +-- Table structure for table ipv6_reservations +-- + +CREATE TABLE ipv6_reservations ( + reservation_id SERIAL PRIMARY KEY NOT NULL, + address VARCHAR(39) NOT NULL, + prefix_len SMALLINT NOT NULL DEFAULT '128', + type SMALLINT NOT NULL DEFAULT '0', + dhcp6_iaid INT DEFAULT NULL, + host_id INT NOT NULL, + CONSTRAINT key_dhcp6_address_prefix_len UNIQUE (address, prefix_len), + CONSTRAINT fk_ipv6_reservations_host FOREIGN KEY (host_id) REFERENCES hosts (host_id) ON DELETE CASCADE +); + +CREATE INDEX fk_ipv6_reservations_host_idx ON ipv6_reservations (host_id); + +-- +-- Table structure for table lease_hwaddr_source +-- + +CREATE TABLE lease_hwaddr_source ( + hwaddr_source INT PRIMARY KEY NOT NULL, + name VARCHAR(40) DEFAULT NULL +); + +-- In the event hardware address cannot be determined, we need to satisfy +-- foreign key constraint between lease6 and lease_hardware_source +INSERT INTO lease_hwaddr_source VALUES (0, 'HWADDR_SOURCE_UNKNOWN'); + +-- Hardware address obtained from raw sockets +INSERT INTO lease_hwaddr_source VALUES (1, 'HWADDR_SOURCE_RAW'); + +-- Hardware address converted from IPv6 link-local address with EUI-64 +INSERT INTO lease_hwaddr_source VALUES (2, 'HWADDR_SOURCE_IPV6_LINK_LOCAL'); + +-- Hardware address extracted from client-id (duid) +INSERT INTO lease_hwaddr_source VALUES (4, 'HWADDR_SOURCE_DUID'); + +-- Hardware address extracted from client address relay option (RFC6939) +INSERT INTO lease_hwaddr_source VALUES (8, 'HWADDR_SOURCE_CLIENT_ADDR_RELAY_OPTION'); + +-- Hardware address extracted from remote-id option (RFC4649) +INSERT INTO lease_hwaddr_source VALUES (16, 'HWADDR_SOURCE_REMOTE_ID'); + +-- Hardware address extracted from subscriber-id option (RFC4580) +INSERT INTO lease_hwaddr_source VALUES (32, 'HWADDR_SOURCE_SUBSCRIBER_ID'); + +-- Hardware address extracted from docsis options +INSERT INTO lease_hwaddr_source VALUES (64, 'HWADDR_SOURCE_DOCSIS_CMTS'); + +INSERT INTO lease_hwaddr_source VALUES (128, 'HWADDR_SOURCE_DOCSIS_MODEM'); + +-- Adding ORDER BY clause to sort by lease address +-- +-- FUNCTION that returns a result set containing the data for lease4 dumps +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text + ) as \$\$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name + FROM lease4 l + left outer join lease_state s on (l.state = s.state) + ORDER BY l.address; +\$\$ LANGUAGE SQL; +-- + +-- Add new columns to lease6 +ALTER TABLE lease6 + ADD COLUMN hwaddr BYTEA DEFAULT NULL, + ADD COLUMN hwtype SMALLINT DEFAULT NULL, + ADD COLUMN hwaddr_source SMALLINT DEFAULT NULL; + +-- +-- FUNCTION that returns a result set containing the column names for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE FUNCTION lease6DumpHeader() RETURNS text AS \$\$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state,hwaddr,hwtype,hwaddr_source' as text) as result; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + hwaddr text, + hwtype smallint, + hwaddr_source text + ) AS \$\$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + encode(l.hwaddr,'hex'), + l.hwtype, + h.name + ) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) + ORDER BY l.address; +\$\$ LANGUAGE SQL; + +-- Add columns holding reservations for siaddr, sname and file fields +-- carried within DHCPv4 message. +ALTER TABLE hosts ADD COLUMN dhcp4_next_server BIGINT DEFAULT NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_server_hostname VARCHAR(64) DEFAULT NULL; +ALTER TABLE hosts ADD COLUMN dhcp4_boot_file_name VARCHAR(128) DEFAULT NULL; + +-- Set 3.0 schema version. +UPDATE schema_version + SET version = '3', minor = '0'; + +-- Schema 3.0 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_003.0_to_003.1.sh.in b/src/share/database/scripts/pgsql/upgrade_003.0_to_003.1.sh.in new file mode 100644 index 0000000..d5013cd --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_003.0_to_003.1.sh.in @@ -0,0 +1,65 @@ +#!/bin/sh + +# Copyright (C) 2017-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "3.0" ]; then + printf 'This script upgrades 3.0 to 3.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Upgrade to schema 3.1 begins here: + +-- The 'client-id' host identifier type was missing in the +-- 2.0 -> 3.0 upgrade script. However, it was present in the +-- dhcpdb_create.pgsql file. This means that this entry may +-- or may not be present. By the conditional insert below we +-- will only insert it if it doesn't exist. +INSERT INTO host_identifier_type (type, name) + SELECT 3, 'client-id' + WHERE NOT EXISTS ( + SELECT type FROM host_identifier_type WHERE type = 3 + ); + +-- We also add a new identifier type: flex-id. +INSERT INTO host_identifier_type VALUES (4, 'flex-id'); + +-- Set 3.1 schema version. +UPDATE schema_version + SET version = '3', minor = '1'; + +-- Schema 3.1 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_003.1_to_003.2.sh.in b/src/share/database/scripts/pgsql/upgrade_003.1_to_003.2.sh.in new file mode 100644 index 0000000..f9ec2bb --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_003.1_to_003.2.sh.in @@ -0,0 +1,78 @@ +#!/bin/sh + +# Copyright (C) 2017-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "3.1" ]; then + printf 'This script upgrades 3.1 to 3.2. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Remove constraints which perform too restrictive checks on the inserted +-- host reservations. We want to be able to insert host reservations which +-- include no specific IPv4 address or those that have repeating subnet +-- identifiers, e.g. IPv4 reservations would typically include 0 (or null) +-- IPv6 subnet identifiers. +ALTER TABLE hosts DROP CONSTRAINT key_dhcp4_ipv4_address_subnet_id; +ALTER TABLE hosts DROP CONSTRAINT key_dhcp4_identifier_subnet_id; +ALTER TABLE hosts DROP CONSTRAINT key_dhcp6_identifier_subnet_id; + +-- Create partial indexes instead of the constraints that we have removed. + +-- IPv4 address/IPv4 subnet identifier pair is unique if subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX hosts_dhcp4_ipv4_address_subnet_id ON hosts + (ipv4_address ASC, dhcp4_subnet_id ASC) + WHERE ipv4_address IS NOT NULL AND ipv4_address <> 0; + +-- Client identifier is unique within an IPv4 subnet when subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX hosts_dhcp4_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp4_subnet_id ASC) + WHERE (dhcp4_subnet_id IS NOT NULL AND dhcp4_subnet_id <> 0); + +-- Client identifier is unique within an IPv6 subnet when subnet identifier is +-- not null and not 0. +CREATE UNIQUE INDEX hosts_dhcp6_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp6_subnet_id ASC) + WHERE (dhcp6_subnet_id IS NOT NULL AND dhcp6_subnet_id <> 0); + +-- Set 3.2 schema version. +UPDATE schema_version + SET version = '3', minor = '2'; + +-- Schema 3.2 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_003.2_to_003.3.sh.in b/src/share/database/scripts/pgsql/upgrade_003.2_to_003.3.sh.in new file mode 100644 index 0000000..6933c16 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_003.2_to_003.3.sh.in @@ -0,0 +1,56 @@ +#!/bin/sh + +# Copyright (C) 2018-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "3.2" ]; then + printf 'This script upgrades 3.2 to 3.3. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Change subnet ID columns type to BIGINT to match lease4/6 tables +ALTER TABLE hosts ALTER COLUMN dhcp4_subnet_id TYPE BIGINT; +ALTER TABLE hosts ALTER COLUMN dhcp6_subnet_id TYPE BIGINT; + +ALTER TABLE dhcp4_options ALTER COLUMN dhcp4_subnet_id TYPE BIGINT; +ALTER TABLE dhcp6_options ALTER COLUMN dhcp6_subnet_id TYPE BIGINT; + +-- Set 3.3 schema version. +UPDATE schema_version + SET version = '3', minor = '3'; + +-- Schema 3.3 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_003.3_to_004.0.sh.in b/src/share/database/scripts/pgsql/upgrade_003.3_to_004.0.sh.in new file mode 100644 index 0000000..d7a0885 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_003.3_to_004.0.sh.in @@ -0,0 +1,261 @@ +#!/bin/sh + +# Copyright (C) 2018-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "3.3" ]; then + printf 'This script upgrades 3.3 to 4.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Add a column holding hosts for user context. +ALTER TABLE hosts ADD COLUMN user_context TEXT; + +-- Add a column holding DHCP options for user context. +ALTER TABLE dhcp4_options ADD COLUMN user_context TEXT; +ALTER TABLE dhcp6_options ADD COLUMN user_context TEXT; + +-- Create index for searching leases by subnet identifier. +CREATE INDEX lease4_by_subnet_id ON lease4 (subnet_id); + +-- Create for searching leases by subnet identifier and lease type. +CREATE INDEX lease6_by_subnet_id_lease_type ON lease6 (subnet_id, lease_type); + +-- The index by iaid_subnet_id_duid is not the best choice because there are +-- cases when we don't specify subnet identifier while searching leases. The +-- index will be universal if the subnet_id is the right most column in the +-- index. +DROP INDEX lease6_by_iaid_subnet_id_duid; +CREATE INDEX lease6_by_duid_iaid_subnet_id ON lease6 (duid, iaid, subnet_id); + +-- Create v4 lease statistics table +CREATE TABLE lease4_stat ( + subnet_id BIGINT NOT NULL, + state INT8 NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, state) +); + +-- +-- Create v4 insert trigger procedure +CREATE FUNCTION proc_stat_lease4_insert () RETURNS trigger AS \$stat_lease4_insert\$ +BEGIN + IF NEW.state < 2 THEN + UPDATE lease4_stat + SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new.subnet_id, new.state, 1); + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease4_insert\$ LANGUAGE plpgsql; + +-- Create v4 insert trigger procedure +CREATE TRIGGER stat_lease4_insert +AFTER INSERT ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_insert(); + +-- +-- Create v4 update trigger procedure +CREATE FUNCTION proc_stat_lease4_update () RETURNS trigger AS \$stat_lease4_update\$ +BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease4_update\$ LANGUAGE plpgsql; + +-- Create v4 update trigger +CREATE TRIGGER stat_lease4_update +AFTER UPDATE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_update(); + +-- +-- Create the v4 delete trigger procedure +CREATE FUNCTION proc_stat_lease4_delete () RETURNS trigger AS \$stat_lease4_delete\$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease4_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease4_delete\$ LANGUAGE plpgsql; + +-- Create the v4 delete trigger +CREATE TRIGGER stat_lease4_delete +AFTER DELETE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease4_delete(); + +-- Create v6 lease statistics table +CREATE TABLE lease6_stat ( + subnet_id BIGINT NOT NULL, + lease_type SMALLINT NOT NULL, + state INT8 NOT NULL, + leases BIGINT, + PRIMARY KEY (subnet_id, lease_type, state) +); + +-- +-- Create v6 insert trigger procedure +CREATE FUNCTION proc_stat_lease6_insert () RETURNS trigger AS \$stat_lease6_insert\$ +BEGIN + IF NEW.state < 2 THEN + UPDATE lease6_stat + SET leases = leases + 1 + WHERE + subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + IF NOT FOUND THEN + INSERT INTO lease6_stat + VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease6_insert\$ LANGUAGE plpgsql; + +-- Create v6 insert trigger procedure +CREATE TRIGGER stat_lease6_insert +AFTER INSERT ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_insert(); + +-- +-- Create v6 update trigger procedure +CREATE FUNCTION proc_stat_lease6_update () RETURNS trigger AS \$stat_lease6_update\$ +BEGIN + IF OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease6_update\$ LANGUAGE plpgsql; + +-- Create v6 update trigger +CREATE TRIGGER stat_lease6_update +AFTER UPDATE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_update(); + +-- +-- Create the v6 delete trigger procedure +CREATE FUNCTION proc_stat_lease6_delete() RETURNS trigger AS \$stat_lease6_delete\$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat SET leases = leases - 1 + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease6_delete\$ LANGUAGE plpgsql; + +-- Create the v6 delete trigger +CREATE TRIGGER stat_lease6_delete +AFTER DELETE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE proc_stat_lease6_delete(); + +-- Populate lease4_stat table based on existing leases +-- We only care about assigned and declined states +INSERT INTO lease4_stat (subnet_id, state, leases) + SELECT subnet_id, state, count(state) + FROM lease4 WHERE state < 2 + GROUP BY subnet_id, state ORDER BY subnet_id; + +-- Populate lease6_stat table based on existing leases +-- We only care about assigned and declined states +INSERT INTO lease6_stat (subnet_id, lease_type, state, leases) + SELECT subnet_id, lease_type, state, count(state) + FROM lease6 WHERE state < 2 + GROUP BY subnet_id, lease_type, state + ORDER BY subnet_id; + +-- Set 4.0 schema version. +UPDATE schema_version + SET version = '4', minor = '0'; + +-- Schema 4.0 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_004.0_to_005.0.sh.in b/src/share/database/scripts/pgsql/upgrade_004.0_to_005.0.sh.in new file mode 100644 index 0000000..62c861d --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_004.0_to_005.0.sh.in @@ -0,0 +1,172 @@ +#!/bin/sh + +# Copyright (C) 2018-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "4.0" ]; then + printf 'This script upgrades 4.0 to 5.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Add a column holding leases for user context. +ALTER TABLE lease4 ADD COLUMN user_context TEXT; +ALTER TABLE lease6 ADD COLUMN user_context TEXT; + +-- +-- FUNCTION that returns a result set containing the column names for lease4 dumps +DROP FUNCTION IF EXISTS lease4DumpHeader(); +CREATE FUNCTION lease4DumpHeader() RETURNS text AS \$\$ + select cast('address,hwaddr,client_id,valid_lifetime,expire,subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context' as text) as result; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease4 dumps +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE FUNCTION lease4DumpData() RETURNS + table (address inet, + hwaddr text, + client_id text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + user_context text + ) as \$\$ + SELECT ('0.0.0.0'::inet + l.address), + encode(l.hwaddr,'hex'), + encode(l.client_id,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + l.user_context + FROM lease4 l + left outer join lease_state s on (l.state = s.state) + ORDER BY l.address; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the column names for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE FUNCTION lease6DumpHeader() RETURNS text AS \$\$ + select cast('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,state,hwaddr,hwtype,hwaddr_source,user_context' as text) as result; +\$\$ LANGUAGE SQL; +-- + +-- +-- FUNCTION that returns a result set containing the data for lease6 dumps +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE FUNCTION lease6DumpData() RETURNS + TABLE ( + address text, + duid text, + valid_lifetime bigint, + expire timestamp with time zone, + subnet_id bigint, + pref_lifetime bigint, + name text, + iaid integer, + prefix_len smallint, + fqdn_fwd int, + fqdn_rev int, + hostname text, + state text, + hwaddr text, + hwtype smallint, + hwaddr_source text, + user_context text + ) AS \$\$ + SELECT (l.address, + encode(l.duid,'hex'), + l.valid_lifetime, + l.expire, + l.subnet_id, + l.pref_lifetime, + t.name, + l.iaid, + l.prefix_len, + l.fqdn_fwd::int, + l.fqdn_rev::int, + l.hostname, + s.name, + encode(l.hwaddr,'hex'), + l.hwtype, + h.name, + l.user_context + ) + FROM lease6 l + left outer join lease6_types t on (l.lease_type = t.lease_type) + left outer join lease_state s on (l.state = s.state) + left outer join lease_hwaddr_source h on (l.hwaddr_source = h.hwaddr_source) + ORDER BY l.address; +\$\$ LANGUAGE SQL; +-- + +-- Create logs table (logs table is used by forensic logging hook library) +CREATE TABLE logs ( + timestamp TIMESTAMP WITH TIME ZONE + DEFAULT CURRENT_TIMESTAMP, -- creation timestamp + address VARCHAR(43) NULL, -- address or prefix + log TEXT NOT NULL -- the log itself + ); + +-- Create search indexes +CREATE INDEX timestamp_id ON logs (timestamp); +CREATE INDEX address_id ON logs (address); + +-- Create auth_key in hosts table for storing keys for DHCPv6 reconfigure. +ALTER TABLE hosts ADD COLUMN auth_key VARCHAR(16) DEFAULT NULL; + +-- Convert subnet-id values of 0 to NULL +UPDATE hosts SET dhcp4_subnet_id = NULL WHERE dhcp4_subnet_id = 0; +UPDATE dhcp4_options SET dhcp4_subnet_id = NULL WHERE dhcp4_subnet_id = 0; +UPDATE hosts SET dhcp6_subnet_id = NULL WHERE dhcp6_subnet_id = 0; +UPDATE dhcp6_options SET dhcp6_subnet_id = NULL WHERE dhcp6_subnet_id = 0; + +-- Set 5.0 schema version. +UPDATE schema_version + SET version = '5', minor = '0'; + +-- Schema 5.0 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_005.0_to_005.1.sh.in b/src/share/database/scripts/pgsql/upgrade_005.0_to_005.1.sh.in new file mode 100644 index 0000000..bd3f5d1 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_005.0_to_005.1.sh.in @@ -0,0 +1,52 @@ +#!/bin/sh + +# Copyright (C) 2019-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "5.0" ]; then + printf 'This script upgrades 5.0 to 5.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Put the auth key in hexadecimal (double size but far more user friendly). +ALTER TABLE hosts ALTER COLUMN auth_key TYPE VARCHAR(32); + +-- Set 5.1 schema version. +UPDATE schema_version + SET version = '5', minor = '1'; + +-- Schema 5.1a specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_005.1_to_006.0.sh.in b/src/share/database/scripts/pgsql/upgrade_005.1_to_006.0.sh.in new file mode 100644 index 0000000..b1bf2d3 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_005.1_to_006.0.sh.in @@ -0,0 +1,71 @@ +#!/bin/sh + +# Copyright (C) 2019-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "5.1" ]; then + printf 'This script upgrades 5.1 to 6.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Create a lower case hostname index for hosts. +CREATE INDEX hosts_by_hostname ON hosts (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Create a hostname index for lease4. +CREATE INDEX lease4_by_hostname ON lease4 (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Create a hostname index for lease6. +CREATE INDEX lease6_by_hostname ON lease6 (lower(hostname)) +WHERE hostname IS NOT NULL; + +-- Move to lower case hostnames in lease4 table. +-- Not required so in comment +-- UPDATE lease4 SET hostname = lower(hostname) +-- WHERE lower(hostname) != hostname; + +-- Move to lower case hostnames in lease6 table. +-- Not required so in comment +-- UPDATE lease6 SET hostname = lower(hostname) +-- WHERE lower(hostname) != hostname; + +-- Set 6.0 schema version. +UPDATE schema_version + SET version = '6', minor = '0'; + +-- Schema 5.1a specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_006.0_to_006.1.sh.in b/src/share/database/scripts/pgsql/upgrade_006.0_to_006.1.sh.in new file mode 100644 index 0000000..b036c52 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_006.0_to_006.1.sh.in @@ -0,0 +1,139 @@ +#!/bin/sh + +# Copyright (C) 2020-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "6.0" ]; then + printf 'This script upgrades 6.0 to 6.1. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- Fix v4 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_update () RETURNS trigger AS \$stat_lease4_update\$ +BEGIN + IF OLD.subnet_id != NEW.subnet_id OR OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease4_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (NEW.subnet_id, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease4_update\$ LANGUAGE plpgsql; + +-- +-- Fix the v4 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease4_delete () RETURNS trigger AS \$stat_lease4_delete\$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease4_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease4_delete\$ LANGUAGE plpgsql; + +-- +-- Fix v6 update trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_update () RETURNS trigger AS \$stat_lease6_update\$ +BEGIN + IF OLD.subnet_id != NEW.subnet_id OR + OLD.lease_type != NEW.lease_type OR + OLD.state != NEW.state THEN + IF OLD.state < 2 THEN + -- Decrement the old state count if record exists + UPDATE lease6_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND state = OLD.state; + END IF; + + IF NEW.state < 2 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = NEW.subnet_id AND lease_type = NEW.lease_type + AND state = NEW.state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (NEW.subnet_id, NEW.lease_type, NEW.state, 1); + END IF; + END IF; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease6_update\$ LANGUAGE plpgsql; + +-- +-- Fix the v6 delete trigger procedure +CREATE OR REPLACE FUNCTION proc_stat_lease6_delete() RETURNS trigger AS \$stat_lease6_delete\$ +BEGIN + IF OLD.state < 2 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = OLD.subnet_id AND lease_type = OLD.lease_type + AND OLD.state = state; + END IF; + + -- Return is ignored since this is an after insert + RETURN NULL; +END; +\$stat_lease6_delete\$ LANGUAGE plpgsql; + +-- Set 6.1 schema version. +UPDATE schema_version + SET version = '6', minor = '1'; + +-- Schema 6.1 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_006.1_to_006.2.sh.in b/src/share/database/scripts/pgsql/upgrade_006.1_to_006.2.sh.in new file mode 100644 index 0000000..76bb8cd --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_006.1_to_006.2.sh.in @@ -0,0 +1,71 @@ +#!/bin/sh + +# Copyright (C) 2020-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "6.1" ]; then + printf 'This script upgrades 6.1 to 6.2. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +-- Starting from this version we allow specifying multiple IP reservations +-- for the same address in certain DHCP configurations. The server may check +-- uniqueness of the IP addresses on its own. This is no longer checked at +-- the database level to facilitate the use cases when a single host may +-- get the same reserved IP address via different interfaces. + +-- Replace the unique index with non-unique index so the queries for +-- hosts by IPv4 address are still efficient. +-- +-- Note we have introduced a bug a while ago which causes the index to have +-- different names depending on whether the schema was created via the +-- dhcpdb_create.pgsql script or via updates. Therefore, let's make sure +-- that we drop the index regardless of its current name. +DROP INDEX IF EXISTS key_dhcp4_ipv4_address_subnet_id; +DROP INDEX IF EXISTS hosts_dhcp4_ipv4_address_subnet_id; +CREATE INDEX key_dhcp4_ipv4_address_subnet_id + ON hosts (ipv4_address ASC, dhcp4_subnet_id ASC); + +-- Replace the unique index with non-unique index so the queries for +-- hosts by IPv6 address are still efficient. +ALTER TABLE ipv6_reservations DROP CONSTRAINT IF EXISTS key_dhcp6_address_prefix_len; +CREATE INDEX key_dhcp6_address_prefix_len + ON ipv6_reservations (address ASC, prefix_len ASC); + +-- Update the schema version number +UPDATE schema_version + SET version = '6', minor = '2'; + +-- Schema 6.2 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_006.2_to_007.0.sh.in b/src/share/database/scripts/pgsql/upgrade_006.2_to_007.0.sh.in new file mode 100644 index 0000000..0feeb0a --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_006.2_to_007.0.sh.in @@ -0,0 +1,2807 @@ +#!/bin/sh + +# Copyright (C) 2021-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "6.2" ]; then + printf 'This script upgrades 6.2 to 7.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF + +START TRANSACTION; + +-- This starts schema update to 7.0. It adds a lot (20+) of tables for the config backend. + + +-- Adding on update trigger in MySQL is as easy as using this column definition in CREATE TABLE: +-- modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, +-- Sadly, Postgres has its own convoluted way of doing this. Luckily, the update pattern is +-- the same in many tables, so we can define the trigger function once and the use it everywhere. + +-- First, we need to define a function that will do the actual job. +-- This is used in many, many tables. +CREATE OR REPLACE FUNCTION modification_ts_update() + RETURNS trigger AS \$modification_ts_update\$ + BEGIN + new.modification_ts = CURRENT_TIMESTAMP; + RETURN NULL; + END; + +-- Second, we need to specify which language it was written in. +\$modification_ts_update\$ LANGUAGE plpgsql; + + +-- Create table modification and insert values for modification types. +CREATE TABLE modification ( + id smallint NOT NULL, + modification_type VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +); +INSERT INTO modification VALUES (0,'create'), (1,'update'), (2,'delete'); + + + +-- Now create the table that holds different parameter data types. +CREATE TABLE parameter_data_type ( + id smallint NOT NULL, + name VARCHAR(32) NOT NULL, + PRIMARY KEY (id) +); +INSERT INTO parameter_data_type VALUES + (0,'integer'), + (1,'real'), + (2,'boolean'), + (4,'string'); + + + +-- This table doesn't exist in MySQL. However, it's nice to have an enum that explains what the values +-- in ddns_replace_client_name field in the dhcp{4,6}_shared_network table means. +CREATE TABLE ddns_replace_client_name_types ( + type INT8 PRIMARY KEY NOT NULL, + name VARCHAR(32) +); +-- See enum ReplaceClientNameMode in src/lib/dhcpsrv/d2_client_cfg.h +INSERT INTO ddns_replace_client_name_types (type, name) VALUES + (0, 'RCM_NEVER'), + (1, 'RCM_ALWAYS'), + (2, 'RCM_WHEN_PRESENT'), + (3, 'RCM_WHEN_NOT_PRESENT'); + + + +-- Create table for DHCPv6 servers +CREATE TABLE dhcp6_server ( + id SERIAL PRIMARY KEY NOT NULL, + tag VARCHAR(64) NOT NULL, + description TEXT DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(tag) +); +CREATE INDEX dhcp6_server_idx1 ON dhcp6_server (modification_ts); +CREATE UNIQUE INDEX dhcp6_server_idx2 ON dhcp6_server(tag); +CREATE TRIGGER dhcp6_server_modification_ts_update + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +INSERT INTO dhcp6_server (tag, description) VALUES ('all','special type: all servers'); + +-- Create a table for storing IPv6 shared networks +CREATE TABLE dhcp6_shared_network ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + preferred_lifetime BIGINT DEFAULT NULL, + rapid_commit BOOLEAN DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + interface_id BYTEA DEFAULT NULL, -- 128 bytes + min_preferred_lifetime BIGINT DEFAULT NULL, + max_preferred_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); +CREATE INDEX dhcp6_shared_network_idx1 ON dhcp6_shared_network (name); + +CREATE TRIGGER dhcp6_shared_network_modification_ts_update + AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now we need to create a relationship between defined shared networks and the servers +CREATE TABLE dhcp6_shared_network_server ( + shared_network_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (shared_network_id, server_id), + CONSTRAINT fk_dhcp6_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp6_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp6_shared_network_server_idx1 ON dhcp6_shared_network_server (modification_ts); +CREATE INDEX dhcp6_shared_network_server_idx2 ON dhcp6_shared_network_server (server_id); + + + +-- Create a list of IPv6 subnets +CREATE TABLE dhcp6_subnet ( + subnet_id BIGINT PRIMARY KEY NOT NULL, + subnet_prefix VARCHAR(64) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + preferred_lifetime BIGINT DEFAULT NULL, + rapid_commit BOOLEAN DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + interface_id BYTEA DEFAULT NULL, + min_preferred_lifetime BIGINT DEFAULT NULL, + max_preferred_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE TRIGGER dhcp6_subnet_modification_ts_update + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +CREATE INDEX dhcp6_subnet_idx1 ON dhcp6_subnet (modification_ts); +CREATE INDEX dhcp6_subnet_idx2 ON dhcp6_subnet (shared_network_name); + + + +-- Create a table that holds all address pools in IPv6. +CREATE TABLE dhcp6_pool ( + id SERIAL PRIMARY KEY NOT NULL, + start_address inet NOT NULL, + end_address inet NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) +); +CREATE INDEX dhcp6_pool_idx1 ON dhcp6_pool (modification_ts); +CREATE INDEX dhcp6_pool_idx2 ON dhcp6_pool (subnet_id); + +CREATE TRIGGER dhcp6_pool_modification_ts_update + AFTER UPDATE ON dhcp6_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- And now the same, but for PD pools. +CREATE TABLE dhcp6_pd_pool ( + id SERIAL PRIMARY KEY NOT NULL, + prefix VARCHAR(45) NOT NULL, + prefix_length SMALLINT NOT NULL, + delegated_prefix_length SMALLINT NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + excluded_prefix VARCHAR(45) DEFAULT NULL, + excluded_prefix_length SMALLINT NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet(subnet_id) +); + +CREATE INDEX dhcp6_pd_pool_idx1 ON dhcp6_pd_pool (modification_ts); +CREATE INDEX dhcp6_pd_pool_idx2 ON dhcp6_pd_pool (subnet_id); +CREATE TRIGGER dhcp6_pd_pool_modification_ts_update + AFTER UPDATE ON dhcp6_pd_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +CREATE TABLE dhcp6_subnet_server ( + subnet_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (subnet_id, server_id), + CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION, + UNIQUE (subnet_id, server_id) +); +CREATE INDEX dhcp6_subnet_server_idx1 ON dhcp6_subnet_server(server_id); +CREATE INDEX dhcp6_subnet_server_idx2 ON dhcp6_subnet_server(modification_ts); +CREATE TRIGGER dhcp6_subnet_server_modification_ts_update + AFTER UPDATE ON dhcp6_subnet_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Create table for storing global DHCPv6 parameters. +CREATE TABLE dhcp6_global_parameter ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) NOT NULL, + value TEXT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + parameter_type SMALLINT NOT NULL, + CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id) +); + +CREATE INDEX key_dhcp6_global_parameter_idx1 ON dhcp6_global_parameter(modification_ts); +CREATE INDEX key_dhcp6_global_parameter_idx2 ON dhcp6_global_parameter(name); + +CREATE TRIGGER dhcp6_global_parameter_modification_ts_update + AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +CREATE TABLE dhcp6_global_parameter_server ( + parameter_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (parameter_id, server_id), + CONSTRAINT fk_dhcp6_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp6_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server(id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX key_dhcp6_global_parameter_server_idx1 ON dhcp6_global_parameter_server(modification_ts); +CREATE TRIGGER dhcp6_global_parameter_server_modification_ts_update + AFTER UPDATE ON dhcp6_global_parameter_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Create a table for storing DHCPv6 options. +ALTER TABLE dhcp6_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT DEFAULT NULL, + ADD COLUMN pd_pool_id BIGINT DEFAULT NULL, + ADD CONSTRAINT fk_dhcp6_options_pd_pool FOREIGN KEY (pd_pool_id) + REFERENCES dhcp6_pd_pool(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp6_options_pool FOREIGN KEY (pool_id) + REFERENCES dhcp6_pool (id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp6_options_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE TRIGGER dhcp6_options_modification_ts_update + AFTER UPDATE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +-- Now create a table for associating defined options with servers. +CREATE TABLE dhcp6_options_server ( + option_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_id, server_id), + CONSTRAINT fk_dhcp6_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp6_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp6_options_server_idx1 ON dhcp6_options_server(server_id); +CREATE INDEX dhcp6_options_server_idx2 ON dhcp6_options_server(modification_ts); +CREATE TRIGGER dhcp6_options_server_modification_ts_update + AFTER UPDATE ON dhcp6_options_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- This table is for storing IPv6 option definitions +CREATE TABLE dhcp6_option_def ( + id SERIAL PRIMARY KEY UNIQUE NOT NULL, + code SMALLINT NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type SMALLINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + is_array BOOLEAN NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR DEFAULT NULL, + user_context JSON DEFAULT NULL +); +CREATE INDEX dhcp6_option_def_idx1 ON dhcp6_option_def(modification_ts); +CREATE INDEX dhcp6_option_def_idx2 ON dhcp6_option_def(code, space); +CREATE TRIGGER dhcp6_option_def_modification_ts_update + AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- and another table for storing relationship between option definitions and servers. +CREATE TABLE dhcp6_option_def_server ( + option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + server_id BIGINT NOT NULL REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_def_id, server_id) +); +CREATE TRIGGER dhcp6_option_def_server_modification_ts_update + AFTER UPDATE ON dhcp6_option_def_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Now create two tables for audit revisions... +CREATE TABLE dhcp6_audit_revision ( + id SERIAL PRIMARY KEY NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + log_message TEXT DEFAULT NULL, + server_id BIGINT DEFAULT NULL +); +CREATE TRIGGER dhcp6_audit_revision_modification_ts_update + AFTER UPDATE ON dhcp6_audit_revision + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- ... and the DHCPv6 audit itself. +CREATE TABLE dhcp6_audit ( + id SERIAL UNIQUE NOT NULL, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT NOT NULL, + modification_type SMALLINT NOT NULL, + revision_id BIGINT NOT NULL, + CONSTRAINT fk_dhcp6_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp6_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE +); +CREATE TRIGGER dhcp6_audit_modification_ts_update + AFTER UPDATE ON dhcp6_audit + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); +CREATE INDEX dhcp6_audit_idx1 ON dhcp6_audit (modification_type); +CREATE INDEX dhcp6_audit_idx2 ON dhcp6_audit (revision_id); + + +-- Create table for DHCPv4 servers +CREATE TABLE dhcp4_server ( + id SERIAL PRIMARY KEY NOT NULL, + tag VARCHAR(64) NOT NULL, + description TEXT DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(tag) +); +CREATE INDEX dhcp4_server_modification_ts ON dhcp6_server (modification_ts); +CREATE TRIGGER dhcp4_server_modification_ts_update + AFTER UPDATE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +INSERT INTO dhcp4_server (tag, description) VALUES ('all','special type: all servers'); + +-- Create table for storing global DHCPv4 parameters. +CREATE TABLE dhcp4_global_parameter ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) NOT NULL, + value TEXT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + parameter_type SMALLINT NOT NULL, + CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id) +); +CREATE INDEX dhcp4_global_parameter_idx1 ON dhcp4_global_parameter(modification_ts); +CREATE INDEX dhcp4_global_parameter_idx2 ON dhcp4_global_parameter(name); + +CREATE TRIGGER dhcp4_global_parameter_modification_ts_update + AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +-- and create mapping for the global DHCPv4 parameters mapping to servers +CREATE TABLE dhcp4_global_parameter_server ( + parameter_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (parameter_id, server_id), + CONSTRAINT fk_dhcp4_global_parameter_server_parameter_id FOREIGN KEY (parameter_id) + REFERENCES dhcp4_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_global_parameter_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server(id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX key_dhcp4_global_parameter_idx1 ON dhcp4_global_parameter_server(modification_ts); +CREATE TRIGGER dhcp4_global_parameter_server_modification_ts_update + AFTER UPDATE ON dhcp4_global_parameter_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Create a table for storing IPv4 shared networks +CREATE TABLE dhcp4_shared_network ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id BOOLEAN DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + authoritative BOOLEAN DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + boot_file_name VARCHAR(128) DEFAULT NULL, + next_server inet DEFAULT NULL, -- let's use type inet + server_hostname VARCHAR(64) DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE UNIQUE INDEX dhcp4_shared_network_idx1 ON dhcp4_shared_network (name); +CREATE INDEX dhcp4_shared_network_idx2 ON dhcp4_shared_network (modification_ts); + +CREATE TRIGGER dhcp4_shared_network_modification_ts_update + AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now we need to create a relationship between defined shared networks and the servers +CREATE TABLE dhcp4_shared_network_server ( + shared_network_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (shared_network_id, server_id), + CONSTRAINT fk_dhcp4_shared_network_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id) + REFERENCES dhcp4_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp4_shared_network_server_idx1 ON dhcp4_shared_network_server (modification_ts); +CREATE INDEX dhcp4_shared_network_server_idx2 ON dhcp4_shared_network_server (server_id); + + + +-- Create a list of IPv4 subnets +CREATE TABLE dhcp4_subnet ( + subnet_id BIGINT PRIMARY KEY NOT NULL, + subnet_prefix VARCHAR(64) UNIQUE NOT NULL, + interface_4o6 VARCHAR(128) DEFAULT NULL, + interface_id_4o6 VARCHAR(128) DEFAULT NULL, + subnet_4o6 VARCHAR(64) DEFAULT NULL, + boot_file_name VARCHAR(128) DEFAULT NULL, + client_class VARCHAR(128) DEFAULT NULL, + interface VARCHAR(128) DEFAULT NULL, + match_client_id BOOLEAN DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + next_server inet DEFAULT NULL, + rebind_timer BIGINT DEFAULT NULL, + relay TEXT DEFAULT NULL, + renew_timer BIGINT DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + server_hostname VARCHAR(64) DEFAULT NULL, + shared_network_name VARCHAR(128) DEFAULT NULL, + user_context JSON DEFAULT NULL, + valid_lifetime BIGINT DEFAULT NULL, + authoritative BOOLEAN DEFAULT NULL, + calculate_tee_times BOOLEAN DEFAULT NULL, + t1_percent float DEFAULT NULL, + t2_percent float DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + ddns_send_updates BOOLEAN DEFAULT NULL, + ddns_override_no_update BOOLEAN DEFAULT NULL, + ddns_override_client_update BOOLEAN DEFAULT NULL, + ddns_replace_client_name INT8 DEFAULT NULL, + ddns_generated_prefix VARCHAR(255) DEFAULT NULL, + ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL, + reservations_global BOOLEAN DEFAULT NULL, + reservations_in_subnet BOOLEAN DEFAULT NULL, + reservations_out_of_pool BOOLEAN DEFAULT NULL, + cache_threshold float DEFAULT NULL, + cache_max_age BIGINT DEFAULT NULL, + CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION, + CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name) + REFERENCES ddns_replace_client_name_types (type) +); + +CREATE TRIGGER dhcp4_subnet_modification_ts_update + AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + +CREATE INDEX dhcp4_subnet_idx1 ON dhcp4_subnet (modification_ts); +CREATE INDEX dhcp4_subnet_idx2 ON dhcp4_subnet (shared_network_name); + + + +CREATE TABLE dhcp4_subnet_server ( + subnet_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (subnet_id, server_id), + CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION, + UNIQUE (subnet_id, server_id) +); +CREATE INDEX dhcp4_subnet_server_idx1 ON dhcp4_subnet_server(server_id); +CREATE INDEX dhcp4_subnet_server_idx2 ON dhcp4_subnet_server(modification_ts); +CREATE TRIGGER dhcp4_subnet_server_modification_ts_update + AFTER UPDATE ON dhcp4_subnet_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Create a table that holds all address pools in IPv4. +CREATE TABLE dhcp4_pool ( + id SERIAL PRIMARY KEY NOT NULL, + start_address inet NOT NULL, + end_address inet NOT NULL, + subnet_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + client_class VARCHAR(128) DEFAULT NULL, + require_client_classes TEXT DEFAULT NULL, + user_context JSON DEFAULT NULL, + CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) +); +CREATE INDEX dhcp4_pool_idx1 ON dhcp4_pool (modification_ts); +CREATE INDEX dhcp4_pool_idx2 ON dhcp4_pool (subnet_id); + +CREATE TRIGGER dhcp4_pool_modification_ts_update + AFTER UPDATE ON dhcp4_pool + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- Create a table for storing DHCPv4 options. +ALTER TABLE dhcp4_options + ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL, + ADD COLUMN pool_id BIGINT DEFAULT NULL, + ADD COLUMN modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + ADD CONSTRAINT fk_dhcp4_options_pool FOREIGN KEY (pool_id) + REFERENCES dhcp4_pool (id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT fk_dhcp4_options_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE TRIGGER dhcp4_options_modification_ts_update + AFTER UPDATE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now create a table for associating defined v4 options with servers. +CREATE TABLE dhcp4_options_server ( + option_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_id, server_id), + CONSTRAINT fk_dhcp4_options_server_option_id FOREIGN KEY (option_id) + REFERENCES dhcp4_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_options_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX dhcp4_options_server_idx1 ON dhcp4_options_server(server_id); +CREATE INDEX dhcp4_options_server_idx2 ON dhcp4_options_server(modification_ts); +CREATE TRIGGER dhcp4_options_server_modification_ts_update + AFTER UPDATE ON dhcp4_options_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- This table is for storing IPv4 option definitions +CREATE TABLE dhcp4_option_def ( + id SERIAL PRIMARY KEY UNIQUE NOT NULL, + code SMALLINT NOT NULL, + name VARCHAR(128) NOT NULL, + space VARCHAR(128) NOT NULL, + type SMALLINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + is_array BOOLEAN NOT NULL, + encapsulate VARCHAR(128) NOT NULL, + record_types VARCHAR DEFAULT NULL, + user_context JSON DEFAULT NULL +); +CREATE INDEX dhcp4_option_def_idx1 ON dhcp4_option_def(modification_ts); +CREATE INDEX dhcp4_option_def_idx2 ON dhcp4_option_def(code, space); +CREATE TRIGGER dhcp4_option_def_modification_ts_update + AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- and another table for storing relationship between option definitions and servers. +CREATE TABLE dhcp4_option_def_server ( + option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + server_id BIGINT NOT NULL REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (option_def_id, server_id) +); +CREATE TRIGGER dhcp4_option_def_server_modification_ts_update + AFTER UPDATE ON dhcp4_option_def_server + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + + +-- Now create two tables for audit revisions... +CREATE TABLE dhcp4_audit_revision ( + id SERIAL PRIMARY KEY NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, + log_message TEXT DEFAULT NULL, + server_id BIGINT DEFAULT NULL +); +CREATE TRIGGER dhcp4_audit_revision_modification_ts_update + AFTER UPDATE ON dhcp4_audit_revision + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); + + +-- ... and the DHCPv4 audit itself. +CREATE TABLE dhcp4_audit ( + id SERIAL UNIQUE NOT NULL, + object_type VARCHAR(256) NOT NULL, + object_id BIGINT NOT NULL, + modification_type SMALLINT NOT NULL, + revision_id BIGINT NOT NULL, + CONSTRAINT fk_dhcp4_audit_modification_type FOREIGN KEY (modification_type) + REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dhcp4_audit_revision FOREIGN KEY (revision_id) + REFERENCES dhcp4_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE +); +CREATE TRIGGER dhcp4_audit_modification_ts_update + AFTER UPDATE ON dhcp4_audit + FOR EACH ROW EXECUTE PROCEDURE modification_ts_update(); +CREATE INDEX dhcp4_audit_idx1 ON dhcp4_audit (modification_type); +CREATE INDEX dhcp4_audit_idx2 ON dhcp4_audit (revision_id); + +-- Stores a TEXT value to a session variable +-- name name of session variable to set +-- value TEXT value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value TEXT) +RETURNS VOID +AS \$\$ +DECLARE +BEGIN + PERFORM set_config(name, value, false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;\$\$ +LANGUAGE plpgsql; + +-- Stores a BIGINT value to a session variable +-- Note the value converted to TEXT and then stored as Postgresql does +-- not support any other data type in session variables. +-- name name of session variable to set +-- value BIGINT value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value BIGINT) +RETURNS VOID +AS \$\$ +BEGIN + PERFORM set_config(name, cast(value as text), false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;\$\$ +LANGUAGE plpgsql; + +-- Stores a BOOLEAN value to a session variable +-- Note the value converted to TEXT and then stored as Postgresql does +-- not support any other data type in session variables. +-- name name of session variable to set +-- value BOOLEAN value to store +CREATE OR REPLACE FUNCTION set_session_value(name text, value BOOLEAN) +RETURNS VOID +AS \$\$ +BEGIN + PERFORM set_config(name, cast(value as text), false); + RETURN; + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate; +END;\$\$ +LANGUAGE plpgsql; + + +-- Fetches a text value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns NULL. +-- Postgresql allows you to store custom session values +-- but throws an exception if they have not first been +-- set. This allows us to be a bit more graceful. +CREATE OR REPLACE FUNCTION get_session_value(name TEXT) +RETURNS TEXT +AS \$\$ +DECLARE + text_value TEXT := ''; +BEGIN + text_value = current_setting(name); + RETURN(text_value); + + EXCEPTION + WHEN undefined_object THEN + -- Variable has not been initialized so return NULL + RETURN NULL; + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_value(%, TEXT) failed, sqlstate: %', name, sqlstate; +END;\$\$ +LANGUAGE plpgsql; + +-- Fetches an BIGINT value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns zero. +CREATE OR REPLACE FUNCTION get_session_big_int(name text) +RETURNS BIGINT +AS \$\$ +DECLARE + int_value BIGINT := 0; + text_value TEXT := ''; +BEGIN + text_value = get_session_value(name); + IF text_value is NULL or text_value = '' THEN + RETURN(0); + END IF; + + int_value = cast(text_value as BIGINT); + RETURN(int_value); + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_big_int(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate; + +END;\$\$ +LANGUAGE plpgsql; + +-- Fetches an BOOLEAN value from the session configuration. +-- param name name of the session variable to fetch +-- If the name is not found it returns zero. +CREATE OR REPLACE FUNCTION get_session_boolean(name text) +RETURNS BOOLEAN +AS \$\$ +DECLARE + bool_value BOOLEAN := false; + text_value TEXT := ''; +BEGIN + text_value = get_session_value(name); + IF text_value is NULL or text_value = '' THEN + RETURN(false); + END IF; + + bool_value = cast(text_value as BOOLEAN); + RETURN(bool_value); + + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'get_session_boolean(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate; + +END;\$\$ +LANGUAGE plpgsql; + + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditRevisionDHCP4(audit_ts TIMESTAMP WITH TIME ZONE, + server_tag VARCHAR(64), + audit_log_message TEXT, + cascade_transaction BOOLEAN) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + disable_audit BOOLEAN := false; + audit_revision_id BIGINT; + srv_id BIGINT; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + SELECT id INTO srv_id FROM dhcp4_server WHERE tag = server_tag; + INSERT INTO dhcp4_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id; + + -- Update pertinent session variables. + PERFORM set_session_value('kea.audit_revision_id', audit_revision_id); + PERFORM set_session_value('kea.cascade_transaction', cascade_transaction); + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp4_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. 'create', 'update' or +-- 'delete'. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditEntryDHCP4(object_type_val VARCHAR(256), + object_id_val BIGINT, + modification_type_val VARCHAR(32)) +RETURNS VOID +LANGUAGE plpgsql +as \$\$ +DECLARE + audit_revision_id BIGINT; + disable_audit BOOLEAN := false; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + + IF disable_audit IS NULL OR disable_audit = false THEN + -- Fetch session value most recently created audit_revision_id. + audit_revision_id := get_session_big_int('kea.audit_revision_id'); + INSERT INTO dhcp4_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, + (SELECT id FROM modification WHERE modification_type = modification_type_val), + audit_revision_id); + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv4 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp4_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + test TEXT, + next_server INET DEFAULT NULL, + server_hostname VARCHAR(128) DEFAULT NULL, + boot_file_name VARCHAR(512) DEFAULT NULL, + only_if_required BOOLEAN NOT NULL DEFAULT false, + valid_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + depend_on_known_directly BOOLEAN NOT NULL DEFAULT false, + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX key_dhcp4_client_class_modification_ts on dhcp4_client_class (modification_ts); + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp4_client_class table has a corresponding row +-- in the dhcp4_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp4_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp4_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp4_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_order ( + class_id BIGINT PRIMARY KEY NOT NULL, + order_index BIGINT NOT NULL, + depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false, + CONSTRAINT fk_dhcp4_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE +); + +CREATE INDEX key_dhcp4_client_class_order_index on dhcp4_client_class_order (order_index); + + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass4Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BIGINT := 0; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp4_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp4_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- ON CONFLICT required 9.5 or later + UPDATE dhcp4_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Trigger procedure to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AINS() RETURNS trigger AS \$dhcp4_client_class_AINS\$ +BEGIN + PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, NULL); + PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp4_client_class_AINS\$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class insert trigger +CREATE TRIGGER dhcp4_client_class_AINS + AFTER INSERT ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AINS(); + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AUPD() RETURNS trigger AS \$dhcp4_client_class_AUPD\$ +BEGIN + PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly); + PERFORM set_session_value('kea.client_class_id', NEW.id); + PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp4_client_class_AUPD\$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class update insert trigger +CREATE TRIGGER dhcp4_client_class_AUPD + AFTER UPDATE ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AUPD(); + +-- ----------------------------------------------------------------------- +-- Trigger procedure to create the audit entry for client class delete. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_ADEL() RETURNS trigger AS \$dhcp4_client_class_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_client_class', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp4_client_class_ADEL\$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class delete trigger +CREATE TRIGGER dhcp4_client_class_ADEL + AFTER DELETE ON dhcp4_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_ADEL(); + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp4_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp4_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_dependency ( + class_id BIGINT PRIMARY KEY NOT NULL, + dependency_id BIGINT NOT NULL, + + CONSTRAINT dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp4_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp4_client_class (id) +); + +CREATE INDEX dhcp4_client_class_dependency_id_idx on dhcp4_client_class_dependency (dependency_id); + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - p_class_id id client class, +-- - p_dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassDependency(p_class_id BIGINT, + p_dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + class_index BIGINT; + dependency_index BIGINT; +BEGIN + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF p_class_id IS NULL THEN + RAISE EXCEPTION 'Client class id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + IF p_dependency_id IS NULL THEN + RAISE EXCEPTION 'Class dependency id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Dependencies on self make no sense. + IF p_class_id = p_dependency_id THEN + RAISE EXCEPTION 'Client class must not have dependency on self.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of our class in the hierarchy. + SELECT o.order_index INTO class_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_class_id; + + IF class_index IS NULL THEN + RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of the dependency. + SELECT o.order_index INTO dependency_index FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_dependency_id; + + IF dependency_index IS NULL THEN + RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + RAISE EXCEPTION + 'Client class with id % must not depend on class defined later with id %', + p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp4_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_server AS t1 + LEFT JOIN dhcp4_client_class_server AS t2 + ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = p_class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unmet dependencies for client class with id %', class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + RETURN; +END;\$\$; + + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_check_dependency_BINS() + RETURNS trigger AS \$dhcp4_client_class_check_dependency_BINS\$ +BEGIN + PERFORM checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +\$dhcp4_client_class_check_dependency_BINS\$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class_check_dependency_BINS before insert trigger. +CREATE TRIGGER dhcp4_client_class_check_dependency_BINS + BEFORE INSERT ON dhcp4_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_check_dependency_BINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION updateDHCPv4ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + dependency BOOLEAN; +BEGIN + -- Check if the dependency class references KNOWN/UNKNOWN. + SELECT depend_on_known_directly INTO dependency FROM dhcp4_client_class + WHERE id = dependency_id; + + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = false THEN + SELECT depend_on_known_indirectly INTO dependency FROM dhcp4_client_class_order + WHERE class_id = dependency_id; + END IF; + + IF dependency = true THEN + UPDATE dhcp4_client_class_order + SET depend_on_known_indirectly = true + WHERE class_id = client_class_id; + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_dependency_AINS() + RETURNS TRIGGER AS \$dhcp4_client_class_dependency_AINS\$ +BEGIN + PERFORM updateDHCPv4ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +\$dhcp4_client_class_dependency_AINS\$ +LANGUAGE plpgsql; + +-- Create dhcp4_client_class_check_dependency_AINS after insert trigger. +CREATE TRIGGER dhcp4_client_class_dependency_AINS + AFTER INSERT ON dhcp4_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_dependency_AINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv4 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassKnownDependencyChange() +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + depended BOOLEAN := false; + depends BOOLEAN := false; + client_class_id BIGINT; + depend_on_known_directly BOOLEAN; + depend_on_known_indirectly BOOLEAN; +BEGIN + + -- Session variables are set upon a client class update. + client_class_id := get_session_big_int('kea.client_class_id'); + IF client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency + WHERE dependency_id = client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly'); + depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly'); + IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN + SET depended = true; + END IF; + + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SELECT depend_on_known_directly INTO depends FROM dhcp4_client_class + WHERE id = client_class_id; + + -- If it doesn't depend directly, check indirect dependencies. + IF depends = false THEN + SELECT depend_on_known_indirectly INTO depends FROM dhcp4_client_class_order + WHERE class_id = client_class_id; + END IF; + + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + END IF; + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv4 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp4_client_class_server ( + class_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + CONSTRAINT fk_dhcp4_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp4_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) +); + +CREATE INDEX fk_dhcp4_client_class_server_id ON dhcp4_client_class_server (server_id); + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit_revision table and sets appropriate session +-- variables to be used while creating the audit entries +-- by triggers. This procedure should be called at the +-- beginning of a transaction which modifies configuration +-- data in the database, e.g. when new subnet is added. +-- +-- Parameters: +-- - audit_ts timestamp to be associated with the audit +-- revision. +-- - server_tag is used to retrieve the server_id which +-- associates the changes applied with the particular +-- server or all servers. +-- - audit_log_message is a log message associates with +-- the audit revision. +-- - cascade_transaction is assigned to a session +-- variable which is used in some triggers to determine +-- if the audit entry should be created for them or +-- not. Specifically, this is used when DHCP options +-- are inserted, updated or deleted. If such modification +-- is a part of the larger change (e.g. change in the +-- subnet the options belong to) the dedicated audit +-- entry for options must not be created. On the other +-- hand, if the global option is being added, the +-- audit entry for the option must be created because +-- it is the sole object modified in that case. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditRevisionDHCP6(audit_ts TIMESTAMP WITH TIME ZONE, + server_tag VARCHAR(64), + audit_log_message TEXT, + cascade_transaction BOOLEAN) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + disable_audit BOOLEAN := false; + audit_revision_id BIGINT; + srv_id BIGINT; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + SELECT id INTO srv_id FROM dhcp6_server WHERE tag = server_tag; + INSERT INTO dhcp6_audit_revision (modification_ts, server_id, log_message) + VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id; + + -- Update pertinent session variables. + PERFORM set_session_value('kea.audit_revision_id', audit_revision_id); + PERFORM set_session_value('kea.cascade_transaction', cascade_transaction); + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------- +-- Stored procedure which creates a new entry in the +-- dhcp6_audit table. It should be called from the +-- triggers of the tables where the config modifications +-- are applied. The audit_revision_id variable contains +-- the revision id to be placed in the audit entries. +-- +-- The following parameters are passed to this procedure: +-- - object_type_val: name of the table to be associated +-- with the applied changes. +-- - object_id_val: identifier of the modified object in +-- that table. +-- - modification_type_val: string value indicating the +-- type of the change, i.e. 'create', 'update' or +-- 'delete'. +-- Session variable disable_audit is used to disable +-- the procedure when wiping the database during +-- unit tests. This avoids issues with revision_id +-- being null. +-- ---------------------------------------------------- +CREATE OR REPLACE FUNCTION createAuditEntryDHCP6(object_type_val VARCHAR(256), + object_id_val BIGINT, + modification_type_val VARCHAR(32)) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + audit_revision_id BIGINT; + disable_audit BOOLEAN := false; +BEGIN + -- Fetch session value for disable_audit. + disable_audit := get_session_boolean('kea.disable_audit'); + IF disable_audit = false THEN + -- Fetch session value most recently created audit_revision_id. + audit_revision_id := get_session_big_int('kea.audit_revision_id'); + INSERT INTO dhcp6_audit (object_type, object_id, modification_type, revision_id) + VALUES (object_type_val, object_id_val, + (SELECT id FROM modification WHERE modification_type = modification_type_val), + audit_revision_id); + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Create a table holding the DHCPv6 client classes. Most table +-- columns map directly to respective client class properties in +-- Kea configuration. The depend_on_known_directly column is +-- explicitly set in an insert or update statement to indicate +-- if the client class directly depends on KNOWN or UNKNOWN +-- built-in classes. A caller should determine it by evaluating +-- a test expression before inserting or updating the client +-- class in the database. The nullable follow_class_name column +-- can be used for positioning the inserted or updated client +-- class within the class hierarchy. Set this column value to +-- an existing class name, after which this class should be +-- placed in the class hierarchy. See dhcp6_client_class_order +-- description for the details of how classes are ordered. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(128) UNIQUE NOT NULL, + test TEXT, + only_if_required BOOLEAN NOT NULL DEFAULT false, + valid_lifetime BIGINT DEFAULT NULL, + min_valid_lifetime BIGINT DEFAULT NULL, + max_valid_lifetime BIGINT DEFAULT NULL, + depend_on_known_directly BOOLEAN NOT NULL DEFAULT false, + follow_class_name VARCHAR(128) DEFAULT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX key_dhcp6_client_class_modification_ts on dhcp6_client_class (modification_ts); + +-- ----------------------------------------------------------------------- +-- Create a table for ordering client classes and holding information +-- about indirect dependencies on KNOWN/UKNOWN built-in client classes. +-- Each class in the dhcp6_client_class table has a corresponding row +-- in the dhcp6_client_class_order table. A caller should not modify +-- the contents of this table. Its entries are automatically created +-- upon inserting or updating client classes in the dhcp6_client_classes +-- using triggers. The order_index designates the position of the client +-- class within the class hierarchy. If the follow_class_name value of +-- the dhcp6_client_class table is set to NULL, the client class is +-- appended at the end of the hierarchy. The assigned order_index +-- value for that class is set to a maximum current value + 1. +-- If the follow_client_class specifies a name of an existing class, +-- the generated order_index is set to an id of that class + 1, and +-- the order_index values of the later classes are incremented by 1. +-- The depend_on_known_indirectly column holds a boolean value indicating +-- whether the given class depends on KNOWN/UKNOWN built-in classes +-- via other classes, i.e. it depends on classes that directly or +-- indirectly depend on these built-ins. This value is auto-generated +-- by a trigger on the dhcp6_client_class_dependency table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_order ( + class_id BIGINT PRIMARY KEY NOT NULL, + order_index BIGINT NOT NULL, + depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false, + CONSTRAINT fk_dhcp6_client_class_order_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE +); + +CREATE INDEX key_dhcp6_client_class_order_index on dhcp6_client_class_order (order_index); + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass6Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BIGINT := 0; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp6_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp6_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp6_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, 0); + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Trigger procedure to position an inserted class within the class hierarchy +-- and create audit. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AINS() RETURNS trigger AS \$dhcp6_client_class_AINS\$ +BEGIN + PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, NULL); + PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp6_client_class_AINS\$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class insert trigger +CREATE TRIGGER dhcp6_client_class_AINS + AFTER INSERT ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AINS(); + +-- ----------------------------------------------------------------------- +-- Trigger to position an updated class within the class hierarchy, +-- create audit and remember the direct dependency on the +-- KNOWN/UNKNOWN built-in classes before the class update. +-- When updating a client class, it is very important to ensure that +-- its dependency on KNOWN or UNKNOWN built-in client classes is not +-- changed. It is because there may be other classes that depend on +-- these built-ins via this class. Changing the dependency would break +-- the chain of dependencies for other classes. Here, we store the +-- information about the dependency in the session variables. Their +-- values will be compared with the new dependencies after an update. +-- If they change, an error will be signaled. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AUPD() RETURNS trigger AS \$dhcp6_client_class_AUPD\$ +BEGIN + PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly); + PERFORM set_session_value('kea.client_class_id', NEW.id); + PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name); + PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp6_client_class_AUPD\$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class update insert trigger +CREATE TRIGGER dhcp6_client_class_AUPD + AFTER UPDATE ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AUPD(); + +-- ----------------------------------------------------------------------- +-- Trigger procedure to create the audit entry for client class delete. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_ADEL() RETURNS trigger AS \$dhcp6_client_class_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_client_class', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp6_client_class_ADEL\$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class delete trigger +CREATE TRIGGER dhcp6_client_class_ADEL + AFTER DELETE ON dhcp6_client_class + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_ADEL(); + +-- ----------------------------------------------------------------------- +-- Create a table associating client classes stored in the +-- dhcp6_client_class table with their dependencies. There is +-- an M:N relationship between these tables. Each class may have +-- many dependencies (created using member operator in test expression), +-- and each class may be a dependency for many other classes. A caller +-- is responsible for inserting dependencies for a class after inserting +-- or updating it in the dhcp6_client_class table. A caller should +-- delete all existing dependencies for an updated client class, evaluate +-- test expression to discover new dependencies (in case test expression +-- has changed), and insert new dependencies to this table. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_dependency ( + class_id BIGINT PRIMARY KEY NOT NULL, + dependency_id BIGINT NOT NULL, + + CONSTRAINT dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) ON DELETE CASCADE, + CONSTRAINT dhcp6_client_class_dependency_id FOREIGN KEY (dependency_id) + REFERENCES dhcp6_client_class (id) +); + +CREATE INDEX dhcp6_client_class_dependency_id_idx on dhcp6_client_class_dependency (dependency_id); + +-- ----------------------------------------------------------------------- +-- Stored procedure verifying if class dependency is met. It includes +-- checking if referenced classes exist, are associated with the same +-- server or all servers, and are defined before the class specified with +-- class_id. +-- +-- Parameters: +-- - p_class_id id client class, +-- - p_dependency_id id of the dependency. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassDependency(p_class_id BIGINT, + p_dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + class_index BIGINT; + dependency_index BIGINT; +BEGIN + -- We could check the same with a constraint but later in this + -- trigger we use this value to verify if the dependencies are + -- met. + IF p_class_id IS NULL THEN + RAISE EXCEPTION 'Client class id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + IF p_dependency_id IS NULL THEN + RAISE EXCEPTION 'Class dependency id must not be NULL.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Dependencies on self make no sense. + IF p_class_id = p_dependency_id THEN + RAISE EXCEPTION 'Client class must not have dependency on self.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of our class in the hierarchy. + SELECT o.order_index INTO class_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_class_id; + + IF class_index IS NULL THEN + RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check position of the dependency. + SELECT o.order_index INTO dependency_index FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id + WHERE c.id = p_dependency_id; + + IF dependency_index IS NULL THEN + RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The dependency must not be later than our class. + IF dependency_index > class_index THEN + RAISE EXCEPTION + 'Client class with id % must not depend on class defined later with id %', + p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- Check if all servers associated with the new class have dependent + -- classes configured. This catches the cases that class A belongs to + -- server1 and depends on class B which belongs only to server 2. + -- It is fine if the class B belongs to all servers in this case. + -- Make a SELECT on the dhcp6_client_class_server table to gather + -- all servers to which the class belongs. LEFT JOIN it with the + -- same table, selecting all records matching the dependency class + -- and the servers to which the new class belongs. If there are + -- any NULL records joined it implies that some dependencies are + -- not met (didn't find a dependency for at least one server). + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_server AS t1 + LEFT JOIN dhcp6_client_class_server AS t2 + ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id) + WHERE t1.class_id = p_class_id AND t2.server_id IS NULL + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unmet dependencies for client class with id %', p_class_id + USING ERRCODE = 'sql_routine_exception'; + END IF; + RETURN; +END;\$\$; + + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_check_dependency_BINS() + RETURNS trigger AS \$dhcp6_client_class_check_dependency_BINS\$ +BEGIN + PERFORM checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +\$dhcp6_client_class_check_dependency_BINS\$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class_check_dependency_BINS before insert trigger. +CREATE TRIGGER dhcp6_client_class_check_dependency_BINS + BEFORE INSERT ON dhcp6_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_check_dependency_BINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure setting client class indirect dependency on KNOWN or +-- UNKNOWN built-in classes by checking this flag for the client classes +-- on which it depends. +-- +-- Parameters: +-- - client_class_id id of the client class which dependency is set, +-- - dependency_id id of the client class on which the given class depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION updateDHCPv6ClientClassKnownDependency(client_class_id BIGINT, + dependency_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + dependency BOOLEAN; +BEGIN + -- Check if the dependency class references KNOWN/UNKNOWN. + SELECT depend_on_known_directly INTO dependency FROM dhcp6_client_class + WHERE id = dependency_id; + + -- If it doesn't, check if the dependency references KNOWN/UNKNOWN + -- indirectly (via other classes). + IF dependency = false THEN + SELECT depend_on_known_indirectly INTO dependency FROM dhcp6_client_class_order + WHERE class_id = dependency_id; + END IF; + + IF dependency = true THEN + UPDATE dhcp6_client_class_order + SET depend_on_known_indirectly = true + WHERE class_id = client_class_id; + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN +-- built-in classes by checking this flag for the client classes on which +-- it depends. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_dependency_AINS() + RETURNS TRIGGER AS \$dhcp6_client_class_dependency_AINS\$ +BEGIN + PERFORM updateDHCPv6ClientClassKnownDependency(NEW.class_id, NEW.dependency_id); + RETURN NULL; +END; +\$dhcp6_client_class_dependency_AINS\$ +LANGUAGE plpgsql; + +-- Create dhcp6_client_class_check_dependency_AINS after insert trigger. +CREATE TRIGGER dhcp6_client_class_dependency_AINS + AFTER INSERT ON dhcp6_client_class_dependency + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_dependency_AINS(); + +-- ----------------------------------------------------------------------- +-- Stored procedure to be executed before committing a transaction +-- updating a DHCPv6 client class. It verifies if the class dependency on +-- KNOWN or UNKNOWN built-in classes has changed as a result of the +-- update. It signals an error if it has changed and there is at least +-- one class depending on this class. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassKnownDependencyChange() +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + depended BOOLEAN := false; + depends BOOLEAN := false; + client_class_id BIGINT; + depend_on_known_directly BOOLEAN; + depend_on_known_indirectly BOOLEAN; +BEGIN + + -- Session variables are set upon a client class update. + client_class_id := get_session_big_int('kea.client_class_id'); + IF client_class_id IS NOT NULL THEN + -- Check if any of the classes depend on this class. If not, + -- it is ok to change the dependency on KNOWN/UNKNOWN. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency + WHERE dependency_id = client_class_id LIMIT 1 + ) THEN + -- Using the session variables, determine whether the client class + -- depended on KNOWN/UNKNOWN before the update. + depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly'); + depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly'); + IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN + SET depended = true; + END IF; + + -- Check if the client class depends on KNOWN/UNKNOWN after the update. + SELECT depend_on_known_directly INTO depends FROM dhcp6_client_class + WHERE id = client_class_id; + + -- If it doesn't depend directly, check indirect dependencies. + IF depends = false THEN + SELECT depend_on_known_indirectly INTO depends FROM dhcp6_client_class_order + WHERE class_id = client_class_id; + END IF; + + -- The resulting dependency on KNOWN/UNKNOWN must not change. + IF depended <> depends THEN + RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.' + USING ERRCODE = 'sql_routine_exception'; + END IF; + END IF; + END IF; + RETURN; +END;\$\$; + +-- ----------------------------------------------------------------------- +-- Create table matching DHCPv6 classes with the servers. +-- ----------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS dhcp6_client_class_server ( + class_id BIGINT NOT NULL, + server_id BIGINT NOT NULL, + modification_ts TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL, + PRIMARY KEY (class_id,server_id), + CONSTRAINT fk_dhcp6_client_class_class_id FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE, + CONSTRAINT fk_dhcp6_client_class_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) +); + +CREATE INDEX fk_dhcp6_client_class_server_id ON dhcp6_client_class_server (server_id); + +-- Trigger function for dhcp4_pool_BDEL called BEFORE DELETE on dhcp4_pool +-- It removes pool specific options upon removal of the pool. +CREATE OR REPLACE FUNCTION func_dhcp4_pool_BDEL() RETURNS TRIGGER AS \$dhcp4_pool_BDEL\$ +BEGIN + DELETE FROM dhcp4_options WHERE scope_id = 5 AND pool_id = OLD.id; + RETURN OLD; +END; +\$dhcp4_pool_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_pool_BDEL + BEFORE DELETE ON dhcp4_pool + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_pool_BDEL(); + +-- Trigger function for dhcp6_pool_BDEL called BEFORE DELETE on dhcp6_pool +-- It removes pool specific options upon removal of the pool. +CREATE OR REPLACE FUNCTION func_dhcp6_pool_BDEL() RETURNS TRIGGER AS \$dhcp6_pool_BDEL\$ +BEGIN + DELETE FROM dhcp6_options WHERE scope_id = 5 AND pool_id = OLD.id; + RETURN OLD; +END; +\$dhcp6_pool_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_pool_BDEL + BEFORE DELETE ON dhcp6_pool + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_pool_BDEL(); + +-- Trigger function for dhcp4_global_parameter_AINS called AFTER INSERT on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AINS() RETURNS TRIGGER AS \$dhcp4_global_parameter_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp4_global_parameter_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_AINS + AFTER INSERT ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AINS(); + + +-- Trigger function for dhcp4_global_parameter_AUPD called AFTER UPDATE on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AUPD() RETURNS TRIGGER AS \$dhcp4_global_parameter_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp4_global_parameter_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_AUPD + AFTER UPDATE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AUPD(); + + +-- Trigger function for dhcp4_global_parameter_ADEL called AFTER DELETE on dhcp4_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_ADEL() RETURNS TRIGGER AS \$dhcp4_global_parameter_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp4_global_parameter_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_global_parameter_ADEL + AFTER DELETE ON dhcp4_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_ADEL(); + +-- Trigger function for dhcp4_subnet_AINS called AFTER INSERT on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AINS() RETURNS TRIGGER AS \$dhcp4_subnet_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'create'); + RETURN NULL; +END; +\$dhcp4_subnet_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_AINS + AFTER INSERT ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AINS(); + + +-- Trigger function for dhcp4_subnet_AUPD called AFTER UPDATE on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AUPD() RETURNS TRIGGER AS \$dhcp4_subnet_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'update'); + RETURN NULL; +END; +\$dhcp4_subnet_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_AUPD + AFTER UPDATE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AUPD(); + + +-- Trigger function for dhcp4_shared_network_AINS called AFTER INSERT on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AINS() RETURNS TRIGGER AS \$dhcp4_shared_network_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp4_shared_network_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_AINS + AFTER INSERT ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AINS(); + +-- Trigger function for dhcp4_shared_network_AUPD called AFTER UPDATE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AUPD() RETURNS TRIGGER AS \$dhcp4_shared_network_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp4_shared_network_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_AUPD + AFTER UPDATE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AUPD(); + +-- Trigger function for dhcp4_shared_network_ADEL called AFTER DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_ADEL() RETURNS TRIGGER AS \$dhcp4_shared_network_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp4_shared_network_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_ADEL + AFTER DELETE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_ADEL(); + +-- Trigger function for dhcp4_option_def_AINS called AFTER INSERT on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AINS() RETURNS TRIGGER AS \$dhcp4_option_def_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp4_option_def_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_AINS + AFTER INSERT ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AINS(); + +-- Trigger function for dhcp4_option_def_AUPD called AFTER UPDATE on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AUPD() RETURNS TRIGGER AS \$dhcp4_option_def_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp4_option_def_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_AUPD + AFTER UPDATE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AUPD(); + +-- Trigger function for dhcp4_option_def_ADEL called AFTER DELETE on dhcp4_option_def +CREATE OR REPLACE FUNCTION func_dhcp4_option_def_ADEL() RETURNS TRIGGER AS \$dhcp4_option_def_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_option_def', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp4_option_def_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_option_def_ADEL + AFTER DELETE ON dhcp4_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_ADEL(); + +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: 'create', 'update' or 'delete' +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP4(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := true; + ct TEXT; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp4_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp4_options' table. + PERFORM createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;\$\$; + +-- Trigger function for dhcp4_options_AINS called AFTER INSERT on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_AINS() RETURNS TRIGGER AS \$dhcp4_options_AINS\$ +BEGIN + PERFORM createOptionAuditDHCP4('create', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + RETURN NULL; +END; +\$dhcp4_options_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_AINS + AFTER INSERT ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AINS(); + + +-- Trigger function for dhcp4_options_AUPD called AFTER UPDATE on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_AUPD() RETURNS TRIGGER AS \$dhcp4_options_AUPD\$ +BEGIN + PERFORM createOptionAuditDHCP4('update', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.modification_ts); + RETURN NULL; +END; +\$dhcp4_options_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_AUPD + AFTER UPDATE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AUPD(); + +-- Trigger function for dhcp4_options_ADEL called AFTER DELETE on dhcp4_options +CREATE OR REPLACE FUNCTION func_dhcp4_options_ADEL() RETURNS TRIGGER AS \$dhcp4_options_ADEL\$ +BEGIN + PERFORM createOptionAuditDHCP4('delete', OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + NOW()); + RETURN NULL; +END; +\$dhcp4_options_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_options_ADEL + AFTER DELETE ON dhcp4_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_ADEL(); + +-- Trigger function for dhcp6_global_parameter_AINS called AFTER INSERT on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AINS() RETURNS TRIGGER AS \$dhcp6_global_parameter_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp6_global_parameter_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_AINS + AFTER INSERT ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AINS(); + +-- Trigger function for dhcp6_global_parameter_AUPD called AFTER UPDATE on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AUPD() RETURNS TRIGGER AS \$dhcp6_global_parameter_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp6_global_parameter_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_AUPD + AFTER UPDATE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AUPD(); + +-- Trigger function for dhcp6_global_parameter_ADEL called AFTER DELETE on dhcp6_global_parameter +CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_ADEL() RETURNS TRIGGER AS \$dhcp6_global_parameter_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp6_global_parameter_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_global_parameter_ADEL + AFTER DELETE ON dhcp6_global_parameter + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_ADEL(); + +-- Trigger function for dhcp6_subnet_AINS called AFTER INSERT on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AINS() RETURNS TRIGGER AS \$dhcp6_subnet_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'create'); + RETURN NULL; +END; +\$dhcp6_subnet_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_AINS + AFTER INSERT ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AINS(); + +-- Trigger function for dhcp6_subnet_AUPD called AFTER UPDATE on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AUPD() RETURNS TRIGGER AS \$dhcp6_subnet_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'update'); + RETURN NULL; +END; +\$dhcp6_subnet_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_AUPD + AFTER UPDATE ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AUPD(); + +-- Trigger function for dhcp6_shared_network_AINS called AFTER INSERT on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AINS() RETURNS TRIGGER AS \$dhcp6_shared_network_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp6_shared_network_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_AINS + AFTER INSERT ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AINS(); + +-- Trigger function for dhcp6_shared_network_AUPD called AFTER UPDATE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AUPD() RETURNS TRIGGER AS \$dhcp6_shared_network_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp6_shared_network_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_AUPD + AFTER UPDATE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AUPD(); + +-- Trigger function for dhcp6_shared_network_ADEL called AFTER DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_ADEL() RETURNS TRIGGER AS \$dhcp6_shared_network_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp6_shared_network_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_ADEL + AFTER DELETE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_ADEL(); + +-- Trigger function for dhcp6_option_def_AINS called AFTER INSERT on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AINS() RETURNS TRIGGER AS \$dhcp6_option_def_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp6_option_def_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_AINS + AFTER INSERT ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AINS(); + +-- Trigger function for dhcp6_option_def_AUPD called AFTER UPDATE on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AUPD() RETURNS TRIGGER AS \$dhcp6_option_def_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp6_option_def_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_AUPD + AFTER UPDATE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AUPD(); + +-- Trigger function for dhcp6_option_def_ADEL called AFTER DELETE on dhcp6_option_def +CREATE OR REPLACE FUNCTION func_dhcp6_option_def_ADEL() RETURNS TRIGGER AS \$dhcp6_option_def_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_option_def', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp6_option_def_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_option_def_ADEL + AFTER DELETE ON dhcp6_option_def + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_ADEL(); + +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, + option_id INT, + subnet_id BIGINT, + host_id INT, + network_name VARCHAR(128), + pool_id BIGINT, + pd_pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := false; + +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, create + -- audit entry for the entire subnet, which indicates that + -- it should be treated as the subnet update. + PERFORM createAuditEntryDHCP6('dhcp6_subnet', subnet_id, 'update'); + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- create audit entry for the shared network which + -- indicates that it should be treated as the shared + -- network update. + SELECT id INTO snid FROM dhcp6_shared_network + WHERE name = network_name LIMIT 1; + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', snid, 'update'); + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update'); + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pd pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool + WHERE id = pd_pool_id; + PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update'); + END IF; + END IF; + RETURN; +END;\$\$; + +-- Trigger function for dhcp6_options_AINS called AFTER INSERT on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_AINS() RETURNS TRIGGER AS \$dhcp6_options_AINS\$ +BEGIN + PERFORM createOptionAuditDHCP6('create', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + RETURN NULL; +END; +\$dhcp6_options_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_AINS + AFTER INSERT ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AINS(); + +-- Trigger function for dhcp6_options_AUPD called AFTER UPDATE on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_AUPD() RETURNS TRIGGER AS \$dhcp6_options_AUPD\$ +BEGIN + PERFORM createOptionAuditDHCP6('update', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id, + NEW.host_id, NEW.shared_network_name, NEW.pool_id, + NEW.pd_pool_id, NEW.modification_ts); + RETURN NULL; +END; +\$dhcp6_options_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_AUPD + AFTER UPDATE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AUPD(); + + +-- Trigger function for dhcp6_options_ADEL called AFTER DELETE on dhcp6_options +CREATE OR REPLACE FUNCTION func_dhcp6_options_ADEL() RETURNS TRIGGER AS \$dhcp6_options_ADEL\$ +BEGIN + PERFORM createOptionAuditDHCP6('delete', OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id, + OLD.host_id, OLD.shared_network_name, OLD.pool_id, + OLD.pd_pool_id, NOW()); + RETURN NULL; +END; +\$dhcp6_options_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_options_ADEL + AFTER DELETE ON dhcp6_options + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_ADEL(); + + +-- Trigger function for dhcp4_server_AINS called AFTER INSERT on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_AINS() RETURNS TRIGGER AS \$dhcp4_server_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp4_server_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_AINS + AFTER INSERT ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AINS(); + + +-- Trigger function for dhcp4_server_AUPD called AFTER UPDATE on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_AUPD() RETURNS TRIGGER AS \$dhcp4_server_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp4_server_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_AUPD + AFTER UPDATE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AUPD(); + + +-- Trigger function for dhcp4_server_ADEL called AFTER DELETE on dhcp4_server +CREATE OR REPLACE FUNCTION func_dhcp4_server_ADEL() RETURNS TRIGGER AS \$dhcp4_server_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_server', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp4_server_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_server_ADEL + AFTER DELETE ON dhcp4_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_ADEL(); + + +-- Trigger function for dhcp6_server_AINS called AFTER INSERT on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_AINS() RETURNS TRIGGER AS \$dhcp6_server_AINS\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'create'); + RETURN NULL; +END; +\$dhcp6_server_AINS\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_AINS + AFTER INSERT ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AINS(); + + +-- Trigger function for dhcp6_server_AUPD called AFTER UPDATE on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_AUPD() RETURNS TRIGGER AS \$dhcp6_server_AUPD\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'update'); + RETURN NULL; +END; +\$dhcp6_server_AUPD\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_AUPD + AFTER UPDATE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AUPD(); + + +-- Trigger function for dhcp6_server_ADEL called AFTER DELETE on dhcp6_server +CREATE OR REPLACE FUNCTION func_dhcp6_server_ADEL() RETURNS TRIGGER AS \$dhcp6_server_ADEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_server', OLD.id, 'delete'); + RETURN NULL; +END; +\$dhcp6_server_ADEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_server_ADEL + AFTER DELETE ON dhcp6_server + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_ADEL(); + + +-- Trigger function for dhcp4_shared_network_BDEL called BEFORE DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp4_shared_network_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +\$dhcp4_shared_network_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_shared_network_BDEL + BEFORE DELETE ON dhcp4_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_BDEL(); + +-- Trigger function for dhcp4_subnet_BDEL called BEFORE DELETE on dhcp4_subnet +CREATE OR REPLACE FUNCTION func_dhcp4_subnet_BDEL() RETURNS TRIGGER AS \$dhcp4_subnet_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, 'delete'); + DELETE FROM dhcp4_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp4_options WHERE dhcp4_subnet_id = OLD.subnet_id; + RETURN OLD; +END; +\$dhcp4_subnet_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp4_subnet_BDEL + BEFORE DELETE ON dhcp4_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_BDEL(); + +-- Trigger function for dhcp6_shared_network_BDEL called BEFORE DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp6_shared_network_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +\$dhcp6_shared_network_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_shared_network_BDEL + BEFORE DELETE ON dhcp6_shared_network + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_BDEL(); + +-- Trigger function for dhcp6_subnet_BDEL called BEFORE DELETE on dhcp6_subnet +CREATE OR REPLACE FUNCTION func_dhcp6_subnet_BDEL() RETURNS TRIGGER AS \$dhcp6_subnet_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, 'delete'); + DELETE FROM dhcp6_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_pd_pool WHERE subnet_id = OLD.subnet_id; + DELETE FROM dhcp6_options WHERE dhcp6_subnet_id = OLD.subnet_id; + RETURN OLD; +END; +\$dhcp6_subnet_BDEL\$ +LANGUAGE plpgsql; + +CREATE TRIGGER dhcp6_subnet_BDEL + BEFORE DELETE ON dhcp6_subnet + FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_BDEL(); + +-- Trigger function for dhcp6_pd_pool_BDEL called BEFORE DELETE on dhcp6_pd_pool +CREATE OR REPLACE FUNCTION func_dhcp6_pd_pool_BDEL() RETURNS TRIGGER AS \$dhcp6_pd_pool_BDEL\$ +BEGIN + DELETE FROM dhcp6_options WHERE scope_id = 6 AND pd_pool_id = OLD.id; + RETURN OLD; +END; +\$dhcp6_pd_pool_BDEL\$ +LANGUAGE plpgsql; + +-- Update the schema version number +UPDATE schema_version + SET version = '7', minor = '0'; + +-- Schema 7.0 specification ends here. + +-- Commit the script transaction +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_007_to_008.sh.in b/src/share/database/scripts/pgsql/upgrade_007_to_008.sh.in new file mode 100644 index 0000000..fe18652 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_007_to_008.sh.in @@ -0,0 +1,514 @@ +#!/bin/sh + +# Copyright (C) 2021-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "7.0" ]; then + printf 'This script upgrades 7.0 to 8.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This starts schema update to 8.0. It adds a few missing elements for CB and +-- functions for kea-admin's lease-dump and lease-upload commands. + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv4 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp4_option_def + ADD COLUMN class_id BIGINT NULL DEFAULT NULL; + +ALTER TABLE dhcp4_option_def + ADD CONSTRAINT fk_dhcp4_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp4_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Extend the table holding DHCPv6 option definitions with a nullable +-- column matching option defintions with client classes. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_option_def + ADD COLUMN class_id BIGINT NULL DEFAULT NULL; + +ALTER TABLE dhcp6_option_def + ADD CONSTRAINT fk_dhcp6_option_def_client_class_id + FOREIGN KEY (class_id) + REFERENCES dhcp6_client_class (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + +-- ----------------------------------------------------------------------- +-- Add missing preferred_lifetime columns to dhcp6_client_class table. +-- ----------------------------------------------------------------------- +ALTER TABLE dhcp6_client_class + ADD COLUMN preferred_lifetime BIGINT DEFAULT NULL, + ADD COLUMN min_preferred_lifetime BIGINT DEFAULT NULL, + ADD COLUMN max_preferred_lifetime BIGINT DEFAULT NULL; + +-- ----------------------------------------------------------------------- +-- Add option scopes +-- ----------------------------------------------------------------------- +-- Add scope for shared network specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(4, 'shared-network'); + +-- Add scope for pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(5, 'pool'); + +-- Add scope for PD pool specific options. +INSERT INTO dhcp_option_scope (scope_id, scope_name) + VALUES(6, 'pd-pool'); + + +-- Drop the existing function, createOptionAuditDHCP6 so we can replace it +-- with one that has slightly different arguments. +DROP FUNCTION IF EXISTS createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, option_id INT, subnet_id BIGINT, + host_id INT, network_name VARCHAR(128), + pool_id BIGINT, pd_pool_id BIGINT, + modification_ts TIMESTAMP WITH TIME ZONE); + +-- ----------------------------------------------------- +-- +-- New version of the createOptionAuditDHCP6 stored +-- procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR(32), + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR(128), + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid VARCHAR(128); + sid BIGINT; + cascade_transaction BOOLEAN := false; + +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;\$\$; + +-- Fix mangled constraints on dhcp4_subnet_server table. +ALTER TABLE dhcp4_subnet_server + DROP CONSTRAINT fk_dhcp6_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION, + DROP CONSTRAINT fk_dhcp6_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION; + +-- Add missing foreign key indexes. PostgreSQL does not automatically create indexes for +-- foreign key constraints. These have been added using the basic guideline: +-- +-- If the constraint does not reference a static table (e.g. parameter_data_type), +-- and the referencing column is not the primary key or the first +-- column in the primary key, and does not already have an index, then an index +-- should be added to the table for the referencing column. +-- +-- dhcp6_global_parameter_server +CREATE INDEX fk_dhcp6_global_parameter_server_server_id ON dhcp6_global_parameter_server (server_id); + +-- dhcp6_options +-- Missing foreign key constraint and indexes +ALTER TABLE dhcp6_options ADD CONSTRAINT fk_dhcp6_options_subnet + FOREIGN KEY (dhcp6_subnet_id) + REFERENCES dhcp6_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE INDEX fk_dhcp6_options_subnet ON dhcp6_options (dhcp6_subnet_id); +CREATE INDEX fk_dhcp6_options_pd_pool ON dhcp6_options (pd_pool_id); +CREATE INDEX fk_dhcp6_options_pool ON dhcp6_options (pool_id); +CREATE INDEX fk_dhcp6_options_shared_network ON dhcp6_options (shared_network_name); + +-- dhcp6_option_def_server +-- Missing foreign key constraints and index +ALTER TABLE dhcp6_option_def_server + ADD CONSTRAINT fk_dhcp6_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + ADD CONSTRAINT fk_dhcp6_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION; + +CREATE INDEX fk_dhcp6_option_def_server_server_id ON dhcp6_option_def_server (server_id); + +-- dhcp6_option_def +CREATE INDEX fk_dhcp6_option_def_client_class_id ON dhcp6_option_def (class_id); + +-- dhcp4_global_parameter_server +CREATE INDEX fk_dhcp4_global_parameter_server_server_id ON dhcp4_global_parameter_server (server_id); + +-- dhcp4_options +-- Missing foreign key constraint and indexes +ALTER TABLE dhcp4_options ADD CONSTRAINT fk_dhcp4_options_subnet + FOREIGN KEY (dhcp4_subnet_id) + REFERENCES dhcp4_subnet(subnet_id) + ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE INDEX fk_dhcp4_options_subnet ON dhcp4_options (dhcp4_subnet_id); +CREATE INDEX fk_dhcp4_options_pool ON dhcp4_options (pool_id); +CREATE INDEX fk_dhcp4_options_shared_network ON dhcp4_options (shared_network_name); + +-- dhcp4_option_def_server +-- Missing foreign key constraints and index +ALTER TABLE dhcp4_option_def_server + ADD CONSTRAINT fk_dhcp4_option_def_server_option_def_id FOREIGN KEY (option_def_id) + REFERENCES dhcp4_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION, + ADD CONSTRAINT fk_dhcp4_option_def_server_server_id FOREIGN KEY (server_id) + REFERENCES dhcp4_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION; + +CREATE INDEX fk_dhcp4_option_def_server_server_id ON dhcp4_option_def_server (server_id); + +-- dhcp4_option_def +CREATE INDEX fk_dhcp4_option_def_client_class_id ON dhcp4_option_def (class_id); + +-- Create a function that separates groups of two hexadecimals +-- with colons. +CREATE OR REPLACE FUNCTION colonSeparatedHex(hex TEXT) +RETURNS TEXT +AS \$\$ +DECLARE + i INT := 3; + length INT := LENGTH(hex); + output TEXT; +BEGIN + -- Add a leading zero if the first octet has a single hexadecimal character. + IF MOD(length, 2) = 1 THEN + hex := CONCAT('0', hex); + length := length + 1; + END IF; + + -- Start with the first octet. + output := SUBSTR(hex, 1, 2); + + -- Add one octet at a time and a leading colon with each. + WHILE i < length LOOP + output := CONCAT(output, ':', SUBSTR(hex, i, 2)); + i := i + 2; + END LOOP; + + -- Memfile uses lowercase hexadecimals. + output := LOWER(output); + + RETURN output; +END +\$\$ LANGUAGE plpgsql; + +-- Modify the function to output a memfile-ready CSV file. +-- Some columns that are SMALLINT in the lease4 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +DROP FUNCTION IF EXISTS lease4DumpData(); +CREATE OR REPLACE FUNCTION lease4DumpData() +RETURNS TABLE ( + address INET, + hwaddr VARCHAR, + client_id VARCHAR, + valid_lifetime BIGINT, + expire BIGINT, + subnet_id BIGINT, + fqdn_fwd INT, + fqdn_rev INT, + hostname VARCHAR, + state INT8, + user_context VARCHAR +) AS \$\$ + SELECT + ('0.0.0.0'::inet + address), + colonSeparatedHex(encode(hwaddr, 'hex')), + colonSeparatedHex(encode(client_id, 'hex')), + valid_lifetime, + extract(epoch from expire)::bigint, + subnet_id, + fqdn_fwd::int, + fqdn_rev::int, + replace(hostname, ',', ','), + state, + replace(user_context, ',', ',') + FROM lease4 + ORDER BY address; +\$\$ LANGUAGE SQL; + +-- hwtype and hwaddr_source need to be last to match memfile format. +DROP FUNCTION IF EXISTS lease6DumpHeader(); +CREATE OR REPLACE FUNCTION lease6DumpHeader() +RETURNS TEXT AS \$\$ + SELECT CAST('address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,hwaddr,state,user_context,hwtype,hwaddr_source' AS TEXT) AS result; +\$\$ LANGUAGE SQL; + +-- Modify the function to output a memfile-ready CSV file. +-- Some columns that are SMALLINT in the lease6 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +DROP FUNCTION IF EXISTS lease6DumpData(); +CREATE OR REPLACE FUNCTION lease6DumpData() +RETURNS TABLE ( + address VARCHAR, + duid VARCHAR, + valid_lifetime BIGINT, + expire BIGINT, + subnet_id BIGINT, + pref_lifetime BIGINT, + lease_type SMALLINT, + iaid INT, + prefix_len SMALLINT, + fqdn_fwd INT, + fqdn_rev INT, + hostname VARCHAR, + hwaddr VARCHAR, + state INT8, + user_context VARCHAR, + hwtype SMALLINT, + hwaddr_source SMALLINT +) AS \$\$ + SELECT + address, + colonSeparatedHex(encode(duid, 'hex')), + valid_lifetime, + extract(epoch from expire)::bigint, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd::int, + fqdn_rev::int, + replace(hostname, ',', ','), + colonSeparatedHex(encode(hwaddr, 'hex')), + state, + replace(user_context, ',', ','), + hwtype, + hwaddr_source + FROM lease6 + ORDER BY address; +\$\$ LANGUAGE SQL; + +-- Create a procedure that inserts a v4 lease from memfile data. +-- Some columns that are SMALLINT in the lease4 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +CREATE OR REPLACE FUNCTION lease4Upload( + IN address VARCHAR, + IN hwaddr VARCHAR, + IN client_id VARCHAR, + IN valid_lifetime BIGINT, + IN expire BIGINT, + IN subnet_id BIGINT, + IN fqdn_fwd INT, + IN fqdn_rev INT, + IN hostname VARCHAR, + IN state INT8, + IN user_context VARCHAR +) RETURNS VOID AS \$\$ +BEGIN + INSERT INTO lease4 ( + address, + hwaddr, + client_id, + valid_lifetime, + expire, + subnet_id, + fqdn_fwd, + fqdn_rev, + hostname, + state, + user_context + ) VALUES ( + address::inet - '0.0.0.0'::inet, + decode(replace(hwaddr, ':', ''), 'hex'), + decode(replace(client_id, ':', ''), 'hex'), + valid_lifetime, + to_timestamp(expire), + subnet_id, + fqdn_fwd::int::boolean, + fqdn_rev::int::boolean, + replace(hostname, ',', ','), + state, + replace(user_context, ',', ',') + ); +END +\$\$ LANGUAGE plpgsql; + +-- Create a procedure that inserts a v6 lease from memfile data. +-- Some columns that are SMALLINT in the lease6 table have their type promoted +-- to INT in the declaration of this function for backwards compatibility with +-- PostgreSQL versions. +CREATE OR REPLACE FUNCTION lease6Upload( + IN address VARCHAR, + IN duid VARCHAR, + IN valid_lifetime BIGINT, + IN expire BIGINT, + IN subnet_id BIGINT, + IN pref_lifetime BIGINT, + IN lease_type INT, + IN iaid INT, + IN prefix_len INT, + IN fqdn_fwd INT, + IN fqdn_rev INT, + IN hostname VARCHAR, + IN hwaddr VARCHAR, + IN state INT8, + IN user_context VARCHAR, + IN hwtype INT, + IN hwaddr_source INT +) RETURNS VOID AS \$\$ +BEGIN + INSERT INTO lease6 ( + address, + duid, + valid_lifetime, + expire, + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd, + fqdn_rev, + hostname, + hwaddr, + state, + user_context, + hwtype, + hwaddr_source + ) VALUES ( + address, + decode(replace(duid, ':', ''), 'hex'), + valid_lifetime, + to_timestamp(expire), + subnet_id, + pref_lifetime, + lease_type, + iaid, + prefix_len, + fqdn_fwd::int::boolean, + fqdn_rev::int::boolean, + replace(hostname, ',', ','), + decode(replace(hwaddr, ':', ''), 'hex'), + state, + replace(user_context, ',', ','), + hwtype, + hwaddr_source + ); +END +\$\$ LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '8', minor = '0'; + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_008_to_009.sh.in b/src/share/database/scripts/pgsql/upgrade_008_to_009.sh.in new file mode 100644 index 0000000..b68ebf6 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_008_to_009.sh.in @@ -0,0 +1,292 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "8.0" ]; then + printf 'This script upgrades 8.0 to 9.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This starts schema update to 9.0. + +-- Add missing cascade to constraint on dhcp4/6_subnet_server tables. +ALTER TABLE dhcp4_subnet_server + DROP CONSTRAINT fk_dhcp4_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE CASCADE, + DROP CONSTRAINT fk_dhcp4_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp4_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE dhcp6_subnet_server + DROP CONSTRAINT fk_dhcp6_subnet_server_server_id, + ADD CONSTRAINT fk_dhcp6_subnet_server_server_id + FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE CASCADE, + DROP CONSTRAINT fk_dhcp6_subnet_server_subnet_id, + ADD CONSTRAINT fk_dhcp6_subnet_server_subnet_id + FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE CASCADE; + +-- Fix constraint typo on dhcp4_option_def_server +ALTER TABLE dhcp4_option_def_server + DROP CONSTRAINT dhcp4_option_def_server_option_def_id_fkey, + ADD CONSTRAINT dhcp4_option_def_server_option_def_id_fkey + FOREIGN KEY (option_def_id) REFERENCES dhcp4_option_def(id) ON DELETE CASCADE; + +-- DROP shared-network ADEL triggers that should not exist. +DROP TRIGGER IF EXISTS dhcp4_shared_network_ADEL on dhcp4_shared_network CASCADE; +DROP TRIGGER IF EXISTS dhcp6_shared_network_ADEL on dhcp6_shared_network CASCADE; + +-- Replace createOptionAuditDHCP4() with a version that has local variable +-- snid correctly declared as a BIGINT. +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP4(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp4_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp4_options' table. + PERFORM createAuditEntryDHCP4('dhcp4_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp4_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id; + UPDATE dhcp4_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;\$\$; + +-- Replace createOptionAuditDHCP6() with a version that has local variable +-- snid correctly declared as a BIGINT. +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;\$\$; + +-- Returns the epoch GMT time in second from a timestamp with time zone +-- +-- param input_ts timestamp value to convert +-- return a BIGINT containing the number of seconds since the epoch in GMT. +CREATE OR REPLACE FUNCTION gmt_epoch(input_ts TIMESTAMP WITH TIME ZONE) +RETURNS BIGINT +AS \$\$ +DECLARE + gmt_epoch BIGINT; +BEGIN + SELECT (extract(epoch from input_ts) + extract(timezone from input_ts))::BIGINT INTO gmt_epoch; + RETURN gmt_epoch; + EXCEPTION + WHEN OTHERS THEN + RAISE EXCEPTION 'gmt_epoch(%) : failed, sqlstate: %', input_ts, sqlstate; +END;\$\$ +LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '9', minor = '0'; + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_009_to_010.sh.in b/src/share/database/scripts/pgsql/upgrade_009_to_010.sh.in new file mode 100644 index 0000000..4c66c42 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_009_to_010.sh.in @@ -0,0 +1,335 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "9.0" ]; then + printf 'This script upgrades 9.0 to 10.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This starts schema update to 10.0. +-- It adds corrections for client classes for CB + +-- Replace setClientClass4Order(): +-- 1. l_depend_on_known_indirectly needs to be BOOL +-- 2. follow_class_index needs to be BIGINT + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass4Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BOOL := false; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp4_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp4_client_class AS c + INNER JOIN dhcp4_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp4_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp4_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp4_client_class_dependency AS d + INNER JOIN dhcp4_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp4_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp4_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, false); + RETURN; +END;\$\$; + +-- Replace setClientClass6Order(): +-- 1. l_depend_on_known_indirectly needs to be BOOL +-- 2. follow_class_index needs to be BIGINT + +-- ----------------------------------------------------------------------- +-- Stored procedure positioning an inserted or updated client class +-- within the class hierarchy, depending on the value of the +-- new_follow_class_name parameter. +-- +-- Parameters: +-- - id id of the positioned class, +-- - new_follow_class_name name of the class after which this class should be +-- positioned within the class hierarchy. +-- - old_follow_class_name previous name of the class after which this +-- class was positioned within the class hierarchy. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION setClientClass6Order(id BIGINT, + new_follow_class_name VARCHAR(128), + old_follow_class_name VARCHAR(128)) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- Used to fetch class's current value for depend_on_known_indirectly + l_depend_on_known_indirectly BOOL := false; + + -- Optionally set if the follow_class_name column value is specified. + follow_class_index BIGINT; +BEGIN + -- Fetch the class's current value of depend_on_known_indirectly. + SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly + FROM dhcp6_client_class_order WHERE id = class_id; + + -- Save it to the current session for use elsewhere during this transaction. + -- Note this does not work prior to Postgres 9.2 unless the variables are + -- defined in postgresql.conf. I think for now we put up with CB not supported + -- prior to 9.2 or we tell people how to edit the conf file. + PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly); + + -- Bail if the class is updated without re-positioning. + IF( + l_depend_on_known_indirectly IS NOT NULL AND + ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR + (new_follow_class_name = old_follow_class_name)) + ) THEN + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM should we update the session value also or is it moot? + UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = false + WHERE class_id = id; + RETURN; + END IF; + + IF new_follow_class_name IS NOT NULL THEN + -- Get the position of the class after which the new class should be added. + SELECT o.order_index INTO follow_class_index + FROM dhcp6_client_class AS c + INNER JOIN dhcp6_client_class_order AS o + ON c.id = o.class_id + WHERE c.name = new_follow_class_name; + + IF follow_class_index IS NULL THEN + -- The class with a name specified with new_follow_class_name does + -- not exist. + RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- We need to place the new class at the position of follow_class_index + 1. + -- There may be a class at this position already. + IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN + -- There is a class at this position already. Let's move all classes + -- starting from this position by one to create a spot for the new + -- class. + UPDATE dhcp6_client_class_order + SET order_index = order_index + 1 + WHERE order_index >= follow_class_index + 1; + -- TKM postgresql doesn't like order by here, does it matter? + -- ORDER BY order_index DESC; + END IF; + + ELSE + -- A caller did not specify the new_follow_class_name value. Let's append the + -- new class at the end of the hierarchy. + SELECT MAX(order_index) INTO follow_class_index FROM dhcp6_client_class_order; + IF follow_class_index IS NULL THEN + -- Apparently, there are no classes. Let's start from 0. + follow_class_index = 0; + END IF; + END IF; + + -- Check if moving the class doesn't break dependent classes. + IF EXISTS( + SELECT 1 FROM dhcp6_client_class_dependency AS d + INNER JOIN dhcp6_client_class_order AS o + ON d.class_id = o.class_id + WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1 + LIMIT 1 + ) THEN + RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id + USING ERRCODE = 'sql_routine_exception'; + END IF; + + -- The depend_on_known_indirectly is set to 0 because this procedure is invoked + -- whenever the dhcp6_client_class record is updated. Such update may include + -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes. + -- This value will be later adjusted when dependencies are inserted. + -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later. + UPDATE dhcp6_client_class_order + SET order_index = follow_class_index + 1, + depend_on_known_indirectly = l_depend_on_known_indirectly + WHERE class_id = id; + IF FOUND THEN + RETURN; + END IF; + + INSERT INTO dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly) + VALUES (id, follow_class_index + 1, false); + RETURN; +END;\$\$; + +-- Change primary key to composite, dependency table can have multiple rows +-- per class id. +ALTER TABLE dhcp4_client_class_dependency DROP CONSTRAINT dhcp4_client_class_dependency_pkey; +ALTER TABLE dhcp4_client_class_dependency ADD PRIMARY KEY(class_id, dependency_id); + +ALTER TABLE dhcp6_client_class_dependency DROP CONSTRAINT dhcp6_client_class_dependency_pkey; +ALTER TABLE dhcp6_client_class_dependency ADD PRIMARY KEY(class_id, dependency_id); + +-- Replace triggers that verify class dependency. +-- Because they are BEFORE INSERT triggers they need to return NEW not NULL. +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp4_client_class_check_dependency_BINS() + RETURNS trigger AS \$dhcp4_client_class_check_dependency_BINS\$ +BEGIN + PERFORM checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NEW; +END; +\$dhcp4_client_class_check_dependency_BINS\$ +LANGUAGE plpgsql; + +-- ----------------------------------------------------------------------- +-- Trigger verifying if class dependency is met. It includes checking +-- if referenced classes exist, are associated with the same server +-- or all servers, and are defined before the class specified with +-- class_id. +-- ----------------------------------------------------------------------- +CREATE OR REPLACE FUNCTION func_dhcp6_client_class_check_dependency_BINS() + RETURNS trigger AS \$dhcp6_client_class_check_dependency_BINS\$ +BEGIN + PERFORM checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id); + RETURN NEW; +END; +\$dhcp6_client_class_check_dependency_BINS\$ +LANGUAGE plpgsql; + +-- Update the schema version number. +UPDATE schema_version + SET version = '10', minor = '0'; + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_010_to_011.sh.in b/src/share/database/scripts/pgsql/upgrade_010_to_011.sh.in new file mode 100644 index 0000000..6252657 --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_010_to_011.sh.in @@ -0,0 +1,152 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "10.0" ]; then + printf 'This script upgrades 10.0 to 11.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This starts schema update to 11.0. + +-- Replace createOptionAuditDHCP6() with a version corrected +-- where clause when scope is 6 (i.e. PD pool) +-- +-- ----------------------------------------------------- +-- +-- Stored procedure which updates modification timestamp of +-- a parent object when an option is modified. +-- +-- The following parameters are passed to the procedure: +-- - modification_type: "create", "update" or "delete" +-- - scope_id: identifier of the option scope, e.g. +-- global, subnet specific etc. See dhcp_option_scope +-- for specific values. +-- - option_id: identifier of the option. +-- - p_subnet_id: identifier of the subnet if the option +-- belongs to the subnet. +-- - host_id: identifier of the host if the option +-- - belongs to the host. +-- - network_name: shared network name if the option +-- belongs to the shared network. +-- - pool_id: identifier of the pool if the option +-- belongs to the pool. +-- - pd_pool_id: identifier of the pool if the option +-- belongs to the pd pool. +-- - p_modification_ts: modification timestamp of the +-- option. +-- Some arguments are prefixed with "p_" to avoid ambiguity +-- with column names in SQL statements. PostgreSQL does not +-- allow table aliases to be used with column names in update +-- set expressions. +-- ----------------------------------------------------- +CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR, + scope_id SMALLINT, + option_id INT, + p_subnet_id BIGINT, + host_id INT, + network_name VARCHAR, + pool_id BIGINT, + pd_pool_id BIGINT, + p_modification_ts TIMESTAMP WITH TIME ZONE) +RETURNS VOID +LANGUAGE plpgsql +AS \$\$ +DECLARE + -- These variables will hold shared network id and subnet id that + -- we will select. + snid BIGINT; + sid BIGINT; + cascade_transaction BOOLEAN; +BEGIN + -- Cascade transaction flag is set to true to prevent creation of + -- the audit entries for the options when the options are + -- created as part of the parent object creation or update. + -- For example: when the option is added as part of the subnet + -- addition, the cascade transaction flag is equal to true. If + -- the option is added into the existing subnet the cascade + -- transaction is equal to false. Note that depending on the option + -- scope the audit entry will contain the object_type value + -- of the parent object to cause the server to replace the + -- entire subnet. The only case when the object_type will be + -- set to 'dhcp6_options' is when a global option is added. + -- Global options do not have the owner. + + cascade_transaction := get_session_boolean('kea.cascade_transaction'); + IF cascade_transaction = false THEN + -- todo: host manager hasn't been updated to use audit + -- mechanisms so ignore host specific options for now. + IF scope_id = 0 THEN + -- If a global option is added or modified, create audit + -- entry for the 'dhcp6_options' table. + PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type); + ELSEIF scope_id = 1 THEN + -- If subnet specific option is added or modified, update + -- the modification timestamp of this subnet to allow the + -- servers to refresh the subnet information. This will + -- also result in creating an audit entry for this subnet. + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = p_subnet_id; + ELSEIF scope_id = 4 THEN + -- If shared network specific option is added or modified, + -- update the modification timestamp of this shared network + -- to allow the servers to refresh the shared network + -- information. This will also result in creating an + -- audit entry for this shared network. + SELECT id INTO snid FROM dhcp6_shared_network WHERE name = network_name LIMIT 1; + UPDATE dhcp6_shared_network SET modification_ts = p_modification_ts + WHERE id = snid; + ELSEIF scope_id = 5 THEN + -- If pool specific option is added or modified, update + -- the modification timestamp of the owning subnet. + SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + ELSEIF scope_id = 6 THEN + -- If pd pool specific option is added or modified, create + -- audit entry for the subnet which this pool belongs to. + SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool WHERE id = pd_pool_id; + UPDATE dhcp6_subnet SET modification_ts = p_modification_ts + WHERE subnet_id = sid; + END IF; + END IF; + RETURN; +END;\$\$; + +-- Update the schema version number. +UPDATE schema_version + SET version = '11', minor = '0'; + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_011_to_012.sh.in b/src/share/database/scripts/pgsql/upgrade_011_to_012.sh.in new file mode 100644 index 0000000..00a02dc --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_011_to_012.sh.in @@ -0,0 +1,106 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "11.0" ]; then + printf 'This script upgrades 11.0 to 12.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This line starts the schema upgrade to version 12. + +-- Modify shared-network-name foreign key constraint on dhcp4_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp4_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp4_subnet + DROP CONSTRAINT fk_dhcp4_subnet_shared_network, + ADD CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp4_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger function on dhcp4_shared_network to explicitly +-- update dhcp4_subnets. This ensures there are audit entries for updated +-- subnets. +-- Trigger function for dhcp4_shared_network_BDEL called BEFORE DELETE on dhcp4_shared_network +CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp4_shared_network_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete'); + -- Explicitly update subnets now rather than via foreign key constraint, this ensures the + -- audit entries for subnets will preceded that of the shared-network, keeping the order + -- of the entries the same as they are for MySQL. + UPDATE dhcp4_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +\$dhcp4_shared_network_BDEL\$ +LANGUAGE plpgsql; + +-- Modify shared-network-name foreign key constraint on dhcp6_subnet to not perform +-- the update when the network is deleted the cascaded update will not execute +-- dhcp6_subnet update trigger leaving the updated subnets without audit_entries. +ALTER TABLE dhcp6_subnet + DROP CONSTRAINT fk_dhcp6_subnet_shared_network, + ADD CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name) + REFERENCES dhcp6_shared_network (name) + ON DELETE NO ACTION ON UPDATE NO ACTION; + +-- Modify BEFORE delete trigger function on dhcp6_shared_network to explicitly +-- update dhcp6_subnets. This ensures there are audit entries for updated +-- subnets. +-- Trigger function for dhcp6_shared_network_BDEL called BEFORE DELETE on dhcp6_shared_network +CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp6_shared_network_BDEL\$ +BEGIN + PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete'); + -- Explicitly update subnets now rather than via foreign key constraint, this ensures the + -- audit entries for subnets will preceded that of the shared-network, keeping the order + -- of the entries the same as they are for MySQL. + UPDATE dhcp6_subnet SET shared_network_name = NULL WHERE shared_network_name = OLD.name; + DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name; + RETURN OLD; +END; +\$dhcp6_shared_network_BDEL\$ +LANGUAGE plpgsql; + +-- Add user_context column to client class tables. +ALTER TABLE dhcp4_client_class ADD COLUMN user_context JSON DEFAULT NULL; +ALTER TABLE dhcp6_client_class ADD COLUMN user_context JSON DEFAULT NULL; + +-- Update the schema version number. +UPDATE schema_version + SET version = '12', minor = '0'; + +-- This line concludes the schema upgrade to version 12. + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/upgrade_012_to_013.sh.in b/src/share/database/scripts/pgsql/upgrade_012_to_013.sh.in new file mode 100644 index 0000000..bb45b9e --- /dev/null +++ b/src/share/database/scripts/pgsql/upgrade_012_to_013.sh.in @@ -0,0 +1,681 @@ +#!/bin/sh + +# Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +VERSION=$(pgsql_version "$@") + +if [ "$VERSION" != "12.0" ]; then + printf 'This script upgrades 12.0 to 12.0. ' + printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}" + exit 0 +fi + +psql "$@" >/dev/null <<EOF +START TRANSACTION; + +-- This line starts the schema upgrade to version 13. + +-- JSON functions -- + +-- Helper function that avoids a casting error when the string +-- presumed to be in JSON format, is empty. +CREATE OR REPLACE FUNCTION json_cast(IN json_candidate TEXT) +RETURNS JSON +AS \$\$ +BEGIN + IF LENGTH(json_candidate) = 0 THEN + RETURN '{}'::json; + END IF; + RETURN json_candidate::json; +END; +\$\$ LANGUAGE plpgsql; + +-- Function that establishes whether JSON functions are supported. +-- They should be provided with PostgreSQL >= 9.4. +CREATE OR REPLACE FUNCTION isJsonSupported() +RETURNS BOOLEAN +AS \$\$ +BEGIN + IF get_session_value('json_supported') IS NULL THEN + IF (SELECT proname FROM pg_proc WHERE proname = 'json_extract_path') = 'json_extract_path' THEN + PERFORM set_session_value('kea.json_supported', true); + ELSE + PERFORM set_session_value('kea.json_supported', false); + END IF; + END IF; + RETURN get_session_value('kea.json_supported'); +END +\$\$ LANGUAGE plpgsql; + +-- Schema changes related to lease limiting start here. -- + +-- Recreate the triggers that update the leaseX_stat tables as stored procedures. -- + +CREATE OR REPLACE FUNCTION lease4_AINS_lease4_stat(IN new_state BIGINT, + IN new_subnet_id BIGINT) +RETURNS VOID +AS \$\$ +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert the state count record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_AUPD_lease4_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN new_state BIGINT, + IN new_subnet_id BIGINT) +RETURNS VOID +AS \$\$ +BEGIN + IF old_subnet_id != new_subnet_id OR old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease4_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists. + UPDATE lease4_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND state = new_state; + + -- Insert new state record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease4_stat VALUES (new_subnet_id, new_state, 1); + END IF; + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_ADEL_lease4_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT) +RETURNS VOID +AS \$\$ +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists. + UPDATE lease4_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND old_state = state; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AINS_lease6_stat(IN new_state BIGINT, + IN new_subnet_id BIGINT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +BEGIN + IF new_state = 0 OR new_state = 1 THEN + -- Update the state count if it exists. + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert the state count record if it does not exist. + IF NOT FOUND THEN + INSERT INTO lease6_stat VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AUPD_lease6_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN old_lease_type SMALLINT, + IN new_state BIGINT, + IN new_subnet_id BIGINT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +BEGIN + IF old_subnet_id != new_subnet_id OR + old_lease_type != new_lease_type OR + old_state != new_state THEN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the old state count if record exists. + UPDATE lease6_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; + + IF new_state = 0 OR new_state = 1 THEN + -- Increment the new state count if record exists + UPDATE lease6_stat SET leases = leases + 1 + WHERE subnet_id = new_subnet_id AND lease_type = new_lease_type + AND state = new_state; + + -- Insert new state record if it does not exist + IF NOT FOUND THEN + INSERT INTO lease6_stat + VALUES (new_subnet_id, new_lease_type, new_state, 1); + END IF; + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_ADEL_lease6_stat(IN old_state BIGINT, + IN old_subnet_id BIGINT, + IN old_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +BEGIN + IF old_state = 0 OR old_state = 1 THEN + -- Decrement the state count if record exists + UPDATE lease6_stat + SET leases = GREATEST(leases - 1, 0) + WHERE subnet_id = old_subnet_id AND lease_type = old_lease_type + AND state = old_state; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +-- Create tables that contain the number of active leases. -- + +CREATE TABLE lease4_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL PRIMARY KEY, + leases BIGINT NOT NULL +); + +CREATE TABLE lease6_stat_by_client_class ( + client_class VARCHAR(128) NOT NULL, + lease_type SMALLINT NOT NULL, + leases BIGINT NOT NULL, + PRIMARY KEY (client_class, lease_type), + CONSTRAINT fk_lease6_stat_by_client_class_lease_type FOREIGN KEY (lease_type) + REFERENCES lease6_types (lease_type) +); + +-- Create procedures to be called for each row in after-event triggers for +-- INSERT, UPDATE and DELETE on lease tables. + +CREATE OR REPLACE FUNCTION lease4_AINS_lease4_stat_by_client_class(IN new_state BIGINT, + IN new_user_context TEXT) +RETURNS VOID +AS \$\$ +DECLARE + class VARCHAR(128); +BEGIN + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF NOT FOUND THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + END LOOP; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_AUPD_lease4_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN new_state BIGINT, + IN new_user_context TEXT) +RETURNS VOID +AS \$\$ +DECLARE + old_client_classes TEXT; + new_client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + SELECT json_cast(old_user_context)->'ISC'->'client-classes' INTO old_client_classes; + SELECT json_cast(new_user_context)->'ISC'->'client-classes' INTO new_client_classes; + + IF old_state != new_state OR old_client_classes != new_client_classes THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class; + END LOOP; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease4_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class; + IF NOT FOUND THEN + INSERT INTO lease4_stat_by_client_class VALUES (class, 1); + END IF; + END LOOP; + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease4_ADEL_lease4_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT) +RETURNS VOID +AS \$\$ +DECLARE + class VARCHAR(128); +BEGIN + -- Only state 0 is accounted for in lease limiting. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease4_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class; + END LOOP; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AINS_lease6_stat_by_client_class(IN new_state BIGINT, + IN new_user_context TEXT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +DECLARE + client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + -- Only state 0 is needed for lease limiting. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF NOT FOUND THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + END LOOP; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_AUPD_lease6_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN old_lease_type SMALLINT, + IN new_state BIGINT, + IN new_user_context TEXT, + IN new_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +DECLARE + old_client_classes TEXT; + new_client_classes TEXT; + class VARCHAR(128); + length INT; + i INT; +BEGIN + SELECT json_cast(old_user_context)->'ISC'->'client-classes' INTO old_client_classes; + SELECT json_cast(new_user_context)->'ISC'->'client-classes' INTO new_client_classes; + + IF old_state != new_state OR old_client_classes != new_client_classes OR old_lease_type != new_lease_type THEN + -- Check if it's moving away from a counted state. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + END LOOP; + END IF; + + -- Check if it's moving into a counted state. + IF new_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(new_client_classes)) LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Upsert to increment the lease count. + UPDATE lease6_stat_by_client_class SET leases = leases + 1 + WHERE client_class = class AND lease_type = new_lease_type; + IF NOT FOUND THEN + INSERT INTO lease6_stat_by_client_class VALUES (class, new_lease_type, 1); + END IF; + END LOOP; + END IF; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION lease6_ADEL_lease6_stat_by_client_class(IN old_state BIGINT, + IN old_user_context TEXT, + IN old_lease_type SMALLINT) +RETURNS VOID +AS \$\$ +DECLARE + client_classes VARCHAR(1024); + class VARCHAR(128); + length INT; + i INT; +BEGIN + -- Only state 0 is accounted for in lease limiting. But check both states to be consistent with lease6_stat. + IF old_state = 0 THEN + -- Dive into client classes. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(old_user_context)->'ISC'->'client-classes') LOOP + SELECT TRIM('"' FROM class) INTO class; + + -- Decrement the lease count if the record exists. + UPDATE lease6_stat_by_client_class SET leases = GREATEST(leases - 1, 0) + WHERE client_class = class AND lease_type = old_lease_type; + END LOOP; + END IF; +END; +\$\$ LANGUAGE plpgsql; + +-- Recreate the after-event triggers for INSERT, UPDATE and DELETE on lease tables to call the -- +-- stored procedures above in pairs of two: for client classes and for subnets. -- + +DROP TRIGGER IF EXISTS stat_lease4_insert ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_AINS() +RETURNS trigger AS \$lease4_AINS\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_AINS_lease4_stat_by_client_class(NEW.state, NEW.user_context); + END IF; + PERFORM lease4_AINS_lease4_stat(NEW.state, NEW.subnet_id); + RETURN NULL; +END; +\$lease4_AINS\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_AINS AFTER INSERT ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_AINS(); + +DROP TRIGGER IF EXISTS stat_lease4_update ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_AUPD() +RETURNS trigger AS \$lease4_AUPD\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_AUPD_lease4_stat_by_client_class(OLD.state, OLD.user_context, NEW.state, NEW.user_context); + END IF; + PERFORM lease4_AUPD_lease4_stat(OLD.state, OLD.subnet_id, NEW.state, NEW.subnet_id); + RETURN NULL; +END; +\$lease4_AUPD\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_AUPD AFTER UPDATE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_AUPD(); + +DROP TRIGGER IF EXISTS stat_lease4_delete ON lease4; + +CREATE OR REPLACE FUNCTION func_lease4_ADEL() +RETURNS trigger AS \$lease4_ADEL\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease4_ADEL_lease4_stat_by_client_class(OLD.state, OLD.user_context); + END IF; + PERFORM lease4_ADEL_lease4_stat(OLD.state, OLD.subnet_id); + RETURN NULL; +END; +\$lease4_ADEL\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease4_ADEL AFTER DELETE ON lease4 + FOR EACH ROW EXECUTE PROCEDURE func_lease4_ADEL(); + +DROP TRIGGER IF EXISTS stat_lease6_insert ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_AINS() +RETURNS trigger AS \$lease6_AINS\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_AINS_lease6_stat_by_client_class(NEW.state, NEW.user_context, NEW.lease_type); + END IF; + PERFORM lease6_AINS_lease6_stat(NEW.state, NEW.subnet_id, NEW.lease_type); + RETURN NULL; +END; +\$lease6_AINS\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_AINS AFTER INSERT ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_AINS(); + +DROP TRIGGER IF EXISTS stat_lease6_update ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_AUPD() +RETURNS trigger AS \$lease6_AUPD\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_AUPD_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type, NEW.state, NEW.user_context, NEW.lease_type); + END IF; + PERFORM lease6_AUPD_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type, NEW.state, NEW.subnet_id, NEW.lease_type); + RETURN NULL; +END; +\$lease6_AUPD\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_AUPD AFTER UPDATE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_AUPD(); + +DROP TRIGGER IF EXISTS stat_lease6_delete ON lease6; + +CREATE OR REPLACE FUNCTION func_lease6_ADEL() +RETURNS trigger AS \$lease6_ADEL\$ +BEGIN + IF isJsonSupported() = true THEN + PERFORM lease6_ADEL_lease6_stat_by_client_class(OLD.state, OLD.user_context, OLD.lease_type); + END IF; + PERFORM lease6_ADEL_lease6_stat(OLD.state, OLD.subnet_id, OLD.lease_type); + RETURN NULL; +END; +\$lease6_ADEL\$ LANGUAGE plpgsql; + +CREATE TRIGGER lease6_ADEL AFTER DELETE ON lease6 + FOR EACH ROW EXECUTE PROCEDURE func_lease6_ADEL(); + +-- Create functions that return an empty TEXT if all limits allow for more leases, or otherwise a +-- TEXT in one of the following JSON formats detailing the limit that was reached: +-- { "limit-type": "client-class", "name": foo, "lease-type": "address", "limit": 2, "count": 2 } +-- { "limit-type": "subnet", "id": 1, "lease-type": "IA_PD", "limit": 2, "count": 2 } +-- The following format for user_context is assumed: +-- { "ISC": { "limits": { "client-classes": [ { "name": "foo", "address-limit": 2, "prefix-limit": 1 } ], +-- "subnet": { "id": 1, "address-limit": 2, "prefix-limit": 1 } } } } + +CREATE OR REPLACE FUNCTION checkLease4Limits(user_context TEXT) +RETURNS TEXT +AS \$\$ +DECLARE + class TEXT; + name VARCHAR(255); + sid INT; + lease_limit INT; + lease_count INT; +BEGIN + -- Dive into client class limits. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(user_context)->'ISC'->'limits'->'client-classes') LOOP + SELECT TRIM('"' FROM (json_cast(class)->'name')::text) INTO name; + SELECT json_cast(class)->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease4_stat_by_client_class INTO lease_count WHERE client_class = name; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + END LOOP; + + -- Dive into subnet limits. + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'id' INTO sid; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease4_stat WHERE subnet_id = sid AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END; +\$\$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION checkLease6Limits(user_context TEXT) +RETURNS TEXT +AS \$\$ +DECLARE + class TEXT; + name VARCHAR(255); + sid INT; + lease_limit INT; + lease_count INT; +BEGIN + -- Dive into client class limits. + FOR class IN SELECT * FROM JSON_ARRAY_ELEMENTS(json_cast(user_context)->'ISC'->'limits'->'client-classes') LOOP + SELECT TRIM('"' FROM (json_cast(class)->'name')::text) INTO name; + SELECT json_cast(class)->'address-limit' INTO lease_limit; + + IF lease_limit IS NOT NULL THEN + -- Get the address count for this client class. + SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + + SELECT json_cast(class)->'prefix-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the prefix count for this client class. + SELECT leases FROM lease6_stat_by_client_class WHERE client_class = name AND lease_type = 2 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for client class "', name, '", current lease count ', lease_count); + END IF; + END IF; + END LOOP; + + -- Dive into subnet limits. + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'id' INTO sid; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'address-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this subnet. + SELECT leases FROM lease6_stat WHERE subnet_id = sid AND lease_type = 0 AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('address limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + SELECT json_cast(user_context)->'ISC'->'limits'->'subnet'->'prefix-limit' INTO lease_limit; + IF lease_limit IS NOT NULL THEN + -- Get the lease count for this client class. + SELECT leases FROM lease6_stat WHERE subnet_id = sid AND lease_type = 2 AND state = 0 INTO lease_count; + IF lease_count IS NULL THEN + lease_count := 0; + END IF; + + -- Compare. Return immediately if the limit is surpassed. + IF lease_limit <= lease_count THEN + RETURN CONCAT('prefix limit ', lease_limit, ' for subnet ID ', sid, ', current lease count ', lease_count); + END IF; + END IF; + + RETURN ''; +END; +\$\$ LANGUAGE plpgsql; + +-- Improve hosts indexes for better performance of global reservations +-- Create new index that uses only dhcp_identifier. +CREATE INDEX key_dhcp_identifier on hosts (dhcp_identifier, dhcp_identifier_type); + +-- Modify existing indexes to include subnet_id values of 0, so index is also used +-- for global reservations. +DROP INDEX IF EXISTS key_dhcp4_identifier_subnet_id; +CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp4_subnet_id ASC) + WHERE (dhcp4_subnet_id IS NOT NULL); + +DROP INDEX IF EXISTS key_dhcp6_identifier_subnet_id; +CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id ON hosts + (dhcp_identifier ASC, dhcp_identifier_type ASC, dhcp6_subnet_id ASC) + WHERE (dhcp6_subnet_id IS NOT NULL); + +-- Update the schema version number. +UPDATE schema_version + SET version = '13', minor = '0'; + +-- This line concludes the schema upgrade to version 13. + +-- Commit the script transaction. +COMMIT; + +EOF diff --git a/src/share/database/scripts/pgsql/wipe_data.sh.in b/src/share/database/scripts/pgsql/wipe_data.sh.in new file mode 100644 index 0000000..088b802 --- /dev/null +++ b/src/share/database/scripts/pgsql/wipe_data.sh.in @@ -0,0 +1,117 @@ +#!/bin/sh + +# Copyright (C) 2019-2022 Internet Systems Consortium, Inc. ("ISC") +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# This script is primarily used for MySQL unit tests, which need to +# ensure an empty, but schema correct database for each test. It +# deletes ALL transient data from an existing Kea MySQL schema, +# including leases, reservations, etc... Use at your own peril. +# Reference tables will be left in-tact. + +# shellcheck disable=SC1091 +# SC1091: Not following: ... was not specified as input (see shellcheck -x). + +# Exit with error if commands exit with non-zero and if undefined variables are +# used. +set -eu + +# shellcheck disable=SC2034 +# SC2034: ... appears unused. Verify use (or export if used externally). +prefix="@prefix@" + +# Include utilities. Use installed version if available and +# use build version if it isn't. +if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then + . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh" +else + . "@abs_top_builddir@/src/bin/admin/admin-utils.sh" +fi + +# First argument must be the expected schema version <major>.<minor> +# Check if it's passed at all. +if [ "$#" -lt "1" ]; then + printf "Required at least one parameter: schema version number, e.g. 7.0\n" + exit 1 +fi +exp_version="$1" +shift + +# Remaining arguments are used as pgsql command line arguments + +# If the existing schema doesn't match, the fail +VERSION=$(pgsql_version "$@") +if [ "$VERSION" = "" ]; then + printf "Cannot wipe data, schema version could not be detected.\n" + exit 1 +fi + +if [ "$VERSION" != "$exp_version" ]; then + printf 'Cannot wipe data, wrong schema version. ' + printf 'Expected version %s, found %s.\n' "${exp_version}" "${VERSION}" + exit 1 +fi + +# Delete transient data from tables. We're using delete instead +# of truncate because it is much faster since our unit tests +# create very little data. +# Note we disable revision auditing to avoid issues with delete +# triggers. +psql "$@" >/dev/null <<EOF +SELECT set_config('kea.disable_audit', 'true', false); +START TRANSACTION; +DELETE FROM hosts CASCADE; +DELETE FROM dhcp4_options; +DELETE FROM ipv6_reservations; +DELETE FROM dhcp6_options; +DELETE FROM lease4; +DELETE FROM lease4_stat; +DELETE FROM lease6; +DELETE FROM lease6_stat; +DELETE FROM logs; +DELETE FROM lease4_stat_by_client_class; +DELETE FROM lease6_stat_by_client_class; + +-- Config Backend tables +DELETE FROM dhcp4_audit; +DELETE FROM dhcp4_audit_revision; +DELETE FROM dhcp4_global_parameter; +DELETE FROM dhcp4_global_parameter_server; +DELETE FROM dhcp4_option_def; +DELETE FROM dhcp4_option_def_server; +DELETE FROM dhcp4_options; +DELETE FROM dhcp4_options_server; +DELETE FROM dhcp4_pool; +DELETE FROM dhcp4_shared_network; +DELETE FROM dhcp4_subnet; +DELETE FROM dhcp4_subnet_server; +DELETE FROM dhcp4_shared_network_server; +DELETE FROM dhcp4_client_class_order; +DELETE FROM dhcp4_client_class_dependency; +DELETE FROM dhcp4_client_class_server; +DELETE FROM dhcp4_client_class; +DELETE FROM dhcp4_server WHERE tag != 'all'; -- preserve the special tag + +DELETE FROM dhcp6_audit; +DELETE FROM dhcp6_audit_revision; +DELETE FROM dhcp6_global_parameter; +DELETE FROM dhcp6_global_parameter_server; +DELETE FROM dhcp6_option_def; +DELETE FROM dhcp6_option_def_server; +DELETE FROM dhcp6_options; +DELETE FROM dhcp6_options_server; +DELETE FROM dhcp6_pool; +DELETE FROM dhcp6_pd_pool; +DELETE FROM dhcp6_shared_network; +DELETE FROM dhcp6_subnet; +DELETE FROM dhcp6_client_class_order; +DELETE FROM dhcp6_client_class_dependency; +DELETE FROM dhcp6_client_class_server; +DELETE FROM dhcp6_client_class; +DELETE FROM dhcp6_server WHERE tag != 'all'; -- preserve the special tag + +COMMIT; +EOF |