d_controller.h 21 KB

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