ccsession.cc 15 KB

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