command.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <auth/command.h>
  15. #include <auth/auth_log.h>
  16. #include <auth/auth_srv.h>
  17. #include <cc/data.h>
  18. #include <datasrc/memory_datasrc.h>
  19. #include <config/ccsession.h>
  20. #include <exceptions/exceptions.h>
  21. #include <dns/rrclass.h>
  22. #include <string>
  23. #include <boost/scoped_ptr.hpp>
  24. #include <boost/shared_ptr.hpp>
  25. #include <sys/types.h>
  26. #include <unistd.h>
  27. using boost::scoped_ptr;
  28. using namespace isc::auth;
  29. using namespace isc::config;
  30. using namespace isc::data;
  31. using namespace isc::datasrc;
  32. using namespace isc::dns;
  33. using namespace std;
  34. namespace {
  35. /// An exception that is thrown if an error occurs while handling a command
  36. /// on an \c AuthSrv object.
  37. ///
  38. /// Currently it's only used internally, since \c execAuthServerCommand()
  39. /// (which is the only interface to this module) catches all \c isc::
  40. /// exceptions and converts them.
  41. class AuthCommandError : public isc::Exception {
  42. public:
  43. AuthCommandError(const char* file, size_t line, const char* what) :
  44. isc::Exception(file, line, what) {}
  45. };
  46. /// An abstract base class that represents a single command identifier
  47. /// for an \c AuthSrv object.
  48. ///
  49. /// Each of derived classes of \c AuthCommand, which are hidden inside the
  50. /// implementation, corresponds to a command executed on \c AuthSrv, such as
  51. /// "shutdown". The derived class is responsible to execute the corresponding
  52. /// command with the given command arguments (if any) in its \c exec()
  53. /// method.
  54. ///
  55. /// In the initial implementation the existence of the command classes is
  56. /// hidden inside the implementation since the only public interface is
  57. /// \c execAuthServerCommand(), which does not expose this class.
  58. /// In future, we may want to make this framework more dynamic, i.e.,
  59. /// registering specific derived classes run time outside of this
  60. /// implementation. If and when that happens the definition of the abstract
  61. /// class will be published.
  62. class AuthCommand {
  63. ///
  64. /// \name Constructors and Destructor
  65. ///
  66. /// Note: The copy constructor and the assignment operator are
  67. /// intentionally defined as private to make it explicit that this is a
  68. /// pure base class.
  69. //@{
  70. private:
  71. AuthCommand(const AuthCommand& source);
  72. AuthCommand& operator=(const AuthCommand& source);
  73. protected:
  74. /// \brief The default constructor.
  75. ///
  76. /// This is intentionally defined as \c protected as this base class should
  77. /// never be instantiated (except as part of a derived class).
  78. AuthCommand() {}
  79. public:
  80. /// The destructor.
  81. virtual ~AuthCommand() {}
  82. //@}
  83. /// Execute a single control command.
  84. ///
  85. /// Specific derived methods can throw exceptions. When called via
  86. /// \c execAuthServerCommand(), all BIND 10 exceptions are caught
  87. /// and converted into an error code.
  88. /// The derived method may also throw an exception of class
  89. /// \c AuthCommandError when it encounters an internal error, such as
  90. /// semantics error on the command arguments.
  91. ///
  92. /// \param server The \c AuthSrv object on which the command is executed.
  93. /// \param args Command specific argument.
  94. virtual void exec(AuthSrv& server, isc::data::ConstElementPtr args) = 0;
  95. };
  96. // Handle the "shutdown" command. An optional parameter "pid" is used to
  97. // see if it is really for our instance.
  98. class ShutdownCommand : public AuthCommand {
  99. public:
  100. virtual void exec(AuthSrv& server, isc::data::ConstElementPtr args) {
  101. // Is the pid argument provided?
  102. if (args && args->contains("pid")) {
  103. // If it is, we check it is the same as our PID
  104. // This might throw in case the type is not an int, but that's
  105. // OK, as it'll get converted to an error on higher level.
  106. const int pid(args->get("pid")->intValue());
  107. const pid_t my_pid(getpid());
  108. if (my_pid != pid) {
  109. // It is not for us
  110. //
  111. // Note that this is completely expected situation, if
  112. // there are multiple instances of the server running and
  113. // another instance is being shut down, we get the message
  114. // too, due to the multicast nature of our message bus.
  115. return;
  116. }
  117. }
  118. LOG_DEBUG(auth_logger, DBG_AUTH_SHUT, AUTH_SHUTDOWN);
  119. server.stop();
  120. }
  121. };
  122. // Handle the "sendstats" command. No argument is assumed.
  123. class SendStatsCommand : public AuthCommand {
  124. public:
  125. virtual void exec(AuthSrv& server, isc::data::ConstElementPtr) {
  126. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_RECEIVED_SENDSTATS);
  127. server.submitStatistics();
  128. }
  129. };
  130. // Handle the "loadzone" command.
  131. class LoadZoneCommand : public AuthCommand {
  132. public:
  133. virtual void exec(AuthSrv& server, isc::data::ConstElementPtr args) {
  134. // parse and validate the args.
  135. if (!validate(server, args)) {
  136. return;
  137. }
  138. // Load a new zone and replace the current zone with the new one.
  139. // TODO: eventually this should be incremental or done in some way
  140. // that doesn't block other server operations.
  141. // TODO: we may (should?) want to check the "last load time" and
  142. // the timestamp of the file and skip loading if the file isn't newer.
  143. boost::shared_ptr<InMemoryZoneFinder> zone_finder(
  144. new InMemoryZoneFinder(old_zone_finder->getClass(),
  145. old_zone_finder->getOrigin()));
  146. zone_finder->load(old_zone_finder->getFileName());
  147. old_zone_finder->swap(*zone_finder);
  148. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_LOAD_ZONE)
  149. .arg(zone_finder->getOrigin()).arg(zone_finder->getClass());
  150. }
  151. private:
  152. // zone finder to be updated with the new file.
  153. boost::shared_ptr<InMemoryZoneFinder> old_zone_finder;
  154. // A helper private method to parse and validate command parameters.
  155. // On success, it sets 'old_zone_finder' to the zone to be updated.
  156. // It returns true if everything is okay; and false if the command is
  157. // valid but there's no need for further process.
  158. bool validate(AuthSrv& server, isc::data::ConstElementPtr args) {
  159. if (args == NULL) {
  160. isc_throw(AuthCommandError, "Null argument");
  161. }
  162. // In this initial implementation, we assume memory data source
  163. // for class IN by default.
  164. ConstElementPtr datasrc_elem = args->get("datasrc");
  165. if (datasrc_elem) {
  166. if (datasrc_elem->stringValue() == "sqlite3") {
  167. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_SQLITE3);
  168. return (false);
  169. } else if (datasrc_elem->stringValue() != "memory") {
  170. // (note: at this point it's guaranteed that datasrc_elem
  171. // is of string type)
  172. isc_throw(AuthCommandError,
  173. "Data source type " << datasrc_elem->stringValue()
  174. << " is not supported");
  175. }
  176. }
  177. ConstElementPtr class_elem = args->get("class");
  178. const RRClass zone_class = class_elem ?
  179. RRClass(class_elem->stringValue()) : RRClass::IN();
  180. AuthSrv::InMemoryClientPtr datasrc(server.getInMemoryClient(zone_class));
  181. if (datasrc == NULL) {
  182. isc_throw(AuthCommandError, "Memory data source is disabled");
  183. }
  184. ConstElementPtr origin_elem = args->get("origin");
  185. if (!origin_elem) {
  186. isc_throw(AuthCommandError, "Zone origin is missing");
  187. }
  188. const Name origin(origin_elem->stringValue());
  189. // Get the current zone
  190. const InMemoryClient::FindResult result = datasrc->findZone(origin);
  191. if (result.code != result::SUCCESS) {
  192. isc_throw(AuthCommandError, "Zone " << origin <<
  193. " is not found in data source");
  194. }
  195. old_zone_finder = boost::dynamic_pointer_cast<InMemoryZoneFinder>(
  196. result.zone_finder);
  197. return (true);
  198. }
  199. };
  200. // The factory of command objects.
  201. AuthCommand*
  202. createAuthCommand(const string& command_id) {
  203. // For the initial implementation we use a naive if-else blocks
  204. // (see also createAuthConfigParser())
  205. if (command_id == "shutdown") {
  206. return (new ShutdownCommand());
  207. } else if (command_id == "sendstats") {
  208. return (new SendStatsCommand());
  209. } else if (command_id == "loadzone") {
  210. return (new LoadZoneCommand());
  211. } else if (false && command_id == "_throw_exception") {
  212. // This is for testing purpose only and should not appear in the
  213. // actual configuration syntax.
  214. // XXX: ModuleCCSession doesn't seem to validate commands (unlike
  215. // config), so we should disable this case for now.
  216. throw runtime_error("throwing for test");
  217. }
  218. isc_throw(AuthCommandError, "Unknown command identifier: " << command_id);
  219. }
  220. } // end of unnamed namespace
  221. ConstElementPtr
  222. execAuthServerCommand(AuthSrv& server, const string& command_id,
  223. ConstElementPtr args)
  224. {
  225. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_RECEIVED_COMMAND).arg(command_id);
  226. try {
  227. scoped_ptr<AuthCommand>(createAuthCommand(command_id))->exec(server,
  228. args);
  229. } catch (const isc::Exception& ex) {
  230. LOG_ERROR(auth_logger, AUTH_COMMAND_FAILED).arg(command_id)
  231. .arg(ex.what());
  232. return (createAnswer(1, ex.what()));
  233. }
  234. return (createAnswer());
  235. }