ccsession.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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 <ctype.h>
  20. #include <algorithm>
  21. #include <cerrno>
  22. #include <fstream>
  23. #include <iostream>
  24. #include <set>
  25. #include <sstream>
  26. #include <string>
  27. #include <boost/bind.hpp>
  28. #include <boost/foreach.hpp>
  29. #include <cc/data.h>
  30. #include <module_spec.h>
  31. #include <cc/session.h>
  32. #include <exceptions/exceptions.h>
  33. #include <config/config_log.h>
  34. #include <config/ccsession.h>
  35. #include <log/logger_support.h>
  36. #include <log/logger_specification.h>
  37. #include <log/logger_manager.h>
  38. #include <log/logger_name.h>
  39. using namespace std;
  40. using isc::data::Element;
  41. using isc::data::ConstElementPtr;
  42. using isc::data::ElementPtr;
  43. using isc::data::JSONError;
  44. namespace isc {
  45. namespace config {
  46. /// Creates a standard config/command protocol answer message
  47. ConstElementPtr
  48. createAnswer() {
  49. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  50. ElementPtr answer_content = Element::createList();
  51. answer_content->add(Element::create(0));
  52. answer->set("result", answer_content);
  53. return (answer);
  54. }
  55. ConstElementPtr
  56. createAnswer(const int rcode, ConstElementPtr arg) {
  57. if (rcode != 0 && (!arg || arg->getType() != Element::string)) {
  58. isc_throw(CCSessionError, "Bad or no argument for rcode != 0");
  59. }
  60. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  61. ElementPtr answer_content = Element::createList();
  62. answer_content->add(Element::create(rcode));
  63. answer_content->add(arg);
  64. answer->set("result", answer_content);
  65. return (answer);
  66. }
  67. ConstElementPtr
  68. createAnswer(const int rcode, const std::string& arg) {
  69. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  70. ElementPtr answer_content = Element::createList();
  71. answer_content->add(Element::create(rcode));
  72. answer_content->add(Element::create(arg));
  73. answer->set("result", answer_content);
  74. return (answer);
  75. }
  76. ConstElementPtr
  77. parseAnswer(int &rcode, ConstElementPtr msg) {
  78. if (msg &&
  79. msg->getType() == Element::map &&
  80. msg->contains("result")) {
  81. ConstElementPtr result = msg->get("result");
  82. if (result->getType() != Element::list) {
  83. isc_throw(CCSessionError, "Result element in answer message is not a list");
  84. } else if (result->get(0)->getType() != Element::integer) {
  85. isc_throw(CCSessionError, "First element of result is not an rcode in answer message");
  86. }
  87. rcode = result->get(0)->intValue();
  88. if (result->size() > 1) {
  89. if (rcode == 0 || result->get(1)->getType() == Element::string) {
  90. return (result->get(1));
  91. } else {
  92. isc_throw(CCSessionError, "Error description in result with rcode != 0 is not a string");
  93. }
  94. } else {
  95. if (rcode == 0) {
  96. return (ElementPtr());
  97. } else {
  98. isc_throw(CCSessionError, "Result with rcode != 0 does not have an error description");
  99. }
  100. }
  101. } else {
  102. isc_throw(CCSessionError, "No result part in answer message");
  103. }
  104. }
  105. ConstElementPtr
  106. createCommand(const std::string& command) {
  107. return (createCommand(command, ElementPtr()));
  108. }
  109. ConstElementPtr
  110. createCommand(const std::string& command, ConstElementPtr arg) {
  111. ElementPtr cmd = Element::createMap();
  112. ElementPtr cmd_parts = Element::createList();
  113. cmd_parts->add(Element::create(command));
  114. if (arg) {
  115. cmd_parts->add(arg);
  116. }
  117. cmd->set("command", cmd_parts);
  118. return (cmd);
  119. }
  120. std::string
  121. parseCommand(ConstElementPtr& arg, ConstElementPtr command) {
  122. if (command &&
  123. command->getType() == Element::map &&
  124. command->contains("command")) {
  125. ConstElementPtr cmd = command->get("command");
  126. if (cmd->getType() == Element::list &&
  127. cmd->size() > 0 &&
  128. cmd->get(0)->getType() == Element::string) {
  129. if (cmd->size() > 1) {
  130. arg = cmd->get(1);
  131. } else {
  132. arg = Element::createMap();
  133. }
  134. return (cmd->get(0)->stringValue());
  135. } else {
  136. isc_throw(CCSessionError, "Command part in command message missing, empty, or not a list");
  137. }
  138. } else {
  139. isc_throw(CCSessionError, "Command Element empty or not a map with \"command\"");
  140. }
  141. }
  142. namespace {
  143. // Temporary workaround functions for missing functionality in
  144. // getValue() (main problem described in ticket #993)
  145. // This returns either the value set for the given relative id,
  146. // or its default value
  147. // (intentially defined here so this interface does not get
  148. // included in ConfigData as it is)
  149. ConstElementPtr getValueOrDefault(ConstElementPtr config_part,
  150. const std::string& relative_id,
  151. const ConfigData& config_data,
  152. const std::string& full_id) {
  153. if (config_part->contains(relative_id)) {
  154. return config_part->get(relative_id);
  155. } else {
  156. return config_data.getDefaultValue(full_id);
  157. }
  158. }
  159. // Prefix name with "b10-".
  160. //
  161. // Root logger names are based on the name of the binary they're from (e.g.
  162. // b10-resolver). This, however, is not how they appear internally (in for
  163. // instance bindctl, where a module name is based on what is specified in
  164. // the .spec file (e.g. Resolver)).
  165. //
  166. // This function prefixes the name read in the configuration with 'b10-" and
  167. // leaves the module code as it is. (It is now a required convention that the
  168. // name from the specfile and the actual binary name should match). To take
  169. // account of the use of capital letters in module names in bindctl, the first
  170. // letter of the name read in is lower-cased.
  171. //
  172. // In this way, you configure resolver logging with the name "resolver" and in
  173. // the printed output it becomes "b10-resolver".
  174. //
  175. // To allow for (a) people using b10-resolver in the configuration instead of
  176. // "resolver" and (b) that fact that during the resolution of wildcards in
  177. //
  178. // \param instring String to prefix. Lowercase the first character and apply
  179. // the prefix. If empty, "b10-" is returned.
  180. std::string
  181. b10Prefix(const std::string& instring) {
  182. std::string result = instring;
  183. if (!result.empty()) {
  184. result[0] = static_cast<char>(tolower(result[0]));
  185. }
  186. return (std::string("b10-") + result);
  187. }
  188. // Reads a output_option subelement of a logger configuration,
  189. // and sets the values thereing to the given OutputOption struct,
  190. // or defaults values if they are not provided (from config_data).
  191. void
  192. readOutputOptionConf(isc::log::OutputOption& output_option,
  193. ConstElementPtr output_option_el,
  194. const ConfigData& config_data)
  195. {
  196. ConstElementPtr destination_el = getValueOrDefault(output_option_el,
  197. "destination", config_data,
  198. "loggers/output_options/destination");
  199. output_option.destination = isc::log::getDestination(destination_el->stringValue());
  200. ConstElementPtr output_el = getValueOrDefault(output_option_el,
  201. "output", config_data,
  202. "loggers/output_options/output");
  203. if (output_option.destination == isc::log::OutputOption::DEST_CONSOLE) {
  204. output_option.stream = isc::log::getStream(output_el->stringValue());
  205. } else if (output_option.destination == isc::log::OutputOption::DEST_FILE) {
  206. output_option.filename = output_el->stringValue();
  207. } else if (output_option.destination == isc::log::OutputOption::DEST_SYSLOG) {
  208. output_option.facility = output_el->stringValue();
  209. }
  210. output_option.flush = getValueOrDefault(output_option_el,
  211. "flush", config_data,
  212. "loggers/output_options/flush")->boolValue();
  213. output_option.maxsize = getValueOrDefault(output_option_el,
  214. "maxsize", config_data,
  215. "loggers/output_options/maxsize")->intValue();
  216. output_option.maxver = getValueOrDefault(output_option_el,
  217. "maxver", config_data,
  218. "loggers/output_options/maxver")->intValue();
  219. }
  220. // Reads a full 'loggers' configuration, and adds the loggers therein
  221. // to the given vector, fills in blanks with defaults from config_data
  222. void
  223. readLoggersConf(std::vector<isc::log::LoggerSpecification>& specs,
  224. ConstElementPtr logger,
  225. const ConfigData& config_data)
  226. {
  227. // Read name, adding prefix as required.
  228. std::string lname = logger->get("name")->stringValue();
  229. ConstElementPtr severity_el = getValueOrDefault(logger,
  230. "severity", config_data,
  231. "loggers/severity");
  232. isc::log::Severity severity = isc::log::getSeverity(
  233. severity_el->stringValue());
  234. int dbg_level = getValueOrDefault(logger, "debuglevel",
  235. config_data,
  236. "loggers/debuglevel")->intValue();
  237. bool additive = getValueOrDefault(logger, "additive", config_data,
  238. "loggers/additive")->boolValue();
  239. isc::log::LoggerSpecification logger_spec(
  240. lname, severity, dbg_level, additive
  241. );
  242. if (logger->contains("output_options")) {
  243. BOOST_FOREACH(ConstElementPtr output_option_el,
  244. logger->get("output_options")->listValue()) {
  245. // create outputoptions
  246. isc::log::OutputOption output_option;
  247. readOutputOptionConf(output_option,
  248. output_option_el,
  249. config_data);
  250. logger_spec.addOutputOption(output_option);
  251. }
  252. }
  253. specs.push_back(logger_spec);
  254. }
  255. // Copies the map for a logger, changing the of the logger. This is
  256. // used because the logger being copied is "const", but we want to
  257. // change a top-level name, so need to create a new one.
  258. ElementPtr
  259. copyLogger(ConstElementPtr& cur_logger, const std::string& new_name) {
  260. ElementPtr new_logger(Element::createMap());
  261. // since we'll only be updating one first-level element,
  262. // and we return as const again, a shallow map copy is
  263. // enough
  264. new_logger->setValue(cur_logger->mapValue());
  265. new_logger->set("name", Element::create(new_name));
  266. return (new_logger);
  267. }
  268. } // end anonymous namespace
  269. ConstElementPtr
  270. getRelatedLoggers(ConstElementPtr loggers) {
  271. // Keep a list of names for easier lookup later
  272. std::set<std::string> our_names;
  273. const std::string& root_name = isc::log::getRootLoggerName();
  274. ElementPtr result = isc::data::Element::createList();
  275. BOOST_FOREACH(ConstElementPtr cur_logger, loggers->listValue()) {
  276. // Need to add the b10- prefix to names ready from the spec file.
  277. const std::string cur_name = cur_logger->get("name")->stringValue();
  278. const std::string mod_name = b10Prefix(cur_name);
  279. if (mod_name == root_name || mod_name.find(root_name + ".") == 0) {
  280. // Note this name so that we don't add a wildcard that matches it.
  281. our_names.insert(mod_name);
  282. // We want to store the logger with the modified name (i.e. with
  283. // the b10- prefix). As we are dealing with const loggers, we
  284. // store a modified copy of the data.
  285. result->add(copyLogger(cur_logger, mod_name));
  286. LOG_DEBUG(config_logger, DBG_CONFIG_PROCESS, CONFIG_LOG_EXPLICIT)
  287. .arg(cur_name);
  288. } else if (!cur_name.empty() && (cur_name[0] != '*')) {
  289. // Not a wildcard logger and we are ignore it, note the fact.
  290. LOG_DEBUG(config_logger, DBG_CONFIG_PROCESS,
  291. CONFIG_LOG_IGNORE_EXPLICIT).arg(cur_name);
  292. }
  293. }
  294. // Mow find the wildcard names (the one that start with "*").
  295. BOOST_FOREACH(ConstElementPtr cur_logger, loggers->listValue()) {
  296. std::string cur_name = cur_logger->get("name")->stringValue();
  297. // if name is '*', or starts with '*.', replace * with root
  298. // logger name.
  299. if (cur_name == "*" || cur_name.length() > 1 &&
  300. cur_name[0] == '*' && cur_name[1] == '.') {
  301. // Substitute the "*" with the root name
  302. std::string mod_name = cur_name;
  303. mod_name.replace(0, 1, root_name);
  304. // Mow add it to the result list, but only if a logger with
  305. // that name was not configured explicitly
  306. if (our_names.find(mod_name) == our_names.end()) {
  307. // We substitute the name here already, but as
  308. // we are dealing with consts, we copy the data
  309. result->add(copyLogger(cur_logger, mod_name));
  310. LOG_DEBUG(config_logger, DBG_CONFIG_PROCESS,
  311. CONFIG_LOG_WILD_MATCH).arg(cur_name);
  312. } else if (!cur_name.empty() && (cur_name[0] == '*')) {
  313. // Is a wildcard and we are ignoring it.
  314. LOG_DEBUG(config_logger, DBG_CONFIG_PROCESS,
  315. CONFIG_LOG_IGNORE_WILD).arg(cur_name);
  316. }
  317. }
  318. }
  319. return result;
  320. }
  321. void
  322. default_logconfig_handler(const std::string& module_name,
  323. ConstElementPtr new_config,
  324. const ConfigData& config_data) {
  325. config_data.getModuleSpec().validateConfig(new_config, true);
  326. std::vector<isc::log::LoggerSpecification> specs;
  327. if (new_config->contains("loggers")) {
  328. ConstElementPtr loggers = getRelatedLoggers(new_config->get("loggers"));
  329. BOOST_FOREACH(ConstElementPtr logger,
  330. loggers->listValue()) {
  331. readLoggersConf(specs, logger, config_data);
  332. }
  333. }
  334. isc::log::LoggerManager logger_manager;
  335. logger_manager.process(specs.begin(), specs.end());
  336. }
  337. ModuleSpec
  338. ModuleCCSession::readModuleSpecification(const std::string& filename) {
  339. std::ifstream file;
  340. ModuleSpec module_spec;
  341. // this file should be declared in a @something@ directive
  342. file.open(filename.c_str());
  343. if (!file) {
  344. LOG_ERROR(config_logger, CONFIG_OPEN_FAIL).arg(filename).arg(strerror(errno));
  345. isc_throw(CCSessionInitError, strerror(errno));
  346. }
  347. try {
  348. module_spec = moduleSpecFromFile(file, true);
  349. } catch (const JSONError& pe) {
  350. LOG_ERROR(config_logger, CONFIG_JSON_PARSE).arg(filename).arg(pe.what());
  351. isc_throw(CCSessionInitError, pe.what());
  352. } catch (const ModuleSpecError& dde) {
  353. LOG_ERROR(config_logger, CONFIG_MOD_SPEC_FORMAT).arg(filename).arg(dde.what());
  354. isc_throw(CCSessionInitError, dde.what());
  355. }
  356. file.close();
  357. return (module_spec);
  358. }
  359. void
  360. ModuleCCSession::startCheck() {
  361. // data available on the command channel. process it in the synchronous
  362. // mode.
  363. checkCommand();
  364. // start asynchronous read again.
  365. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  366. }
  367. ModuleCCSession::ModuleCCSession(
  368. const std::string& spec_file_name,
  369. isc::cc::AbstractSession& session,
  370. isc::data::ConstElementPtr(*config_handler)(
  371. isc::data::ConstElementPtr new_config),
  372. isc::data::ConstElementPtr(*command_handler)(
  373. const std::string& command, isc::data::ConstElementPtr args),
  374. bool start_immediately,
  375. bool handle_logging
  376. ) :
  377. started_(false),
  378. session_(session)
  379. {
  380. module_specification_ = readModuleSpecification(spec_file_name);
  381. setModuleSpec(module_specification_);
  382. module_name_ = module_specification_.getFullSpec()->get("module_name")->stringValue();
  383. config_handler_ = config_handler;
  384. command_handler_ = command_handler;
  385. session_.establish(NULL);
  386. session_.subscribe(module_name_, "*");
  387. // send the data specification
  388. ConstElementPtr spec_msg = createCommand("module_spec",
  389. module_specification_.getFullSpec());
  390. unsigned int seq = session_.group_sendmsg(spec_msg, "ConfigManager");
  391. ConstElementPtr answer, env;
  392. session_.group_recvmsg(env, answer, false, seq);
  393. int rcode;
  394. ConstElementPtr err = parseAnswer(rcode, answer);
  395. if (rcode != 0) {
  396. LOG_ERROR(config_logger, CONFIG_MOD_SPEC_REJECT).arg(answer->str());
  397. isc_throw(CCSessionInitError, answer->str());
  398. }
  399. setLocalConfig(Element::fromJSON("{}"));
  400. // get any stored configuration from the manager
  401. if (config_handler_) {
  402. ConstElementPtr cmd = Element::fromJSON("{ \"command\": [\"get_config\", {\"module_name\":\"" + module_name_ + "\"} ] }");
  403. seq = session_.group_sendmsg(cmd, "ConfigManager");
  404. session_.group_recvmsg(env, answer, false, seq);
  405. ConstElementPtr new_config = parseAnswer(rcode, answer);
  406. if (rcode == 0) {
  407. handleConfigUpdate(new_config);
  408. } else {
  409. LOG_ERROR(config_logger, CONFIG_GET_FAIL).arg(new_config->str());
  410. isc_throw(CCSessionInitError, answer->str());
  411. }
  412. }
  413. // Keep track of logging settings automatically
  414. if (handle_logging) {
  415. addRemoteConfig("Logging", default_logconfig_handler, false);
  416. }
  417. if (start_immediately) {
  418. start();
  419. }
  420. }
  421. void
  422. ModuleCCSession::start() {
  423. if (started_) {
  424. isc_throw(CCSessionError, "Module CC session already started");
  425. }
  426. // register callback for asynchronous read
  427. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  428. started_ = true;
  429. }
  430. /// Validates the new config values, if they are correct,
  431. /// call the config handler with the values that have changed
  432. /// If that results in success, store the new config
  433. ConstElementPtr
  434. ModuleCCSession::handleConfigUpdate(ConstElementPtr new_config) {
  435. ConstElementPtr answer;
  436. ElementPtr errors = Element::createList();
  437. if (!config_handler_) {
  438. answer = createAnswer(1, module_name_ + " does not have a config handler");
  439. } else if (!module_specification_.validateConfig(new_config, false,
  440. errors)) {
  441. std::stringstream ss;
  442. ss << "Error in config validation: ";
  443. BOOST_FOREACH(ConstElementPtr error, errors->listValue()) {
  444. ss << error->stringValue();
  445. }
  446. answer = createAnswer(2, ss.str());
  447. } else {
  448. // remove the values that have not changed
  449. ConstElementPtr diff = removeIdentical(new_config, getLocalConfig());
  450. // handle config update
  451. answer = config_handler_(diff);
  452. int rcode;
  453. parseAnswer(rcode, answer);
  454. if (rcode == 0) {
  455. ElementPtr local_config = getLocalConfig();
  456. isc::data::merge(local_config, diff);
  457. setLocalConfig(local_config);
  458. }
  459. }
  460. return (answer);
  461. }
  462. bool
  463. ModuleCCSession::hasQueuedMsgs() const {
  464. return (session_.hasQueuedMsgs());
  465. }
  466. ConstElementPtr
  467. ModuleCCSession::checkConfigUpdateCommand(const std::string& target_module,
  468. ConstElementPtr arg)
  469. {
  470. if (target_module == module_name_) {
  471. return (handleConfigUpdate(arg));
  472. } else {
  473. // ok this update is not for us, if we have this module
  474. // in our remote config list, update that
  475. updateRemoteConfig(target_module, arg);
  476. // we're not supposed to answer to this, so return
  477. return (ElementPtr());
  478. }
  479. }
  480. ConstElementPtr
  481. ModuleCCSession::checkModuleCommand(const std::string& cmd_str,
  482. const std::string& target_module,
  483. ConstElementPtr arg) const
  484. {
  485. if (target_module == module_name_) {
  486. if (command_handler_) {
  487. ElementPtr errors = Element::createList();
  488. if (module_specification_.validateCommand(cmd_str,
  489. arg,
  490. errors)) {
  491. return (command_handler_(cmd_str, arg));
  492. } else {
  493. std::stringstream ss;
  494. ss << "Error in command validation: ";
  495. BOOST_FOREACH(ConstElementPtr error,
  496. errors->listValue()) {
  497. ss << error->stringValue();
  498. }
  499. return (createAnswer(3, ss.str()));
  500. }
  501. } else {
  502. return (createAnswer(1,
  503. "Command given but no "
  504. "command handler for module"));
  505. }
  506. }
  507. return (ElementPtr());
  508. }
  509. int
  510. ModuleCCSession::checkCommand() {
  511. ConstElementPtr cmd, routing, data;
  512. if (session_.group_recvmsg(routing, data, true)) {
  513. /* ignore result messages (in case we're out of sync, to prevent
  514. * pingpongs */
  515. if (data->getType() != Element::map || data->contains("result")) {
  516. return (0);
  517. }
  518. ConstElementPtr arg;
  519. ConstElementPtr answer;
  520. try {
  521. std::string cmd_str = parseCommand(arg, data);
  522. std::string target_module = routing->get("group")->stringValue();
  523. if (cmd_str == "config_update") {
  524. answer = checkConfigUpdateCommand(target_module, arg);
  525. } else {
  526. answer = checkModuleCommand(cmd_str, target_module, arg);
  527. }
  528. } catch (const CCSessionError& re) {
  529. LOG_ERROR(config_logger, CONFIG_CCSESSION_MSG).arg(re.what());
  530. } catch (const std::exception& stde) {
  531. // No matter what unexpected error happens, we do not want
  532. // to crash because of an incoming event, so we log the
  533. // exception and continue to run
  534. LOG_ERROR(config_logger, CONFIG_CCSESSION_MSG_INTERNAL).arg(stde.what());
  535. }
  536. if (!isNull(answer)) {
  537. session_.reply(routing, answer);
  538. }
  539. }
  540. return (0);
  541. }
  542. ModuleSpec
  543. ModuleCCSession::fetchRemoteSpec(const std::string& module, bool is_filename) {
  544. if (is_filename) {
  545. // It is a filename, simply load it.
  546. return (readModuleSpecification(module));
  547. } else {
  548. // It's module name, request it from config manager
  549. // Send the command
  550. ConstElementPtr cmd(createCommand("get_module_spec",
  551. Element::fromJSON("{\"module_name\": \"" + module +
  552. "\"}")));
  553. unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  554. ConstElementPtr env, answer;
  555. session_.group_recvmsg(env, answer, false, seq);
  556. int rcode;
  557. ConstElementPtr spec_data = parseAnswer(rcode, answer);
  558. if (rcode == 0 && spec_data) {
  559. // received OK, construct the spec out of it
  560. ModuleSpec spec = ModuleSpec(spec_data);
  561. if (module != spec.getModuleName()) {
  562. // It's a different module!
  563. isc_throw(CCSessionError, "Module name mismatch");
  564. }
  565. return (spec);
  566. } else {
  567. isc_throw(CCSessionError, "Error getting config for " +
  568. module + ": " + answer->str());
  569. }
  570. }
  571. }
  572. std::string
  573. ModuleCCSession::addRemoteConfig(const std::string& spec_name,
  574. void (*handler)(const std::string& module,
  575. ConstElementPtr,
  576. const ConfigData&),
  577. bool spec_is_filename)
  578. {
  579. // First get the module name, specification and default config
  580. const ModuleSpec rmod_spec(fetchRemoteSpec(spec_name, spec_is_filename));
  581. const std::string module_name(rmod_spec.getModuleName());
  582. ConfigData rmod_config(rmod_spec);
  583. // Get the current configuration values from config manager
  584. ConstElementPtr cmd(createCommand("get_config",
  585. Element::fromJSON("{\"module_name\": \"" +
  586. module_name + "\"}")));
  587. const unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  588. ConstElementPtr env, answer;
  589. session_.group_recvmsg(env, answer, false, seq);
  590. int rcode;
  591. ConstElementPtr new_config = parseAnswer(rcode, answer);
  592. ElementPtr local_config;
  593. if (rcode == 0 && new_config) {
  594. // Merge the received config into existing local config
  595. local_config = rmod_config.getLocalConfig();
  596. isc::data::merge(local_config, new_config);
  597. rmod_config.setLocalConfig(local_config);
  598. } else {
  599. isc_throw(CCSessionError, "Error getting config for " + module_name + ": " + answer->str());
  600. }
  601. // all ok, add it
  602. remote_module_configs_[module_name] = rmod_config;
  603. if (handler) {
  604. remote_module_handlers_[module_name] = handler;
  605. handler(module_name, local_config, rmod_config);
  606. }
  607. // Make sure we get updates in future
  608. session_.subscribe(module_name);
  609. return (module_name);
  610. }
  611. void
  612. ModuleCCSession::removeRemoteConfig(const std::string& module_name) {
  613. std::map<std::string, ConfigData>::iterator it;
  614. it = remote_module_configs_.find(module_name);
  615. if (it != remote_module_configs_.end()) {
  616. remote_module_configs_.erase(it);
  617. remote_module_handlers_.erase(module_name);
  618. session_.unsubscribe(module_name);
  619. }
  620. }
  621. ConstElementPtr
  622. ModuleCCSession::getRemoteConfigValue(const std::string& module_name,
  623. const std::string& identifier) const
  624. {
  625. std::map<std::string, ConfigData>::const_iterator it =
  626. remote_module_configs_.find(module_name);
  627. if (it != remote_module_configs_.end()) {
  628. return ((*it).second.getValue(identifier));
  629. } else {
  630. isc_throw(CCSessionError,
  631. "Remote module " + module_name + " not found.");
  632. }
  633. }
  634. void
  635. ModuleCCSession::updateRemoteConfig(const std::string& module_name,
  636. ConstElementPtr new_config)
  637. {
  638. std::map<std::string, ConfigData>::iterator it;
  639. it = remote_module_configs_.find(module_name);
  640. if (it != remote_module_configs_.end()) {
  641. ElementPtr rconf = (*it).second.getLocalConfig();
  642. isc::data::merge(rconf, new_config);
  643. std::map<std::string, RemoteHandler>::iterator hit =
  644. remote_module_handlers_.find(module_name);
  645. if (hit != remote_module_handlers_.end()) {
  646. hit->second(module_name, new_config, it->second);
  647. }
  648. }
  649. }
  650. }
  651. }