ccsession.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. using namespace std;
  32. using isc::data::Element;
  33. using isc::data::ConstElementPtr;
  34. using isc::data::ElementPtr;
  35. using isc::data::JSONError;
  36. namespace isc {
  37. namespace config {
  38. /// Creates a standard config/command protocol answer message
  39. ConstElementPtr
  40. createAnswer() {
  41. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  42. ElementPtr answer_content = Element::createList();
  43. answer_content->add(Element::create(0));
  44. answer->set("result", answer_content);
  45. return (answer);
  46. }
  47. ConstElementPtr
  48. createAnswer(const int rcode, ConstElementPtr arg) {
  49. if (rcode != 0 && (!arg || arg->getType() != Element::string)) {
  50. isc_throw(CCSessionError, "Bad or no argument for rcode != 0");
  51. }
  52. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  53. ElementPtr answer_content = Element::createList();
  54. answer_content->add(Element::create(rcode));
  55. answer_content->add(arg);
  56. answer->set("result", answer_content);
  57. return (answer);
  58. }
  59. ConstElementPtr
  60. createAnswer(const int rcode, const std::string& arg) {
  61. ElementPtr answer = Element::fromJSON("{\"result\": [] }");
  62. ElementPtr answer_content = Element::createList();
  63. answer_content->add(Element::create(rcode));
  64. answer_content->add(Element::create(arg));
  65. answer->set("result", answer_content);
  66. return (answer);
  67. }
  68. ConstElementPtr
  69. parseAnswer(int &rcode, ConstElementPtr msg) {
  70. if (msg &&
  71. msg->getType() == Element::map &&
  72. msg->contains("result")) {
  73. ConstElementPtr result = msg->get("result");
  74. if (result->getType() != Element::list) {
  75. isc_throw(CCSessionError, "Result element in answer message is not a list");
  76. } else if (result->get(0)->getType() != Element::integer) {
  77. isc_throw(CCSessionError, "First element of result is not an rcode in answer message");
  78. }
  79. rcode = result->get(0)->intValue();
  80. if (result->size() > 1) {
  81. if (rcode == 0 || result->get(1)->getType() == Element::string) {
  82. return (result->get(1));
  83. } else {
  84. isc_throw(CCSessionError, "Error description in result with rcode != 0 is not a string");
  85. }
  86. } else {
  87. if (rcode == 0) {
  88. return (ElementPtr());
  89. } else {
  90. isc_throw(CCSessionError, "Result with rcode != 0 does not have an error description");
  91. }
  92. }
  93. } else {
  94. isc_throw(CCSessionError, "No result part in answer message");
  95. }
  96. }
  97. ConstElementPtr
  98. createCommand(const std::string& command) {
  99. return (createCommand(command, ElementPtr()));
  100. }
  101. ConstElementPtr
  102. createCommand(const std::string& command, ConstElementPtr arg) {
  103. ElementPtr cmd = Element::createMap();
  104. ElementPtr cmd_parts = Element::createList();
  105. cmd_parts->add(Element::create(command));
  106. if (arg) {
  107. cmd_parts->add(arg);
  108. }
  109. cmd->set("command", cmd_parts);
  110. return (cmd);
  111. }
  112. std::string
  113. parseCommand(ConstElementPtr& arg, ConstElementPtr command) {
  114. if (command &&
  115. command->getType() == Element::map &&
  116. command->contains("command")) {
  117. ConstElementPtr cmd = command->get("command");
  118. if (cmd->getType() == Element::list &&
  119. cmd->size() > 0 &&
  120. cmd->get(0)->getType() == Element::string) {
  121. if (cmd->size() > 1) {
  122. arg = cmd->get(1);
  123. } else {
  124. arg = Element::createMap();
  125. }
  126. return (cmd->get(0)->stringValue());
  127. } else {
  128. isc_throw(CCSessionError, "Command part in command message missing, empty, or not a list");
  129. }
  130. } else {
  131. isc_throw(CCSessionError, "Command Element empty or not a map with \"command\"");
  132. }
  133. }
  134. ModuleSpec
  135. ModuleCCSession::readModuleSpecification(const std::string& filename) {
  136. std::ifstream file;
  137. ModuleSpec module_spec;
  138. // this file should be declared in a @something@ directive
  139. file.open(filename.c_str());
  140. if (!file) {
  141. LOG_ERROR(config_logger, CONFIG_FOPEN_ERR).arg(filename).arg(strerror(errno));
  142. isc_throw(CCSessionInitError, strerror(errno));
  143. }
  144. try {
  145. module_spec = moduleSpecFromFile(file, true);
  146. } catch (const JSONError& pe) {
  147. LOG_ERROR(config_logger, CONFIG_JSON_PARSE).arg(filename).arg(pe.what());
  148. isc_throw(CCSessionInitError, pe.what());
  149. } catch (const ModuleSpecError& dde) {
  150. LOG_ERROR(config_logger, CONFIG_MODULE_SPEC).arg(filename).arg(dde.what());
  151. isc_throw(CCSessionInitError, dde.what());
  152. }
  153. file.close();
  154. return (module_spec);
  155. }
  156. void
  157. ModuleCCSession::startCheck() {
  158. // data available on the command channel. process it in the synchronous
  159. // mode.
  160. checkCommand();
  161. // start asynchronous read again.
  162. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  163. }
  164. ModuleCCSession::ModuleCCSession(
  165. const std::string& spec_file_name,
  166. isc::cc::AbstractSession& session,
  167. isc::data::ConstElementPtr(*config_handler)(
  168. isc::data::ConstElementPtr new_config),
  169. isc::data::ConstElementPtr(*command_handler)(
  170. const std::string& command, isc::data::ConstElementPtr args)
  171. ) :
  172. session_(session)
  173. {
  174. module_specification_ = readModuleSpecification(spec_file_name);
  175. setModuleSpec(module_specification_);
  176. module_name_ = module_specification_.getFullSpec()->get("module_name")->stringValue();
  177. config_handler_ = config_handler;
  178. command_handler_ = command_handler;
  179. session_.establish(NULL);
  180. session_.subscribe(module_name_, "*");
  181. //session_.subscribe("Boss", "*");
  182. //session_.subscribe("statistics", "*");
  183. // send the data specification
  184. ConstElementPtr spec_msg = createCommand("module_spec",
  185. module_specification_.getFullSpec());
  186. unsigned int seq = session_.group_sendmsg(spec_msg, "ConfigManager");
  187. ConstElementPtr answer, env;
  188. session_.group_recvmsg(env, answer, false, seq);
  189. int rcode;
  190. ConstElementPtr err = parseAnswer(rcode, answer);
  191. if (rcode != 0) {
  192. LOG_ERROR(config_logger, CONFIG_MANAGER_MOD_SPEC).arg(answer->str());
  193. isc_throw(CCSessionInitError, answer->str());
  194. }
  195. setLocalConfig(Element::fromJSON("{}"));
  196. // get any stored configuration from the manager
  197. if (config_handler_) {
  198. ConstElementPtr cmd = Element::fromJSON("{ \"command\": [\"get_config\", {\"module_name\":\"" + module_name_ + "\"} ] }");
  199. seq = session_.group_sendmsg(cmd, "ConfigManager");
  200. session_.group_recvmsg(env, answer, false, seq);
  201. ConstElementPtr new_config = parseAnswer(rcode, answer);
  202. if (rcode == 0) {
  203. handleConfigUpdate(new_config);
  204. } else {
  205. LOG_ERROR(config_logger, CONFIG_MANAGER_CONFIG).arg(new_config->str());
  206. isc_throw(CCSessionInitError, answer->str());
  207. }
  208. }
  209. // register callback for asynchronous read
  210. session_.startRead(boost::bind(&ModuleCCSession::startCheck, this));
  211. }
  212. /// Validates the new config values, if they are correct,
  213. /// call the config handler with the values that have changed
  214. /// If that results in success, store the new config
  215. ConstElementPtr
  216. ModuleCCSession::handleConfigUpdate(ConstElementPtr new_config) {
  217. ConstElementPtr answer;
  218. ElementPtr errors = Element::createList();
  219. if (!config_handler_) {
  220. answer = createAnswer(1, module_name_ + " does not have a config handler");
  221. } else if (!module_specification_.validateConfig(new_config, false,
  222. errors)) {
  223. std::stringstream ss;
  224. ss << "Error in config validation: ";
  225. BOOST_FOREACH(ConstElementPtr error, errors->listValue()) {
  226. ss << error->stringValue();
  227. }
  228. answer = createAnswer(2, ss.str());
  229. } else {
  230. // remove the values that have not changed
  231. ConstElementPtr diff = removeIdentical(new_config, getLocalConfig());
  232. // handle config update
  233. answer = config_handler_(diff);
  234. int rcode;
  235. parseAnswer(rcode, answer);
  236. if (rcode == 0) {
  237. ElementPtr local_config = getLocalConfig();
  238. isc::data::merge(local_config, diff);
  239. setLocalConfig(local_config);
  240. }
  241. }
  242. return (answer);
  243. }
  244. bool
  245. ModuleCCSession::hasQueuedMsgs() const {
  246. return (session_.hasQueuedMsgs());
  247. }
  248. ConstElementPtr
  249. ModuleCCSession::checkConfigUpdateCommand(const std::string& target_module,
  250. ConstElementPtr arg)
  251. {
  252. if (target_module == module_name_) {
  253. return (handleConfigUpdate(arg));
  254. } else {
  255. // ok this update is not for us, if we have this module
  256. // in our remote config list, update that
  257. updateRemoteConfig(target_module, arg);
  258. // we're not supposed to answer to this, so return
  259. return (ElementPtr());
  260. }
  261. }
  262. ConstElementPtr
  263. ModuleCCSession::checkModuleCommand(const std::string& cmd_str,
  264. const std::string& target_module,
  265. ConstElementPtr arg) const
  266. {
  267. if (target_module == module_name_) {
  268. if (command_handler_) {
  269. ElementPtr errors = Element::createList();
  270. if (module_specification_.validateCommand(cmd_str,
  271. arg,
  272. errors)) {
  273. return (command_handler_(cmd_str, arg));
  274. } else {
  275. std::stringstream ss;
  276. ss << "Error in command validation: ";
  277. BOOST_FOREACH(ConstElementPtr error,
  278. errors->listValue()) {
  279. ss << error->stringValue();
  280. }
  281. return (createAnswer(3, ss.str()));
  282. }
  283. } else {
  284. return (createAnswer(1,
  285. "Command given but no "
  286. "command handler for module"));
  287. }
  288. }
  289. return (ElementPtr());
  290. }
  291. int
  292. ModuleCCSession::checkCommand() {
  293. ConstElementPtr cmd, routing, data;
  294. if (session_.group_recvmsg(routing, data, true)) {
  295. /* ignore result messages (in case we're out of sync, to prevent
  296. * pingpongs */
  297. if (data->getType() != Element::map || data->contains("result")) {
  298. return (0);
  299. }
  300. ConstElementPtr arg;
  301. ConstElementPtr answer;
  302. try {
  303. std::string cmd_str = parseCommand(arg, data);
  304. std::string target_module = routing->get("group")->stringValue();
  305. if (cmd_str == "config_update") {
  306. answer = checkConfigUpdateCommand(target_module, arg);
  307. } else {
  308. answer = checkModuleCommand(cmd_str, target_module, arg);
  309. }
  310. } catch (const CCSessionError& re) {
  311. LOG_ERROR(config_logger, CONFIG_CCSESSION_MSG).arg(re.what());
  312. }
  313. if (!isNull(answer)) {
  314. session_.reply(routing, answer);
  315. }
  316. }
  317. return (0);
  318. }
  319. std::string
  320. ModuleCCSession::addRemoteConfig(const std::string& spec_name,
  321. void (*handler)(const std::string& module,
  322. ConstElementPtr),
  323. bool spec_is_filename)
  324. {
  325. std::string module_name;
  326. ModuleSpec rmod_spec;
  327. if (spec_is_filename) {
  328. // It's a file name, so load it
  329. rmod_spec = readModuleSpecification(spec_name);
  330. module_name =
  331. rmod_spec.getFullSpec()->get("module_name")->stringValue();
  332. } else {
  333. // It's module name, request it from config manager
  334. ConstElementPtr cmd = Element::fromJSON("{ \"command\": ["
  335. "\"get_module_spec\","
  336. "{\"module_name\": \"" +
  337. module_name + "\"} ] }");
  338. unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  339. ConstElementPtr env, answer;
  340. session_.group_recvmsg(env, answer, false, seq);
  341. int rcode;
  342. ConstElementPtr spec_data = parseAnswer(rcode, answer);
  343. if (rcode == 0 && spec_data) {
  344. rmod_spec = ModuleSpec(spec_data);
  345. module_name = spec_name;
  346. if (module_name != rmod_spec.getModuleName()) {
  347. isc_throw(CCSessionError, "Module name mismatch");
  348. }
  349. } else {
  350. isc_throw(CCSessionError, "Error getting config for " + module_name + ": " + answer->str());
  351. }
  352. }
  353. ConfigData rmod_config = ConfigData(rmod_spec);
  354. // Get the current configuration values for that module
  355. ConstElementPtr cmd = Element::fromJSON("{ \"command\": [\"get_config\", {\"module_name\":\"" + module_name + "\"} ] }");
  356. unsigned int seq = session_.group_sendmsg(cmd, "ConfigManager");
  357. ConstElementPtr env, answer;
  358. session_.group_recvmsg(env, answer, false, seq);
  359. int rcode;
  360. ConstElementPtr new_config = parseAnswer(rcode, answer);
  361. ElementPtr local_config;
  362. if (rcode == 0 && new_config) {
  363. local_config = rmod_config.getLocalConfig();
  364. isc::data::merge(local_config, new_config);
  365. rmod_config.setLocalConfig(local_config);
  366. } else {
  367. isc_throw(CCSessionError, "Error getting config for " + module_name + ": " + answer->str());
  368. }
  369. // all ok, add it
  370. remote_module_configs_[module_name] = rmod_config;
  371. if (handler) {
  372. remote_module_handlers_[module_name] = handler;
  373. handler(module_name, local_config);
  374. }
  375. session_.subscribe(module_name);
  376. return (module_name);
  377. }
  378. void
  379. ModuleCCSession::removeRemoteConfig(const std::string& module_name) {
  380. std::map<std::string, ConfigData>::iterator it;
  381. it = remote_module_configs_.find(module_name);
  382. if (it != remote_module_configs_.end()) {
  383. remote_module_configs_.erase(it);
  384. remote_module_handlers_.erase(module_name);
  385. session_.unsubscribe(module_name);
  386. }
  387. }
  388. ConstElementPtr
  389. ModuleCCSession::getRemoteConfigValue(const std::string& module_name,
  390. const std::string& identifier) const
  391. {
  392. std::map<std::string, ConfigData>::const_iterator it =
  393. remote_module_configs_.find(module_name);
  394. if (it != remote_module_configs_.end()) {
  395. return ((*it).second.getValue(identifier));
  396. } else {
  397. isc_throw(CCSessionError,
  398. "Remote module " + module_name + " not found.");
  399. }
  400. }
  401. void
  402. ModuleCCSession::updateRemoteConfig(const std::string& module_name,
  403. ConstElementPtr new_config)
  404. {
  405. std::map<std::string, ConfigData>::iterator it;
  406. it = remote_module_configs_.find(module_name);
  407. if (it != remote_module_configs_.end()) {
  408. ElementPtr rconf = (*it).second.getLocalConfig();
  409. isc::data::merge(rconf, new_config);
  410. std::map<std::string, RemoteHandler>::iterator hit =
  411. remote_module_handlers_.find(module_name);
  412. if (hit != remote_module_handlers_.end()) {
  413. hit->second(module_name, new_config);
  414. }
  415. }
  416. }
  417. }
  418. }