d_controller.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. #include <d2/d2_log.h>
  15. #include <config/ccsession.h>
  16. #include <d2/d_controller.h>
  17. #include <exceptions/exceptions.h>
  18. #include <log/logger_support.h>
  19. #include <sstream>
  20. namespace isc {
  21. namespace d2 {
  22. DControllerBasePtr DControllerBase::controller_;
  23. // Note that the constructor instantiates the controller's primary IOService.
  24. DControllerBase::DControllerBase(const char* app_name, const char* bin_name)
  25. : app_name_(app_name), bin_name_(bin_name),
  26. verbose_(false), spec_file_name_(""),
  27. io_service_(new isc::asiolink::IOService()){
  28. }
  29. void
  30. DControllerBase::setController(const DControllerBasePtr& controller) {
  31. if (controller_) {
  32. // This shouldn't happen, but let's make sure it can't be done.
  33. // It represents a programmatic error.
  34. isc_throw (DControllerBaseError,
  35. "Multiple controller instances attempted.");
  36. }
  37. controller_ = controller;
  38. }
  39. void
  40. DControllerBase::launch(int argc, char* argv[], const bool test_mode) {
  41. // Step 1 is to parse the command line arguments.
  42. try {
  43. parseArgs(argc, argv);
  44. } catch (const InvalidUsage& ex) {
  45. usage(ex.what());
  46. throw; // rethrow it
  47. }
  48. // Do not initialize logger here if we are running unit tests. It would
  49. // replace an instance of unit test specific logger.
  50. if (!test_mode) {
  51. // Now that we know what the mode flags are, we can init logging.
  52. Daemon::loggerInit(bin_name_.c_str(), verbose_);
  53. }
  54. LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_STARTING)
  55. .arg(app_name_).arg(getpid());
  56. try {
  57. // Step 2 is to create and initialize the application process object.
  58. initProcess();
  59. } catch (const std::exception& ex) {
  60. LOG_FATAL(dctl_logger, DCTL_INIT_PROCESS_FAIL)
  61. .arg(app_name_).arg(ex.what());
  62. isc_throw (ProcessInitError,
  63. "Application Process initialization failed: " << ex.what());
  64. }
  65. LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_STANDALONE).arg(app_name_);
  66. // Step 3 is to load configuration from file.
  67. int rcode;
  68. isc::data::ConstElementPtr comment
  69. = isc::config::parseAnswer(rcode, configFromFile());
  70. if (rcode != 0) {
  71. LOG_FATAL(dctl_logger, DCTL_CONFIG_FILE_LOAD_FAIL)
  72. .arg(app_name_).arg(comment->stringValue());
  73. isc_throw (ProcessInitError, "Could Not load configration file: "
  74. << comment->stringValue());
  75. }
  76. // Everything is clear for launch, so start the application's
  77. // event loop.
  78. try {
  79. runProcess();
  80. } catch (const std::exception& ex) {
  81. LOG_FATAL(dctl_logger, DCTL_PROCESS_FAILED)
  82. .arg(app_name_).arg(ex.what());
  83. isc_throw (ProcessRunError,
  84. "Application process event loop failed: " << ex.what());
  85. }
  86. // All done, so bail out.
  87. LOG_INFO(dctl_logger, DCTL_STOPPING).arg(app_name_);
  88. }
  89. void
  90. DControllerBase::parseArgs(int argc, char* argv[])
  91. {
  92. // Iterate over the given command line options. If its a stock option
  93. // ("s" or "v") handle it here. If its a valid custom option, then
  94. // invoke customOption.
  95. int ch;
  96. opterr = 0;
  97. optind = 1;
  98. std::string opts("vc:" + getCustomOpts());
  99. while ((ch = getopt(argc, argv, opts.c_str())) != -1) {
  100. switch (ch) {
  101. case 'v':
  102. // Enables verbose logging.
  103. verbose_ = true;
  104. break;
  105. case 'c':
  106. // config file name
  107. if (optarg == NULL) {
  108. isc_throw(InvalidUsage, "configuration file name missing");
  109. }
  110. Daemon::init(optarg);
  111. break;
  112. case '?': {
  113. // We hit an invalid option.
  114. isc_throw(InvalidUsage, "unsupported option: ["
  115. << static_cast<char>(optopt) << "] "
  116. << (!optarg ? "" : optarg));
  117. break;
  118. }
  119. default:
  120. // We hit a valid custom option
  121. if (!customOption(ch, optarg)) {
  122. // This would be a programmatic error.
  123. isc_throw(InvalidUsage, " Option listed but implemented?: ["
  124. << static_cast<char>(ch) << "] "
  125. << (!optarg ? "" : optarg));
  126. }
  127. break;
  128. }
  129. }
  130. // There was too much information on the command line.
  131. if (argc > optind) {
  132. isc_throw(InvalidUsage, "extraneous command line information");
  133. }
  134. }
  135. isc::data::ConstElementPtr
  136. DControllerBase::configHandler(isc::data::ConstElementPtr new_config) {
  137. LOG_DEBUG(dctl_logger, DBGLVL_COMMAND, DCTL_CONFIG_UPDATE)
  138. .arg(controller_->getAppName()).arg(new_config->str());
  139. // Invoke the instance method on the controller singleton.
  140. return (controller_->updateConfig(new_config));
  141. }
  142. // Static callback which invokes non-static handler on singleton
  143. isc::data::ConstElementPtr
  144. DControllerBase::commandHandler(const std::string& command,
  145. isc::data::ConstElementPtr args) {
  146. LOG_DEBUG(dctl_logger, DBGLVL_COMMAND, DCTL_COMMAND_RECEIVED)
  147. .arg(controller_->getAppName()).arg(command)
  148. .arg(args ? args->str() : "(no args)");
  149. // Invoke the instance method on the controller singleton.
  150. return (controller_->executeCommand(command, args));
  151. }
  152. bool
  153. DControllerBase::customOption(int /* option */, char* /*optarg*/)
  154. {
  155. // Default implementation returns false.
  156. return (false);
  157. }
  158. void
  159. DControllerBase::initProcess() {
  160. LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_INIT_PROCESS).arg(app_name_);
  161. // Invoke virtual method to instantiate the application process.
  162. try {
  163. process_.reset(createProcess());
  164. } catch (const std::exception& ex) {
  165. isc_throw(DControllerBaseError, std::string("createProcess failed: ")
  166. + ex.what());
  167. }
  168. // This is pretty unlikely, but will test for it just to be safe..
  169. if (!process_) {
  170. isc_throw(DControllerBaseError, "createProcess returned NULL");
  171. }
  172. // Invoke application's init method (Note this call should throw
  173. // DProcessBaseError if it fails).
  174. process_->init();
  175. }
  176. isc::data::ConstElementPtr
  177. DControllerBase::configFromFile() {
  178. isc::data::ConstElementPtr module_config;
  179. try {
  180. std::string config_file = getConfigFileName();
  181. if (config_file.empty()) {
  182. // Basic sanity check: file name must not be empty.
  183. isc_throw(BadValue, "JSON configuration file not specified. Please "
  184. "use -c command line option.");
  185. }
  186. // Read contents of the file and parse it as JSON
  187. isc::data::ConstElementPtr whole_config =
  188. isc::data::Element::fromJSONFile(config_file, true);
  189. // Extract derivation-specific portion of the configuration.
  190. module_config = whole_config->get(getAppName());
  191. if (!module_config) {
  192. isc_throw(BadValue, "Config file " << config_file <<
  193. " does not include '" <<
  194. getAppName() << "' entry.");
  195. }
  196. } catch (const std::exception& ex) {
  197. // build an error result
  198. isc::data::ConstElementPtr error =
  199. isc::config::createAnswer(1,
  200. std::string("Configuration parsing failed: ") + ex.what());
  201. return (error);
  202. }
  203. return (updateConfig(module_config));
  204. }
  205. void
  206. DControllerBase::runProcess() {
  207. LOG_DEBUG(dctl_logger, DBGLVL_START_SHUT, DCTL_RUN_PROCESS).arg(app_name_);
  208. if (!process_) {
  209. // This should not be possible.
  210. isc_throw(DControllerBaseError, "Process not initialized");
  211. }
  212. // Invoke the application process's run method. This may throw
  213. // DProcessBaseError
  214. process_->run();
  215. }
  216. // Instance method for handling new config
  217. isc::data::ConstElementPtr
  218. DControllerBase::updateConfig(isc::data::ConstElementPtr new_config) {
  219. return (process_->configure(new_config));
  220. }
  221. // Instance method for executing commands
  222. isc::data::ConstElementPtr
  223. DControllerBase::executeCommand(const std::string& command,
  224. isc::data::ConstElementPtr args) {
  225. // Shutdown is universal. If its not that, then try it as
  226. // an custom command supported by the derivation. If that
  227. // doesn't pan out either, than send to it the application
  228. // as it may be supported there.
  229. isc::data::ConstElementPtr answer;
  230. if (command.compare(SHUT_DOWN_COMMAND) == 0) {
  231. answer = shutdownProcess(args);
  232. } else {
  233. // It wasn't shutdown, so may be a custom controller command.
  234. int rcode = 0;
  235. answer = customControllerCommand(command, args);
  236. isc::config::parseAnswer(rcode, answer);
  237. if (rcode == COMMAND_INVALID)
  238. {
  239. // It wasn't controller command, so may be an application command.
  240. answer = process_->command(command, args);
  241. }
  242. }
  243. return (answer);
  244. }
  245. isc::data::ConstElementPtr
  246. DControllerBase::customControllerCommand(const std::string& command,
  247. isc::data::ConstElementPtr /* args */) {
  248. // Default implementation always returns invalid command.
  249. return (isc::config::createAnswer(COMMAND_INVALID,
  250. "Unrecognized command: " + command));
  251. }
  252. isc::data::ConstElementPtr
  253. DControllerBase::shutdownProcess(isc::data::ConstElementPtr args) {
  254. if (process_) {
  255. return (process_->shutdown(args));
  256. }
  257. // Not really a failure, but this condition is worth noting. In reality
  258. // it should be pretty hard to cause this.
  259. LOG_WARN(dctl_logger, DCTL_NOT_RUNNING).arg(app_name_);
  260. return (isc::config::createAnswer(0, "Process has not been initialzed."));
  261. }
  262. void
  263. DControllerBase::usage(const std::string & text)
  264. {
  265. if (text != "") {
  266. std::cerr << "Usage error: " << text << std::endl;
  267. }
  268. std::cerr << "Usage: " << bin_name_ << std::endl
  269. << " -c <config file name> : mandatory,"
  270. << " specifies name of configuration file " << std::endl
  271. << " -v: optional, verbose output " << std::endl;
  272. // add any derivation specific usage
  273. std::cerr << getUsageText() << std::endl;
  274. }
  275. DControllerBase::~DControllerBase() {
  276. }
  277. std::string
  278. DControllerBase::getConfigFileName() {
  279. return (Daemon::getConfigFile());
  280. }
  281. }; // namespace isc::d2
  282. // Provide an implementation until we figure out a better way to do this.
  283. void
  284. dhcp::Daemon::loggerInit(const char* log_name, bool verbose) {
  285. setenv("B10_LOCKFILE_DIR_FROM_BUILD", "/tmp", 1);
  286. setenv("B10_LOGGER_ROOT", log_name, 0);
  287. setenv("B10_LOGGER_SEVERITY", (verbose ? "DEBUG":"INFO"), 0);
  288. setenv("B10_LOGGER_DBGLEVEL", "99", 0);
  289. setenv("B10_LOGGER_DESTINATION", "stdout", 0);
  290. isc::log::initLogger();
  291. }
  292. }; // namespace isc