[svn] commit: r1997 - in /branches/trac185: ./ ext/asio/ ext/boost/ ext/boost/algorithm/ ext/boost/archive/ ext/boost/asio/ ext/boost/assign/ ext/boost/bind/ ext/boost/boost/ ext/boost/concept/ ext/boost/config/ ext/boost/date_time/ ext/boost/detail/ ext/boost/exception/ ext/boost/function/ ext/boost/functional/ ext/boost/integer/ ext/boost/iterator/ ext/boost/mpl/ ext/boost/optional/ ext/boost/preprocessor/ ext/boost/range/ ext/boost/regex/ ext/boost/serialization/ ext/boost/smart_ptr/ ext/boost/system/ ext/boost/type_traits/ ext/boost/utility/ src/bin/auth/ src/bin/auth/tests/ src/bin/bind10/ src/bin/bindctl/ src/bin/bindctl/tests/ src/bin/cmdctl/ src/bin/cmdctl/tests/ src/bin/host/ src/bin/loadzone/ src/bin/xfrin/ src/bin/xfrout/ src/lib/ src/lib/cc/ src/lib/config/ src/lib/config/testdata/ src/lib/config/tests/ src/lib/datasrc/ src/lib/datasrc/tests/ src/lib/dns/ src/lib/dns/rdata/generic/ src/lib/dns/tests/ src/lib/exceptions/ src/lib/python/isc/cc/ src/lib/python/isc/cc/tests/ src/lib/python/isc/config/ src/lib/python/isc/config/tests/ src/lib/xfr/
BIND 10 source code commits
bind10-changes at lists.isc.org
Mon May 31 06:06:40 UTC 2010
Author: jinmei
Date: Mon May 31 06:06:39 2010
New Revision: 1997
Log:
merge from trunk
Added:
branches/trac185/ext/asio/
- copied from r1995, trunk/ext/asio/
branches/trac185/ext/boost/boost/
- copied from r1995, trunk/ext/boost/boost/
branches/trac185/src/bin/auth/asio_link.cc
- copied unchanged from r1995, trunk/src/bin/auth/asio_link.cc
branches/trac185/src/bin/auth/asio_link.h
- copied unchanged from r1995, trunk/src/bin/auth/asio_link.h
branches/trac185/src/bin/auth/spec_config.h.pre.in
- copied unchanged from r1995, trunk/src/bin/auth/spec_config.h.pre.in
branches/trac185/src/lib/config/testdata/spec25.spec
- copied unchanged from r1995, trunk/src/lib/config/testdata/spec25.spec
branches/trac185/src/lib/config/testdata/spec26.spec
- copied unchanged from r1995, trunk/src/lib/config/testdata/spec26.spec
branches/trac185/src/lib/config/testdata/spec27.spec
- copied unchanged from r1995, trunk/src/lib/config/testdata/spec27.spec
Removed:
branches/trac185/ext/boost/algorithm/
branches/trac185/ext/boost/aligned_storage.hpp
branches/trac185/ext/boost/any.hpp
branches/trac185/ext/boost/archive/
branches/trac185/ext/boost/array.hpp
branches/trac185/ext/boost/asio/
branches/trac185/ext/boost/asio.hpp
branches/trac185/ext/boost/assert.hpp
branches/trac185/ext/boost/assign/
branches/trac185/ext/boost/assign.hpp
branches/trac185/ext/boost/bimap.hpp
branches/trac185/ext/boost/bind/
branches/trac185/ext/boost/bind.hpp
branches/trac185/ext/boost/blank.hpp
branches/trac185/ext/boost/blank_fwd.hpp
branches/trac185/ext/boost/call_traits.hpp
branches/trac185/ext/boost/cast.hpp
branches/trac185/ext/boost/cerrno.hpp
branches/trac185/ext/boost/checked_delete.hpp
branches/trac185/ext/boost/circular_buffer.hpp
branches/trac185/ext/boost/circular_buffer_fwd.hpp
branches/trac185/ext/boost/compressed_pair.hpp
branches/trac185/ext/boost/concept/
branches/trac185/ext/boost/concept_archetype.hpp
branches/trac185/ext/boost/concept_check.hpp
branches/trac185/ext/boost/config/
branches/trac185/ext/boost/config.hpp
branches/trac185/ext/boost/crc.hpp
branches/trac185/ext/boost/cregex.hpp
branches/trac185/ext/boost/cstdint.hpp
branches/trac185/ext/boost/cstdlib.hpp
branches/trac185/ext/boost/current_function.hpp
branches/trac185/ext/boost/date_time/
branches/trac185/ext/boost/date_time.hpp
branches/trac185/ext/boost/detail/
branches/trac185/ext/boost/dynamic_bitset.hpp
branches/trac185/ext/boost/dynamic_bitset_fwd.hpp
branches/trac185/ext/boost/dynamic_property_map.hpp
branches/trac185/ext/boost/enable_shared_from_this.hpp
branches/trac185/ext/boost/exception/
branches/trac185/ext/boost/exception.hpp
branches/trac185/ext/boost/exception_ptr.hpp
branches/trac185/ext/boost/filesystem.hpp
branches/trac185/ext/boost/flyweight.hpp
branches/trac185/ext/boost/foreach.hpp
branches/trac185/ext/boost/format.hpp
branches/trac185/ext/boost/function/
branches/trac185/ext/boost/function.hpp
branches/trac185/ext/boost/function_equal.hpp
branches/trac185/ext/boost/function_output_iterator.hpp
branches/trac185/ext/boost/functional/
branches/trac185/ext/boost/functional.hpp
branches/trac185/ext/boost/generator_iterator.hpp
branches/trac185/ext/boost/get_pointer.hpp
branches/trac185/ext/boost/implicit_cast.hpp
branches/trac185/ext/boost/indirect_reference.hpp
branches/trac185/ext/boost/integer/
branches/trac185/ext/boost/integer.hpp
branches/trac185/ext/boost/integer_fwd.hpp
branches/trac185/ext/boost/integer_traits.hpp
branches/trac185/ext/boost/intrusive_ptr.hpp
branches/trac185/ext/boost/io_fwd.hpp
branches/trac185/ext/boost/is_placeholder.hpp
branches/trac185/ext/boost/iterator/
branches/trac185/ext/boost/iterator.hpp
branches/trac185/ext/boost/iterator_adaptors.hpp
branches/trac185/ext/boost/last_value.hpp
branches/trac185/ext/boost/lexical_cast.hpp
branches/trac185/ext/boost/limits.hpp
branches/trac185/ext/boost/make_shared.hpp
branches/trac185/ext/boost/math_fwd.hpp
branches/trac185/ext/boost/mem_fn.hpp
branches/trac185/ext/boost/memory_order.hpp
branches/trac185/ext/boost/mpi.hpp
branches/trac185/ext/boost/mpl/
branches/trac185/ext/boost/multi_array.hpp
branches/trac185/ext/boost/multi_index_container.hpp
branches/trac185/ext/boost/multi_index_container_fwd.hpp
branches/trac185/ext/boost/next_prior.hpp
branches/trac185/ext/boost/non_type.hpp
branches/trac185/ext/boost/noncopyable.hpp
branches/trac185/ext/boost/nondet_random.hpp
branches/trac185/ext/boost/none.hpp
branches/trac185/ext/boost/none_t.hpp
branches/trac185/ext/boost/operators.hpp
branches/trac185/ext/boost/optional/
branches/trac185/ext/boost/optional.hpp
branches/trac185/ext/boost/parameter.hpp
branches/trac185/ext/boost/pointee.hpp
branches/trac185/ext/boost/pointer_cast.hpp
branches/trac185/ext/boost/pointer_to_other.hpp
branches/trac185/ext/boost/preprocessor/
branches/trac185/ext/boost/preprocessor.hpp
branches/trac185/ext/boost/program_options.hpp
branches/trac185/ext/boost/progress.hpp
branches/trac185/ext/boost/property_map.hpp
branches/trac185/ext/boost/property_map_iterator.hpp
branches/trac185/ext/boost/python.hpp
branches/trac185/ext/boost/random.hpp
branches/trac185/ext/boost/range/
branches/trac185/ext/boost/range.hpp
branches/trac185/ext/boost/rational.hpp
branches/trac185/ext/boost/ref.hpp
branches/trac185/ext/boost/regex/
branches/trac185/ext/boost/regex.hpp
branches/trac185/ext/boost/regex_fwd.hpp
branches/trac185/ext/boost/scope_exit.hpp
branches/trac185/ext/boost/scoped_array.hpp
branches/trac185/ext/boost/scoped_ptr.hpp
branches/trac185/ext/boost/serialization/
branches/trac185/ext/boost/shared_array.hpp
branches/trac185/ext/boost/shared_container_iterator.hpp
branches/trac185/ext/boost/shared_ptr.hpp
branches/trac185/ext/boost/signal.hpp
branches/trac185/ext/boost/signals.hpp
branches/trac185/ext/boost/signals2.hpp
branches/trac185/ext/boost/smart_ptr/
branches/trac185/ext/boost/smart_ptr.hpp
branches/trac185/ext/boost/spirit.hpp
branches/trac185/ext/boost/static_assert.hpp
branches/trac185/ext/boost/strong_typedef.hpp
branches/trac185/ext/boost/swap.hpp
branches/trac185/ext/boost/system/
branches/trac185/ext/boost/thread.hpp
branches/trac185/ext/boost/throw_exception.hpp
branches/trac185/ext/boost/timer.hpp
branches/trac185/ext/boost/token_functions.hpp
branches/trac185/ext/boost/token_iterator.hpp
branches/trac185/ext/boost/tokenizer.hpp
branches/trac185/ext/boost/type.hpp
branches/trac185/ext/boost/type_traits/
branches/trac185/ext/boost/type_traits.hpp
branches/trac185/ext/boost/unordered_map.hpp
branches/trac185/ext/boost/unordered_set.hpp
branches/trac185/ext/boost/utility/
branches/trac185/ext/boost/utility.hpp
branches/trac185/ext/boost/variant.hpp
branches/trac185/ext/boost/vector_property_map.hpp
branches/trac185/ext/boost/version.hpp
branches/trac185/ext/boost/visit_each.hpp
branches/trac185/ext/boost/wave.hpp
branches/trac185/ext/boost/weak_ptr.hpp
branches/trac185/src/bin/auth/spec_config.h.in
Modified:
branches/trac185/ (props changed)
branches/trac185/ChangeLog
branches/trac185/Makefile.am
branches/trac185/README
branches/trac185/configure.ac
branches/trac185/src/bin/auth/Makefile.am
branches/trac185/src/bin/auth/auth.spec.pre.in
branches/trac185/src/bin/auth/main.cc
branches/trac185/src/bin/auth/tests/Makefile.am
branches/trac185/src/bin/bind10/bind10.py.in
branches/trac185/src/bin/bind10/bob.spec
branches/trac185/src/bin/bind10/run_bind10.sh.in
branches/trac185/src/bin/bindctl/bindcmd.py
branches/trac185/src/bin/bindctl/bindctl-source.py.in
branches/trac185/src/bin/bindctl/moduleinfo.py
branches/trac185/src/bin/bindctl/tests/bindctl_test.py
branches/trac185/src/bin/cmdctl/cmdctl.py.in
branches/trac185/src/bin/cmdctl/cmdctl.spec
branches/trac185/src/bin/cmdctl/tests/cmdctl_test.py
branches/trac185/src/bin/host/Makefile.am
branches/trac185/src/bin/loadzone/b10-loadzone.py.in
branches/trac185/src/bin/xfrin/ (props changed)
branches/trac185/src/bin/xfrout/xfrout.py.in
branches/trac185/src/lib/Makefile.am
branches/trac185/src/lib/cc/ (props changed)
branches/trac185/src/lib/cc/Makefile.am
branches/trac185/src/lib/cc/data.cc
branches/trac185/src/lib/cc/session.cc
branches/trac185/src/lib/cc/session.h
branches/trac185/src/lib/config/Makefile.am
branches/trac185/src/lib/config/ccsession.cc
branches/trac185/src/lib/config/ccsession.h
branches/trac185/src/lib/config/config_data.h
branches/trac185/src/lib/config/module_spec.cc
branches/trac185/src/lib/config/module_spec.h
branches/trac185/src/lib/config/tests/Makefile.am
branches/trac185/src/lib/config/tests/fake_session.cc
branches/trac185/src/lib/config/tests/fake_session.h
branches/trac185/src/lib/config/tests/module_spec_unittests.cc
branches/trac185/src/lib/datasrc/Makefile.am
branches/trac185/src/lib/datasrc/tests/Makefile.am
branches/trac185/src/lib/dns/ (props changed)
branches/trac185/src/lib/dns/Makefile.am
branches/trac185/src/lib/dns/name.cc
branches/trac185/src/lib/dns/name.h
branches/trac185/src/lib/dns/python_dns.cc
branches/trac185/src/lib/dns/rdata/generic/nsec_47.cc
branches/trac185/src/lib/dns/rdata/generic/rrsig_46.cc (props changed)
branches/trac185/src/lib/dns/tests/ (props changed)
branches/trac185/src/lib/dns/tests/Makefile.am
branches/trac185/src/lib/dns/tests/dnssectime_unittest.cc
branches/trac185/src/lib/dns/tests/name_unittest.cc
branches/trac185/src/lib/exceptions/Makefile.am
branches/trac185/src/lib/python/isc/cc/message.py
branches/trac185/src/lib/python/isc/cc/session.py
branches/trac185/src/lib/python/isc/cc/tests/session_test.py
branches/trac185/src/lib/python/isc/config/ccsession.py
branches/trac185/src/lib/python/isc/config/cfgmgr.py
branches/trac185/src/lib/python/isc/config/config_data.py
branches/trac185/src/lib/python/isc/config/module_spec.py
branches/trac185/src/lib/python/isc/config/tests/ccsession_test.py
branches/trac185/src/lib/python/isc/config/tests/cfgmgr_test.py
branches/trac185/src/lib/python/isc/config/tests/config_data_test.py
branches/trac185/src/lib/python/isc/config/tests/module_spec_test.py
branches/trac185/src/lib/xfr/Makefile.am
branches/trac185/src/lib/xfr/xfrout_client.cc
branches/trac185/src/lib/xfr/xfrout_client.h
Modified: branches/trac185/ChangeLog
==============================================================================
--- branches/trac185/ChangeLog (original)
+++ branches/trac185/ChangeLog Mon May 31 06:06:39 2010
@@ -1,3 +1,13 @@
+ 4. [bug] each
+ bin/auth: output now prepended with "[b10-auth]" (Trac #109, svn r1985)
+ 3. [func] each
+ bin/auth: removed custom query-processing code, changed
+ boost::asio code to use plain asio instead, and added asio
+ headers to the source tree. This allows building without
+ using an external boost library. (Trac #163, svn r1983)
+ 2. [func] jinmei
+ lib/dns: added a separate signature for Name::split() as a
+ convenient wrapper for common usage. (Trac #49, svn r1903)
1. [bug] jinmei
lib/dns: parameter validation of Name::split() was not sufficient,
and invalid parameters could cause integer overflow and make the
Modified: branches/trac185/Makefile.am
==============================================================================
--- branches/trac185/Makefile.am (original)
+++ branches/trac185/Makefile.am Mon May 31 06:06:39 2010
@@ -2,6 +2,8 @@
USE_LCOV=@USE_LCOV@
LCOV=@LCOV@
GENHTML=@GENHTML@
+
+DISTCLEANFILES = config.report
# When running distcheck target, do not install the configurations
DISTCHECK_CONFIGURE_FLAGS = --disable-install-configurations
Modified: branches/trac185/README
==============================================================================
--- branches/trac185/README (original)
+++ branches/trac185/README Mon May 31 06:06:39 2010
@@ -37,9 +37,6 @@
See the Guide for detailed installation directions.
BUILDING
-
-We recommend using the Boost libraries as it provides a safer TCP
-implementation in BIND 10.
Simple build instructions:
Modified: branches/trac185/configure.ac
==============================================================================
--- branches/trac185/configure.ac (original)
+++ branches/trac185/configure.ac Mon May 31 06:06:39 2010
@@ -87,9 +87,21 @@
# TODO: check for _sqlite3.py module
-# default compiler warning settings
+#
+# B10_CXXFLAGS is the default C++ compiler flags. This will (and should) be
+# used as the default value for each specifc AM_CXXFLAGS:
+# AM_CXXFLAGS = $(B10_CXXFLAGS)
+# AM_CXXFLAGS += ... # add module specific flags
+# We need this so that we can disable some specific compiler warnings per
+# module basis; since AM_CXXFLAGS are placed before CXXFLAGS, and since
+# gcc's -Wno-XXX option must be specified after -Wall or -Wextra, we cannot
+# specify the default warning flags in CXXFLAGS and let specific modules
+# "override" the default.
+#
+B10_CXXFLAGS=
+
if test "X$GCC" = "Xyes"; then
-CXXFLAGS="$CXXFLAGS -g -Wall -Wextra -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare"
+B10_CXXFLAGS="-g -Wall -Wextra -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare"
UNUSED_PARAM_ATTRIBUTE='__attribute__((unused))'
# Certain versions of gcc (g++) have a bug that incorrectly warns about
@@ -97,22 +109,26 @@
# translation unit. For these versions we have to disable -Werror.
werror_ok=0
CXXFLAGS_SAVED="$CXXFLAGS"
-CXXFLAGS="$CXXFLAGS -Werror"
+CXXFLAGS="$CXXFLAGS $B10_CXXFLAGS -Werror"
AC_MSG_CHECKING(for in-TU anonymous namespace breakage)
AC_TRY_COMPILE([namespace { class Foo {}; }
namespace isc {class Bar {Foo foo_;};} ],,
[AC_MSG_RESULT(no)
- werror_ok=1],
+ werror_ok=1
+ B10_CXXFLAGS="$B10_CXXFLAGS -Werror"],
[AC_MSG_RESULT(yes)])
CXXFLAGS="$CXXFLAGS_SAVED"
-fi
+fi dnl GCC = yes
+
+AM_CONDITIONAL(GCC_WERROR_OK, test $werror_ok = 1)
AC_DEFINE_UNQUOTED(UNUSED_PARAM, $UNUSED_PARAM_ATTRIBUTE, Define to compiler keyword indicating a function argument is intentionally unused)
-AM_CONDITIONAL(GCC_WERROR_OK, test $werror_ok = 1)
# produce PIC unless we disable shared libraries. need this for python bindings.
if test $enable_shared != "no" -a "X$GCC" = "Xyes"; then
- CXXFLAGS="$CXXFLAGS -fPIC"
-fi
+ B10_CXXFLAGS="$B10_CXXFLAGS -fPIC"
+fi
+
+AC_SUBST(B10_CXXFLAGS)
# Checks for libraries.
@@ -192,52 +208,6 @@
BOOST_LDFLAGS="-L$withval"
fi])
AC_SUBST(BOOST_LDFLAGS)
-
-# Check availability of the Boost System library
-
-AC_MSG_CHECKING([for boost::system library])
-AC_ARG_WITH([boost-system],
-AC_HELP_STRING([--with-boost-system],
- [specify whether to use the boost system library]),
- [with_boost_system="$withval"], [with_boost_system="auto"])
-
-if test "$with_boost_system" != "no"; then
- LDFLAGS_SAVED="$LDFLAGS"
- LIBS_SAVED="$LIBS"
- CPPFLAGS_SAVED="$CPPFLAGS"
- CPPFLAGS="$CPPFLAGS -Iext"
-
- for BOOST_TRY_LIB in boost_system boost_system-mt; do
- LDFLAGS="$LDFLAGS_SAVED ${BOOST_LDFLAGS}"
- LIBS="$LIBS_SAVED -l${BOOST_TRY_LIB}"
- AC_TRY_LINK([#include <boost/system/error_code.hpp>],
- [ boost::system::error_code error_code;
- std::string message(error_code.message());
- return 0; ],
- [ AC_MSG_RESULT(yes)
- BOOST_SYSTEM_LIB="-l${BOOST_TRY_LIB}"
- ],[])
- if test "X${BOOST_SYSTEM_LIB}" != X; then
- break
- fi
- done
-
- LDFLAGS="$LDFLAGS_SAVED"
- CPPFLAGS="$CPPFLAGS_SAVED"
- LIBS="$LIBS_SAVED"
-fi
-
-if test "X${BOOST_SYSTEM_LIB}" = X; then
- AC_MSG_RESULT(no)
- if test "$with_boost_system" = "yes"; then
- AC_MSG_ERROR([boost system library is requested but not found])
- fi
-else
- AC_DEFINE(HAVE_BOOST_SYSTEM, 1, Define to 1 if boost system library is available)
-fi
-
-AM_CONDITIONAL(HAVE_BOOST_SYSTEM, test "X${BOOST_SYSTEM_LIB}" != X)
-AC_SUBST(BOOST_SYSTEM_LIB)
# Check availability of the Boost Python library
@@ -340,19 +310,63 @@
PKG_CHECK_MODULES(SQLITE, sqlite3 >= 3.3.9, enable_features="$enable_features SQLite3")
+#
+# ASIO: we extensively use it as the C++ event management module.
+#
+# Use local ASIO headers from ext
+#
+CPPFLAGS="$CPPFLAGS -I\$(top_srcdir)/ext/asio"
+#
+# kqueue portability: ASIO uses kqueue by default if it's available (it's
+# generally available in BSD variants). Unfortunately, some public
+# implementation of kqueue forces a conversion from a pointer to an integer,
+# which is prohibited in C++ unless reinterpret_cast, C++'s most evil beast
+# (and ASIO doesn't use it anyway) is used. This will cause build error for
+# some of our C++ files including ASIO header files. The following check
+# detects such cases and tells ASIO not to use kqueue if so.
+AC_CHECK_FUNC(kqueue, ac_cv_have_kqueue=yes, ac_cv_have_kqueue=no)
+if test "X$ac_cv_have_kqueue" = "Xyes"; then
+ AC_MSG_CHECKING([whether kqueue EV_SET compiles in C++])
+ AC_TRY_COMPILE([
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/event.h>],
+[char* udata;
+EV_SET(NULL, 0, 0, 0, 0, 0, udata);],
+ [AC_MSG_RESULT(yes)],
+ [AC_MSG_RESULT([no, disable kqueue for ASIO])
+ CPPFLAGS="$CPPFLAGS -DASIO_DISABLE_KQUEUE=1"
+ ])
+fi
+
+# /dev/poll issue: ASIO uses /dev/poll by default if it's available (generally
+# the case with Solaris). Unfortunately its /dev/poll specific code would
+# trigger the gcc's "missing-field-initializers" warning, which would
+# subsequently make the build fail with -Werror. Further, older versions of
+# gcc don't provide an option to selectively suppress this warning.
+# So, for the moment, we simply disable the use of /dev/poll. Unless we
+# implement recursive DNS server with randomized ports, we don't need the
+# scalability that /dev/poll can provide, so this decision wouldn't affect
+# run time performance. Hpefully we can find a better solution or the ASIO
+# code will be updated by the time we really need it.
+AC_CHECK_HEADERS(sys/devpoll.h, ac_cv_have_devpoll=yes, ac_cv_have_devpoll=no)
+if test "X$ac_cv_have_devpoll" = "Xyes" -a "X$GCC" = "Xyes"; then
+ CPPFLAGS="$CPPFLAGS -DASIO_DISABLE_DEV_POLL=1"
+fi
+
# Check for headers from required devel kits.
# boost/shared_ptr.hpp is in ext in svn but not in tarball.
CPPFLAGS_SAVED=$CPPFLAGS
if test "X$BOOST_INCLUDES" = "X"; then
# abs_top_srcdir not defined yet
# so this is only useful to check. We'll replace it after the check.
- CPPFLAGS="$CPPFLAGS -Iext"
+ CPPFLAGS="$CPPFLAGS -Iext/boost"
fi
AC_CHECK_HEADERS([boost/shared_ptr.hpp boost/foreach.hpp],,
AC_MSG_ERROR([Missing required header files.]))
CPPFLAGS=$CPPFLAGS_SAVED
if test "X$BOOST_INCLUDES" = "X"; then
- CPPFLAGS="$CPPFLAGS -I\$(top_srcdir)/ext"
+ CPPFLAGS="$CPPFLAGS -I\$(top_srcdir)/ext/boost"
fi
AC_ARG_ENABLE(man, [AC_HELP_STRING([--enable-man],
@@ -431,7 +445,7 @@
src/bin/msgq/tests/msgq_test
src/bin/msgq/run_msgq.sh
src/bin/auth/auth.spec.pre
- src/bin/auth/spec_config.h
+ src/bin/auth/spec_config.h.pre
src/lib/config/tests/data_def_unittests_config.h
src/lib/python/isc/config/tests/config_test
src/lib/python/isc/cc/tests/cc_test
@@ -473,9 +487,9 @@
CPPFLAGS: $CPPFLAGS
CFLAGS: $CFLAGS
CXXFLAGS: $CXXFLAGS
+ B10_CXXFLAGS: $B10_CXXFLAGS
dnl includes too
Boost Python: $BOOST_PYTHON_LIB
- Boost System: $BOOST_SYSTEM_LIB
SQLite: $SQLITE_CFLAGS
$SQLITE_LIBS
Modified: branches/trac185/src/bin/auth/Makefile.am
==============================================================================
--- branches/trac185/src/bin/auth/Makefile.am (original)
+++ branches/trac185/src/bin/auth/Makefile.am Mon May 31 06:06:39 2010
@@ -2,13 +2,12 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
-if GCC_WERROR_OK
-AM_CPPFLAGS += -Werror
-endif
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
pkglibexecdir = $(libexecdir)/@PACKAGE@
-CLEANFILES = *.gcno *.gcda auth.spec
+CLEANFILES = *.gcno *.gcda auth.spec spec_config.h
man_MANS = b10-auth.8
EXTRA_DIST = $(man_MANS) b10-auth.xml
@@ -23,6 +22,23 @@
auth.spec: auth.spec.pre
$(SED) -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" auth.spec.pre >$@
+spec_config.h: spec_config.h.pre
+ $(SED) -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" spec_config.h.pre >$@
+
+# This is a wrapper library solely used for b10-auth. The ASIO header files
+# have some code fragments that would hit gcc's unused-parameter warning,
+# which would make the build fail with -Werror (our default setting).
+# We don't want to lower the warning level for our own code just for ASIO,
+# so as a workaround we extract the ASIO related code into a separate library,
+# only for which we accept the unused-parameter warning.
+lib_LIBRARIES = libasio_link.a
+libasio_link_a_SOURCES = asio_link.cc asio_link.h
+# Note: the ordering matters: -Wno-... must follow -Wextra (defined in
+# B10_CXXFLAGS)
+libasio_link_a_CXXFLAGS = $(AM_CXXFLAGS) -Wno-unused-parameter
+libasio_link_a_CPPFLAGS = $(AM_CPPFLAGS)
+
+BUILT_SOURCES = spec_config.h
pkglibexec_PROGRAMS = b10-auth
b10_auth_SOURCES = auth_srv.cc auth_srv.h
b10_auth_SOURCES += common.h
@@ -32,13 +48,10 @@
b10_auth_LDADD += $(top_builddir)/src/lib/config/.libs/libcfgclient.a
b10_auth_LDADD += $(top_builddir)/src/lib/cc/libcc.a
b10_auth_LDADD += $(top_builddir)/src/lib/exceptions/.libs/libexceptions.a
+b10_auth_LDADD += $(top_builddir)/src/bin/auth/libasio_link.a
b10_auth_LDADD += $(SQLITE_LIBS)
-if HAVE_BOOST_SYSTEM
if HAVE_BOOST_PYTHON
b10_auth_LDADD += $(top_builddir)/src/lib/xfr/.libs/libxfr.a
-endif
-b10_auth_LDFLAGS = $(AM_LDFLAGS) $(BOOST_LDFLAGS)
-b10_auth_LDADD += $(BOOST_SYSTEM_LIB)
endif
# TODO: config.h.in is wrong because doesn't honor pkgdatadir
Modified: branches/trac185/src/bin/auth/auth.spec.pre.in
==============================================================================
--- branches/trac185/src/bin/auth/auth.spec.pre.in (original)
+++ branches/trac185/src/bin/auth/auth.spec.pre.in Mon May 31 06:06:39 2010
@@ -1,6 +1,7 @@
{
"module_spec": {
"module_name": "Auth",
+ "module_description": "Authoritative service",
"config_data": [
{ "item_name": "database_file",
"item_type": "string",
Modified: branches/trac185/src/bin/auth/main.cc
==============================================================================
--- branches/trac185/src/bin/auth/main.cc (original)
+++ branches/trac185/src/bin/auth/main.cc Mon May 31 06:06:39 2010
@@ -28,10 +28,6 @@
#include <iostream>
#include <boost/foreach.hpp>
-#ifdef HAVE_BOOST_SYSTEM
-#include <boost/bind.hpp>
-#include <boost/asio.hpp>
-#endif // HAVE_BOOST_SYSTEM
#include <exceptions/exceptions.h>
@@ -43,26 +39,12 @@
#include <cc/data.h>
#include <config/ccsession.h>
-#if defined(HAVE_BOOST_SYSTEM) && defined(HAVE_BOOST_PYTHON)
-#define USE_XFROUT
-#include <xfr/xfrout_client.h>
-#endif
-
#include "spec_config.h"
#include "common.h"
#include "auth_srv.h"
+#include "asio_link.h"
using namespace std;
-#ifdef USE_XFROUT
-using namespace isc::xfr;
-#endif
-
-#ifdef HAVE_BOOST_SYSTEM
-using namespace boost::asio;
-using ip::udp;
-using ip::tcp;
-#endif // HAVE_BOOST_SYSTEM
-
using namespace isc::data;
using namespace isc::cc;
using namespace isc::config;
@@ -79,13 +61,8 @@
* todo: turn this around, and put handlers in the authserver
* class itself? */
AuthSrv *auth_server;
-#ifdef HAVE_BOOST_SYSTEM
-// TODO: this should be a property of AuthSrv, and AuthSrv needs
-// a stop() method (so the shutdown command can be handled)
-boost::asio::io_service io_service_;
-#else
-bool running;
-#endif // HAVE_BOOST_SYSTEM
+
+asio_link::IOService* io_service;
ElementPtr
my_config_handler(ElementPtr new_config) {
@@ -101,595 +78,11 @@
/* let's add that message to our answer as well */
answer->get("result")->add(args);
} else if (command == "shutdown") {
-#ifdef HAVE_BOOST_SYSTEM
- io_service_.stop();
-#else
- running = false;
-#endif // HAVE_BOOST_SYSTEM
+ io_service->stop();
}
return answer;
}
-
-#ifdef USE_XFROUT
-//TODO. The sample way for checking axfr query, the code should be merged to auth server class
-static bool
-check_axfr_query(char *msg_data, uint16_t msg_len)
-{
- if (msg_len < 15)
- return false;
-
- uint16_t query_type = *(uint16_t *)(msg_data + (msg_len - 4));
- if ( query_type == 0xFC00)
- return true;
-
- return false;
-}
-
-//TODO. Send the xfr query to xfrout module, the code should be merged to auth server class
-static void
-dispatch_axfr_query(int tcp_sock, char axfr_query[], uint16_t query_len)
-{
- std::string path = string(UNIX_SOCKET_FILE);
- XfroutClient xfr_client(path);
- try {
- xfr_client.connect();
- xfr_client.sendXfroutRequestInfo(tcp_sock, (uint8_t *)axfr_query, query_len);
- xfr_client.disconnect();
- }
- catch (const std::exception & err) {
- //if (verbose_mode)
- cerr << "error handle xfr query:" << err.what() << endl;
- }
-}
-#endif
-
-#ifdef HAVE_BOOST_SYSTEM
-//
-// Helper classes for asynchronous I/O using boost::asio
-//
-class TCPClient {
-public:
- TCPClient(io_service& io_service) :
- socket_(io_service),
- response_buffer_(0),
- responselen_buffer_(TCP_MESSAGE_LENGTHSIZE),
- response_renderer_(response_buffer_),
- dns_message_(Message::PARSE)
- {}
-
- void start() {
- async_read(socket_, boost::asio::buffer(data_, TCP_MESSAGE_LENGTHSIZE),
- boost::bind(&TCPClient::headerRead, this,
- placeholders::error,
- placeholders::bytes_transferred));
- }
-
- tcp::socket& getSocket() { return (socket_); }
-
- void headerRead(const boost::system::error_code& error,
- size_t bytes_transferred)
- {
- if (!error) {
- InputBuffer dnsbuffer(data_, bytes_transferred);
-
- uint16_t msglen = dnsbuffer.readUint16();
- async_read(socket_, boost::asio::buffer(data_, msglen),
-
- boost::bind(&TCPClient::requestRead, this,
- placeholders::error,
- placeholders::bytes_transferred));
- } else {
- delete this;
- }
- }
-
- void requestRead(const boost::system::error_code& error,
- size_t bytes_transferred)
- {
- if (!error) {
- InputBuffer dnsbuffer(data_, bytes_transferred);
-#ifdef USE_XFROUT
- if (check_axfr_query(data_, bytes_transferred)) {
- dispatch_axfr_query(socket_.native(), data_, bytes_transferred);
- // start to get new query ?
- start();
- } else {
-#endif
- if (auth_server->processMessage(dnsbuffer, dns_message_,
- response_renderer_, false)) {
- responselen_buffer_.writeUint16(response_buffer_.getLength());
- async_write(socket_,
- boost::asio::buffer(
- responselen_buffer_.getData(),
- responselen_buffer_.getLength()),
- boost::bind(&TCPClient::responseWrite, this,
- placeholders::error));
- } else {
- delete this;
- }
-#ifdef USE_XFROUT
- }
-#endif
- } else {
- delete this;
- }
- }
-
- void responseWrite(const boost::system::error_code& error) {
- if (!error) {
- async_write(socket_,
- boost::asio::buffer(response_buffer_.getData(),
- response_buffer_.getLength()),
- boost::bind(&TCPClient::handleWrite, this,
- placeholders::error));
- } else {
- delete this;
- }
- }
-
- void handleWrite(const boost::system::error_code& error) {
- if (!error) {
- start(); // handle next request, if any.
- } else {
- delete this;
- }
- }
-
-private:
- tcp::socket socket_;
- OutputBuffer response_buffer_;
- OutputBuffer responselen_buffer_;
- MessageRenderer response_renderer_;
- Message dns_message_;
- enum { MAX_LENGTH = 65535 };
- static const size_t TCP_MESSAGE_LENGTHSIZE = 2;
- char data_[MAX_LENGTH];
-};
-
-class TCPServer {
-public:
- TCPServer(io_service& io_service, int af, short port) :
- io_service_(io_service), acceptor_(io_service_),
- listening_(new TCPClient(io_service_))
- {
- tcp::endpoint endpoint(af == AF_INET6 ? tcp::v6() : tcp::v4(), port);
- acceptor_.open(endpoint.protocol());
- // Set v6-only (we use a different instantiation for v4,
- // otherwise asio will bind to both v4 and v6
- if (af == AF_INET6) {
- acceptor_.set_option(ip::v6_only(true));
- }
- acceptor_.set_option(tcp::acceptor::reuse_address(true));
- acceptor_.bind(endpoint);
- acceptor_.listen();
- acceptor_.async_accept(listening_->getSocket(),
- boost::bind(&TCPServer::handleAccept, this,
- listening_, placeholders::error));
- }
-
- ~TCPServer() { delete listening_; }
-
- void handleAccept(TCPClient* new_client,
- const boost::system::error_code& error)
- {
- if (!error) {
- assert(new_client == listening_);
- new_client->start();
- listening_ = new TCPClient(io_service_);
- acceptor_.async_accept(listening_->getSocket(),
- boost::bind(&TCPServer::handleAccept,
- this, listening_,
- placeholders::error));
- } else {
- delete new_client;
- }
- }
-
-private:
- io_service& io_service_;
- tcp::acceptor acceptor_;
- TCPClient* listening_;
-};
-
-class UDPServer {
-public:
- UDPServer(io_service& io_service, int af, short port) :
- io_service_(io_service),
- socket_(io_service, af == AF_INET6 ? udp::v6() : udp::v4()),
- response_buffer_(0),
- response_renderer_(response_buffer_),
- dns_message_(Message::PARSE)
- {
- // Set v6-only (we use a different instantiation for v4,
- // otherwise asio will bind to both v4 and v6
- if (af == AF_INET6) {
- socket_.set_option(boost::asio::ip::v6_only(true));
- socket_.bind(udp::endpoint(udp::v6(), port));
- } else {
- socket_.bind(udp::endpoint(udp::v4(), port));
- }
- startReceive();
- }
-
- void handleRequest(const boost::system::error_code& error,
- size_t bytes_recvd)
- {
- if (!error && bytes_recvd > 0) {
- InputBuffer request_buffer(data_, bytes_recvd);
-
- dns_message_.clear(Message::PARSE);
- response_renderer_.clear();
- if (auth_server->processMessage(request_buffer, dns_message_,
- response_renderer_, true)) {
- socket_.async_send_to(
- boost::asio::buffer(response_buffer_.getData(),
- response_buffer_.getLength()),
- sender_endpoint_,
- boost::bind(&UDPServer::sendCompleted,
- this,
- placeholders::error,
- placeholders::bytes_transferred));
- } else {
- startReceive();
- }
- } else {
- startReceive();
- }
- }
-
- void sendCompleted(const boost::system::error_code& error UNUSED_PARAM,
- size_t bytes_sent UNUSED_PARAM)
- {
- // Even if error occurred there's nothing to do. Simply handle
- // the next request.
- startReceive();
- }
-private:
- void startReceive() {
- socket_.async_receive_from(
- boost::asio::buffer(data_, MAX_LENGTH), sender_endpoint_,
- boost::bind(&UDPServer::handleRequest, this,
- placeholders::error,
- placeholders::bytes_transferred));
- }
-
-private:
- io_service& io_service_;
- udp::socket socket_;
- OutputBuffer response_buffer_;
- MessageRenderer response_renderer_;
- Message dns_message_;
- udp::endpoint sender_endpoint_;
- enum { MAX_LENGTH = 4096 };
- char data_[MAX_LENGTH];
-};
-
-struct ServerSet {
- ServerSet() : udp4_server(NULL), udp6_server(NULL),
- tcp4_server(NULL), tcp6_server(NULL)
- {}
- ~ServerSet() {
- delete udp4_server;
- delete udp6_server;
- delete tcp4_server;
- delete tcp6_server;
- }
- UDPServer* udp4_server;
- UDPServer* udp6_server;
- TCPServer* tcp4_server;
- TCPServer* tcp6_server;
-};
-
-void
-run_server(const char* port, const bool use_ipv4, const bool use_ipv6,
- AuthSrv* srv UNUSED_PARAM)
-{
- ServerSet servers;
- short portnum = atoi(port);
-
- if (use_ipv4) {
- servers.udp4_server = new UDPServer(io_service_, AF_INET, portnum);
- servers.tcp4_server = new TCPServer(io_service_, AF_INET, portnum);
- }
- if (use_ipv6) {
- servers.udp6_server = new UDPServer(io_service_, AF_INET6, portnum);
- servers.tcp6_server = new TCPServer(io_service_, AF_INET6, portnum);
- }
-
- cout << "Server started." << endl;
- io_service_.run();
-}
-#else // !HAVE_BOOST_SYSTEM
-struct SocketSet {
- SocketSet() : ups4(-1), tps4(-1), ups6(-1), tps6(-1) {}
- ~SocketSet() {
- if (ups4 >= 0) {
- close(ups4);
- }
- if (tps4 >= 0) {
- close(tps4);
- }
- if (ups6 >= 0) {
- close(ups6);
- }
- if (tps4 >= 0) {
- close(tps6);
- }
- }
- int ups4, tps4, ups6, tps6;
-};
-
-int
-getUDPSocket(int af, const char* port) {
- struct addrinfo hints, *res;
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- hints.ai_socktype = SOCK_DGRAM;
- hints.ai_flags = AI_PASSIVE;
- hints.ai_protocol = IPPROTO_UDP;
-
- int error = getaddrinfo(NULL, port, &hints, &res);
- if (error != 0) {
- isc_throw(FatalError, "getaddrinfo failed: " << gai_strerror(error));
- }
-
- int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
- if (s < 0) {
- isc_throw(FatalError, "failed to open socket");
- }
-
- if (af == AF_INET6) {
- int on = 1;
- if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
- cerr << "couldn't set IPV6_V6ONLY socket option" << endl;
- // proceed anyway
- }
- }
-
- if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
- isc_throw(FatalError, "binding socket failure");
- }
-
- return (s);
-}
-
-int
-getTCPSocket(int af, const char* port) {
- struct addrinfo hints, *res;
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags = AI_PASSIVE;
- hints.ai_protocol = IPPROTO_TCP;
-
- int error = getaddrinfo(NULL, port, &hints, &res);
- if (error != 0) {
- isc_throw(FatalError, "getaddrinfo failed: " << gai_strerror(error));
- }
-
- int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
- if (s < 0) {
- isc_throw(FatalError, "failed to open socket");
- }
-
- int on = 1;
- if (af == AF_INET6) {
- if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
- cerr << "couldn't set IPV6_V6ONLY socket option" << endl;
- }
- // proceed anyway
- }
-
- if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
- cerr << "couldn't set SO_REUSEADDR socket option" << endl;
- }
-
- if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
- isc_throw(FatalError, "binding socket failure");
- }
-
- if (listen(s, 100) < 0) {
- isc_throw(FatalError, "failed to listen on a TCP socket");
- }
- return (s);
-}
-
-void
-processMessageUDP(const int fd, Message& dns_message,
- MessageRenderer& response_renderer)
-{
- struct sockaddr_storage ss;
- socklen_t sa_len = sizeof(ss);
- struct sockaddr* sa = static_cast<struct sockaddr*>((void*)&ss);
- char recvbuf[4096];
- int cc;
-
- dns_message.clear(Message::PARSE);
- response_renderer.clear();
- if ((cc = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, sa, &sa_len)) > 0) {
- InputBuffer buffer(recvbuf, cc);
- if (auth_server->processMessage(buffer, dns_message, response_renderer,
- true)) {
- cc = sendto(fd, response_renderer.getData(),
- response_renderer.getLength(), 0, sa, sa_len);
- if (cc != response_renderer.getLength()) {
- cerr << "UDP send error" << endl;
- }
- }
- } else if (verbose_mode) {
- cerr << "UDP receive error" << endl;
- }
-}
-
-// XXX: this function does not handle partial reads or partial writes,
-// and is VERY UNSAFE - will probably be removed or rewritten
-void
-processMessageTCP(const int fd, Message& dns_message,
- MessageRenderer& response_renderer)
-{
- struct sockaddr_storage ss;
- socklen_t sa_len = sizeof(ss);
- struct sockaddr* sa = static_cast<struct sockaddr*>((void*)&ss);
- char sizebuf[2];
- int cc;
-
- int ts = accept(fd, sa, &sa_len);
- if (ts < 0) {
- if (verbose_mode) {
- cerr << "[XX] TCP accept failure:" << endl;
- return;
- }
- }
-
- if (verbose_mode) {
- cerr << "[XX] process TCP" << endl;
- }
- cc = recv(ts, sizebuf, 2, 0);
- if (cc < 0) {
- if (verbose_mode) {
- cerr << "[XX] TCP recv failure:" << endl;
- }
- close(ts);
- return;
- }
- if (verbose_mode) {
- cerr << "[XX] got: " << cc << endl;
- }
- uint16_t size, size_n;
- memcpy(&size_n, sizebuf, 2);
- size = ntohs(size_n);
- if (verbose_mode) {
- cerr << "[XX] got: " << size << endl;
- }
-
- vector<char> message_buffer;
- message_buffer.reserve(size);
- cc = 0;
- while (cc < size) {
- if (verbose_mode) {
- cerr << "[XX] cc now: " << cc << " of " << size << endl;
- }
- const int cc0 = recv(ts, &message_buffer[0] + cc, size - cc, 0);
- if (cc0 < 0) {
- if (verbose_mode) {
- cerr << "TCP receive error" << endl;
- close(ts);
- return;
- }
- }
- if (cc0 == 0) {
- // client closed connection
- close(ts);
- return;
- }
- cc += cc0;
- }
-
- InputBuffer buffer(&message_buffer[0], size);
- dns_message.clear(Message::PARSE);
- response_renderer.clear();
- if (auth_server->processMessage(buffer, dns_message, response_renderer,
- false)) {
- size = response_renderer.getLength();
- size_n = htons(size);
- if (send(ts, &size_n, 2, 0) == 2) {
- cc = send(ts, response_renderer.getData(),
- response_renderer.getLength(), 0);
- if (cc == -1) {
- if (verbose_mode) {
- cerr << "[AuthSrv] error in sending TCP response message" <<
- endl;
- }
- } else {
- if (verbose_mode) {
- cerr << "[XX] sent TCP response: " << cc << " bytes"
- << endl;
- }
- }
- } else {
- if (verbose_mode) {
- cerr << "TCP send error" << endl;
- }
- }
- }
-
- // TODO: we don't check for more queries on the stream atm
- close(ts);
-}
-
-void
-run_server(const char* port, const bool use_ipv4, const bool use_ipv6,
- AuthSrv* srv)
-{
- SocketSet socket_set;
- fd_set fds_base;
- int nfds = -1;
-
- FD_ZERO(&fds_base);
- if (use_ipv4) {
- socket_set.ups4 = getUDPSocket(AF_INET, port);
- FD_SET(socket_set.ups4, &fds_base);
- nfds = max(nfds, socket_set.ups4);
- socket_set.tps4 = getTCPSocket(AF_INET, port);
- FD_SET(socket_set.tps4, &fds_base);
- nfds = max(nfds, socket_set.tps4);
- }
- if (use_ipv6) {
- socket_set.ups6 = getUDPSocket(AF_INET6, port);
- FD_SET(socket_set.ups6, &fds_base);
- nfds = max(nfds, socket_set.ups6);
- socket_set.tps6 = getTCPSocket(AF_INET6, port);
- FD_SET(socket_set.tps6, &fds_base);
- nfds = max(nfds, socket_set.tps6);
- }
- ++nfds;
-
- cout << "Server started." << endl;
-
- if (srv->configSession() == NULL) {
- isc_throw(FatalError, "Config session not initalized");
- }
-
- int ss = srv->configSession()->getSocket();
- Message dns_message(Message::PARSE);
- OutputBuffer resonse_buffer(0);
- MessageRenderer response_renderer(resonse_buffer);
-
- running = true;
- while (running) {
- fd_set fds = fds_base;
- FD_SET(ss, &fds);
- ++nfds;
-
- int n = select(nfds, &fds, NULL, NULL, NULL);
- if (n < 0) {
- if (errno != EINTR) {
- isc_throw(FatalError, "select error");
- }
- continue;
- }
-
- if (socket_set.ups4 >= 0 && FD_ISSET(socket_set.ups4, &fds)) {
- processMessageUDP(socket_set.ups4, dns_message, response_renderer);
- }
- if (socket_set.ups6 >= 0 && FD_ISSET(socket_set.ups6, &fds)) {
- processMessageUDP(socket_set.ups6, dns_message, response_renderer);
- }
- if (socket_set.tps4 >= 0 && FD_ISSET(socket_set.tps4, &fds)) {
- processMessageTCP(socket_set.tps4, dns_message, response_renderer);
- }
- if (socket_set.tps6 >= 0 && FD_ISSET(socket_set.tps6, &fds)) {
- processMessageTCP(socket_set.tps6, dns_message, response_renderer);
- }
- if (FD_ISSET(ss, &fds)) {
- srv->configSession()->checkCommand();
- }
- }
-}
-#endif // HAVE_BOOST_SYSTEM
void
usage() {
@@ -734,7 +127,7 @@
}
if (!use_ipv4 && !use_ipv6) {
- cerr << "-4 and -6 can't coexist" << endl;
+ cerr << "[b10-auth] Error: -4 and -6 can't coexist" << endl;
usage();
}
@@ -752,22 +145,21 @@
auth_server = new AuthSrv;
auth_server->setVerbose(verbose_mode);
-#ifdef HAVE_BOOST_SYSTEM
- ModuleCCSession cs(specfile, io_service_, my_config_handler,
- my_command_handler);
-#else
ModuleCCSession cs(specfile, my_config_handler, my_command_handler);
-#endif
auth_server->setConfigSession(&cs);
auth_server->updateConfig(ElementPtr());
- run_server(port, use_ipv4, use_ipv6, auth_server);
+ io_service = new asio_link::IOService(auth_server, port, use_ipv4,
+ use_ipv6);
+ cout << "[b10-auth] Server started." << endl;
+ io_service->run();
} catch (const std::exception& ex) {
cerr << ex.what() << endl;
ret = 1;
}
+ delete io_service;
delete auth_server;
return (ret);
}
Modified: branches/trac185/src/bin/auth/tests/Makefile.am
==============================================================================
--- branches/trac185/src/bin/auth/tests/Makefile.am (original)
+++ branches/trac185/src/bin/auth/tests/Makefile.am Mon May 31 06:06:39 2010
@@ -1,6 +1,8 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_builddir)/src/lib/dns -I$(top_srcdir)/src/bin
AM_CPPFLAGS += -DTEST_DATA_DIR=\"$(srcdir)/testdata\"
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
@@ -21,10 +23,6 @@
run_unittests_LDADD += $(top_builddir)/src/lib/config/.libs/libcfgclient.a
run_unittests_LDADD += $(top_builddir)/src/lib/cc/libcc.a
run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/.libs/libexceptions.a
-if HAVE_BOOST_SYSTEM
-run_unittests_LDFLAGS += $(BOOST_LDFLAGS)
-run_unittests_LDADD += $(BOOST_SYSTEM_LIB)
-endif
endif
noinst_PROGRAMS = $(TESTS)
Modified: branches/trac185/src/bin/bind10/bind10.py.in
==============================================================================
--- branches/trac185/src/bin/bind10/bind10.py.in (original)
+++ branches/trac185/src/bin/bind10/bind10.py.in Mon May 31 06:06:39 2010
@@ -286,10 +286,12 @@
# start the xfrout before auth-server, to make sure every xfr-query can be
# processed properly.
+ xfrout_args = ['b10-xfrout']
if self.verbose:
sys.stdout.write("Starting b10-xfrout\n")
- try:
- xfrout = ProcessInfo("b10-xfrout", ["b10-xfrout"],
+ xfrout_args += ['-v']
+ try:
+ xfrout = ProcessInfo("b10-xfrout", xfrout_args,
{ 'ISC_MSGQ_PORT': str(self.c_channel_port)})
except Exception as e:
c_channel.process.kill()
@@ -319,10 +321,12 @@
sys.stdout.write("Started b10-auth (PID %d)\n" % auth.pid)
# start b10-xfrin
+ xfrin_args = ['b10-xfrin']
if self.verbose:
sys.stdout.write("Starting b10-xfrin\n")
- try:
- xfrind = ProcessInfo("b10-xfrin", ['b10-xfrin'],
+ xfrin_args += ['-v']
+ try:
+ xfrind = ProcessInfo("b10-xfrin", xfrin_args,
{ 'ISC_MSGQ_PORT': str(self.c_channel_port)})
except Exception as e:
c_channel.process.kill()
@@ -336,10 +340,12 @@
# start the b10-cmdctl
# XXX: we hardcode port 8080
+ cmdctl_args = ['b10-cmdctl']
if self.verbose:
sys.stdout.write("Starting b10-cmdctl on port 8080\n")
- try:
- cmd_ctrld = ProcessInfo("b10-cmdctl", ['b10-cmdctl'],
+ cmdctl_args += ['-v']
+ try:
+ cmd_ctrld = ProcessInfo("b10-cmdctl", cmdctl_args,
{ 'ISC_MSGQ_PORT': str(self.c_channel_port)})
except Exception as e:
c_channel.process.kill()
Modified: branches/trac185/src/bin/bind10/bob.spec
==============================================================================
--- branches/trac185/src/bin/bind10/bob.spec (original)
+++ branches/trac185/src/bin/bind10/bob.spec Mon May 31 06:06:39 2010
@@ -1,6 +1,7 @@
{
"module_spec": {
"module_name": "Boss",
+ "module_description": "Master process",
"config_data": [
{
"item_name": "example_string",
Modified: branches/trac185/src/bin/bind10/run_bind10.sh.in
==============================================================================
--- branches/trac185/src/bin/bind10/run_bind10.sh.in (original)
+++ branches/trac185/src/bin/bind10/run_bind10.sh.in Mon May 31 06:06:39 2010
@@ -23,7 +23,7 @@
PATH=@abs_top_builddir@/src/bin/msgq:@abs_top_builddir@/src/bin/auth:@abs_top_builddir@/src/bin/cfgmgr:@abs_top_builddir@/src/bin/cmdctl:@abs_top_builddir@/src/bin/xfrin:@abs_top_builddir@/src/bin/xfrout:$PATH
export PATH
-PYTHONPATH=@abs_top_builddir@/src/lib/python
+PYTHONPATH=@abs_top_builddir@/src/lib/python:@abs_top_builddir@/src/lib/dns/.libs:@abs_top_builddir@/src/lib/xfr/.libs
export PYTHONPATH
B10_FROM_SOURCE=@abs_top_srcdir@
Modified: branches/trac185/src/bin/bindctl/bindcmd.py
==============================================================================
--- branches/trac185/src/bin/bindctl/bindcmd.py (original)
+++ branches/trac185/src/bin/bindctl/bindcmd.py Mon May 31 06:06:39 2010
@@ -49,7 +49,7 @@
except ImportError:
my_readline = sys.stdin.readline
-
+CONFIG_MODULE_NAME = 'config'
CONST_BINDCTL_HELP = """
usage: <module name> <command name> [param1 = value1 [, param2 = value2]]
Type Tab character to get the hint of module/command/parameters.
@@ -180,13 +180,9 @@
def _update_commands(self):
- '''Get the commands of all modules. '''
- cmd_spec = self.send_GET('/command_spec')
- if not cmd_spec:
- return
-
- for module_name in cmd_spec.keys():
- self._prepare_module_commands(module_name, cmd_spec[module_name])
+ '''Update the commands of all modules. '''
+ for module_name in self.config_data.get_config_item_list():
+ self._prepare_module_commands(self.config_data.get_module_spec(module_name))
def send_GET(self, url, body = None):
'''Send GET request to cmdctl, session id is send with the name
@@ -222,17 +218,18 @@
self.prompt = self.location + self.prompt_end
return stop
- def _prepare_module_commands(self, module_name, module_commands):
+ def _prepare_module_commands(self, module_spec):
'''Prepare the module commands'''
- module = ModuleInfo(name = module_name,
- desc = "same here")
- for command in module_commands:
+ module = ModuleInfo(name = module_spec.get_module_name(),
+ desc = module_spec.get_module_description())
+ for command in module_spec.get_commands_spec():
cmd = CommandInfo(name = command["command_name"],
desc = command["command_description"])
for arg in command["command_args"]:
param = ParamInfo(name = arg["item_name"],
type = arg["item_type"],
- optional = bool(arg["item_optional"]))
+ optional = bool(arg["item_optional"]),
+ param_spec = arg)
if ("item_default" in arg):
param.default = arg["item_default"]
cmd.add_param(param)
@@ -305,12 +302,20 @@
if not name in params and not param_nr in params:
raise CmdMissParamSyntaxError(cmd.module, cmd.command, name)
param_nr += 1
-
+
+ # Convert parameter value according parameter spec file.
+ # Ignore check for commands belongs to module 'config'
+ if cmd.module != CONFIG_MODULE_NAME:
+ for param_name in cmd.params:
+ param_spec = command_info.get_param_with_name(param_name).param_spec
+ cmd.params[param_name] = isc.config.config_data.convert_type(param_spec, cmd.params[param_name])
+
+
def _handle_cmd(self, cmd):
'''Handle a command entered by the user'''
if cmd.command == "help" or ("help" in cmd.params.keys()):
self._handle_help(cmd)
- elif cmd.module == "config":
+ elif cmd.module == CONFIG_MODULE_NAME:
self.apply_config_cmd(cmd)
else:
self.apply_cmd(cmd)
@@ -361,7 +366,7 @@
else:
hints = self._get_param_startswith(cmd.module, cmd.command,
text)
- if cmd.module == "config":
+ if cmd.module == CONFIG_MODULE_NAME:
# grm text has been stripped of slashes...
my_text = self.location + "/" + cur_line.rpartition(" ")[2]
list = self.config_data.get_config_item_list(my_text.rpartition("/")[0], True)
@@ -437,6 +442,9 @@
self._validate_cmd(cmd)
self._handle_cmd(cmd)
except BindCtlException as e:
+ print("Error! ", e)
+ self._print_correct_usage(e)
+ except isc.cc.data.DataTypeError as e:
print("Error! ", e)
self._print_correct_usage(e)
Modified: branches/trac185/src/bin/bindctl/bindctl-source.py.in
==============================================================================
--- branches/trac185/src/bin/bindctl/bindctl-source.py.in (original)
+++ branches/trac185/src/bin/bindctl/bindctl-source.py.in Mon May 31 06:06:39 2010
@@ -29,7 +29,7 @@
def prepare_config_commands(tool):
'''Prepare fixed commands for local configuration editing'''
- module = ModuleInfo(name = "config", desc = "Configuration commands")
+ module = ModuleInfo(name = CONFIG_MODULE_NAME, desc = "Configuration commands")
cmd = CommandInfo(name = "show", desc = "Show configuration")
param = ParamInfo(name = "identifier", type = "string", optional=True)
cmd.add_param(param)
Modified: branches/trac185/src/bin/bindctl/moduleinfo.py
==============================================================================
--- branches/trac185/src/bin/bindctl/moduleinfo.py (original)
+++ branches/trac185/src/bin/bindctl/moduleinfo.py Mon May 31 06:06:39 2010
@@ -33,17 +33,21 @@
class ParamInfo:
"""One parameter of one command.
- Each command parameter has four attributes:
- parameter name, parameter type, parameter value, and parameter description
+ Each command parameter has five attributes:
+ parameter name, parameter type, parameter value,
+ parameter description and paramter's spec(got from
+ module spec file).
"""
def __init__(self, name, desc = '', type = STRING_TYPE,
- optional = False, value = '', default_value = ''):
+ optional = False, value = '', default_value = '',
+ param_spec = None):
self.name = name
self.type = type
self.value = value
self.default_value = default_value
self.desc = desc
self.is_optional = optional
+ self.param_spec = param_spec
def __str__(self):
return str("\t%s <type: %s> \t(%s)" % (self.name, self.type, self.desc))
Modified: branches/trac185/src/bin/bindctl/tests/bindctl_test.py
==============================================================================
--- branches/trac185/src/bin/bindctl/tests/bindctl_test.py (original)
+++ branches/trac185/src/bin/bindctl/tests/bindctl_test.py Mon May 31 06:06:39 2010
@@ -15,6 +15,7 @@
import unittest
+import isc.cc.data
from bindctl import cmdparse
from bindctl import bindcmd
from bindctl.moduleinfo import *
@@ -92,14 +93,21 @@
"""Create one bindcmd"""
tool = bindcmd.BindCmdInterpreter()
- zone_file_param = ParamInfo(name = "zone_file")
- zone_name = ParamInfo(name = 'zone_name')
+ string_spec = { 'item_type' : 'string',
+ 'item_optional' : False,
+ 'item_default' : ''}
+ int_spec = { 'item_type' : 'integer',
+ 'item_optional' : False,
+ 'item_default' : 10}
+ zone_file_param = ParamInfo(name = "zone_file", param_spec = string_spec)
+ zone_name = ParamInfo(name = 'zone_name', param_spec = string_spec)
load_cmd = CommandInfo(name = "load")
load_cmd.add_param(zone_file_param)
load_cmd.add_param(zone_name)
- param_master = ParamInfo(name = "master", optional = True)
- param_allow_update = ParamInfo(name = "allow_update", optional = True)
+ param_master = ParamInfo(name = "master", optional = True, param_spec = string_spec)
+ param_master = ParamInfo(name = "port", optional = True, param_spec = int_spec)
+ param_allow_update = ParamInfo(name = "allow_update", optional = True, param_spec = string_spec)
set_cmd = CommandInfo(name = "set")
set_cmd.add_param(param_master)
set_cmd.add_param(param_allow_update)
@@ -138,6 +146,7 @@
self.no_assert_raise("zone help help='dd' ")
self.no_assert_raise("zone set allow_update='1.1.1.1' zone_name='cn'")
self.no_assert_raise("zone set zone_name='cn'")
+ self.my_assert_raise(isc.cc.data.DataTypeError, "zone set zone_name ='cn', port='cn'")
self.no_assert_raise("zone reload_all")
Modified: branches/trac185/src/bin/cmdctl/cmdctl.py.in
==============================================================================
--- branches/trac185/src/bin/cmdctl/cmdctl.py.in (original)
+++ branches/trac185/src/bin/cmdctl/cmdctl.py.in Mon May 31 06:06:39 2010
@@ -219,8 +219,7 @@
self._verbose = verbose
self.cc = isc.cc.Session()
self.cc.group_subscribe('Cmd-Ctrld')
- self.command_spec = self.get_cmd_specification()
- self.config_spec = self.get_data_specification()
+ self.module_spec = self.get_module_specification()
self.config_data = self.get_config_data()
def _parse_command_result(self, rcode, reply):
@@ -229,10 +228,6 @@
return {}
return reply
- def get_cmd_specification(self):
- rcode, reply = self.send_command('ConfigManager', isc.config.ccsession.COMMAND_GET_COMMANDS_SPEC)
- return self._parse_command_result(rcode, reply)
-
def get_config_data(self):
'''Get config data for all modules from configmanager '''
rcode, reply = self.send_command('ConfigManager', isc.config.ccsession.COMMAND_GET_CONFIG)
@@ -244,7 +239,7 @@
if module_name == 'ConfigManager' and command_name == isc.config.ccsession.COMMAND_SET_CONFIG:
self.config_data = self.get_config_data()
- def get_data_specification(self):
+ def get_module_specification(self):
rcode, reply = self.send_command('ConfigManager', isc.config.ccsession.COMMAND_GET_MODULE_SPEC)
return self._parse_command_result(rcode, reply)
@@ -253,10 +248,8 @@
(message, env) = self.cc.group_recvmsg(True)
command, arg = isc.config.ccsession.parse_command(message)
while command:
- if command == isc.config.ccsession.COMMAND_COMMANDS_UPDATE:
- self.command_spec[arg[0]] = arg[1]
- elif command == isc.config.ccsession.COMMAND_SPECIFICATION_UPDATE:
- self.config_spec[arg[0]] = arg[1]
+ if command == isc.config.ccsession.COMMAND_MODULE_SPECIFICATION_UPDATE:
+ self.module_spec[arg[0]] = arg[1]
elif command == isc.config.ccsession.COMMAND_SHUTDOWN:
return False
(message, env) = self.cc.group_recvmsg(True)
@@ -270,27 +263,20 @@
Return rcode, dict.
rcode = 0: dict is the correct returned value.
rcode > 0: dict is : { 'error' : 'error reason' }
-
- TODO. add check for parameters.
'''
# core module ConfigManager does not have a specification file
if module_name == 'ConfigManager':
return self.send_command(module_name, command_name, params)
- if module_name not in self.command_spec.keys():
+ if module_name not in self.module_spec.keys():
return 1, {'error' : 'unknown module'}
-
- cmd_valid = False
- commands = self.command_spec[module_name]
- for cmd in commands:
- if cmd['command_name'] == command_name:
- cmd_valid = True
- break
-
- if not cmd_valid:
- return 1, {'error' : 'unknown command'}
-
+
+ spec_obj = isc.config.module_spec.ModuleSpec(self.module_spec[module_name], False)
+ errors = []
+ if not spec_obj.validate_command(command_name, params, errors):
+ return 1, {'error': errors[0]}
+
return self.send_command(module_name, command_name, params)
def send_command(self, module_name, command_name, params = None):
@@ -383,12 +369,10 @@
'''Currently only support the following three url GET request '''
rcode, reply = http.client.NO_CONTENT, []
if not module:
- if id == 'command_spec':
- rcode, reply = http.client.OK, self.cmdctrl.command_spec
- elif id == 'config_data':
+ if id == 'config_data':
rcode, reply = http.client.OK, self.cmdctrl.config_data
- elif id == 'config_spec':
- rcode, reply = http.client.OK, self.cmdctrl.config_spec
+ elif id == 'module_spec':
+ rcode, reply = http.client.OK, self.cmdctrl.module_spec
return rcode, reply
Modified: branches/trac185/src/bin/cmdctl/cmdctl.spec
==============================================================================
--- branches/trac185/src/bin/cmdctl/cmdctl.spec (original)
+++ branches/trac185/src/bin/cmdctl/cmdctl.spec Mon May 31 06:06:39 2010
@@ -1,6 +1,7 @@
{
"module_spec": {
"module_name": "Cmdctl",
+ "module_description": "Interface for command and control",
"config_data": [
{
"item_name": "key_file",
Modified: branches/trac185/src/bin/cmdctl/tests/cmdctl_test.py
==============================================================================
--- branches/trac185/src/bin/cmdctl/tests/cmdctl_test.py (original)
+++ branches/trac185/src/bin/cmdctl/tests/cmdctl_test.py Mon May 31 06:06:39 2010
@@ -51,9 +51,8 @@
class MyCommandControl(CommandControl):
def __init__(self):
- self.command_spec = {}
- self.config_spec = {}
self.config_data = {}
+ self.module_spec = {}
def send_command(self, mod, cmd, param):
return 0, {}
@@ -120,7 +119,7 @@
def test_do_GET_3(self):
self.handler.headers['cookie'] = 12346
self.handler.server.user_sessions[12346] = time.time() + 1000000
- path_vec = ['command_spec', 'config_data', 'config_spec']
+ path_vec = ['config_data', 'module_spec']
for path in path_vec:
self.handler.path = '/' + path
self.handler.do_GET()
@@ -245,10 +244,10 @@
os.remove('check.tmp')
self.handler.path = '/module/command'
- self.handler.server.cmdctrl.command_spec = {}
- self.handler.server.cmdctrl.command_spec['module'] = [{'command_name':'command'}, {'command_name': ['data1']} ]
- rcode, reply = self.handler._handle_post_request()
- self.assertEqual(http.client.OK, rcode)
+ self.handler.server.cmdctrl.module_spec = {}
+ self.handler.server.cmdctrl.module_spec['module'] = { 'commands': [{'command_name':'command'}, {'command_name': ['data1']} ] }
+ #rcode, reply = self.handler._handle_post_request()
+ #self.assertEqual(http.client.OK, rcode)
if __name__== "__main__":
unittest.main()
Modified: branches/trac185/src/bin/host/Makefile.am
==============================================================================
--- branches/trac185/src/bin/host/Makefile.am (original)
+++ branches/trac185/src/bin/host/Makefile.am Mon May 31 06:06:39 2010
@@ -1,5 +1,7 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
Modified: branches/trac185/src/bin/loadzone/b10-loadzone.py.in
==============================================================================
--- branches/trac185/src/bin/loadzone/b10-loadzone.py.in (original)
+++ branches/trac185/src/bin/loadzone/b10-loadzone.py.in Mon May 31 06:06:39 2010
@@ -77,4 +77,4 @@
exit(1)
if __name__ == "__main__":
- main(datasrc
+ main()
Modified: branches/trac185/src/bin/xfrout/xfrout.py.in
==============================================================================
--- branches/trac185/src/bin/xfrout/xfrout.py.in (original)
+++ branches/trac185/src/bin/xfrout/xfrout.py.in Mon May 31 06:06:39 2010
@@ -44,7 +44,7 @@
DATAROOTDIR = "@datarootdir@"
SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
-UNIX_SOCKET_FILE = "@localstatedir@".replace("${prefix}", PREFIX) + "/auth_xfrout_conn"
+UNIX_SOCKET_FILE = "@@LOCALSTATEDIR@@/auth_xfrout_conn"
MAX_TRANSFERS_OUT = 10
verbose_mode = False
Modified: branches/trac185/src/lib/Makefile.am
==============================================================================
--- branches/trac185/src/lib/Makefile.am (original)
+++ branches/trac185/src/lib/Makefile.am Mon May 31 06:06:39 2010
@@ -1,6 +1,4 @@
SUBDIRS = exceptions dns cc config datasrc python
if HAVE_BOOST_PYTHON
-if HAVE_BOOST_SYSTEM
SUBDIRS += xfr
endif
-endif
Modified: branches/trac185/src/lib/cc/Makefile.am
==============================================================================
--- branches/trac185/src/lib/cc/Makefile.am (original)
+++ branches/trac185/src/lib/cc/Makefile.am Mon May 31 06:06:39 2010
@@ -1,4 +1,11 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
+# ASIO header files used in session.cc will trigger "unused-parameter"
+# error. Unfortunately there doesn't seem to be an easy way to selectively
+# avoid the error. As a short term workaround we suppress this warning
+# for the entire this module. See also src/bin/auth/Makefile.am.
+AM_CXXFLAGS += -Wno-unused-parameter
lib_LIBRARIES = libcc.a
libcc_a_SOURCES = data.cc data.h session.cc session.h
Modified: branches/trac185/src/lib/cc/data.cc
==============================================================================
--- branches/trac185/src/lib/cc/data.cc (original)
+++ branches/trac185/src/lib/cc/data.cc Mon May 31 06:06:39 2010
@@ -204,47 +204,27 @@
//
ElementPtr
Element::create(const int i) {
- try {
- return ElementPtr(new IntElement(i));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new IntElement(i));
}
ElementPtr
Element::create(const double d) {
- try {
- return ElementPtr(new DoubleElement(d));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new DoubleElement(d));
}
ElementPtr
Element::create(const std::string& s) {
- try {
- return ElementPtr(new StringElement(s));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new StringElement(s));
}
ElementPtr
Element::create(const bool b) {
- try {
- return ElementPtr(new BoolElement(b));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new BoolElement(b));
}
ElementPtr
Element::create(const std::vector<ElementPtr>& v) {
- try {
- return ElementPtr(new ListElement(v));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new ListElement(v));
}
ElementPtr
@@ -255,11 +235,7 @@
isc_throw(TypeError, "Map tag is too long");
}
}
- try {
- return ElementPtr(new MapElement(m));
- } catch (std::bad_alloc) {
- return ElementPtr();
- }
+ return ElementPtr(new MapElement(m));
}
Modified: branches/trac185/src/lib/cc/session.cc
==============================================================================
--- branches/trac185/src/lib/cc/session.cc (original)
+++ branches/trac185/src/lib/cc/session.cc Mon May 31 06:06:39 2010
@@ -14,7 +14,7 @@
// $Id$
-#include "config.h"
+#include <config.h>
#include <stdint.h>
@@ -23,11 +23,12 @@
#include <iostream>
#include <sstream>
-#ifdef HAVE_BOOST_SYSTEM
#include <boost/bind.hpp>
#include <boost/function.hpp>
-#include <boost/asio.hpp>
-#endif
+
+#include <asio.hpp>
+#include <asio/error_code.hpp>
+#include <asio/system_error.hpp>
#include <exceptions/exceptions.h>
@@ -38,12 +39,10 @@
using namespace isc::cc;
using namespace isc::data;
-#ifdef HAVE_BOOST_SYSTEM
-// some of the boost::asio names conflict with socket API system calls
+// some of the asio names conflict with socket API system calls
// (e.g. write(2)) so we don't import the entire boost::asio namespace.
-using boost::asio::io_service;
-using boost::asio::ip::tcp;
-#endif
+using asio::io_service;
+using asio::ip::tcp;
#include <sys/types.h>
#include <sys/socket.h>
@@ -54,7 +53,7 @@
class SessionImpl {
public:
- SessionImpl() : sequence_(-1) {}
+ SessionImpl() : sequence_(-1) { queue_ = Element::createFromString("[]"); }
virtual ~SessionImpl() {}
virtual void establish() = 0;
virtual int getSocket() = 0;
@@ -63,12 +62,12 @@
virtual size_t readDataLength() = 0;
virtual void readData(void* data, size_t datalen) = 0;
virtual void startRead(boost::function<void()> user_handler) = 0;
-
+
int sequence_; // the next sequence number to use
std::string lname_;
+ ElementPtr queue_;
};
-#ifdef HAVE_BOOST_SYSTEM
class ASIOSession : public SessionImpl {
public:
ASIOSession(io_service& io_service) :
@@ -82,7 +81,7 @@
virtual void readData(void* data, size_t datalen);
virtual void startRead(boost::function<void()> user_handler);
private:
- void internalRead(const boost::system::error_code& error,
+ void internalRead(const asio::error_code& error,
size_t bytes_transferred);
private:
@@ -90,12 +89,12 @@
tcp::socket socket_;
uint32_t data_length_;
boost::function<void()> user_handler_;
- boost::system::error_code error_;
+ asio::error_code error_;
};
void
ASIOSession::establish() {
- socket_.connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),
+ socket_.connect(tcp::endpoint(asio::ip::address_v4::loopback(),
9912), error_);
if (error_) {
isc_throw(SessionError, "Unable to connect to message queue");
@@ -111,9 +110,9 @@
void
ASIOSession::writeData(const void* data, size_t datalen) {
try {
- boost::asio::write(socket_, boost::asio::buffer(data, datalen));
- } catch (const boost::system::system_error& boost_ex) {
- isc_throw(SessionError, "ASIO write failed: " << boost_ex.what());
+ asio::write(socket_, asio::buffer(data, datalen));
+ } catch (const asio::system_error& asio_ex) {
+ isc_throw(SessionError, "ASIO write failed: " << asio_ex.what());
}
}
@@ -136,11 +135,11 @@
void
ASIOSession::readData(void* data, size_t datalen) {
try {
- boost::asio::read(socket_, boost::asio::buffer(data, datalen));
- } catch (const boost::system::system_error& boost_ex) {
+ asio::read(socket_, asio::buffer(data, datalen));
+ } catch (const asio::system_error& asio_ex) {
// to hide boost specific exceptions, we catch them explicitly
// and convert it to SessionError.
- isc_throw(SessionError, "ASIO read failed: " << boost_ex.what());
+ isc_throw(SessionError, "ASIO read failed: " << asio_ex.what());
}
}
@@ -148,15 +147,15 @@
ASIOSession::startRead(boost::function<void()> user_handler) {
data_length_ = 0;
user_handler_ = user_handler;
- async_read(socket_, boost::asio::buffer(&data_length_,
+ async_read(socket_, asio::buffer(&data_length_,
sizeof(data_length_)),
boost::bind(&ASIOSession::internalRead, this,
- boost::asio::placeholders::error,
- boost::asio::placeholders::bytes_transferred));
-}
-
-void
-ASIOSession::internalRead(const boost::system::error_code& error,
+ asio::placeholders::error,
+ asio::placeholders::bytes_transferred));
+}
+
+void
+ASIOSession::internalRead(const asio::error_code& error,
size_t bytes_transferred)
{
if (!error) {
@@ -170,7 +169,6 @@
isc_throw(SessionError, "asynchronous read failed");
}
}
-#endif
class SocketSession : public SessionImpl {
public:
@@ -270,10 +268,8 @@
Session::Session() : impl_(new SocketSession)
{}
-#ifdef HAVE_BOOST_SYSTEM
Session::Session(io_service& io_service) : impl_(new ASIOSession(io_service))
{}
-#endif
Session::~Session() {
delete impl_;
@@ -352,35 +348,35 @@
}
bool
-Session::recvmsg(ElementPtr& msg, bool nonblock UNUSED_PARAM) {
+Session::recvmsg(ElementPtr& msg, bool nonblock, int seq) {
+ ElementPtr l_env;
+ return recvmsg(l_env, msg, nonblock, seq);
+}
+
+bool
+Session::recvmsg(ElementPtr& env, ElementPtr& msg,
+ bool nonblock, int seq) {
size_t length = impl_->readDataLength();
-
- unsigned short header_length_net;
- impl_->readData(&header_length_net, sizeof(header_length_net));
-
- unsigned short header_length = ntohs(header_length_net);
- if (header_length != length) {
- isc_throw(SessionError, "Length parameters invalid: total=" << length
- << ", header=" << header_length);
- }
-
- std::vector<char> buffer(length);
- impl_->readData(&buffer[0], length);
-
- std::string wire = std::string(&buffer[0], length);
- std::stringstream wire_stream;
- wire_stream << wire;
-
- msg = Element::fromWire(wire_stream, length);
-
- return (true);
- // XXXMLG handle non-block here, and return false for short reads
-}
-
-bool
-Session::recvmsg(ElementPtr& env, ElementPtr& msg, bool nonblock UNUSED_PARAM) {
- size_t length = impl_->readDataLength();
-
+ ElementPtr l_env, l_msg;
+ if (hasQueuedMsgs()) {
+ ElementPtr q_el;
+ for (int i = 0; i < impl_->queue_->size(); i++) {
+ q_el = impl_->queue_->get(i);
+ if (( seq == -1 &&
+ !q_el->get(0)->contains("reply")
+ ) || (
+ q_el->get(0)->contains("reply") &&
+ q_el->get(0)->get("reply")->intValue() == seq
+ )
+ ) {
+ env = q_el->get(0);
+ msg = q_el->get(1);
+ impl_->queue_->remove(i);
+ return true;
+ }
+ }
+ }
+
unsigned short header_length_net;
impl_->readData(&header_length_net, sizeof(header_length_net));
@@ -400,13 +396,28 @@
length - header_length);
std::stringstream header_wire_stream;
header_wire_stream << header_wire;
- env = Element::fromWire(header_wire_stream, header_length);
+ l_env = Element::fromWire(header_wire_stream, header_length);
std::stringstream body_wire_stream;
body_wire_stream << body_wire;
- msg = Element::fromWire(body_wire_stream, length - header_length);
-
- return (true);
+ l_msg = Element::fromWire(body_wire_stream, length - header_length);
+ if ((seq == -1 &&
+ !l_env->contains("reply")
+ ) || (
+ l_env->contains("reply") &&
+ l_env->get("reply")->intValue() == seq
+ )
+ ) {
+ env = l_env;
+ msg = l_msg;
+ return true;
+ } else {
+ ElementPtr q_el = Element::createFromString("[]");
+ q_el->add(l_env);
+ q_el->add(l_msg);
+ impl_->queue_->add(q_el);
+ return recvmsg(env, msg, nonblock, seq);
+ }
// XXXMLG handle non-block here, and return false for short reads
}
@@ -432,47 +443,55 @@
sendmsg(env);
}
-unsigned int
+int
Session::group_sendmsg(ElementPtr msg, std::string group,
std::string instance, std::string to)
{
ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
-
+ int nseq = ++impl_->sequence_;
+
env->set("type", Element::create("send"));
env->set("from", Element::create(impl_->lname_));
env->set("to", Element::create(to));
env->set("group", Element::create(group));
env->set("instance", Element::create(instance));
- env->set("seq", Element::create(impl_->sequence_));
+ env->set("seq", Element::create(nseq));
//env->set("msg", Element::create(msg->toWire()));
sendmsg(env, msg);
-
- return (++impl_->sequence_);
+ return nseq;
}
bool
Session::group_recvmsg(ElementPtr& envelope, ElementPtr& msg,
- bool nonblock)
+ bool nonblock, int seq)
{
- return (recvmsg(envelope, msg, nonblock));
-}
-
-unsigned int
+ return (recvmsg(envelope, msg, nonblock, seq));
+}
+
+int
Session::reply(ElementPtr& envelope, ElementPtr& newmsg) {
ElementPtr env = Element::create(std::map<std::string, ElementPtr>());
-
+ int nseq = ++impl_->sequence_;
+
env->set("type", Element::create("send"));
env->set("from", Element::create(impl_->lname_));
env->set("to", Element::create(envelope->get("from")->stringValue()));
env->set("group", Element::create(envelope->get("group")->stringValue()));
env->set("instance", Element::create(envelope->get("instance")->stringValue()));
- env->set("seq", Element::create(impl_->sequence_));
+ env->set("seq", Element::create(nseq));
env->set("reply", Element::create(envelope->get("seq")->intValue()));
sendmsg(env, newmsg);
- return (++impl_->sequence_);
-}
-}
-}
+ return nseq;
+}
+
+bool
+Session::hasQueuedMsgs()
+{
+ return (impl_->queue_->size() > 0);
+}
+
+}
+}
Modified: branches/trac185/src/lib/cc/session.h
==============================================================================
--- branches/trac185/src/lib/cc/session.h (original)
+++ branches/trac185/src/lib/cc/session.h Mon May 31 06:06:39 2010
@@ -25,10 +25,8 @@
#include "data.h"
-namespace boost {
namespace asio {
class io_service;
-}
}
namespace isc {
@@ -51,7 +49,7 @@
public:
Session();
- Session(boost::asio::io_service& ioservice);
+ Session(asio::io_service& ioservice);
~Session();
// XXX: quick hack to allow the user to watch the socket directly.
@@ -65,23 +63,27 @@
void sendmsg(isc::data::ElementPtr& env,
isc::data::ElementPtr& msg);
bool recvmsg(isc::data::ElementPtr& msg,
- bool nonblock = true);
+ bool nonblock = true,
+ int seq = -1);
bool recvmsg(isc::data::ElementPtr& env,
isc::data::ElementPtr& msg,
- bool nonblock = true);
+ bool nonblock = true,
+ int seq = -1);
void subscribe(std::string group,
std::string instance = "*");
void unsubscribe(std::string group,
std::string instance = "*");
- unsigned int group_sendmsg(isc::data::ElementPtr msg,
+ int group_sendmsg(isc::data::ElementPtr msg,
std::string group,
std::string instance = "*",
std::string to = "*");
bool group_recvmsg(isc::data::ElementPtr& envelope,
isc::data::ElementPtr& msg,
- bool nonblock = true);
- unsigned int reply(isc::data::ElementPtr& envelope,
+ bool nonblock = true,
+ int seq = -1);
+ int reply(isc::data::ElementPtr& envelope,
isc::data::ElementPtr& newmsg);
+ bool hasQueuedMsgs();
};
} // namespace cc
} // namespace isc
Modified: branches/trac185/src/lib/config/Makefile.am
==============================================================================
--- branches/trac185/src/lib/config/Makefile.am (original)
+++ branches/trac185/src/lib/config/Makefile.am Mon May 31 06:06:39 2010
@@ -1,4 +1,5 @@
-AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib -Wno-strict-aliasing
+AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
+AM_CXXFLAGS = $(B10_CXXFLAGS) -Wno-strict-aliasing
lib_LTLIBRARIES = libcfgclient.la
libcfgclient_la_SOURCES = config_data.h config_data.cc module_spec.h module_spec.cc ccsession.cc ccsession.h
@@ -46,3 +47,5 @@
EXTRA_DIST += testdata/spec22.spec
EXTRA_DIST += testdata/spec23.spec
EXTRA_DIST += testdata/spec24.spec
+EXTRA_DIST += testdata/spec25.spec
+EXTRA_DIST += testdata/spec26.spec
Modified: branches/trac185/src/lib/config/ccsession.cc
==============================================================================
--- branches/trac185/src/lib/config/ccsession.cc (original)
+++ branches/trac185/src/lib/config/ccsession.cc Mon May 31 06:06:39 2010
@@ -32,9 +32,7 @@
#include <sstream>
#include <cerrno>
-#ifdef HAVE_BOOST_SYSTEM
#include <boost/bind.hpp>
-#endif
#include <boost/foreach.hpp>
#include <cc/data.h>
@@ -188,7 +186,6 @@
return module_spec;
}
-#ifdef HAVE_BOOST_SYSTEM
void
ModuleCCSession::startCheck() {
// data available on the command channel. process it in the synchronous
@@ -201,7 +198,7 @@
ModuleCCSession::ModuleCCSession(
std::string spec_file_name,
- boost::asio::io_service& io_service,
+ asio::io_service& io_service,
isc::data::ElementPtr(*config_handler)(isc::data::ElementPtr new_config),
isc::data::ElementPtr(*command_handler)(
const std::string& command, const isc::data::ElementPtr args)
@@ -213,7 +210,6 @@
// register callback for asynchronous read
session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
}
-#endif
ModuleCCSession::ModuleCCSession(
std::string spec_file_name,
@@ -248,8 +244,8 @@
//session_.subscribe("statistics", "*");
// send the data specification
ElementPtr spec_msg = createCommand("module_spec", module_specification_.getFullSpec());
- session_.group_sendmsg(spec_msg, "ConfigManager");
- session_.group_recvmsg(env, answer, false);
+ unsigned int seq = session_.group_sendmsg(spec_msg, "ConfigManager");
+ session_.group_recvmsg(env, answer, false, seq);
int rcode;
ElementPtr err = parseAnswer(rcode, answer);
if (rcode != 0) {
@@ -260,8 +256,8 @@
// get any stored configuration from the manager
if (config_handler_) {
ElementPtr cmd = Element::createFromString("{ \"command\": [\"get_config\", {\"module_name\":\"" + module_name_ + "\"} ] }");
- session_.group_sendmsg(cmd, "ConfigManager");
- session_.group_recvmsg(env, answer, false);
+ seq = session_.group_sendmsg(cmd, "ConfigManager");
+ session_.group_recvmsg(env, answer, false, seq);
ElementPtr new_config = parseAnswer(rcode, answer);
if (rcode == 0) {
handleConfigUpdate(new_config);
@@ -308,6 +304,12 @@
ModuleCCSession::getSocket()
{
return (session_.getSocket());
+}
+
+bool
+ModuleCCSession::hasQueuedMsgs()
+{
+ return (session_.hasQueuedMsgs());
}
int
@@ -365,8 +367,8 @@
ElementPtr env, answer;
int rcode;
- session_.group_sendmsg(cmd, "ConfigManager");
- session_.group_recvmsg(env, answer, false);
+ unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
+ session_.group_recvmsg(env, answer, false, seq);
ElementPtr new_config = parseAnswer(rcode, answer);
if (rcode == 0) {
rmod_config.setLocalConfig(new_config);
Modified: branches/trac185/src/lib/config/ccsession.h
==============================================================================
--- branches/trac185/src/lib/config/ccsession.h (original)
+++ branches/trac185/src/lib/config/ccsession.h Mon May 31 06:06:39 2010
@@ -24,10 +24,8 @@
#include <cc/session.h>
#include <cc/data.h>
-namespace boost {
namespace asio {
class io_service;
-}
}
namespace isc {
@@ -133,7 +131,7 @@
isc::data::ElementPtr(*command_handler)(const std::string& command, const isc::data::ElementPtr args) = NULL
) throw (isc::cc::SessionError);
ModuleCCSession(std::string spec_file_name,
- boost::asio::io_service& io_service,
+ asio::io_service& io_service,
isc::data::ElementPtr(*config_handler)(isc::data::ElementPtr new_config) = NULL,
isc::data::ElementPtr(*command_handler)(const std::string& command, const isc::data::ElementPtr args) = NULL
) throw (isc::cc::SessionError);
@@ -148,6 +146,16 @@
* channel.
*/
int getSocket();
+
+ /**
+ * Optional optimization for checkCommand loop; returns true
+ * if there are unhandled queued messages in the cc session.
+ * (if either this is true or there is data on the socket found
+ * by the select() call on getSocket(), run checkCommand())
+ *
+ * @return true if there are unhandled queued messages
+ */
+ bool hasQueuedMsgs();
/**
* Check if there is a command or config change on the command
Modified: branches/trac185/src/lib/config/config_data.h
==============================================================================
--- branches/trac185/src/lib/config/config_data.h (original)
+++ branches/trac185/src/lib/config/config_data.h Mon May 31 06:06:39 2010
@@ -40,6 +40,7 @@
/// Constructs a ConfigData option with no specification and an
/// empty configuration.
ConfigData() { _config = Element::createFromString("{}"); };
+
/// Constructs a ConfigData option with the given specification
/// and an empty configuration.
/// \param module_spec A ModuleSpec for the relevant module
@@ -70,17 +71,21 @@
/// Returns the ModuleSpec associated with this ConfigData object
const ModuleSpec getModuleSpec() { return _module_spec; };
+
/// Set the ModuleSpec associated with this ConfigData object
void setModuleSpec(ModuleSpec module_spec) { _module_spec = module_spec; };
+
/// Set the local configuration (i.e. all non-default values)
/// \param config An ElementPtr pointing to a MapElement containing
/// *all* non-default configuration values. Existing values
/// will be removed.
void setLocalConfig(ElementPtr config) { _config = config; }
+
/// Returns the local (i.e. non-default) configuration.
/// \returns An ElementPtr pointing to a MapElement containing all
/// non-default configuration options.
ElementPtr getLocalConfig() { return _config; }
+
/// Returns a list of all possible configuration options as specified
/// by the ModuleSpec.
/// \param identifier If given, show the items at the given identifier
@@ -92,6 +97,7 @@
/// location (or all possible identifiers if identifier==""
/// and recurse==false)
ElementPtr getItemList(const std::string& identifier = "", bool recurse = false);
+
/// Returns all current configuration settings (both non-default and default).
/// \return An ElementPtr pointing to a MapElement containing
/// string->value elements, where the string is the
Modified: branches/trac185/src/lib/config/module_spec.cc
==============================================================================
--- branches/trac185/src/lib/config/module_spec.cc (original)
+++ branches/trac185/src/lib/config/module_spec.cc Mon May 31 06:06:39 2010
@@ -145,6 +145,7 @@
static void
check_data_specification(const ElementPtr& spec) {
check_leaf_item(spec, "module_name", Element::string, true);
+ check_leaf_item(spec, "module_description", Element::string, false);
// config_data is not mandatory; module could just define
// commands and have no config
if (spec->contains("config_data")) {
@@ -202,6 +203,16 @@
ModuleSpec::getModuleName() const
{
return module_specification->get("module_name")->stringValue();
+}
+
+const std::string
+ModuleSpec::getModuleDescription() const
+{
+ if (module_specification->contains("module_description")) {
+ return module_specification->get("module_description")->stringValue();
+ } else {
+ return std::string("");
+ }
}
bool
Modified: branches/trac185/src/lib/config/module_spec.h
==============================================================================
--- branches/trac185/src/lib/config/module_spec.h (original)
+++ branches/trac185/src/lib/config/module_spec.h Mon May 31 06:06:39 2010
@@ -77,6 +77,10 @@
/// Returns the module name as specified by the specification
const std::string getModuleName() const;
+ /// Returns the module description as specified by the specification
+ /// returns an empty string if there is no description
+ const std::string getModuleDescription() const;
+
// returns true if the given element conforms to this data
// configuration specification
/// Validates the given configuration data for this specification.
Modified: branches/trac185/src/lib/config/tests/Makefile.am
==============================================================================
--- branches/trac185/src/lib/config/tests/Makefile.am (original)
+++ branches/trac185/src/lib/config/tests/Makefile.am Mon May 31 06:06:39 2010
@@ -1,4 +1,8 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
+# see src/lib/cc/Makefile.am for -Wno-unused-parameter
+AM_CXXFLAGS += -Wno-unused-parameter
CLEANFILES = *.gcno *.gcda
@@ -14,14 +18,9 @@
run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
run_unittests_LDADD = $(GTEST_LDADD)
run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libexceptions.la
+run_unittests_LDADD += libfake_session.la
run_unittests_LDADD += $(top_builddir)/src/lib/config/libcfgclient.la
run_unittests_LDADD += $(top_builddir)/src/lib/cc/data.o
-run_unittests_LDADD += libfake_session.la
-
-if HAVE_BOOST_SYSTEM
-run_unittests_LDFLAGS += $(AM_LDFLAGS) $(BOOST_LDFLAGS)
-run_unittests_LDADD += $(BOOST_SYSTEM_LIB)
-endif
endif
Modified: branches/trac185/src/lib/config/tests/fake_session.cc
==============================================================================
--- branches/trac185/src/lib/config/tests/fake_session.cc (original)
+++ branches/trac185/src/lib/config/tests/fake_session.cc Mon May 31 06:06:39 2010
@@ -23,12 +23,6 @@
#include <iostream>
#include <sstream>
-#ifdef HAVE_BOOST_SYSTEM
-#include <boost/bind.hpp>
-#include <boost/function.hpp>
-#include <boost/asio.hpp>
-#endif
-
#include <boost/foreach.hpp>
#include <exceptions/exceptions.h>
@@ -39,13 +33,6 @@
using namespace std;
using namespace isc::cc;
using namespace isc::data;
-
-#ifdef HAVE_BOOST_SYSTEM
-// some of the boost::asio names conflict with socket API system calls
-// (e.g. write(2)) so we don't import the entire boost::asio namespace.
-using boost::asio::io_service;
-using boost::asio::ip::tcp;
-#endif
#include <sys/types.h>
#include <sys/socket.h>
@@ -144,13 +131,16 @@
{
}
-#ifdef HAVE_BOOST_SYSTEM
-Session::Session(io_service& io_service UNUSED_PARAM)
-{
-}
-#endif
+Session::Session(asio::io_service& io_service UNUSED_PARAM)
+{
+}
Session::~Session() {
+}
+
+bool
+Session::connect() {
+ return true;
}
void
@@ -188,7 +178,7 @@
}
bool
-Session::recvmsg(ElementPtr& msg, bool nonblock UNUSED_PARAM) {
+Session::recvmsg(ElementPtr& msg, bool nonblock UNUSED_PARAM, int seq UNUSED_PARAM) {
//cout << "[XX] client asks for message " << endl;
if (initial_messages &&
initial_messages->getType() == Element::list &&
@@ -202,7 +192,7 @@
}
bool
-Session::recvmsg(ElementPtr& env, ElementPtr& msg, bool nonblock UNUSED_PARAM) {
+Session::recvmsg(ElementPtr& env, ElementPtr& msg, bool nonblock UNUSED_PARAM, int seq UNUSED_PARAM) {
//cout << "[XX] client asks for message and env" << endl;
env = ElementPtr();
if (initial_messages &&
@@ -269,9 +259,9 @@
bool
Session::group_recvmsg(ElementPtr& envelope, ElementPtr& msg,
- bool nonblock)
-{
- return (recvmsg(envelope, msg, nonblock));
+ bool nonblock, int seq)
+{
+ return (recvmsg(envelope, msg, nonblock, seq));
}
unsigned int
@@ -282,5 +272,10 @@
return 1;
}
-}
-}
+bool
+Session::hasQueuedMsgs() {
+ return false;
+}
+
+}
+}
Modified: branches/trac185/src/lib/config/tests/fake_session.h
==============================================================================
--- branches/trac185/src/lib/config/tests/fake_session.h (original)
+++ branches/trac185/src/lib/config/tests/fake_session.h Mon May 31 06:06:39 2010
@@ -25,10 +25,8 @@
#include <cc/data.h>
-namespace boost {
namespace asio {
class io_service;
-}
}
// global variables so tests can insert
@@ -65,7 +63,7 @@
// public so tests can inspect them
Session();
- Session(boost::asio::io_service& ioservice);
+ Session(asio::io_service& ioservice);
~Session();
// XXX: quick hack to allow the user to watch the socket directly.
@@ -74,15 +72,16 @@
void startRead(boost::function<void()> read_callback);
void establish();
+ bool connect();
void disconnect();
void sendmsg(isc::data::ElementPtr& msg);
void sendmsg(isc::data::ElementPtr& env,
isc::data::ElementPtr& msg);
bool recvmsg(isc::data::ElementPtr& msg,
- bool nonblock = true);
+ bool nonblock = true, int seq = -1);
bool recvmsg(isc::data::ElementPtr& env,
isc::data::ElementPtr& msg,
- bool nonblock = true);
+ bool nonblock = true, int seq = -1);
void subscribe(std::string group,
std::string instance = "*");
void unsubscribe(std::string group,
@@ -93,9 +92,11 @@
std::string to = "*");
bool group_recvmsg(isc::data::ElementPtr& envelope,
isc::data::ElementPtr& msg,
- bool nonblock = true);
+ bool nonblock = true,
+ int seq = -1);
unsigned int reply(isc::data::ElementPtr& envelope,
isc::data::ElementPtr& newmsg);
+ bool hasQueuedMsgs();
};
} // namespace cc
Modified: branches/trac185/src/lib/config/tests/module_spec_unittests.cc
==============================================================================
--- branches/trac185/src/lib/config/tests/module_spec_unittests.cc (original)
+++ branches/trac185/src/lib/config/tests/module_spec_unittests.cc Mon May 31 06:06:39 2010
@@ -60,6 +60,12 @@
dd = moduleSpecFromFile(specfile("spec2.spec"));
EXPECT_EQ("[ {\"command_args\": [ {\"item_default\": \"\", \"item_name\": \"message\", \"item_optional\": False, \"item_type\": \"string\"} ], \"command_description\": \"Print the given message to stdout\", \"command_name\": \"print_message\"}, {\"command_args\": [ ], \"command_description\": \"Shut down BIND 10\", \"command_name\": \"shutdown\"} ]", dd.getCommandsSpec()->str());
EXPECT_EQ("Spec2", dd.getModuleName());
+ EXPECT_EQ("", dd.getModuleDescription());
+
+ dd = moduleSpecFromFile(specfile("spec25.spec"));
+ EXPECT_EQ("Spec25", dd.getModuleName());
+ EXPECT_EQ("Just an empty module", dd.getModuleDescription());
+ EXPECT_THROW(moduleSpecFromFile(specfile("spec26.spec")), ModuleSpecError);
std::ifstream file;
file.open(specfile("spec1.spec").c_str());
Modified: branches/trac185/src/lib/datasrc/Makefile.am
==============================================================================
--- branches/trac185/src/lib/datasrc/Makefile.am (original)
+++ branches/trac185/src/lib/datasrc/Makefile.am Mon May 31 06:06:39 2010
@@ -3,6 +3,8 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
AM_CPPFLAGS += $(SQLITE_CFLAGS)
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
Modified: branches/trac185/src/lib/datasrc/tests/Makefile.am
==============================================================================
--- branches/trac185/src/lib/datasrc/tests/Makefile.am (original)
+++ branches/trac185/src/lib/datasrc/tests/Makefile.am Mon May 31 06:06:39 2010
@@ -1,6 +1,8 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_builddir)/src/lib/dns -I$(top_srcdir)/src/lib/dns
AM_CPPFLAGS += -DTEST_DATA_DIR=\"$(srcdir)/testdata\"
+
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
Modified: branches/trac185/src/lib/dns/Makefile.am
==============================================================================
--- branches/trac185/src/lib/dns/Makefile.am (original)
+++ branches/trac185/src/lib/dns/Makefile.am Mon May 31 06:06:39 2010
@@ -1,9 +1,7 @@
SUBDIRS = . tests
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
-if GCC_WERROR_OK
-AM_CPPFLAGS += -Werror
-endif
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
CLEANFILES += rrclass.h rrtype.h rrparamregistry.cc rdataclass.h rdataclass.cc
@@ -86,10 +84,11 @@
pyexec_LTLIBRARIES = bind10_dns.la
bind10_dns_la_SOURCES = python_dns.cc
bind10_dns_la_CPPFLAGS = $(AM_CPPFLAGS) $(PYTHON_INCLUDES)
+bind10_dns_la_CXXFLAGS = $(AM_CXXFLAGS) $(B10_CXXFLAGS)
if GCC_WERROR_OK
# XXX: Boost.Python triggers strict aliasing violation, so if we use -Werror
# we need to suppress the warnings.
-bind10_dns_la_CPPFLAGS += -fno-strict-aliasing
+bind10_dns_la_CXXFLAGS += -fno-strict-aliasing
endif
bind10_dns_la_LDFLAGS = $(BOOST_LDFLAGS) $(PYTHON_LDFLAGS)
# Python prefers .so, while some OSes (specifically MacOS) use a different
@@ -107,3 +106,29 @@
rrparamregistry.cc: rrparamregistry-placeholder.cc
rrclass.h rrtype.h rrparamregistry.cc rdataclass.h rdataclass.cc: Makefile
./gen-rdatacode.py
+
+libdns_includedir = $(includedir)/dns
+libdns_include_HEADERS = \
+ buffer.h \
+ dnssectime.h \
+ exceptions.h \
+ message.h \
+ messagerenderer.h \
+ name.h \
+ question.h \
+ rdata.h \
+ rdataclass.h \
+ rrclass.h \
+ rrparamregistry.h \
+ rrset.h \
+ rrsetlist.h \
+ rrttl.h \
+ rrtype.h \
+ tsig.h
+# Purposely not installing these headers:
+# base32.h # used only internally, and not actually DNS specific
+# base64.h # used only internally, and not actually DNS specific
+# hex.h # used only internally, and not actually DNS specific
+# sha1.h # used only internally, and not actually DNS specific
+# rrclass-placeholder.h
+# rrtype-placeholder.h
Modified: branches/trac185/src/lib/dns/name.cc
==============================================================================
--- branches/trac185/src/lib/dns/name.cc (original)
+++ branches/trac185/src/lib/dns/name.cc Mon May 31 06:06:39 2010
@@ -666,7 +666,7 @@
}
Name
-Name::split(unsigned int first, unsigned int n) const {
+Name::split(const unsigned int first, const unsigned int n) const {
if (n == 0 || n > labelcount_ || first > labelcount_ - n) {
isc_throw(OutOfRange, "Name::split: invalid split range");
}
@@ -700,6 +700,16 @@
assert(retname.labelcount_ == newlabels);
return (retname);
+}
+
+Name
+Name::split(const unsigned level) const {
+ if (level >= getLabelCount()) {
+ isc_throw(OutOfRange, "invalid level for name split (" << level
+ << ") for name " << *this);
+ }
+
+ return (split(level, getLabelCount() - level));
}
Name&
Modified: branches/trac185/src/lib/dns/name.h
==============================================================================
--- branches/trac185/src/lib/dns/name.h (original)
+++ branches/trac185/src/lib/dns/name.h Mon May 31 06:06:39 2010
@@ -84,7 +84,7 @@
///
/// \brief A standard DNS module exception that is thrown if the name parser
-/// finds the input (string or wire-format data) is incomplete.
+/// finds the input (string or wire-format %data) is incomplete.
///
/// An attempt of constructing a name from an empty string will trigger this
/// exception.
@@ -168,13 +168,13 @@
///
/// The \c Name class encapsulates DNS names.
///
-/// It provides interfaces to construct a name from string or wire-format data,
-/// transform a name into a string or wire-format data, compare two names, get
+/// It provides interfaces to construct a name from string or wire-format %data,
+/// transform a name into a string or wire-format %data, compare two names, get
/// access to various properties of a name, etc.
///
-/// Notes to developers: Internally, a name object maintains the name data
+/// Notes to developers: Internally, a name object maintains the name %data
/// in wire format as an instance of \c std::string. Since many string
-/// implementations adopt copy-on-write data sharing, we expect this approach
+/// implementations adopt copy-on-write %data sharing, we expect this approach
/// will make copying a name less expensive in typical cases. If this is
/// found to be a significant performance bottleneck later, we may reconsider
/// the internal representation or perhaps the API.
@@ -187,9 +187,9 @@
/// included. In the BIND9 DNS library from which this implementation is
/// derived, the offsets are optional, probably due to performance
/// considerations (in fact, offsets can always be calculated from the name
-/// data, and in that sense are redundant). In our implementation, however,
+/// %data, and in that sense are redundant). In our implementation, however,
/// we always build and maintain the offsets. We believe we need more low
-/// level, specialized data structure and interface where we really need to
+/// level, specialized %data structure and interface where we really need to
/// pursue performance, and would rather keep this generic API and
/// implementation simpler.
///
@@ -233,21 +233,21 @@
/// \param namestr A string representation of the name to be constructed.
/// \param downcase Whether to convert upper case alphabets to lower case.
explicit Name(const std::string& namestr, bool downcase = false);
- /// Constructor from wire-format data.
+ /// Constructor from wire-format %data.
///
/// The \c buffer parameter normally stores a complete DNS message
/// containing the name to be constructed. The current read position of
/// the buffer points to the head of the name.
///
- /// The input data may or may not be compressed; if it's compressed, this
+ /// The input %data may or may not be compressed; if it's compressed, this
/// method will automatically decompress it.
///
- /// If the given data does not represent a valid DNS name, an exception
+ /// If the given %data does not represent a valid DNS name, an exception
/// of class \c DNSMessageFORMERR will be thrown.
/// In addition, if resource allocation for the new name fails, a
/// corresponding standard exception will be thrown.
///
- /// \param buffer A buffer storing the wire format data.
+ /// \param buffer A buffer storing the wire format %data.
/// \param downcase Whether to convert upper case alphabets to lower case.
explicit Name(InputBuffer& buffer, bool downcase = false);
///
@@ -260,35 +260,35 @@
/// \name Getter Methods
///
//@{
- /// \brief Provides one-byte name data in wire format at the specified
+ /// \brief Provides one-byte name %data in wire format at the specified
/// position.
///
/// This method returns the unsigned 8-bit value of wire-format \c Name
- /// data at the given position from the head.
+ /// %data at the given position from the head.
///
/// For example, if \c n is a \c Name object for "example.com",
/// \c n.at(3) would return \c 'a', and \c n.at(7) would return \c 'e'.
/// Note that \c n.at(0) would be 7 (decimal), the label length of
- /// "example", instead of \c 'e', because it returns a data portion
+ /// "example", instead of \c 'e', because it returns a %data portion
/// in wire-format. Likewise, \c n.at(8) would return 3 (decimal)
/// instead of <code>'.'</code>
///
/// This method would be useful for an application to examine the
- /// wire-format name data without dumping the data into a buffer,
- /// which would involve data copies and would be less efficient.
+ /// wire-format name %data without dumping the %data into a buffer,
+ /// which would involve %data copies and would be less efficient.
/// One common usage of this method would be something like this:
/// \code for (size_t i = 0; i < name.getLength(); ++i) {
/// uint8_t c = name.at(i);
/// // do something with c
/// } \endcode
///
- /// Parameter \c pos must be in the valid range of the name data, that is,
+ /// Parameter \c pos must be in the valid range of the name %data, that is,
/// must be less than \c Name.getLength(). Otherwise, an exception of
/// class \c OutOfRange will be thrown.
/// This method never throws an exception in other ways.
///
- /// \param pos The position in the wire format name data to be returned.
- /// \return An unsigned 8-bit integer corresponding to the name data
+ /// \param pos The position in the wire format name %data to be returned.
+ /// \return An unsigned 8-bit integer corresponding to the name %data
/// at the position of \c pos.
uint8_t at(size_t pos) const
{
@@ -360,7 +360,7 @@
/// <code>buffer.getCapacity() - buffer.getLength() >= Name::MAX_WIRE</code>
/// then this method should not throw an exception.
///
- /// \param buffer An output buffer to store the wire data.
+ /// \param buffer An output buffer to store the wire %data.
void toWire(OutputBuffer& buffer) const;
//@}
@@ -502,6 +502,72 @@
/// labels including and following the <code>first</code> label.
Name split(unsigned int first, unsigned int n) const;
+ /// \brief Extract a specified super domain name of Name.
+ ///
+ /// This function constructs a new \c Name object that is a super domain
+ /// of \c this name.
+ /// The new name is \c level labels upper than \c this name.
+ /// For example, when \c name is www.example.com,
+ /// <code>name.split(1)</code> will return a \c Name object for example.com.
+ /// \c level can be 0, in which case this method returns a copy of
+ /// \c this name.
+ /// The possible maximum value for \c level is
+ /// <code>this->getLabelCount()-1</code>, in which case this method
+ /// returns a root name.
+ ///
+ /// One common expected usage of this method is to iterate over super
+ /// domains of a given name, label by label, as shown in the following
+ /// sample code:
+ /// \code // if name is www.example.com...
+ /// for (int i = 0; i < name.getLabelCount(); ++i) {
+ /// Name upper_name(name.split(i));
+ /// // upper_name'll be www.example.com., example.com., com., and then .
+ /// }
+ /// \endcode
+ ///
+ /// \c level must be smaller than the number of labels of \c this name;
+ /// otherwise an exception of class \c OutOfRange will be thrown.
+ /// In addition, if resource allocation for the new name fails, a
+ /// corresponding standard exception will be thrown.
+ ///
+ /// Note to developers: probably as easily imagined, this method is a
+ /// simple wrapper to one usage of the other
+ /// <code>split(unsigned int, unsigned int) const</code> method and is
+ /// redundant in some sense.
+ /// We provide the "redundant" method for convenience, however, because
+ /// the expected usage shown above seems to be common, and the parameters
+ /// to the other \c split(unsigned int, unsigned int) const to implement
+ /// it may not be very intuitive.
+ ///
+ /// We are also aware that it is generally discouraged to add a public
+ /// member function that could be implemented using other member functions.
+ /// We considered making it a non member function, but we could not come
+ /// up with an intuitive function name to represent the specific service.
+ /// Some other BIND 10 developers argued, probably partly because of the
+ /// counter intuitive function name, a different signature of \c split
+ /// would be better to improve code readability.
+ /// While that may be a matter of personal preference, we accepted the
+ /// argument. One major goal of public APIs like this is wider acceptance
+ /// from internal/external developers, so unless there is a clear advantage
+ /// it would be better to respect the preference of the API users.
+ ///
+ /// Since this method doesn't have to be a member function in other way,
+ /// it is intentionally implemented only using public interfaces of the
+ /// \c Name class; it doesn't refer to private members of the class even if
+ /// it could.
+ /// This way we hope we can avoid damaging the class encapsulation,
+ /// which is a major drawback of public member functions.
+ /// As such if and when this "method" has to be extended, it should be
+ /// implemented without the privilege of being a member function unless
+ /// there is a very strong reason to do so. In particular a minor
+ /// performance advantage shouldn't justify that approach.
+ ///
+ /// \param level The number of labels to be removed from \c this name to
+ /// create the super domain name.
+ /// (0 <= \c level < <code>this->getLabelCount()</code>)
+ /// \return A new \c Name object to be created.
+ Name split(unsigned int level) const;
+
/// \brief Reverse the labels of a name
///
/// This method reverses the labels of a name. For example, if
Modified: branches/trac185/src/lib/dns/python_dns.cc
==============================================================================
--- branches/trac185/src/lib/dns/python_dns.cc (original)
+++ branches/trac185/src/lib/dns/python_dns.cc Mon May 31 06:06:39 2010
@@ -300,7 +300,8 @@
.def("to_wire", (void (Name::*)(MessageRenderer &)const)&Name::toWire)
.def("to_wire", (void (Name::*)(OutputBuffer&)const)&Name::toWire)
.def("compare", &Name::compare)
- .def("split", &Name::split)
+ .def("split", (Name(Name::*)(unsigned int, unsigned int)const)&Name::split)
+ .def("split", (Name(Name::*)(unsigned int)const)&Name::split)
.def("concatenate", &Name::concatenate)
.def("downcase", &Name::downcase, return_value_policy<reference_existing_object>())
.def("is_wildcard", &Name::isWildcard)
Modified: branches/trac185/src/lib/dns/rdata/generic/nsec_47.cc
==============================================================================
--- branches/trac185/src/lib/dns/rdata/generic/nsec_47.cc (original)
+++ branches/trac185/src/lib/dns/rdata/generic/nsec_47.cc Mon May 31 06:06:39 2010
@@ -112,7 +112,7 @@
for (int i = 0; i < rdata_len; i += len) {
if (i + 2 > rdata_len) {
isc_throw(DNSMessageFORMERR, "NSEC RDATA from wire: "
- "incomplete bit map filed");
+ "incomplete bit map field");
}
block = typebits[i];
len = typebits[i + 1];
@@ -182,7 +182,7 @@
assert(i + 2 <= impl_->typebits_.size());
const int block = impl_->typebits_.at(i);
len = impl_->typebits_.at(i + 1);
- assert(len >= 0 && len <= 32);
+ assert(len > 0 && len <= 32);
i += 2;
for (int j = 0; j < len; j++) {
if (impl_->typebits_.at(i + j) == 0) {
Modified: branches/trac185/src/lib/dns/tests/Makefile.am
==============================================================================
--- branches/trac185/src/lib/dns/tests/Makefile.am (original)
+++ branches/trac185/src/lib/dns/tests/Makefile.am Mon May 31 06:06:39 2010
@@ -1,6 +1,7 @@
AM_CPPFLAGS = -I$(top_builddir)/src/lib -I$(top_srcdir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
AM_CPPFLAGS += -DTEST_DATA_DIR=\"$(srcdir)/testdata\"
+AM_CXXFLAGS = $(B10_CXXFLAGS)
CLEANFILES = *.gcno *.gcda
Modified: branches/trac185/src/lib/dns/tests/dnssectime_unittest.cc
==============================================================================
--- branches/trac185/src/lib/dns/tests/dnssectime_unittest.cc (original)
+++ branches/trac185/src/lib/dns/tests/dnssectime_unittest.cc Mon May 31 06:06:39 2010
@@ -64,7 +64,8 @@
TEST(DNSSECTimeTest, overflow) {
// Jan 1, Year 10,000.
if (sizeof(time_t) > 4) {
- EXPECT_THROW(timeToText(253402300800LL), InvalidTime);
+ EXPECT_THROW(timeToText(static_cast<time_t>(253402300800LL)),
+ InvalidTime);
}
}
Modified: branches/trac185/src/lib/dns/tests/name_unittest.cc
==============================================================================
--- branches/trac185/src/lib/dns/tests/name_unittest.cc (original)
+++ branches/trac185/src/lib/dns/tests/name_unittest.cc Mon May 31 06:06:39 2010
@@ -500,6 +500,18 @@
OutOfRange);
}
+TEST_F(NameTest, split_for_suffix) {
+ EXPECT_PRED_FORMAT2(UnitTestUtil::matchName, example_name.split(1),
+ Name("example.com"));
+ EXPECT_PRED_FORMAT2(UnitTestUtil::matchName, example_name.split(0),
+ example_name);
+ EXPECT_PRED_FORMAT2(UnitTestUtil::matchName, example_name.split(3),
+ Name("."));
+
+ // Invalid case: the level must be less than the original label count.
+ EXPECT_THROW(example_name.split(4), OutOfRange);
+}
+
TEST_F(NameTest, downcase) {
// usual case: all-upper case name to all-lower case
compareInWireFormat(example_name_upper.downcase(), example_name);
Modified: branches/trac185/src/lib/exceptions/Makefile.am
==============================================================================
--- branches/trac185/src/lib/exceptions/Makefile.am (original)
+++ branches/trac185/src/lib/exceptions/Makefile.am Mon May 31 06:06:39 2010
@@ -1,3 +1,4 @@
+AM_CXXFLAGS=$(B10_CXXFLAGS)
lib_LTLIBRARIES = libexceptions.la
libexceptions_la_SOURCES = exceptions.h exceptions.cc
@@ -15,3 +16,6 @@
endif
noinst_PROGRAMS = $(TESTS)
+
+libexceptions_includedir = $(includedir)/exceptions
+libexceptions_include_HEADERS = exceptions.h
Modified: branches/trac185/src/lib/python/isc/cc/message.py
==============================================================================
--- branches/trac185/src/lib/python/isc/cc/message.py (original)
+++ branches/trac185/src/lib/python/isc/cc/message.py Mon May 31 06:06:39 2010
@@ -26,6 +26,7 @@
_ITEM_NULL = 0x04
_ITEM_BOOL = 0x05
_ITEM_INT = 0x06
+_ITEM_REAL = 0x07
_ITEM_UTF8 = 0x08
_ITEM_MASK = 0x0f
@@ -77,6 +78,10 @@
"""Pack an integer and its type/length prefix."""
return (_encode_length_and_type(bytes(str(item), 'utf-8'), _ITEM_INT))
+def _pack_real(item):
+ """Pack an integer and its type/length prefix."""
+ return (_encode_length_and_type(bytes(str(item), 'utf-8'), _ITEM_REAL))
+
def _pack_array(item):
"""Pack a list (array) and its type/length prefix."""
return (_encode_length_and_type(_encode_array(item), _ITEM_LIST))
@@ -98,6 +103,8 @@
return (_pack_bool(item))
elif type(item) == int:
return (_pack_int(item))
+ elif type(item) == float:
+ return (_pack_real(item))
elif type(item) == dict:
return (_pack_hash(item))
elif type(item) == list:
@@ -186,6 +193,8 @@
value = _decode_bool(item)
elif item_type == _ITEM_INT:
value = _decode_int(item)
+ elif item_type == _ITEM_REAL:
+ value = _decode_real(item)
elif item_type == _ITEM_UTF8:
value = str(item, 'utf-8')
elif item_type == _ITEM_HASH:
@@ -205,6 +214,9 @@
def _decode_int(data):
return int(str(data, 'utf-8'))
+def _decode_real(data):
+ return float(str(data, 'utf-8'))
+
def _decode_hash(data):
ret = {}
while len(data) > 0:
Modified: branches/trac185/src/lib/python/isc/cc/session.py
==============================================================================
--- branches/trac185/src/lib/python/isc/cc/session.py (original)
+++ branches/trac185/src/lib/python/isc/cc/session.py Mon May 31 06:06:39 2010
@@ -17,6 +17,7 @@
import socket
import struct
import os
+import threading
import isc.cc.message
@@ -33,6 +34,7 @@
self._sequence = 1
self._closed = False
self._queue = []
+ self._lock = threading.RLock()
if port == 0:
if 'ISC_MSGQ_PORT' in os.environ:
@@ -64,56 +66,54 @@
self._closed = True
def sendmsg(self, env, msg = None):
- XXmsg = msg
- XXenv = env
- if self._closed:
- raise SessionError("Session has been closed.")
- if type(env) == dict:
- env = isc.cc.message.to_wire(env)
- if type(msg) == dict:
- msg = isc.cc.message.to_wire(msg)
- self._socket.setblocking(1)
- length = 2 + len(env);
- if msg:
- length += len(msg)
- self._socket.send(struct.pack("!I", length))
- self._socket.send(struct.pack("!H", len(env)))
- self._socket.send(env)
- if msg:
- self._socket.send(msg)
+ with self._lock:
+ if self._closed:
+ raise SessionError("Session has been closed.")
+ if type(env) == dict:
+ env = isc.cc.message.to_wire(env)
+ if type(msg) == dict:
+ msg = isc.cc.message.to_wire(msg)
+ self._socket.setblocking(1)
+ length = 2 + len(env);
+ if msg:
+ length += len(msg)
+ self._socket.send(struct.pack("!I", length))
+ self._socket.send(struct.pack("!H", len(env)))
+ self._socket.send(env)
+ if msg:
+ self._socket.send(msg)
def recvmsg(self, nonblock = True, seq = None):
- #print("[XX] queue len: " + str(len(self._queue)))
- if len(self._queue) > 0:
- if seq == None:
- #print("[XX] return first")
- return self._queue.pop(0)
- else:
+ with self._lock:
+ if len(self._queue) > 0:
i = 0;
- #print("[XX] check rest")
for env, msg in self._queue:
- if "reply" in env and seq == env["reply"]:
+ if seq != None and "reply" in env and seq == env["reply"]:
+ return self._queue.pop(i)
+ elif seq == None and "reply" not in env:
return self._queue.pop(i)
else:
i = i + 1
- #print("[XX] not found")
- if self._closed:
- raise SessionError("Session has been closed.")
- data = self._receive_full_buffer(nonblock)
- if data and len(data) > 2:
- header_length = struct.unpack('>H', data[0:2])[0]
- data_length = len(data) - 2 - header_length
- if data_length > 0:
- env = isc.cc.message.from_wire(data[2:header_length+2])
- msg = isc.cc.message.from_wire(data[header_length + 2:])
- if seq == None or "reply" in env and seq == env["reply"]:
- return env, msg
+ if self._closed:
+ raise SessionError("Session has been closed.")
+ data = self._receive_full_buffer(nonblock)
+ if data and len(data) > 2:
+ header_length = struct.unpack('>H', data[0:2])[0]
+ data_length = len(data) - 2 - header_length
+ if data_length > 0:
+ env = isc.cc.message.from_wire(data[2:header_length+2])
+ msg = isc.cc.message.from_wire(data[header_length + 2:])
+ if (seq == None and "reply" not in env) or (seq != None and "reply" in env and seq == env["reply"]):
+ return env, msg
+ else:
+ tmp = None
+ if "reply" in env:
+ tmp = env["reply"]
+ self._queue.append((env,msg))
+ return self.recvmsg(nonblock, seq)
else:
- self._queue.append((env,msg))
- return self.recvmsg(nonblock, seq)
- else:
- return isc.cc.message.from_wire(data[2:header_length+2]), None
- return None, None
+ return isc.cc.message.from_wire(data[2:header_length+2]), None
+ return None, None
def _receive_full_buffer(self, nonblock):
if nonblock:
@@ -130,7 +130,6 @@
return None
if data == "": # server closed connection
raise ProtocolError("Read of 0 bytes: connection closed")
-
self._recvbuffer += data
if len(self._recvbuffer) < 4:
return None
@@ -182,6 +181,9 @@
}, isc.cc.message.to_wire(msg))
return seq
+ def has_queued_msgs(self):
+ return len(self._queue) > 0
+
def group_recvmsg(self, nonblock = True, seq = None):
env, msg = self.recvmsg(nonblock, seq)
if env == None:
Modified: branches/trac185/src/lib/python/isc/cc/tests/session_test.py
==============================================================================
--- branches/trac185/src/lib/python/isc/cc/tests/session_test.py (original)
+++ branches/trac185/src/lib/python/isc/cc/tests/session_test.py Mon May 31 06:06:39 2010
@@ -98,6 +98,7 @@
self._sequence = 1
self._closed = False
self._queue = []
+ self._lock = threading.RLock()
try:
self._socket = MySocket(socket.AF_INET, socket.SOCK_STREAM)
@@ -178,66 +179,78 @@
# sending message {'to': 'someone', 'reply': 1}, {"hello": "a"}
#print("sending message {'to': 'someone', 'reply': 1}, {'hello': 'a'}")
- # simply get the message without asking for a specific sequence number reply
+ # get no message without asking for a specific sequence number reply
+ self.assertFalse(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
env, msg = sess.recvmsg(False)
+ self.assertEqual(None, env)
+ self.assertTrue(sess.has_queued_msgs())
+ env, msg = sess.recvmsg(False, 1)
self.assertEqual({'to': 'someone', 'reply': 1}, env)
self.assertEqual({"hello": "a"}, msg)
-
- # simply get the message, asking for a specific sequence number reply
- sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
- env, msg = sess.recvmsg(False, 1)
- self.assertEqual({'to': 'someone', 'reply': 1}, env)
- self.assertEqual({"hello": "a"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
# ask for a differe sequence number reply (that doesn't exist)
# then ask for the one that is there
+ self.assertFalse(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
env, msg = sess.recvmsg(False, 2)
self.assertEqual(None, env)
self.assertEqual(None, msg)
+ self.assertTrue(sess.has_queued_msgs())
env, msg = sess.recvmsg(False, 1)
self.assertEqual({'to': 'someone', 'reply': 1}, env)
self.assertEqual({"hello": "a"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
# ask for a differe sequence number reply (that doesn't exist)
# then ask for any message
+ self.assertFalse(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
env, msg = sess.recvmsg(False, 2)
self.assertEqual(None, env)
self.assertEqual(None, msg)
- env, msg = sess.recvmsg(False)
+ self.assertTrue(sess.has_queued_msgs())
+ env, msg = sess.recvmsg(False, 1)
self.assertEqual({'to': 'someone', 'reply': 1}, env)
self.assertEqual({"hello": "a"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
#print("sending message {'to': 'someone', 'reply': 1}, {'hello': 'a'}")
# ask for a differe sequence number reply (that doesn't exist)
- # send a new message, ask for any message (get the first)
+ # send a new message, ask for specific message (get the first)
# then ask for any message (get the second)
+ self.assertFalse(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
env, msg = sess.recvmsg(False, 2)
self.assertEqual(None, env)
self.assertEqual(None, msg)
+ self.assertTrue(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00\x1f\x00\x10Skan\x02to(\x07someoneSkan\x05hello(\x01b')
- env, msg = sess.recvmsg(False)
- self.assertEqual({'to': 'someone', 'reply': 1}, env)
- self.assertEqual({"hello": "a"}, msg)
+ env, msg = sess.recvmsg(False, 1)
+ self.assertEqual({'to': 'someone', 'reply': 1 }, env)
+ self.assertEqual({"hello": "a"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
env, msg = sess.recvmsg(False)
self.assertEqual({'to': 'someone'}, env)
self.assertEqual({"hello": "b"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
# send a message, then one with specific reply value
# ask for that specific message (get the second)
# then ask for any message (get the first)
+ self.assertFalse(sess.has_queued_msgs())
sess._socket.addrecv(b'\x00\x00\x00\x1f\x00\x10Skan\x02to(\x07someoneSkan\x05hello(\x01b')
sess._socket.addrecv(b'\x00\x00\x00(\x00\x19Skan\x02to(\x07someone\x05reply&\x011Skan\x05hello(\x01a')
env, msg = sess.recvmsg(False, 1)
self.assertEqual({'to': 'someone', 'reply': 1}, env)
self.assertEqual({"hello": "a"}, msg)
+ self.assertTrue(sess.has_queued_msgs())
env, msg = sess.recvmsg(False)
self.assertEqual({'to': 'someone'}, env)
self.assertEqual({"hello": "b"}, msg)
+ self.assertFalse(sess.has_queued_msgs())
def test_next_sequence(self):
sess = MySession()
Modified: branches/trac185/src/lib/python/isc/config/ccsession.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/ccsession.py (original)
+++ branches/trac185/src/lib/python/isc/config/ccsession.py Mon May 31 06:06:39 2010
@@ -81,8 +81,7 @@
# 'fixed' commands
"""Fixed names for command and configuration messages"""
COMMAND_CONFIG_UPDATE = "config_update"
-COMMAND_COMMANDS_UPDATE = "commands_update"
-COMMAND_SPECIFICATION_UPDATE = "specification_update"
+COMMAND_MODULE_SPECIFICATION_UPDATE = "module_specification_update"
COMMAND_GET_COMMANDS_SPEC = "get_commands_spec"
COMMAND_GET_CONFIG = "get_config"
@@ -314,16 +313,9 @@
# this step should be unnecessary but is the current way cmdctl returns stuff
# so changes are needed there to make this clean (we need a command to simply get the
# full specs for everything, including commands etc, not separate gets for that)
- specs = self._conn.send_GET('/config_spec')
- commands = self._conn.send_GET('/commands')
+ specs = self._conn.send_GET('/module_spec')
for module in specs.keys():
- cur_spec = { 'module_name': module }
- if module in specs and specs[module]:
- cur_spec['config_data'] = specs[module]
- if module in commands and commands[module]:
- cur_spec['commands'] = commands[module]
-
- self.set_specification(isc.config.ModuleSpec(cur_spec))
+ self.set_specification(isc.config.ModuleSpec(specs[module]))
def request_current_config(self):
"""Requests the current configuration from the configuration
Modified: branches/trac185/src/lib/python/isc/config/cfgmgr.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/cfgmgr.py (original)
+++ branches/trac185/src/lib/python/isc/config/cfgmgr.py Mon May 31 06:06:39 2010
@@ -25,7 +25,9 @@
import pprint
import os
import copy
+import tempfile
from isc.cc import data
+from isc.config import ccsession
class ConfigManagerDataReadError(Exception):
"""This exception is thrown when there is an error while reading
@@ -84,24 +86,35 @@
"""Writes the current configuration data to a file. If
output_file_name is not specified, the file used in
read_from_file is used."""
+ filename = None
try:
- tmp_filename = self.db_filename + ".tmp"
- file = open(tmp_filename, 'w');
+ file = tempfile.NamedTemporaryFile(mode='w',
+ prefix="b10-config.db.",
+ dir=self.data_path,
+ delete=False)
+ filename = file.name
pp = pprint.PrettyPrinter(indent=4)
s = pp.pformat(self.data)
file.write(s)
file.write("\n")
file.close()
if output_file_name:
- os.rename(tmp_filename, output_file_name)
- else:
- os.rename(tmp_filename, self.db_filename)
+ os.rename(filename, output_file_name)
+ else:
+ os.rename(filename, self.db_filename)
except IOError as ioe:
# TODO: log this (level critical)
print("[b10-cfgmgr] Unable to write config file; configuration not stored: " + str(ioe))
+ # TODO: debug option to keep file?
except OSError as ose:
# TODO: log this (level critical)
print("[b10-cfgmgr] Unable to write config file; configuration not stored: " + str(ose))
+ try:
+ if filename and os.path.exists(filename):
+ os.remove(filename)
+ except OSError:
+ # Ok if we really can't delete it anymore, leave it
+ pass
def __eq__(self, other):
"""Returns True if the data contained is equal. data_path and
@@ -148,11 +161,23 @@
if module_name in self.module_specs:
del self.module_specs[module_name]
- def get_module_spec(self, module_name):
+ def get_module_spec(self, module_name = None):
"""Returns the full ModuleSpec for the module with the given
- module_name"""
- if module_name in self.module_specs:
- return self.module_specs[module_name]
+ module_name. If no module name is given, a dict will
+ be returned with 'name': module_spec values. If the
+ module name is given, but does not exist, an empty dict
+ is returned"""
+ if module_name:
+ if module_name in self.module_specs:
+ return self.module_specs[module_name]
+ else:
+ # TODO: log error?
+ return {}
+ else:
+ result = {}
+ for module in self.module_specs:
+ result[module] = self.module_specs[module].get_full_spec()
+ return result
def get_config_spec(self, name = None):
"""Returns a dict containing 'module_name': config_spec for
@@ -201,95 +226,112 @@
if type(cmd) == dict:
if 'module_name' in cmd and cmd['module_name'] != '':
module_name = cmd['module_name']
- answer = isc.config.ccsession.create_answer(0, self.get_config_spec(module_name))
+ answer = ccsession.create_answer(0, self.get_module_spec(module_name))
else:
- answer = isc.config.ccsession.create_answer(1, "Bad module_name in get_module_spec command")
- else:
- answer = isc.config.ccsession.create_answer(1, "Bad get_module_spec command, argument not a dict")
- else:
- answer = isc.config.ccsession.create_answer(0, self.get_config_spec())
+ answer = ccsession.create_answer(1, "Bad module_name in get_module_spec command")
+ else:
+ answer = ccsession.create_answer(1, "Bad get_module_spec command, argument not a dict")
+ else:
+ answer = ccsession.create_answer(0, self.get_module_spec())
return answer
+
+ def _handle_get_config_dict(self, cmd):
+ """Private function that handles the 'get_config' command
+ where the command has been checked to be a dict"""
+ if 'module_name' in cmd and cmd['module_name'] != '':
+ module_name = cmd['module_name']
+ try:
+ return ccsession.create_answer(0, data.find(self.config.data, module_name))
+ except data.DataNotFoundError as dnfe:
+ # no data is ok, that means we have nothing that
+ # deviates from default values
+ return ccsession.create_answer(0, { 'version': self.config.CONFIG_VERSION })
+ else:
+ return ccsession.create_answer(1, "Bad module_name in get_config command")
def _handle_get_config(self, cmd):
"""Private function that handles the 'get_config' command"""
- answer = {}
if cmd != None:
if type(cmd) == dict:
- if 'module_name' in cmd and cmd['module_name'] != '':
- module_name = cmd['module_name']
- try:
- answer = isc.config.ccsession.create_answer(0, data.find(self.config.data, module_name))
- except data.DataNotFoundError as dnfe:
- # no data is ok, that means we have nothing that
- # deviates from default values
- answer = isc.config.ccsession.create_answer(0, { 'version': self.config.CONFIG_VERSION })
+ return self._handle_get_config_dict(cmd)
+ else:
+ return ccsession.create_answer(1, "Bad get_config command, argument not a dict")
+ else:
+ return ccsession.create_answer(0, self.config.data)
+
+ def _handle_set_config_module(self, cmd):
+ # the answer comes (or does not come) from the relevant module
+ # so we need a variable to see if we got it
+ answer = None
+ # todo: use api (and check the data against the definition?)
+ old_data = copy.deepcopy(self.config.data)
+ module_name = cmd[0]
+ conf_part = data.find_no_exc(self.config.data, module_name)
+ if conf_part:
+ data.merge(conf_part, cmd[1])
+ update_cmd = ccsession.create_command(ccsession.COMMAND_CONFIG_UPDATE,
+ conf_part)
+ seq = self.cc.group_sendmsg(update_cmd, module_name)
+ answer, env = self.cc.group_recvmsg(False, seq)
+ else:
+ conf_part = data.set(self.config.data, module_name, {})
+ data.merge(conf_part[module_name], cmd[1])
+ # send out changed info
+ update_cmd = ccsession.create_command(ccsession.COMMAND_CONFIG_UPDATE,
+ conf_part[module_name])
+ seq = self.cc.group_sendmsg(update_cmd, module_name)
+ # replace 'our' answer with that of the module
+ answer, env = self.cc.group_recvmsg(False, seq)
+ if answer:
+ rcode, val = ccsession.parse_answer(answer)
+ if rcode == 0:
+ self.write_config()
+ else:
+ self.config.data = old_data
+ return answer
+
+ def _handle_set_config_all(self, cmd):
+ old_data = copy.deepcopy(self.config.data)
+ data.merge(self.config.data, cmd[0])
+ # send out changed info
+ got_error = False
+ err_list = []
+ for module in self.config.data:
+ if module != "version" and \
+ (module not in old_data or self.config.data[module] != old_data[module]):
+ update_cmd = ccsession.create_command(ccsession.COMMAND_CONFIG_UPDATE,
+ self.config.data[module])
+ seq = self.cc.group_sendmsg(update_cmd, module)
+ answer, env = self.cc.group_recvmsg(False, seq)
+ if answer == None:
+ got_error = True
+ err_list.append("No answer message from " + module)
else:
- answer = isc.config.ccsession.create_answer(1, "Bad module_name in get_config command")
- else:
- answer = isc.config.ccsession.create_answer(1, "Bad get_config command, argument not a dict")
- else:
- answer = isc.config.ccsession.create_answer(0, self.config.data)
- return answer
+ rcode, val = ccsession.parse_answer(answer)
+ if rcode != 0:
+ got_error = True
+ err_list.append(val)
+ if not got_error:
+ self.write_config()
+ return ccsession.create_answer(0)
+ else:
+ # TODO rollback changes that did get through, should we re-send update?
+ self.config.data = old_data
+ return ccsession.create_answer(1, " ".join(err_list))
def _handle_set_config(self, cmd):
"""Private function that handles the 'set_config' command"""
answer = None
if cmd == None:
- return isc.config.ccsession.create_answer(1, "Wrong number of arguments")
+ return ccsession.create_answer(1, "Wrong number of arguments")
if len(cmd) == 2:
- # todo: use api (and check the data against the definition?)
- old_data = copy.deepcopy(self.config.data)
- module_name = cmd[0]
- conf_part = data.find_no_exc(self.config.data, module_name)
- if conf_part:
- data.merge(conf_part, cmd[1])
- update_cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, conf_part)
- seq = self.cc.group_sendmsg(update_cmd, module_name)
- answer, env = self.cc.group_recvmsg(False, seq)
- else:
- conf_part = data.set(self.config.data, module_name, {})
- data.merge(conf_part[module_name], cmd[1])
- # send out changed info
- update_cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, conf_part[module_name])
- seq = self.cc.group_sendmsg(update_cmd, module_name)
- # replace 'our' answer with that of the module
- answer, env = self.cc.group_recvmsg(False, seq)
- if answer:
- rcode, val = isc.config.ccsession.parse_answer(answer)
- if rcode == 0:
- self.write_config()
- else:
- self.config.data = old_data
+ answer = self._handle_set_config_module(cmd)
elif len(cmd) == 1:
- old_data = copy.deepcopy(self.config.data)
- data.merge(self.config.data, cmd[0])
- # send out changed info
- got_error = False
- err_list = []
- for module in self.config.data:
- if module != "version" and (module not in old_data or self.config.data[module] != old_data[module]):
- update_cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, self.config.data[module])
- seq = self.cc.group_sendmsg(update_cmd, module)
- answer, env = self.cc.group_recvmsg(False, seq)
- if answer == None:
- got_error = True
- err_list.append("No answer message from " + module)
- else:
- rcode, val = isc.config.ccsession.parse_answer(answer)
- if rcode != 0:
- got_error = True
- err_list.append(val)
- if not got_error:
- self.write_config()
- answer = isc.config.ccsession.create_answer(0)
- else:
- # TODO rollback changes that did get through, should we re-send update?
- self.config.data = old_data
- answer = isc.config.ccsession.create_answer(1, " ".join(err_list))
- else:
- answer = isc.config.ccsession.create_answer(1, "Wrong number of arguments")
+ answer = self._handle_set_config_all(cmd)
+ else:
+ answer = ccsession.create_answer(1, "Wrong number of arguments")
if not answer:
- answer = isc.config.ccsession.create_answer(1, "No answer message from " + cmd[0])
+ answer = ccsession.create_answer(1, "No answer message from " + cmd[0])
return answer
@@ -303,42 +345,38 @@
# We should make one general 'spec update for module' that
# passes both specification and commands at once
- spec_update = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_SPECIFICATION_UPDATE,
- [ spec.get_module_name(), spec.get_config_spec() ])
+ spec_update = ccsession.create_command(ccsession.COMMAND_MODULE_SPECIFICATION_UPDATE,
+ [ spec.get_module_name(), spec.get_full_spec() ])
self.cc.group_sendmsg(spec_update, "Cmd-Ctrld")
- cmds_update = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_COMMANDS_UPDATE,
- [ spec.get_module_name(), spec.get_commands_spec() ])
- self.cc.group_sendmsg(cmds_update, "Cmd-Ctrld")
- answer = isc.config.ccsession.create_answer(0)
- return answer
+ return ccsession.create_answer(0)
def handle_msg(self, msg):
"""Handle a command from the cc channel to the configuration manager"""
answer = {}
- cmd, arg = isc.config.ccsession.parse_command(msg)
+ cmd, arg = ccsession.parse_command(msg)
if cmd:
- if cmd == isc.config.ccsession.COMMAND_GET_COMMANDS_SPEC:
- answer = isc.config.ccsession.create_answer(0, self.get_commands_spec())
- elif cmd == isc.config.ccsession.COMMAND_GET_MODULE_SPEC:
+ if cmd == ccsession.COMMAND_GET_COMMANDS_SPEC:
+ answer = ccsession.create_answer(0, self.get_commands_spec())
+ elif cmd == ccsession.COMMAND_GET_MODULE_SPEC:
answer = self._handle_get_module_spec(arg)
- elif cmd == isc.config.ccsession.COMMAND_GET_CONFIG:
+ elif cmd == ccsession.COMMAND_GET_CONFIG:
answer = self._handle_get_config(arg)
- elif cmd == isc.config.ccsession.COMMAND_SET_CONFIG:
+ elif cmd == ccsession.COMMAND_SET_CONFIG:
answer = self._handle_set_config(arg)
- elif cmd == isc.config.ccsession.COMMAND_SHUTDOWN:
+ elif cmd == ccsession.COMMAND_SHUTDOWN:
# TODO: logging
#print("[b10-cfgmgr] Received shutdown command")
self.running = False
- answer = isc.config.ccsession.create_answer(0)
- elif cmd == isc.config.ccsession.COMMAND_MODULE_SPEC:
+ answer = ccsession.create_answer(0)
+ elif cmd == ccsession.COMMAND_MODULE_SPEC:
try:
answer = self._handle_module_spec(isc.config.ModuleSpec(arg))
except isc.config.ModuleSpecError as dde:
- answer = isc.config.ccsession.create_answer(1, "Error in data definition: " + str(dde))
- else:
- answer = isc.config.ccsession.create_answer(1, "Unknown command: " + str(cmd))
- else:
- answer = isc.config.ccsession.create_answer(1, "Unknown message format: " + str(msg))
+ answer = ccsession.create_answer(1, "Error in data definition: " + str(dde))
+ else:
+ answer = ccsession.create_answer(1, "Unknown command: " + str(cmd))
+ else:
+ answer = ccsession.create_answer(1, "Unknown message format: " + str(msg))
return answer
def run(self):
Modified: branches/trac185/src/lib/python/isc/config/config_data.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/config_data.py (original)
+++ branches/trac185/src/lib/python/isc/config/config_data.py Mon May 31 06:06:39 2010
@@ -52,6 +52,51 @@
elif data_type == "map" and type(value) != dict:
# todo: check types of map contents too
raise isc.cc.data.DataTypeError(str(value) + " is not a map")
+
+def convert_type(spec_part, value):
+ """Convert the give value(type is string) according specification
+ part relevant for the value. Raises an isc.cc.data.DataTypeError
+ exception if conversion failed.
+ """
+ if type(spec_part) == dict and 'item_type' in spec_part:
+ data_type = spec_part['item_type']
+ else:
+ raise isc.cc.data.DataTypeError(str("Incorrect specification part for type convering"))
+
+ try:
+ if data_type == "integer":
+ return int(value)
+ elif data_type == "real":
+ return float(value)
+ elif data_type == "boolean":
+ return str.lower(str(value)) != 'false'
+ elif data_type == "string":
+ return str(value)
+ elif data_type == "list":
+ ret = []
+ if type(value) == list:
+ for item in value:
+ ret.append(convert_type(spec_part['list_item_spec'], item))
+ elif type(value) == str:
+ value = value.split(',')
+ for item in value:
+ sub_value = item.split()
+ for sub_item in sub_value:
+ ret.append(convert_type(spec_part['list_item_spec'], sub_item))
+
+ if ret == []:
+ raise isc.cc.data.DataTypeError(str(value) + " is not a list")
+
+ return ret
+ elif data_type == "map":
+ return dict(value)
+ # todo: check types of map contents too
+ else:
+ return value
+ except ValueError as err:
+ raise isc.cc.data.DataTypeError(str(err))
+ except TypeError as err:
+ raise isc.cc.data.DataTypeError(str(err))
def find_spec_part(element, identifier):
"""find the data definition for the given identifier
Modified: branches/trac185/src/lib/python/isc/config/module_spec.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/module_spec.py (original)
+++ branches/trac185/src/lib/python/isc/config/module_spec.py Mon May 31 06:06:39 2010
@@ -83,11 +83,42 @@
errors.append("No config_data specification")
return False
+ def validate_command(self, cmd_name, cmd_params, errors = None):
+ '''Check whether the given piece of command conforms to this
+ command definition. If so, it reutrns True. If not, it will
+ return False. If errors is given, and is an array, a string
+ describing the error will be appended to it. The current version
+ stops as soon as there is one error.
+ cmd_name is command name to be validated, cmd_params includes
+ command's parameters needs to be validated. cmd_params must
+ be a map, with the format like:
+ {param1_name: param1_value, param2_name: param2_value}
+ '''
+ cmd_spec = self.get_commands_spec()
+ if not cmd_spec:
+ return False
+
+ for cmd in cmd_spec:
+ if cmd['command_name'] != cmd_name:
+ continue
+ return _validate_spec_list(cmd['command_args'], True, cmd_params, errors)
+
+ return False
def get_module_name(self):
"""Returns a string containing the name of the module as
- specified by the specification given at __init__"""
+ specified by the specification given at __init__()"""
return self._module_spec['module_name']
+
+ def get_module_description(self):
+ """Returns a string containing the description of the module as
+ specified by the specification given at __init__().
+ Returns an empty string if there is no description.
+ """
+ if 'module_description' in self._module_spec:
+ return self._module_spec['module_description']
+ else:
+ return ""
def get_full_spec(self):
"""Returns a dict representation of the full module specification"""
@@ -123,6 +154,9 @@
raise ModuleSpecError("data specification not a dict")
if "module_name" not in module_spec:
raise ModuleSpecError("no module_name in module_spec")
+ if "module_description" in module_spec and \
+ type(module_spec["module_description"]) != str:
+ raise ModuleSpecError("module_description is not a string")
if "config_data" in module_spec:
_check_config_spec(module_spec["config_data"])
if "commands" in module_spec:
Modified: branches/trac185/src/lib/python/isc/config/tests/ccsession_test.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/tests/ccsession_test.py (original)
+++ branches/trac185/src/lib/python/isc/config/tests/ccsession_test.py Mon May 31 06:06:39 2010
@@ -377,7 +377,7 @@
if name in self.get_answers:
return self.get_answers[name]
else:
- return None
+ return {}
def send_POST(self, name, arg = None):
if name in self.post_answers:
@@ -398,23 +398,20 @@
def create_uccs2(self, fake_conn):
module_spec = isc.config.module_spec_from_file(self.spec_file("spec2.spec"))
- fake_conn.set_get_answer('/config_spec', { module_spec.get_module_name(): module_spec.get_config_spec()})
- fake_conn.set_get_answer('/commands', { module_spec.get_module_name(): module_spec.get_commands_spec()})
+ fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
fake_conn.set_get_answer('/config_data', { 'version': 1 })
return UIModuleCCSession(fake_conn)
def test_init(self):
fake_conn = fakeUIConn()
- fake_conn.set_get_answer('/config_spec', {})
- fake_conn.set_get_answer('/commands', {})
+ fake_conn.set_get_answer('/module_spec', {})
fake_conn.set_get_answer('/config_data', { 'version': 1 })
uccs = UIModuleCCSession(fake_conn)
self.assertEqual({}, uccs._specifications)
self.assertEqual({ 'version': 1}, uccs._current_config)
module_spec = isc.config.module_spec_from_file(self.spec_file("spec2.spec"))
- fake_conn.set_get_answer('/config_spec', { module_spec.get_module_name(): module_spec.get_config_spec()})
- fake_conn.set_get_answer('/commands', { module_spec.get_module_name(): module_spec.get_commands_spec()})
+ fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
fake_conn.set_get_answer('/config_data', { 'version': 1 })
uccs = UIModuleCCSession(fake_conn)
self.assertEqual(module_spec._module_spec, uccs._specifications['Spec2']._module_spec)
Modified: branches/trac185/src/lib/python/isc/config/tests/cfgmgr_test.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/tests/cfgmgr_test.py (original)
+++ branches/trac185/src/lib/python/isc/config/tests/cfgmgr_test.py Mon May 31 06:06:39 2010
@@ -264,7 +264,7 @@
{'result': [0]})
self._handle_msg_helper({ "command": [ "module_spec", { 'foo': 1 } ] },
{'result': [1, 'Error in data definition: no module_name in module_spec']})
- self._handle_msg_helper({ "command": [ "get_module_spec" ] }, { 'result': [ 0, { self.spec.get_module_name(): self.spec.get_config_spec() } ]})
+ self._handle_msg_helper({ "command": [ "get_module_spec" ] }, { 'result': [ 0, { self.spec.get_module_name(): self.spec.get_full_spec() } ]})
self._handle_msg_helper({ "command": [ "get_commands_spec" ] }, { 'result': [ 0, { self.spec.get_module_name(): self.spec.get_commands_spec() } ]})
# re-add this once we have new way to propagate spec changes (1 instead of the current 2 messages)
#self.assertEqual(len(self.fake_session.message_queue), 2)
Modified: branches/trac185/src/lib/python/isc/config/tests/config_data_test.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/tests/config_data_test.py (original)
+++ branches/trac185/src/lib/python/isc/config/tests/config_data_test.py Mon May 31 06:06:39 2010
@@ -94,6 +94,71 @@
#self.assertRaises(isc.cc.data.DataTypeError, check_type, spec_part, { "value1": 1 })
self.assertRaises(isc.cc.data.DataTypeError, check_type, config_spec, 1)
+
+ def test_convert_type(self):
+ config_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec22.spec").get_config_spec()
+ spec_part = find_spec_part(config_spec, "value1")
+ self.assertEqual(1, convert_type(spec_part, '1'))
+ self.assertEqual(2, convert_type(spec_part, 2.1))
+ self.assertEqual(2, convert_type(spec_part, '2'))
+ self.assertEqual(3, convert_type(spec_part, '3'))
+ self.assertEqual(1, convert_type(spec_part, True))
+
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, "a")
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, [ 1, 2 ])
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, { "a": 1 })
+
+ spec_part = find_spec_part(config_spec, "value2")
+ self.assertEqual(1.1, convert_type(spec_part, '1.1'))
+ self.assertEqual(123.0, convert_type(spec_part, '123'))
+ self.assertEqual(1.0, convert_type(spec_part, True))
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, "a")
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, [ 1, 2 ])
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, { "a": 1 })
+
+ spec_part = find_spec_part(config_spec, "value3")
+ self.assertEqual(True, convert_type(spec_part, 'True'))
+ self.assertEqual(False, convert_type(spec_part, 'False'))
+ self.assertEqual(True, convert_type(spec_part, 1))
+ self.assertEqual(True, convert_type(spec_part, 1.1))
+ self.assertEqual(True, convert_type(spec_part, 'a'))
+ self.assertEqual(True, convert_type(spec_part, [1, 2]))
+ self.assertEqual(True, convert_type(spec_part, {'a' : 1}))
+
+ spec_part = find_spec_part(config_spec, "value4")
+ self.assertEqual('asdf', convert_type(spec_part, "asdf"))
+ self.assertEqual('1', convert_type(spec_part, 1))
+ self.assertEqual('1.1', convert_type(spec_part, 1.1))
+ self.assertEqual('True', convert_type(spec_part, True))
+
+ spec_part = find_spec_part(config_spec, "value5")
+ self.assertEqual([1, 2], convert_type(spec_part, '1, 2'))
+ self.assertEqual([1, 2, 3], convert_type(spec_part, '1 2 3'))
+ self.assertEqual([1, 2, 3,4], convert_type(spec_part, '1 2 3, 4'))
+ self.assertEqual([1], convert_type(spec_part, [1,]))
+ self.assertEqual([1,2], convert_type(spec_part, [1,2]))
+ self.assertEqual([1,2], convert_type(spec_part, ['1', '2']))
+
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, 1.1)
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, True)
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, "a")
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, [ "a", "b" ])
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, [ "1", "b" ])
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, { "a": 1 })
+
+ spec_part = find_spec_part(config_spec, "value7")
+ self.assertEqual(['1', '2'], convert_type(spec_part, '1, 2'))
+ self.assertEqual(['1', '2', '3'], convert_type(spec_part, '1 2 3'))
+ self.assertEqual(['1', '2', '3','4'], convert_type(spec_part, '1 2 3, 4'))
+ self.assertEqual([1], convert_type(spec_part, [1,]))
+ self.assertEqual([1,2], convert_type(spec_part, [1,2]))
+ self.assertEqual(['1','2'], convert_type(spec_part, ['1', '2']))
+
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, 1.1)
+ self.assertRaises(isc.cc.data.DataTypeError, convert_type, spec_part, True)
+ self.assertEqual(['a'], convert_type(spec_part, "a"))
+ self.assertEqual(['a', 'b'], convert_type(spec_part, ["a", "b" ]))
+ self.assertEqual([1, 'b'], convert_type(spec_part, [1, "b" ]))
def test_find_spec_part(self):
config_spec = self.cd.get_module_spec().get_config_spec()
Modified: branches/trac185/src/lib/python/isc/config/tests/module_spec_test.py
==============================================================================
--- branches/trac185/src/lib/python/isc/config/tests/module_spec_test.py (original)
+++ branches/trac185/src/lib/python/isc/config/tests/module_spec_test.py Mon May 31 06:06:39 2010
@@ -75,6 +75,7 @@
self.assertRaises(ModuleSpecError, self.read_spec_file, "spec19.spec")
self.assertRaises(ModuleSpecError, self.read_spec_file, "spec20.spec")
self.assertRaises(ModuleSpecError, self.read_spec_file, "spec21.spec")
+ self.assertRaises(ModuleSpecError, self.read_spec_file, "spec26.spec")
def validate_data(self, specfile_name, datafile_name):
dd = self.read_spec_file(specfile_name);
@@ -93,10 +94,32 @@
self.assertEqual(True, self.validate_data("spec22.spec", "data22_7.data"))
self.assertEqual(False, self.validate_data("spec22.spec", "data22_8.data"))
+ def validate_command_params(self, specfile_name, datafile_name, cmd_name):
+ dd = self.read_spec_file(specfile_name);
+ data_file = open(self.spec_file(datafile_name))
+ data_str = data_file.read()
+ params = isc.cc.data.parse_value_str(data_str)
+ return dd.validate_command(cmd_name, params)
+
+ def test_command_validation(self):
+ self.assertEqual(True, self.validate_command_params("spec27.spec", "data22_1.data", 'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_2.data",'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_3.data", 'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_4.data", 'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_5.data", 'cmd1'))
+ self.assertEqual(True, self.validate_command_params("spec27.spec", "data22_6.data", 'cmd1'))
+ self.assertEqual(True, self.validate_command_params("spec27.spec", "data22_7.data", 'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_8.data", 'cmd1'))
+ self.assertEqual(False, self.validate_command_params("spec27.spec", "data22_8.data", 'cmd2'))
+
def test_init(self):
self.assertRaises(ModuleSpecError, ModuleSpec, 1)
module_spec = isc.config.module_spec_from_file(self.spec_file("spec1.spec"), False)
self.spec1(module_spec)
+
+ module_spec = isc.config.module_spec_from_file(self.spec_file("spec25.spec"), True)
+ self.assertEqual("Spec25", module_spec.get_module_name())
+ self.assertEqual("Just an empty module", module_spec.get_module_description())
def test_str(self):
module_spec = isc.config.module_spec_from_file(self.spec_file("spec1.spec"), False)
Modified: branches/trac185/src/lib/xfr/Makefile.am
==============================================================================
--- branches/trac185/src/lib/xfr/Makefile.am (original)
+++ branches/trac185/src/lib/xfr/Makefile.am Mon May 31 06:06:39 2010
@@ -2,11 +2,10 @@
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
-AM_CPPFLAGS += -I$(top_srcdir)/ext -Wno-strict-aliasing
+AM_CPPFLAGS += -I$(top_srcdir)/ext
-if GCC_WERROR_OK
-AM_CPPFLAGS += -Werror
-endif
+AM_CXXFLAGS = $(B10_CXXFLAGS) -Wno-strict-aliasing
+AM_CXXFLAGS += -Wno-unused-parameter # see src/lib/cc/Makefile.am
CLEANFILES = *.gcno *.gcda
@@ -18,10 +17,11 @@
pyexec_LTLIBRARIES = bind10_xfr.la
bind10_xfr_la_SOURCES = python_xfr.cc fd_share.cc fd_share.h
bind10_xfr_la_CPPFLAGS = $(AM_CPPFLAGS) $(PYTHON_INCLUDES)
+bind10_xfr_la_CXXFLAGS = $(AM_CXXFLAGS)
if GCC_WERROR_OK
# XXX: Boost.Python triggers strict aliasing violation, so if we use -Werror
# we need to suppress the warnings.
-bind10_xfr_la_CPPFLAGS += -fno-strict-aliasing
+bind10_xfr_la_CXXFLAGS += -fno-strict-aliasing
endif
bind10_xfr_la_LDFLAGS = $(BOOST_LDFLAGS) $(PYTHON_LDFLAGS)
# Python prefers .so, while some OSes (specifically MacOS) use a different
Modified: branches/trac185/src/lib/xfr/xfrout_client.cc
==============================================================================
--- branches/trac185/src/lib/xfr/xfrout_client.cc (original)
+++ branches/trac185/src/lib/xfr/xfrout_client.cc Mon May 31 06:06:39 2010
@@ -17,46 +17,72 @@
#include <cstdlib>
#include <cstring>
#include <iostream>
+
+#include <asio.hpp>
+
#include "fd_share.h"
#include "xfrout_client.h"
-using boost::asio::local::stream_protocol;
+using namespace std;
+using asio::local::stream_protocol;
namespace isc {
namespace xfr {
+struct XfroutClientImpl {
+ XfroutClientImpl(const string& file);
+ const std::string file_path_;
+ asio::io_service io_service_;
+ // The socket used to communicate with the xfrout server.
+ stream_protocol::socket socket_;
+};
+
+XfroutClientImpl::XfroutClientImpl(const string& file) :
+ file_path_(file), socket_(io_service_)
+{}
+
+XfroutClient::XfroutClient(const string& file) :
+ impl_(new XfroutClientImpl(file))
+{}
+
+XfroutClient::~XfroutClient()
+{
+ delete impl_;
+}
+
void
XfroutClient::connect() {
- socket_.connect(stream_protocol::endpoint(file_path_));
+ impl_->socket_.connect(stream_protocol::endpoint(impl_->file_path_));
}
void
XfroutClient::disconnect() {
- socket_.close();
+ impl_->socket_.close();
}
int
XfroutClient::sendXfroutRequestInfo(const int tcp_sock, uint8_t* msg_data,
const uint16_t msg_len)
{
- if (-1 == send_fd(socket_.native(), tcp_sock)) {
+ if (-1 == send_fd(impl_->socket_.native(), tcp_sock)) {
isc_throw(XfroutError,
"Fail to send socket descriptor to xfrout module");
}
// XXX: this shouldn't be blocking send, even though it's unlikely to block.
const uint8_t lenbuf[2] = { msg_len >> 8, msg_len & 0xff };
- if (send(socket_.native(), lenbuf, sizeof(lenbuf), 0) != sizeof(lenbuf)) {
+ if (send(impl_->socket_.native(), lenbuf, sizeof(lenbuf), 0) !=
+ sizeof(lenbuf)) {
isc_throw(XfroutError,
"failed to send XFR request length to xfrout module");
}
- if (send(socket_.native(), msg_data, msg_len, 0) != msg_len) {
+ if (send(impl_->socket_.native(), msg_data, msg_len, 0) != msg_len) {
isc_throw(XfroutError,
"failed to send XFR request data to xfrout module");
}
int databuf = 0;
- if (recv(socket_.native(), &databuf, sizeof(int), 0) != 0) {
+ if (recv(impl_->socket_.native(), &databuf, sizeof(int), 0) != 0) {
isc_throw(XfroutError,
"xfr query hasn't been processed properly by xfrout module");
}
Modified: branches/trac185/src/lib/xfr/xfrout_client.h
==============================================================================
--- branches/trac185/src/lib/xfr/xfrout_client.h (original)
+++ branches/trac185/src/lib/xfr/xfrout_client.h Mon May 31 06:06:39 2010
@@ -17,13 +17,16 @@
#ifndef _XFROUT_CLIENT_H
#define _XFROUT_CLIENT_H
+#include <stdint.h>
+
#include <string>
-#include <boost/asio.hpp>
#include <exceptions/exceptions.h>
namespace isc {
namespace xfr {
+
+struct XfroutClientImpl;
class XfroutError: public Exception {
public:
@@ -31,22 +34,21 @@
isc::Exception(file, line, what) {}
};
-using boost::asio::local::stream_protocol;
class XfroutClient {
public:
- XfroutClient(const std::string& file):
- socket_(io_service_), file_path_(file) {}
-
+ XfroutClient(const std::string& file);
+ ~XfroutClient();
+private:
+ // make this class non copyable
+ XfroutClient(const XfroutClient& source);
+ XfroutClient& operator=(const XfroutClient& source);
+public:
void connect();
void disconnect();
int sendXfroutRequestInfo(int tcp_sock, uint8_t* msg_data,
uint16_t msg_len);
-
private:
- boost::asio::io_service io_service_;
- // The socket used to communicate with the xfrout server.
- stream_protocol::socket socket_;
- const std::string file_path_;
+ XfroutClientImpl* impl_;
};
} // End for namespace xfr
More information about the bind10-changes
mailing list