d_controller.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // Copyright (C) 2013 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. #ifndef D_CONTROLLER_H
  15. #define D_CONTROLLER_H
  16. #include <asiolink/asiolink.h>
  17. #include <cc/data.h>
  18. #include <cc/session.h>
  19. #include <config/ccsession.h>
  20. #include <d2/d2_log.h>
  21. #include <d2/d_process.h>
  22. #include <exceptions/exceptions.h>
  23. #include <log/logger_support.h>
  24. #include <boost/shared_ptr.hpp>
  25. #include <boost/noncopyable.hpp>
  26. namespace isc {
  27. namespace d2 {
  28. /// @brief DControllerBase launch exit status values. Upon service shutdown
  29. /// normal or otherwise, the Controller's launch method will return one of
  30. /// these values.
  31. /// @brief Exception thrown when the command line is invalid.
  32. class InvalidUsage : public isc::Exception {
  33. public:
  34. InvalidUsage(const char* file, size_t line, const char* what) :
  35. isc::Exception(file, line, what) { };
  36. };
  37. /// @brief Exception thrown when the application process fails.
  38. class ProcessInitError: public isc::Exception {
  39. public:
  40. ProcessInitError (const char* file, size_t line, const char* what) :
  41. isc::Exception(file, line, what) { };
  42. };
  43. /// @brief Exception thrown when the session start up fails.
  44. class SessionStartError: public isc::Exception {
  45. public:
  46. SessionStartError (const char* file, size_t line, const char* what) :
  47. isc::Exception(file, line, what) { };
  48. };
  49. /// @brief Exception thrown when the application process encounters an
  50. /// operation in its event loop (i.e. run method).
  51. class ProcessRunError: public isc::Exception {
  52. public:
  53. ProcessRunError (const char* file, size_t line, const char* what) :
  54. isc::Exception(file, line, what) { };
  55. };
  56. /// @brief Exception thrown when the session end fails.
  57. class SessionEndError: public isc::Exception {
  58. public:
  59. SessionEndError (const char* file, size_t line, const char* what) :
  60. isc::Exception(file, line, what) { };
  61. };
  62. /// @brief Exception thrown when the controller encounters an operational error.
  63. class DControllerBaseError : public isc::Exception {
  64. public:
  65. DControllerBaseError (const char* file, size_t line, const char* what) :
  66. isc::Exception(file, line, what) { };
  67. };
  68. /// @brief Defines a shared pointer to DControllerBase.
  69. class DControllerBase;
  70. typedef boost::shared_ptr<DControllerBase> DControllerBasePtr;
  71. /// @brief Defines a shared pointer to a Session.
  72. typedef boost::shared_ptr<isc::cc::Session> SessionPtr;
  73. /// @brief Defines a shared pointer to a ModuleCCSession.
  74. typedef boost::shared_ptr<isc::config::ModuleCCSession> ModuleCCSessionPtr;
  75. /// @brief Application Controller
  76. ///
  77. /// DControllerBase is an abstract singleton which provides the framework and
  78. /// services for managing an application process that implements the
  79. /// DProcessBase interface. It allows the process to run either in
  80. /// integrated mode as a BIND10 module or stand-alone. It coordinates command
  81. /// line argument parsing, process instantiation and initialization, and runtime
  82. /// control through external command and configuration event handling.
  83. /// It creates the IOService instance which is used for runtime control
  84. /// events and passes the IOService into the application process at process
  85. /// creation. In integrated mode it is responsible for establishing BIND10
  86. /// session(s) and passes this IOService into the session creation method(s).
  87. /// It also provides the callback handlers for command and configuration events
  88. /// received from the external framework (aka BIND10). For example, when
  89. /// running in integrated mode and a user alters the configuration with the
  90. /// bindctl tool, BIND10 will emit a configuration message which is sensed by
  91. /// the controller's IOService. The IOService in turn invokes the configuration
  92. /// callback, DControllerBase::configHandler(). If the user issues a command
  93. /// such as shutdown via bindctl, BIND10 will emit a command message, which is
  94. /// sensed by controller's IOService which invokes the command callback,
  95. /// DControllerBase::commandHandler().
  96. ///
  97. /// NOTE: Derivations must supply their own static singleton instance method(s)
  98. /// for creating and fetching the instance. The base class declares the instance
  99. /// member in order for it to be available for BIND10 callback functions. This
  100. /// would not be required if BIND10 supported instance method callbacks.
  101. class DControllerBase : public boost::noncopyable {
  102. public:
  103. /// @brief Constructor
  104. ///
  105. /// @param name name is a text label for the controller. Typically this
  106. /// would be the BIND10 module name.
  107. DControllerBase(const char* name);
  108. /// @brief Destructor
  109. virtual ~DControllerBase();
  110. /// @brief Acts as the primary entry point into the controller execution
  111. /// and provides the outermost application control logic:
  112. ///
  113. /// 1. parse command line arguments
  114. /// 2. instantiate and initialize the application process
  115. /// 3. establish BIND10 session(s) if in integrated mode
  116. /// 4. start and wait on the application process event loop
  117. /// 5. upon event loop completion, disconnect from BIND10 (if needed)
  118. /// 6. exit to the caller
  119. ///
  120. /// It is intended to be called from main() and be given the command line
  121. /// arguments. Note this method is deliberately not virtual to ensure the
  122. /// proper sequence of events occur.
  123. ///
  124. /// @param argc is the number of command line arguments supplied
  125. /// @param argv is the array of string (char *) command line arguments
  126. ///
  127. /// @throw throws one of the following exceptions:
  128. /// InvalidUsage - Indicates invalid command line.
  129. /// ProcessInitError - Failed to create and initialize application
  130. /// process object.
  131. /// SessionStartError - Could not connect to BIND10 (integrated mode only).
  132. /// ProcessRunError - A fatal error occurred while in the application
  133. /// process event loop.
  134. /// SessionEndError - Could not disconnect from BIND10 (integrated mode
  135. /// only).
  136. void launch(int argc, char* argv[]);
  137. /// @brief A dummy configuration handler that always returns success.
  138. ///
  139. /// This configuration handler does not perform configuration
  140. /// parsing and always returns success. A dummy handler should
  141. /// be installed using \ref isc::config::ModuleCCSession ctor
  142. /// to get the initial configuration. This initial configuration
  143. /// comprises values for only those elements that were modified
  144. /// the previous session. The D2 configuration parsing can't be
  145. /// used to parse the initial configuration because it may need the
  146. /// full configuration to satisfy dependencies between the
  147. /// various configuration values. Installing the dummy handler
  148. /// that guarantees to return success causes initial configuration
  149. /// to be stored for the session being created and that it can
  150. /// be later accessed with \ref isc::ConfigData::getFullConfig.
  151. ///
  152. /// @param new_config new configuration.
  153. ///
  154. /// @return success configuration status.
  155. static isc::data::ConstElementPtr
  156. dummyConfigHandler(isc::data::ConstElementPtr new_config);
  157. /// @brief A callback for handling all incoming configuration updates.
  158. ///
  159. /// As a pointer to this method is used as a callback in ASIO for
  160. /// ModuleCCSession, it has to be static. It acts as a wrapper around
  161. /// the virtual instance method, updateConfig.
  162. ///
  163. /// @param new_config textual representation of the new configuration
  164. ///
  165. /// @return status of the config update
  166. static isc::data::ConstElementPtr
  167. configHandler(isc::data::ConstElementPtr new_config);
  168. /// @brief A callback for handling all incoming commands.
  169. ///
  170. /// As a pointer to this method is used as a callback in ASIO for
  171. /// ModuleCCSession, it has to be static. It acts as a wrapper around
  172. /// the virtual instance method, executeCommand.
  173. ///
  174. /// @param command textual representation of the command
  175. /// @param args parameters of the command
  176. ///
  177. /// @return status of the processed command
  178. static isc::data::ConstElementPtr
  179. commandHandler(const std::string& command, isc::data::ConstElementPtr args);
  180. /// @brief Instance method invoked by the configuration event handler and
  181. /// which processes the actual configuration update. Provides behavioral
  182. /// path for both integrated and stand-alone modes. The current
  183. /// implementation will merge the configuration update into the existing
  184. /// configuration and then invoke the application process' configure method.
  185. ///
  186. /// @TODO This implementation is will evolve as the D2 configuration
  187. /// management task is implemented (trac #2957).
  188. ///
  189. /// @param new_config is the new configuration
  190. ///
  191. /// @return returns an Element that contains the results of configuration
  192. /// update composed of an integer status value (0 means successful,
  193. /// non-zero means failure), and a string explanation of the outcome.
  194. virtual isc::data::ConstElementPtr
  195. updateConfig(isc::data::ConstElementPtr new_config);
  196. /// @brief Instance method invoked by the command event handler and which
  197. /// processes the actual command directive.
  198. ///
  199. /// It supports the execution of:
  200. ///
  201. /// 1. Stock controller commands - commands common to all DControllerBase
  202. /// derivations. Currently there is only one, the shutdown command.
  203. ///
  204. /// 2. Custom controller commands - commands that the deriving controller
  205. /// class implements. These commands are executed by the deriving
  206. /// controller.
  207. ///
  208. /// 3. Custom application commands - commands supported by the application
  209. /// process implementation. These commands are executed by the application
  210. /// process.
  211. ///
  212. /// @param command is a string label representing the command to execute.
  213. /// @param args is a set of arguments (if any) required for the given
  214. /// command.
  215. ///
  216. /// @return an Element that contains the results of command composed
  217. /// of an integer status value and a string explanation of the outcome.
  218. /// The status value is one of the following:
  219. /// D2::COMMAND_SUCCESS - Command executed successfully
  220. /// D2::COMMAND_ERROR - Command is valid but suffered an operational
  221. /// failure.
  222. /// D2::COMMAND_INVALID - Command is not recognized as valid be either
  223. /// the controller or the application process.
  224. virtual isc::data::ConstElementPtr
  225. executeCommand(const std::string& command, isc::data::ConstElementPtr args);
  226. protected:
  227. /// @brief Virtual method that provides derivations the opportunity to
  228. /// support additional command line options. It is invoked during command
  229. /// line argument parsing (see parseArgs method) if the option is not
  230. /// recognized as a stock DControllerBase option.
  231. ///
  232. /// @param option is the option "character" from the command line, without
  233. /// any prefixing hyphen(s)
  234. /// @optarg optarg is the argument value (if one) associated with the option
  235. ///
  236. /// @return must return true if the option was valid, false is it is
  237. /// invalid. (Note the default implementation always returns false.)
  238. virtual bool customOption(int option, char *optarg);
  239. /// @brief Abstract method that is responsible for instantiating the
  240. /// application process object. It is invoked by the controller after
  241. /// command line argument parsing as part of the process initialization
  242. /// (see initProcess method).
  243. ///
  244. /// @return returns a pointer to the new process object (DProcessBase*)
  245. /// or NULL if the create fails.
  246. /// Note this value is subsequently wrapped in a smart pointer.
  247. virtual DProcessBase* createProcess() = 0;
  248. /// @brief Virtual method that provides derivations the opportunity to
  249. /// support custom external commands executed by the controller. This
  250. /// method is invoked by the processCommand if the received command is
  251. /// not a stock controller command.
  252. ///
  253. /// @param command is a string label representing the command to execute.
  254. /// @param args is a set of arguments (if any) required for the given
  255. /// command.
  256. ///
  257. /// @return an Element that contains the results of command composed
  258. /// of an integer status value and a string explanation of the outcome.
  259. /// The status value is one of the following:
  260. /// D2::COMMAND_SUCCESS - Command executed successfully
  261. /// D2::COMMAND_ERROR - Command is valid but suffered an operational
  262. /// failure.
  263. /// D2::COMMAND_INVALID - Command is not recognized as a valid custom
  264. /// controller command.
  265. virtual isc::data::ConstElementPtr customControllerCommand(
  266. const std::string& command, isc::data::ConstElementPtr args);
  267. /// @brief Virtual method which is invoked after the controller successfully
  268. /// establishes BIND10 connectivity. It provides an opportunity for the
  269. /// derivation to execute any custom behavior associated with session
  270. /// establishment.
  271. ///
  272. /// Note, it is not called when running stand-alone.
  273. ///
  274. /// @throw should throw a DControllerBaseError if it fails.
  275. virtual void onSessionConnect(){};
  276. /// @brief Virtual method which is invoked as the first action taken when
  277. /// the controller is terminating the session(s) with BIND10. It provides
  278. /// an opportunity for the derivation to execute any custom behavior
  279. /// associated with session termination.
  280. ///
  281. /// Note, it is not called when running stand-alone.
  282. ///
  283. /// @throw should throw a DControllerBaseError if it fails.
  284. virtual void onSessionDisconnect(){};
  285. /// @brief Virtual method which can be used to contribute derivation
  286. /// specific usage text. It is invoked by the usage() method under
  287. /// invalid usage conditions.
  288. ///
  289. /// @return returns the desired text.
  290. virtual const std::string getUsageText() const {
  291. return ("");
  292. }
  293. /// @brief Virtual method which returns a string containing the option
  294. /// letters for any custom command line options supported by the derivation.
  295. /// These are added to the stock options of "s" and "v" during command
  296. /// line interpretation.
  297. ///
  298. /// @return returns a string containing the custom option letters.
  299. virtual const std::string getCustomOpts() const {
  300. return ("");
  301. }
  302. /// @brief Supplies the controller name.
  303. ///
  304. /// @return returns the controller name string
  305. const std::string getName() const {
  306. return (name_);
  307. }
  308. /// @brief Supplies whether or not the controller is in stand alone mode.
  309. ///
  310. /// @return returns true if in stand alone mode, false otherwise
  311. bool isStandAlone() {
  312. return (stand_alone_);
  313. }
  314. /// @brief Method for enabling or disabling stand alone mode.
  315. ///
  316. /// @param value is the new value to assign the flag.
  317. void setStandAlone(bool value) {
  318. stand_alone_ = value;
  319. }
  320. /// @brief Supplies whether or not verbose logging is enabled.
  321. ///
  322. /// @return returns true if verbose logging is enabled.
  323. bool isVerbose() {
  324. return (verbose_);
  325. }
  326. /// @brief Method for enabling or disabling verbose logging.
  327. ///
  328. /// @param value is the new value to assign the flag.
  329. void setVerbose(bool value) {
  330. verbose_ = value;
  331. }
  332. /// @brief Getter for fetching the controller's IOService
  333. ///
  334. /// @return returns a pointer reference to the IOService.
  335. IOServicePtr& getIOService() {
  336. return (io_service_);
  337. }
  338. /// @brief Getter for fetching the name of the controller's BIND10 spec
  339. /// file.
  340. ///
  341. /// @return returns the file name string.
  342. const std::string getSpecFileName() const {
  343. return (spec_file_name_);
  344. }
  345. /// @brief Setter for setting the name of the controller's BIND10 spec file.
  346. ///
  347. /// @param value is the file name string.
  348. void setSpecFileName(const std::string& spec_file_name) {
  349. spec_file_name_ = spec_file_name;
  350. }
  351. /// @brief Static getter which returns the singleton instance.
  352. ///
  353. /// @return returns a pointer reference to the private singleton instance
  354. /// member.
  355. static DControllerBasePtr& getController() {
  356. return (controller_);
  357. }
  358. /// @brief Static setter which sets the singleton instance.
  359. ///
  360. /// @param controller is a pointer to the singleton instance.
  361. ///
  362. /// @throw throws DControllerBase error if an attempt is made to set the
  363. /// instance a second time.
  364. static void setController(const DControllerBasePtr& controller);
  365. private:
  366. /// @brief Processes the command line arguments. It is the first step
  367. /// taken after the controller has been launched. It combines the stock
  368. /// list of options with those returned by getCustomOpts(), and uses
  369. /// cstdlib's getopt to loop through the command line. The stock options
  370. /// It handles stock options directly, and passes any custom options into
  371. /// the customOption method. Currently there are only two stock options
  372. /// -s for stand alone mode, and -v for verbose logging.
  373. ///
  374. /// @param argc is the number of command line arguments supplied
  375. /// @param argv is the array of string (char *) command line arguments
  376. ///
  377. /// @throw throws InvalidUsage when there are usage errors.
  378. void parseArgs(int argc, char* argv[]);
  379. /// @brief Instantiates the application process and then initializes it.
  380. /// This is the second step taken during launch, following successful
  381. /// command line parsing. It is used to invoke the derivation-specific
  382. /// implementation of createProcess, following by an invoking of the
  383. /// newly instantiated process's init method.
  384. ///
  385. /// @throw throws DControllerBaseError or indirectly DProcessBaseError
  386. /// if there is a failure creating or initializing the application process.
  387. void initProcess();
  388. /// @brief Establishes connectivity with BIND10. This method is used
  389. /// invoked during launch, if running in integrated mode, following
  390. /// successful process initialization. It is responsible for establishing
  391. /// the BIND10 control and config sessions. During the session creation,
  392. /// it passes in the controller's IOService and the callbacks for command
  393. /// directives and config events. Lastly, it will invoke the onConnect
  394. /// method providing the derivation an opportunity to execute any custom
  395. /// logic associated with session establishment.
  396. ///
  397. /// @throw the BIND10 framework may throw std::exceptions.
  398. void establishSession();
  399. /// @brief Invokes the application process's event loop,(DBaseProcess::run).
  400. /// It is called during launch only after successfully completing the
  401. /// requested setup: command line parsing, application initialization,
  402. /// and session establishment (if not stand-alone).
  403. /// The process event loop is expected to only return upon application
  404. /// shutdown either in response to the shutdown command or due to an
  405. /// unrecoverable error.
  406. ///
  407. // @throw throws DControllerBaseError or indirectly DProcessBaseError
  408. void runProcess();
  409. /// @brief Terminates connectivity with BIND10. This method is invoked
  410. /// in integrated mode after the application event loop has exited. It
  411. /// first calls the onDisconnect method providing the derivation an
  412. /// opportunity to execute custom logic if needed, and then terminates the
  413. /// BIND10 config and control sessions.
  414. ///
  415. /// @throw the BIND10 framework may throw std:exceptions.
  416. void disconnectSession();
  417. /// @brief Initiates shutdown procedure. This method is invoked
  418. /// by executeCommand in response to the shutdown command. It will invoke
  419. /// the application process's shutdown method, which causes the process to
  420. /// exit it's event loop.
  421. ///
  422. /// @return returns an Element that contains the results of shutdown
  423. /// attempt composed of an integer status value (0 means successful,
  424. /// non-zero means failure), and a string explanation of the outcome.
  425. isc::data::ConstElementPtr shutdown();
  426. /// @brief Prints the program usage text to std error.
  427. ///
  428. /// @param text is a string message which will preceded the usage text.
  429. /// This is intended to be used for specific usage violation messages.
  430. void usage(const std::string& text);
  431. private:
  432. /// @brief Text label for the controller. Typically this would be the
  433. /// BIND10 module name.
  434. std::string name_;
  435. /// @brief Indicates if the controller stand alone mode is enabled. When
  436. /// enabled, the controller will not establish connectivity with BIND10.
  437. bool stand_alone_;
  438. /// @brief Indicates if the verbose logging mode is enabled.
  439. bool verbose_;
  440. /// @brief The absolute file name of the BIND10 spec file.
  441. std::string spec_file_name_;
  442. /// @brief Pointer to the instance of the process.
  443. ///
  444. /// This is required for config and command handlers to gain access to
  445. /// the process
  446. DProcessBasePtr process_;
  447. /// @brief Shared pointer to an IOService object, used for ASIO operations.
  448. IOServicePtr io_service_;
  449. /// @brief Helper session object that represents raw connection to msgq.
  450. SessionPtr cc_session_;
  451. /// @brief Session that receives configuration and commands.
  452. ModuleCCSessionPtr config_session_;
  453. /// @brief Singleton instance value.
  454. static DControllerBasePtr controller_;
  455. // DControllerTest is named a friend class to facilitate unit testing while
  456. // leaving the intended member scopes intact.
  457. friend class DControllerTest;
  458. };
  459. }; // namespace isc::d2
  460. }; // namespace isc
  461. #endif