ccsession.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. // Copyright (C) 2009 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 <config.h>
  15. #include <stdexcept>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <sys/time.h>
  19. #include <iostream>
  20. #include <fstream>
  21. #include <sstream>
  22. #include <cerrno>
  23. #include <boost/bind.hpp>
  24. #include <boost/foreach.hpp>
  25. #include <cc/data.h>
  26. #include <module_spec.h>
  27. #include <cc/session.h>
  28. #include <exceptions/exceptions.h>
  29. #include <config/config_log.h>
  30. #include <config/ccsession.h>
  31. #include <log/logger_support.h>
  32. #include <log/logger_specification.h>
  33. #include <log/logger_manager.h>
  34. using namespace std;
  35. using isc::data::Element;
  36. using isc::data::ConstElementPtr;
  37. using isc::data::ElementPtr;
  38. using isc::data::JSONError;
  39. namespace isc {
  40. namespace config {
  41. /// Creates a standard config/command protocol answer message
  42. ConstElementPtr
  43. createAnswer() {
  44. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  45. ElementPtr answer_content = Element::createList();
  46. answer_content->add(Element::create(0));
  47. answer->set("result", answer_content);
  48. return (answer);
  49. }
  50. ConstElementPtr
  51. createAnswer(const int rcode, ConstElementPtr arg) {
  52. if (rcode != 0 && (!arg || arg->getType() != Element::string)) {
  53. isc_throw(CCSessionError, "Bad or no argument for rcode != 0");
  54. }
  55. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  56. ElementPtr answer_content = Element::createList();
  57. answer_content->add(Element::create(rcode));
  58. answer_content->add(arg);
  59. answer->set("result", answer_content);
  60. return (answer);
  61. }
  62. ConstElementPtr
  63. createAnswer(const int rcode, const std::string& arg) {
  64. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  65. ElementPtr answer_content = Element::createList();
  66. answer_content->add(Element::create(rcode));
  67. answer_content->add(Element::create(arg));
  68. answer->set("result", answer_content);
  69. return (answer);
  70. }
  71. ConstElementPtr
  72. parseAnswer(int &rcode, ConstElementPtr msg) {
  73. if (msg &&
  74. msg->getType() == Element::map &&
  75. msg->contains("result")) {
  76. ConstElementPtr result = msg->get("result");
  77. if (result->getType() != Element::list) {
  78. isc_throw(CCSessionError, "Result element in answer message is not a list");
  79. } else if (result->get(0)->getType() != Element::integer) {
  80. isc_throw(CCSessionError, "First element of result is not an rcode in answer message");
  81. }
  82. rcode = result->get(0)->intValue();
  83. if (result->size() > 1) {
  84. if (rcode == 0 || result->get(1)->getType() == Element::string) {
  85. return (result->get(1));
  86. } else {
  87. isc_throw(CCSessionError, "Error description in result with rcode != 0 is not a string");
  88. }
  89. } else {
  90. if (rcode == 0) {
  91. return (ElementPtr());
  92. } else {
  93. isc_throw(CCSessionError, "Result with rcode != 0 does not have an error description");
  94. }
  95. }
  96. } else {
  97. isc_throw(CCSessionError, "No result part in answer message");
  98. }
  99. }
  100. ConstElementPtr
  101. createCommand(const std::string& command) {
  102. return (createCommand(command, ElementPtr()));
  103. }
  104. ConstElementPtr
  105. createCommand(const std::string& command, ConstElementPtr arg) {
  106. ElementPtr cmd = Element::createMap();
  107. ElementPtr cmd_parts = Element::createList();
  108. cmd_parts->add(Element::create(command));
  109. if (arg) {
  110. cmd_parts->add(arg);
  111. }
  112. cmd->set("command", cmd_parts);
  113. return (cmd);
  114. }
  115. std::string
  116. parseCommand(ConstElementPtr& arg, ConstElementPtr command) {
  117. if (command &&
  118. command->getType() == Element::map &&
  119. command->contains("command")) {
  120. ConstElementPtr cmd = command->get("command");
  121. if (cmd->getType() == Element::list &&
  122. cmd->size() > 0 &&
  123. cmd->get(0)->getType() == Element::string) {
  124. if (cmd->size() > 1) {
  125. arg = cmd->get(1);
  126. } else {
  127. arg = Element::createMap();
  128. }
  129. return (cmd->get(0)->stringValue());
  130. } else {
  131. isc_throw(CCSessionError, "Command part in command message missing, empty, or not a list");
  132. }
  133. } else {
  134. isc_throw(CCSessionError, "Command Element empty or not a map with \"command\"");
  135. }
  136. }
  137. namespace {
  138. // Temporary workaround functions for missing functionality in
  139. // getValue() (main problem described in ticket #993)
  140. // This returns either the value set for the given relative id,
  141. // or its default value
  142. // (intentially defined here so this interface does not get
  143. // included in ConfigData as it is)
  144. ConstElementPtr getValueOrDefault(ConstElementPtr config_part,
  145. const std::string& relative_id,
  146. const ConfigData& config_data,
  147. const std::string& full_id) {
  148. if (config_part->contains(relative_id)) {
  149. return config_part->get(relative_id);
  150. } else {
  151. return config_data.getDefaultValue(full_id);
  152. }
  153. }
  154. // Reads a output_option subelement of a logger configuration,
  155. // and sets the values thereing to the given OutputOption struct,
  156. // or defaults values if they are not provided (from config_data).
  157. void
  158. readOutputOptionConf(isc::log::OutputOption& output_option,
  159. ConstElementPtr output_option_el,
  160. const ConfigData& config_data)
  161. {
  162. ConstElementPtr destination_el = getValueOrDefault(output_option_el,
  163. "destination", config_data,
  164. "loggers/output_options/destination");
  165. output_option.destination = isc::log::getDestination(destination_el->stringValue());
  166. ConstElementPtr output_el = getValueOrDefault(output_option_el,
  167. "output", config_data,
  168. "loggers/output_options/output");
  169. if (output_option.destination == isc::log::OutputOption::DEST_CONSOLE) {
  170. output_option.stream = isc::log::getStream(output_el->stringValue());
  171. } else if (output_option.destination == isc::log::OutputOption::DEST_FILE) {
  172. output_option.filename = output_el->stringValue();
  173. } else if (output_option.destination == isc::log::OutputOption::DEST_SYSLOG) {
  174. output_option.facility = output_el->stringValue();
  175. }
  176. output_option.flush = getValueOrDefault(output_option_el,
  177. "flush", config_data,
  178. "loggers/output_options/flush")->boolValue();
  179. output_option.maxsize = getValueOrDefault(output_option_el,
  180. "maxsize", config_data,
  181. "loggers/output_options/maxsize")->intValue();
  182. output_option.maxver = getValueOrDefault(output_option_el,
  183. "maxver", config_data,
  184. "loggers/output_options/maxver")->intValue();
  185. }
  186. // Reads a full 'loggers' configuration, and adds the loggers therein
  187. // to the given vector, fills in blanks with defaults from config_data
  188. void
  189. readLoggersConf(std::vector<isc::log::LoggerSpecification>& specs,
  190. ConstElementPtr logger,
  191. const ConfigData& config_data)
  192. {
  193. const std::string lname = logger->get("name")->stringValue();
  194. ConstElementPtr severity_el = getValueOrDefault(logger,
  195. "severity", config_data,
  196. "loggers/severity");
  197. isc::log::Severity severity = isc::log::getSeverity(
  198. severity_el->stringValue());
  199. int dbg_level = getValueOrDefault(logger, "debuglevel",
  200. config_data,
  201. "loggers/debuglevel")->intValue();
  202. bool additive = getValueOrDefault(logger, "additive", config_data,
  203. "loggers/additive")->boolValue();
  204. isc::log::LoggerSpecification logger_spec(
  205. lname, severity, dbg_level, additive
  206. );
  207. if (logger->contains("output_options")) {
  208. BOOST_FOREACH(ConstElementPtr output_option_el,
  209. logger->get("output_options")->listValue()) {
  210. // create outputoptions
  211. isc::log::OutputOption output_option;
  212. readOutputOptionConf(output_option,
  213. output_option_el,
  214. config_data);
  215. logger_spec.addOutputOption(output_option);
  216. }
  217. }
  218. specs.push_back(logger_spec);
  219. }
  220. } // end anonymous namespace
  221. void
  222. default_logconfig_handler(const std::string& module_name,
  223. ConstElementPtr new_config,
  224. const ConfigData& config_data) {
  225. config_data.getModuleSpec().validateConfig(new_config, true);
  226. std::vector<isc::log::LoggerSpecification> specs;
  227. if (new_config->contains("loggers")) {
  228. BOOST_FOREACH(ConstElementPtr logger,
  229. new_config->get("loggers")->listValue()) {
  230. readLoggersConf(specs, logger, config_data);
  231. }
  232. }
  233. isc::log::LoggerManager logger_manager;
  234. logger_manager.process(specs.begin(), specs.end());
  235. }
  236. ModuleSpec
  237. ModuleCCSession::readModuleSpecification(const std::string& filename) {
  238. std::ifstream file;
  239. ModuleSpec module_spec;
  240. // this file should be declared in a @something@ directive
  241. file.open(filename.c_str());
  242. if (!file) {
  243. LOG_ERROR(config_logger, CONFIG_FOPEN_ERR).arg(filename).arg(strerror(errno));
  244. isc_throw(CCSessionInitError, strerror(errno));
  245. }
  246. try {
  247. module_spec = moduleSpecFromFile(file, true);
  248. } catch (const JSONError& pe) {
  249. LOG_ERROR(config_logger, CONFIG_JSON_PARSE).arg(filename).arg(pe.what());
  250. isc_throw(CCSessionInitError, pe.what());
  251. } catch (const ModuleSpecError& dde) {
  252. LOG_ERROR(config_logger, CONFIG_MODULE_SPEC).arg(filename).arg(dde.what());
  253. isc_throw(CCSessionInitError, dde.what());
  254. }
  255. file.close();
  256. return (module_spec);
  257. }
  258. void
  259. ModuleCCSession::startCheck() {
  260. // data available on the command channel. process it in the synchronous
  261. // mode.
  262. checkCommand();
  263. // start asynchronous read again.
  264. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  265. }
  266. ModuleCCSession::ModuleCCSession(
  267. const std::string& spec_file_name,
  268. isc::cc::AbstractSession& session,
  269. isc::data::ConstElementPtr(*config_handler)(
  270. isc::data::ConstElementPtr new_config),
  271. isc::data::ConstElementPtr(*command_handler)(
  272. const std::string& command, isc::data::ConstElementPtr args),
  273. bool start_immediately,
  274. bool handle_logging
  275. ) :
  276. started_(false),
  277. session_(session)
  278. {
  279. module_specification_ = readModuleSpecification(spec_file_name);
  280. setModuleSpec(module_specification_);
  281. module_name_ = module_specification_.getFullSpec()->get("module_name")->stringValue();
  282. config_handler_ = config_handler;
  283. command_handler_ = command_handler;
  284. session_.establish(NULL);
  285. session_.subscribe(module_name_, "*");
  286. // send the data specification
  287. ConstElementPtr spec_msg = createCommand("module_spec",
  288. module_specification_.getFullSpec());
  289. unsigned int seq = session_.group_sendmsg(spec_msg, "ConfigManager");
  290. ConstElementPtr answer, env;
  291. session_.group_recvmsg(env, answer, false, seq);
  292. int rcode;
  293. ConstElementPtr err = parseAnswer(rcode, answer);
  294. if (rcode != 0) {
  295. LOG_ERROR(config_logger, CONFIG_MANAGER_MOD_SPEC).arg(answer->str());
  296. isc_throw(CCSessionInitError, answer->str());
  297. }
  298. setLocalConfig(Element::fromJSON("{}"));
  299. // get any stored configuration from the manager
  300. if (config_handler_) {
  301. ConstElementPtr cmd = Element::fromJSON("{ \"command\": [\"get_config\", {\"module_name\":\"" + module_name_ + "\"} ] }");
  302. seq = session_.group_sendmsg(cmd, "ConfigManager");
  303. session_.group_recvmsg(env, answer, false, seq);
  304. ConstElementPtr new_config = parseAnswer(rcode, answer);
  305. if (rcode == 0) {
  306. handleConfigUpdate(new_config);
  307. } else {
  308. LOG_ERROR(config_logger, CONFIG_MANAGER_CONFIG).arg(new_config->str());
  309. isc_throw(CCSessionInitError, answer->str());
  310. }
  311. }
  312. // Keep track of logging settings automatically
  313. if (handle_logging) {
  314. addRemoteConfig("Logging", default_logconfig_handler, false);
  315. }
  316. if (start_immediately) {
  317. start();
  318. }
  319. }
  320. void
  321. ModuleCCSession::start() {
  322. if (started_) {
  323. isc_throw(CCSessionError, "Module CC session already started");
  324. }
  325. // register callback for asynchronous read
  326. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  327. started_ = true;
  328. }
  329. /// Validates the new config values, if they are correct,
  330. /// call the config handler with the values that have changed
  331. /// If that results in success, store the new config
  332. ConstElementPtr
  333. ModuleCCSession::handleConfigUpdate(ConstElementPtr new_config) {
  334. ConstElementPtr answer;
  335. ElementPtr errors = Element::createList();
  336. if (!config_handler_) {
  337. answer = createAnswer(1, module_name_ + " does not have a config handler");
  338. } else if (!module_specification_.validateConfig(new_config, false,
  339. errors)) {
  340. std::stringstream ss;
  341. ss << "Error in config validation: ";
  342. BOOST_FOREACH(ConstElementPtr error, errors->listValue()) {
  343. ss << error->stringValue();
  344. }
  345. answer = createAnswer(2, ss.str());
  346. } else {
  347. // remove the values that have not changed
  348. ConstElementPtr diff = removeIdentical(new_config, getLocalConfig());
  349. // handle config update
  350. answer = config_handler_(diff);
  351. int rcode;
  352. parseAnswer(rcode, answer);
  353. if (rcode == 0) {
  354. ElementPtr local_config = getLocalConfig();
  355. isc::data::merge(local_config, diff);
  356. setLocalConfig(local_config);
  357. }
  358. }
  359. return (answer);
  360. }
  361. bool
  362. ModuleCCSession::hasQueuedMsgs() const {
  363. return (session_.hasQueuedMsgs());
  364. }
  365. ConstElementPtr
  366. ModuleCCSession::checkConfigUpdateCommand(const std::string& target_module,
  367. ConstElementPtr arg)
  368. {
  369. if (target_module == module_name_) {
  370. return (handleConfigUpdate(arg));
  371. } else {
  372. // ok this update is not for us, if we have this module
  373. // in our remote config list, update that
  374. updateRemoteConfig(target_module, arg);
  375. // we're not supposed to answer to this, so return
  376. return (ElementPtr());
  377. }
  378. }
  379. ConstElementPtr
  380. ModuleCCSession::checkModuleCommand(const std::string& cmd_str,
  381. const std::string& target_module,
  382. ConstElementPtr arg) const
  383. {
  384. if (target_module == module_name_) {
  385. if (command_handler_) {
  386. ElementPtr errors = Element::createList();
  387. if (module_specification_.validateCommand(cmd_str,
  388. arg,
  389. errors)) {
  390. return (command_handler_(cmd_str, arg));
  391. } else {
  392. std::stringstream ss;
  393. ss << "Error in command validation: ";
  394. BOOST_FOREACH(ConstElementPtr error,
  395. errors->listValue()) {
  396. ss << error->stringValue();
  397. }
  398. return (createAnswer(3, ss.str()));
  399. }
  400. } else {
  401. return (createAnswer(1,
  402. "Command given but no "
  403. "command handler for module"));
  404. }
  405. }
  406. return (ElementPtr());
  407. }
  408. int
  409. ModuleCCSession::checkCommand() {
  410. ConstElementPtr cmd, routing, data;
  411. if (session_.group_recvmsg(routing, data, true)) {
  412. /* ignore result messages (in case we're out of sync, to prevent
  413. * pingpongs */
  414. if (data->getType() != Element::map || data->contains("result")) {
  415. return (0);
  416. }
  417. ConstElementPtr arg;
  418. ConstElementPtr answer;
  419. try {
  420. std::string cmd_str = parseCommand(arg, data);
  421. std::string target_module = routing->get("group")->stringValue();
  422. if (cmd_str == "config_update") {
  423. answer = checkConfigUpdateCommand(target_module, arg);
  424. } else {
  425. answer = checkModuleCommand(cmd_str, target_module, arg);
  426. }
  427. } catch (const CCSessionError& re) {
  428. LOG_ERROR(config_logger, CONFIG_CCSESSION_MSG).arg(re.what());
  429. } catch (const std::exception& stde) {
  430. // No matter what unexpected error happens, we do not want
  431. // to crash because of an incoming event, so we log the
  432. // exception and continue to run
  433. LOG_ERROR(config_logger, CONFIG_CCSESSION_MSG_INTERNAL).arg(stde.what());
  434. }
  435. if (!isNull(answer)) {
  436. session_.reply(routing, answer);
  437. }
  438. }
  439. return (0);
  440. }
  441. ModuleSpec
  442. ModuleCCSession::fetchRemoteSpec(const std::string& module, bool is_filename) {
  443. if (is_filename) {
  444. // It is a filename, simply load it.
  445. return (readModuleSpecification(module));
  446. } else {
  447. // It's module name, request it from config manager
  448. // Send the command
  449. ConstElementPtr cmd(createCommand("get_module_spec",
  450. Element::fromJSON("{\"module_name\": \"" + module +
  451. "\"}")));
  452. unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  453. ConstElementPtr env, answer;
  454. session_.group_recvmsg(env, answer, false, seq);
  455. int rcode;
  456. ConstElementPtr spec_data = parseAnswer(rcode, answer);
  457. if (rcode == 0 && spec_data) {
  458. // received OK, construct the spec out of it
  459. ModuleSpec spec = ModuleSpec(spec_data);
  460. if (module != spec.getModuleName()) {
  461. // It's a different module!
  462. isc_throw(CCSessionError, "Module name mismatch");
  463. }
  464. return (spec);
  465. } else {
  466. isc_throw(CCSessionError, "Error getting config for " +
  467. module + ": " + answer->str());
  468. }
  469. }
  470. }
  471. std::string
  472. ModuleCCSession::addRemoteConfig(const std::string& spec_name,
  473. void (*handler)(const std::string& module,
  474. ConstElementPtr,
  475. const ConfigData&),
  476. bool spec_is_filename)
  477. {
  478. // First get the module name, specification and default config
  479. const ModuleSpec rmod_spec(fetchRemoteSpec(spec_name, spec_is_filename));
  480. const std::string module_name(rmod_spec.getModuleName());
  481. ConfigData rmod_config(rmod_spec);
  482. // Get the current configuration values from config manager
  483. ConstElementPtr cmd(createCommand("get_config",
  484. Element::fromJSON("{\"module_name\": \"" +
  485. module_name + "\"}")));
  486. const unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  487. ConstElementPtr env, answer;
  488. session_.group_recvmsg(env, answer, false, seq);
  489. int rcode;
  490. ConstElementPtr new_config = parseAnswer(rcode, answer);
  491. ElementPtr local_config;
  492. if (rcode == 0 && new_config) {
  493. // Merge the received config into existing local config
  494. local_config = rmod_config.getLocalConfig();
  495. isc::data::merge(local_config, new_config);
  496. rmod_config.setLocalConfig(local_config);
  497. } else {
  498. isc_throw(CCSessionError, "Error getting config for " + module_name + ": " + answer->str());
  499. }
  500. // all ok, add it
  501. remote_module_configs_[module_name] = rmod_config;
  502. if (handler) {
  503. remote_module_handlers_[module_name] = handler;
  504. handler(module_name, local_config, rmod_config);
  505. }
  506. // Make sure we get updates in future
  507. session_.subscribe(module_name);
  508. return (module_name);
  509. }
  510. void
  511. ModuleCCSession::removeRemoteConfig(const std::string& module_name) {
  512. std::map<std::string, ConfigData>::iterator it;
  513. it = remote_module_configs_.find(module_name);
  514. if (it != remote_module_configs_.end()) {
  515. remote_module_configs_.erase(it);
  516. remote_module_handlers_.erase(module_name);
  517. session_.unsubscribe(module_name);
  518. }
  519. }
  520. ConstElementPtr
  521. ModuleCCSession::getRemoteConfigValue(const std::string& module_name,
  522. const std::string& identifier) const
  523. {
  524. std::map<std::string, ConfigData>::const_iterator it =
  525. remote_module_configs_.find(module_name);
  526. if (it != remote_module_configs_.end()) {
  527. return ((*it).second.getValue(identifier));
  528. } else {
  529. isc_throw(CCSessionError,
  530. "Remote module " + module_name + " not found.");
  531. }
  532. }
  533. void
  534. ModuleCCSession::updateRemoteConfig(const std::string& module_name,
  535. ConstElementPtr new_config)
  536. {
  537. std::map<std::string, ConfigData>::iterator it;
  538. it = remote_module_configs_.find(module_name);
  539. if (it != remote_module_configs_.end()) {
  540. ElementPtr rconf = (*it).second.getLocalConfig();
  541. isc::data::merge(rconf, new_config);
  542. std::map<std::string, RemoteHandler>::iterator hit =
  543. remote_module_handlers_.find(module_name);
  544. if (hit != remote_module_handlers_.end()) {
  545. hit->second(module_name, new_config, it->second);
  546. }
  547. }
  548. }
  549. }
  550. }