d_controller.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. // Copyright (C) 2013-2015 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/io_service.h>
  17. #include <cc/data.h>
  18. #include <d2/d2_log.h>
  19. #include <d2/d_process.h>
  20. #include <d2/io_service_signal.h>
  21. #include <dhcpsrv/daemon.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 Exception thrown when the command line is invalid.
  29. class InvalidUsage : public isc::Exception {
  30. public:
  31. InvalidUsage(const char* file, size_t line, const char* what) :
  32. isc::Exception(file, line, what) { };
  33. };
  34. /// @brief Exception used to convey version info upwards.
  35. /// Since command line argument parsing is done as part of
  36. /// DControllerBase::launch(), it uses this exception to propagate
  37. /// version information up to main(), when command line argument
  38. /// -v or -V is given.
  39. class VersionMessage : public isc::Exception {
  40. public:
  41. VersionMessage(const char* file, size_t line, const char* what) :
  42. isc::Exception(file, line, what) { };
  43. };
  44. /// @brief Exception thrown when the controller launch fails.
  45. class LaunchError: public isc::Exception {
  46. public:
  47. LaunchError (const char* file, size_t line, const char* what) :
  48. isc::Exception(file, line, what) { };
  49. };
  50. /// @brief Exception thrown when the application process fails.
  51. class ProcessInitError: public isc::Exception {
  52. public:
  53. ProcessInitError (const char* file, size_t line, const char* what) :
  54. isc::Exception(file, line, what) { };
  55. };
  56. /// @brief Exception thrown when the application process encounters an
  57. /// operation in its event loop (i.e. run method).
  58. class ProcessRunError: public isc::Exception {
  59. public:
  60. ProcessRunError (const char* file, size_t line, const char* what) :
  61. isc::Exception(file, line, what) { };
  62. };
  63. /// @brief Exception thrown when the controller encounters an operational error.
  64. class DControllerBaseError : public isc::Exception {
  65. public:
  66. DControllerBaseError (const char* file, size_t line, const char* what) :
  67. isc::Exception(file, line, what) { };
  68. };
  69. /// @brief Defines a shared pointer to DControllerBase.
  70. class DControllerBase;
  71. typedef boost::shared_ptr<DControllerBase> DControllerBasePtr;
  72. /// @brief Application Controller
  73. ///
  74. /// DControllerBase is an abstract singleton which provides the framework and
  75. /// services for managing an application process that implements the
  76. /// DProcessBase interface. It runs the process like a stand-alone, command
  77. /// line driven executable, which must be supplied a configuration file at
  78. /// startup. It coordinates command line argument parsing, process
  79. /// instantiation and initialization, and runtime control through external
  80. /// command and configuration event handling.
  81. /// It creates the IOService instance which is used for runtime control
  82. /// events and passes the IOService into the application process at process
  83. /// creation.
  84. /// It provides the callback handlers for command and configuration events
  85. /// which could be triggered by an external source. Such sources are intended
  86. /// to be registered with and monitored by the controller's IOService such that
  87. /// the appropriate handler can be invoked.
  88. ///
  89. /// DControllerBase provides dynamic configuration file reloading upon receipt
  90. /// of SIGHUP, and graceful shutdown upon receipt of either SIGINT or SIGTERM.
  91. ///
  92. /// NOTE: Derivations must supply their own static singleton instance method(s)
  93. /// for creating and fetching the instance. The base class declares the instance
  94. /// member in order for it to be available for static callback functions.
  95. class DControllerBase : public dhcp::Daemon {
  96. public:
  97. /// @brief Constructor
  98. ///
  99. /// @param app_name is display name of the application under control. This
  100. /// name appears in log statements.
  101. /// @param bin_name is the name of the application executable.
  102. DControllerBase(const char* app_name, const char* bin_name);
  103. /// @brief Destructor
  104. virtual ~DControllerBase();
  105. /// @brief returns Kea version on stdout and exit.
  106. /// redeclaration/redefinition. @ref isc::dhcp::Daemon::getVersion()
  107. static std::string getVersion(bool extended);
  108. /// @brief Acts as the primary entry point into the controller execution
  109. /// and provides the outermost application control logic:
  110. ///
  111. /// 1. parse command line arguments
  112. /// 2. instantiate and initialize the application process
  113. /// 3. load the configuration file
  114. /// 4. initialize signal handling
  115. /// 5. start and wait on the application process event loop
  116. /// 6. exit to the caller
  117. ///
  118. /// It is intended to be called from main() and be given the command line
  119. /// arguments.
  120. ///
  121. /// This function can be run in "test mode". It prevents initialization
  122. /// of D2 module logger. This is used in unit tests which initialize logger
  123. /// in their main function. Such a logger uses environmental variables to
  124. /// control severity, verbosity etc.
  125. ///
  126. /// @param argc is the number of command line arguments supplied
  127. /// @param argv is the array of string (char *) command line arguments
  128. /// @param test_mode is a bool value which indicates if
  129. /// @c DControllerBase::launch should be run in the test mode (if true).
  130. /// This parameter doesn't have default value to force test implementers to
  131. /// enable test mode explicitly.
  132. ///
  133. /// @throw throws one of the following exceptions:
  134. /// InvalidUsage - Indicates invalid command line.
  135. /// ProcessInitError - Failed to create and initialize application
  136. /// process object.
  137. /// ProcessRunError - A fatal error occurred while in the application
  138. /// process event loop.
  139. virtual void launch(int argc, char* argv[], const bool test_mode);
  140. /// @brief Instance method invoked by the configuration event handler and
  141. /// which processes the actual configuration update. Provides behavioral
  142. /// path for both integrated and stand-alone modes. The current
  143. /// implementation will merge the configuration update into the existing
  144. /// configuration and then invoke the application process' configure method.
  145. ///
  146. /// @param new_config is the new configuration
  147. ///
  148. /// @return returns an Element that contains the results of configuration
  149. /// update composed of an integer status value (0 means successful,
  150. /// non-zero means failure), and a string explanation of the outcome.
  151. virtual isc::data::ConstElementPtr updateConfig(isc::data::ConstElementPtr
  152. new_config);
  153. /// @brief Reconfigures the process from a configuration file
  154. ///
  155. /// By default the file is assumed to be a JSON text file whose contents
  156. /// include at least:
  157. ///
  158. /// @code
  159. /// { "<module-name>": {<module-config>} }
  160. ///
  161. /// where:
  162. /// module-name : is a label which uniquely identifies the
  163. /// configuration data for this controller's application
  164. ///
  165. /// module-config: a set of zero or more JSON elements which comprise
  166. /// the application's configuration values
  167. /// @endcode
  168. ///
  169. /// The method extracts the set of configuration elements for the
  170. /// module-name which matches the controller's app_name_ and passes that
  171. /// set into @c udpateConfig().
  172. ///
  173. /// The file may contain an arbitrary number of other modules.
  174. ///
  175. /// @return returns an Element that contains the results of configuration
  176. /// update composed of an integer status value (0 means successful,
  177. /// non-zero means failure), and a string explanation of the outcome.
  178. virtual isc::data::ConstElementPtr configFromFile();
  179. /// @brief Instance method invoked by the command event handler and which
  180. /// processes the actual command directive.
  181. ///
  182. /// It supports the execution of:
  183. ///
  184. /// 1. Stock controller commands - commands common to all DControllerBase
  185. /// derivations. Currently there is only one, the shutdown command.
  186. ///
  187. /// 2. Custom controller commands - commands that the deriving controller
  188. /// class implements. These commands are executed by the deriving
  189. /// controller.
  190. ///
  191. /// 3. Custom application commands - commands supported by the application
  192. /// process implementation. These commands are executed by the application
  193. /// process.
  194. ///
  195. /// @param command is a string label representing the command to execute.
  196. /// @param args is a set of arguments (if any) required for the given
  197. /// command.
  198. ///
  199. /// @return an Element that contains the results of command composed
  200. /// of an integer status value and a string explanation of the outcome.
  201. /// The status value is one of the following:
  202. /// D2::COMMAND_SUCCESS - Command executed successfully
  203. /// D2::COMMAND_ERROR - Command is valid but suffered an operational
  204. /// failure.
  205. /// D2::COMMAND_INVALID - Command is not recognized as valid be either
  206. /// the controller or the application process.
  207. virtual isc::data::ConstElementPtr executeCommand(const std::string&
  208. command,
  209. isc::data::
  210. ConstElementPtr args);
  211. /// @brief Fetches the name of the application under control.
  212. ///
  213. /// @return returns the controller service name string
  214. std::string getAppName() const {
  215. return (app_name_);
  216. }
  217. /// @brief Fetches the name of the application executable.
  218. ///
  219. /// @return returns the controller logger name string
  220. std::string getBinName() const {
  221. return (bin_name_);
  222. }
  223. protected:
  224. /// @brief Virtual method that provides derivations the opportunity to
  225. /// support additional command line options. It is invoked during command
  226. /// line argument parsing (see parseArgs method) if the option is not
  227. /// recognized as a stock DControllerBase option.
  228. ///
  229. /// @param option is the option "character" from the command line, without
  230. /// any prefixing hyphen(s)
  231. /// @param optarg is the argument value (if one) associated with the option
  232. ///
  233. /// @return must return true if the option was valid, false if it is
  234. /// invalid. (Note the default implementation always returns false.)
  235. virtual bool customOption(int option, char *optarg);
  236. /// @brief Abstract method that is responsible for instantiating the
  237. /// application process object. It is invoked by the controller after
  238. /// command line argument parsing as part of the process initialization
  239. /// (see initProcess method).
  240. ///
  241. /// @return returns a pointer to the new process object (DProcessBase*)
  242. /// or NULL if the create fails.
  243. /// Note this value is subsequently wrapped in a smart pointer.
  244. virtual DProcessBase* createProcess() = 0;
  245. /// @brief Virtual method that provides derivations the opportunity to
  246. /// support custom external commands executed by the controller. This
  247. /// method is invoked by the processCommand if the received command is
  248. /// not a stock controller command.
  249. ///
  250. /// @param command is a string label representing the command to execute.
  251. /// @param args is a set of arguments (if any) required for the given
  252. /// command.
  253. ///
  254. /// @return an Element that contains the results of command composed
  255. /// of an integer status value and a string explanation of the outcome.
  256. /// The status value is one of the following:
  257. /// D2::COMMAND_SUCCESS - Command executed successfully
  258. /// D2::COMMAND_ERROR - Command is valid but suffered an operational
  259. /// failure.
  260. /// D2::COMMAND_INVALID - Command is not recognized as a valid custom
  261. /// controller command.
  262. virtual isc::data::ConstElementPtr customControllerCommand(
  263. const std::string& command, isc::data::ConstElementPtr args);
  264. /// @brief Virtual method which can be used to contribute derivation
  265. /// specific usage text. It is invoked by the usage() method under
  266. /// invalid usage conditions.
  267. ///
  268. /// @return returns the desired text.
  269. virtual const std::string getUsageText() const {
  270. return ("");
  271. }
  272. /// @brief Virtual method which returns a string containing the option
  273. /// letters for any custom command line options supported by the derivation.
  274. /// These are added to the stock options of "c" and "v" during command
  275. /// line interpretation.
  276. ///
  277. /// @return returns a string containing the custom option letters.
  278. virtual const std::string getCustomOpts() const {
  279. return ("");
  280. }
  281. /// @brief Application-level signal processing method.
  282. ///
  283. /// This method is the last step in processing a OS signal occurrence. It
  284. /// is invoked when an IOSignal's internal timer callback is executed by
  285. /// IOService. It currently supports the following signals as follows:
  286. /// -# SIGHUP - instigates reloading the configuration file
  287. /// -# SIGINT - instigates a graceful shutdown
  288. /// -# SIGTERM - instigates a graceful shutdown
  289. /// If it receives any other signal, it will issue a debug statement and
  290. /// discard it.
  291. /// Derivations wishing to support additional signals could override this
  292. /// method with one that: processes the signal if it is one of additional
  293. /// signals, otherwise invoke this method (DControllerBase::processSignal())
  294. /// with the signal value.
  295. /// @todo Provide a convenient way for derivations to register additional
  296. /// signals.
  297. virtual void processSignal(int signum);
  298. /// @brief Supplies whether or not verbose logging is enabled.
  299. ///
  300. /// @return returns true if verbose logging is enabled.
  301. bool isVerbose() const {
  302. return (verbose_);
  303. }
  304. /// @brief Method for enabling or disabling verbose logging.
  305. ///
  306. /// @param value is the new value to assign the flag.
  307. void setVerbose(bool value) {
  308. verbose_ = value;
  309. }
  310. /// @brief Getter for fetching the controller's IOService
  311. ///
  312. /// @return returns a pointer reference to the IOService.
  313. asiolink::IOServicePtr& getIOService() {
  314. return (io_service_);
  315. }
  316. /// @brief Getter for fetching the name of the controller's config spec
  317. /// file.
  318. ///
  319. /// @return returns the file name string.
  320. const std::string getSpecFileName() const {
  321. return (spec_file_name_);
  322. }
  323. /// @brief Setter for setting the name of the controller's config spec file.
  324. ///
  325. /// @param spec_file_name the file name string.
  326. void setSpecFileName(const std::string& spec_file_name) {
  327. spec_file_name_ = spec_file_name;
  328. }
  329. /// @brief Static getter which returns the singleton instance.
  330. ///
  331. /// @return returns a pointer reference to the private singleton instance
  332. /// member.
  333. static DControllerBasePtr& getController() {
  334. return (controller_);
  335. }
  336. /// @brief Static setter which sets the singleton instance.
  337. ///
  338. /// @param controller is a pointer to the singleton instance.
  339. ///
  340. /// @throw throws DControllerBase error if an attempt is made to set the
  341. /// instance a second time.
  342. static void setController(const DControllerBasePtr& controller);
  343. /// @brief Processes the command line arguments. It is the first step
  344. /// taken after the controller has been launched. It combines the stock
  345. /// list of options with those returned by getCustomOpts(), and uses
  346. /// cstdlib's getopt to loop through the command line.
  347. /// It handles stock options directly, and passes any custom options into
  348. /// the customOption method. Currently there are only two stock options
  349. /// -c for specifying the configuration file, and -v for verbose logging.
  350. ///
  351. /// @param argc is the number of command line arguments supplied
  352. /// @param argv is the array of string (char *) command line arguments
  353. ///
  354. /// @throw InvalidUsage when there are usage errors.
  355. /// @throw VersionMessage if the -v or -V arguments is given.
  356. void parseArgs(int argc, char* argv[]);
  357. /// @brief Instantiates the application process and then initializes it.
  358. /// This is the second step taken during launch, following successful
  359. /// command line parsing. It is used to invoke the derivation-specific
  360. /// implementation of createProcess, following by an invoking of the
  361. /// newly instantiated process's init method.
  362. ///
  363. /// @throw throws DControllerBaseError or indirectly DProcessBaseError
  364. /// if there is a failure creating or initializing the application process.
  365. void initProcess();
  366. /// @brief Invokes the application process's event loop,(DBaseProcess::run).
  367. /// It is called during launch only after successfully completing the
  368. /// requested setup: command line parsing, application initialization,
  369. /// and session establishment (if not stand-alone).
  370. /// The process event loop is expected to only return upon application
  371. /// shutdown either in response to the shutdown command or due to an
  372. /// unrecoverable error.
  373. ///
  374. // @throw throws DControllerBaseError or indirectly DProcessBaseError
  375. void runProcess();
  376. /// @brief Initiates shutdown procedure. This method is invoked
  377. /// by executeCommand in response to the shutdown command. It will invoke
  378. /// the application process's shutdown method which causes the process to
  379. /// to begin its shutdown process.
  380. ///
  381. /// Note, it is assumed that the process of shutting down is neither
  382. /// instantaneous nor synchronous. This method does not "block" waiting
  383. /// until the process has halted. Rather it is used to convey the
  384. /// need to shutdown. A successful return indicates that the shutdown
  385. /// has successfully commenced, but does not indicate that the process
  386. /// has actually exited.
  387. ///
  388. /// @return returns an Element that contains the results of shutdown
  389. /// command composed of an integer status value (0 means successful,
  390. /// non-zero means failure), and a string explanation of the outcome.
  391. ///
  392. /// @param args is a set of derivation-specific arguments (if any)
  393. /// for the shutdown command.
  394. isc::data::ConstElementPtr shutdownProcess(isc::data::ConstElementPtr args);
  395. /// @brief Initializes signal handling
  396. ///
  397. /// This method configures the controller to catch and handle signals.
  398. /// It instantiates an IOSignalQueue, registers @c osSignalHandler() as
  399. /// the SignalSet "on-receipt" handler, and lastly instantiates a SignalSet
  400. /// which listens for SIGHUP, SIGINT, and SIGTERM.
  401. void initSignalHandling();
  402. /// @brief Handler for processing OS-level signals
  403. ///
  404. /// This method is installed as the SignalSet "on-receipt" handler. Upon
  405. /// invocation, it uses the controller's IOSignalQueue to schedule an
  406. /// IOSignal with for the given signal value.
  407. ///
  408. /// @param signum OS signal value (e.g. SIGINT, SIGUSR1 ...) to received
  409. ///
  410. /// @return SignalSet "on-receipt" handlers are required to return a
  411. /// boolean indicating if the OS signal has been processed (true) or if it
  412. /// should be saved for deferred processing (false). Currently this
  413. /// method processes all received signals, so it always returns true.
  414. bool osSignalHandler(int signum);
  415. /// @brief Handler for processing IOSignals
  416. ///
  417. /// This method is supplied as the callback when IOSignals are scheduled.
  418. /// It fetches the IOSignal for the given sequence_id and then invokes
  419. /// the virtual method, @c processSignal() passing it the signal value
  420. /// obtained from the IOSignal. This allows derivations to supply a
  421. /// custom signal processing method, while ensuring IOSignalQueue
  422. /// integrity.
  423. ///
  424. /// @param sequence_id id of the IOSignal instance "received"
  425. void ioSignalHandler(IOSignalId sequence_id);
  426. /// @brief Fetches the current process
  427. ///
  428. /// @return a pointer to the current process instance.
  429. DProcessBasePtr getProcess() {
  430. return (process_);
  431. }
  432. /// @brief Prints the program usage text to std error.
  433. ///
  434. /// @param text is a string message which will preceded the usage text.
  435. /// This is intended to be used for specific usage violation messages.
  436. void usage(const std::string& text);
  437. private:
  438. /// @brief Name of the service under control.
  439. /// This name is used as the configuration module name and appears in log
  440. /// statements.
  441. std::string app_name_;
  442. /// @brief Name of the service executable.
  443. /// By convention this matches the executable name. It is also used to
  444. /// establish the logger name.
  445. std::string bin_name_;
  446. /// @brief Indicates if the verbose logging mode is enabled.
  447. bool verbose_;
  448. /// @brief The absolute file name of the JSON spec file.
  449. std::string spec_file_name_;
  450. /// @brief Pointer to the instance of the process.
  451. ///
  452. /// This is required for config and command handlers to gain access to
  453. /// the process
  454. DProcessBasePtr process_;
  455. /// @brief Shared pointer to an IOService object, used for ASIO operations.
  456. asiolink::IOServicePtr io_service_;
  457. /// @brief Queue for propagating caught signals to the IOService.
  458. IOSignalQueuePtr io_signal_queue_;
  459. /// @brief Singleton instance value.
  460. static DControllerBasePtr controller_;
  461. // DControllerTest is named a friend class to facilitate unit testing while
  462. // leaving the intended member scopes intact.
  463. friend class DControllerTest;
  464. };
  465. }; // namespace isc::d2
  466. }; // namespace isc
  467. #endif