session.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 <cc/session_config.h>
  16. #include <cc/logger.h>
  17. #include <stdint.h>
  18. // XXX: there seems to be a strange dependency between ASIO and std library
  19. // definitions. On some platforms if we include std headers before ASIO
  20. // headers unexpected behaviors will happen.
  21. // A middle term solution is to generalize our local wrapper interface
  22. // (currently only available for the auth server), where all such portability
  23. // issues are hidden, and to have other modules use the wrapper.
  24. #include <unistd.h> // for some IPC/network system calls
  25. #include <asio.hpp>
  26. #include <asio/error_code.hpp>
  27. #include <asio/deadline_timer.hpp>
  28. #include <asio/system_error.hpp>
  29. #include <cstdio>
  30. #include <vector>
  31. #include <iostream>
  32. #include <sstream>
  33. #include <sys/un.h>
  34. #include <boost/bind.hpp>
  35. #include <boost/optional.hpp>
  36. #include <boost/function.hpp>
  37. #include <boost/date_time/posix_time/posix_time_types.hpp>
  38. #include <exceptions/exceptions.h>
  39. #include <cc/data.h>
  40. #include <cc/session.h>
  41. using namespace std;
  42. using namespace isc::cc;
  43. using namespace isc::data;
  44. // some of the asio names conflict with socket API system calls
  45. // (e.g. write(2)) so we don't import the entire asio namespace.
  46. using asio::io_service;
  47. namespace {
  48. /// \brief Sets the given Optional 'result' to the given error code
  49. /// Used as a callback for emulating sync reads with async calls
  50. /// \param result Pointer to the optional to set
  51. /// \param err The error code to set it to
  52. void
  53. setResult(boost::optional<asio::error_code>* result,
  54. const asio::error_code& err)
  55. {
  56. result->reset(err);
  57. }
  58. }
  59. namespace isc {
  60. namespace cc {
  61. class SessionImpl {
  62. public:
  63. SessionImpl(io_service& io_service) :
  64. sequence_(-1), queue_(Element::createList()),
  65. io_service_(io_service), socket_(io_service_), data_length_(0),
  66. timeout_(MSGQ_DEFAULT_TIMEOUT)
  67. {}
  68. void establish(const char& socket_file);
  69. void disconnect();
  70. void writeData(const void* data, size_t datalen);
  71. size_t readDataLength();
  72. // Blocking read. Will throw a SessionTimeout if the timeout value
  73. // (in seconds) is thrown. If timeout is 0 it will block forever
  74. void readData(void* data, size_t datalen);
  75. void startRead(boost::function<void()> user_handler);
  76. void setTimeout(size_t seconds) { timeout_ = seconds; };
  77. size_t getTimeout() const { return timeout_; };
  78. long int sequence_; // the next sequence number to use
  79. std::string lname_;
  80. ElementPtr queue_;
  81. private:
  82. void internalRead(const asio::error_code& error,
  83. size_t bytes_transferred);
  84. private:
  85. io_service& io_service_;
  86. asio::local::stream_protocol::socket socket_;
  87. uint32_t data_length_;
  88. boost::function<void()> user_handler_;
  89. asio::error_code error_;
  90. size_t timeout_;
  91. // By default, unless changed or disabled, blocking reads on
  92. // the msgq channel will time out after 4 seconds in this
  93. // implementation.
  94. // This number is chosen to be low enough so that whatever
  95. // component is blocking does not seem to be hanging, but
  96. // still gives enough time for other modules to respond if they
  97. // are busy. If this choice turns out to be a bad one, we can
  98. // change it later.
  99. static const size_t MSGQ_DEFAULT_TIMEOUT = 4000;
  100. };
  101. void
  102. SessionImpl::establish(const char& socket_file) {
  103. try {
  104. socket_.connect(asio::local::stream_protocol::endpoint(&socket_file),
  105. error_);
  106. } catch(const asio::system_error& se) {
  107. LOG_FATAL(logger, CC_CONN_ERROR).arg(se.what());
  108. isc_throw(SessionError, se.what());
  109. }
  110. if (error_) {
  111. LOG_FATAL(logger, CC_NO_MSGQ).arg(error_.message());
  112. isc_throw(SessionError, "Unable to connect to message queue: " <<
  113. error_.message());
  114. }
  115. }
  116. void
  117. SessionImpl::disconnect() {
  118. socket_.close();
  119. data_length_ = 0;
  120. }
  121. void
  122. SessionImpl::writeData(const void* data, size_t datalen) {
  123. try {
  124. asio::write(socket_, asio::buffer(data, datalen));
  125. } catch (const asio::system_error& asio_ex) {
  126. LOG_FATAL(logger, CC_WRITE_ERROR).arg(asio_ex.what());
  127. isc_throw(SessionError, "ASIO write failed: " << asio_ex.what());
  128. }
  129. }
  130. size_t
  131. SessionImpl::readDataLength() {
  132. size_t ret_len = data_length_;
  133. if (ret_len == 0) {
  134. readData(&data_length_, sizeof(data_length_));
  135. if (data_length_ == 0) {
  136. LOG_ERROR(logger, CC_LENGTH_NOT_READY);
  137. isc_throw(SessionError, "ASIO read: data length is not ready");
  138. }
  139. ret_len = ntohl(data_length_);
  140. }
  141. data_length_ = 0;
  142. return (ret_len);
  143. }
  144. void
  145. SessionImpl::readData(void* data, size_t datalen) {
  146. boost::optional<asio::error_code> read_result;
  147. boost::optional<asio::error_code> timer_result;
  148. try {
  149. asio::async_read(socket_, asio::buffer(data, datalen),
  150. boost::bind(&setResult, &read_result, _1));
  151. asio::deadline_timer timer(socket_.io_service());
  152. if (getTimeout() != 0) {
  153. timer.expires_from_now(boost::posix_time::milliseconds(getTimeout()));
  154. timer.async_wait(boost::bind(&setResult, &timer_result, _1));
  155. }
  156. // wait until either we have read the data we want, the
  157. // timer expires, or one of the two is triggered with an error.
  158. // When one of them has a result, cancel the other, and wait
  159. // until the cancel is processed before we continue
  160. while (!read_result && !timer_result) {
  161. socket_.io_service().run_one();
  162. // Don't cancel the timer if we haven't set it
  163. if (read_result && getTimeout() != 0) {
  164. timer.cancel();
  165. while (!timer_result) {
  166. socket_.io_service().run_one();
  167. }
  168. } else if (timer_result) {
  169. socket_.cancel();
  170. while (!read_result) {
  171. socket_.io_service().run_one();
  172. }
  173. }
  174. }
  175. // asio::error_code evaluates to false if there was no error
  176. if (*read_result) {
  177. if (*read_result == asio::error::operation_aborted) {
  178. LOG_ERROR(logger, CC_TIMEOUT);
  179. isc_throw(SessionTimeout,
  180. "Timeout while reading data from cc session");
  181. } else {
  182. LOG_ERROR(logger, CC_READ_ERROR).arg(read_result->message());
  183. isc_throw(SessionError,
  184. "Error while reading data from cc session: " <<
  185. read_result->message());
  186. }
  187. }
  188. } catch (const asio::system_error& asio_ex) {
  189. // to hide ASIO specific exceptions, we catch them explicitly
  190. // and convert it to SessionError.
  191. LOG_FATAL(logger, CC_READ_EXCEPTION).arg(asio_ex.what());
  192. isc_throw(SessionError, "ASIO read failed: " << asio_ex.what());
  193. }
  194. }
  195. void
  196. SessionImpl::startRead(boost::function<void()> user_handler) {
  197. data_length_ = 0;
  198. user_handler_ = user_handler;
  199. asio::async_read(socket_, asio::buffer(&data_length_,
  200. sizeof(data_length_)),
  201. boost::bind(&SessionImpl::internalRead, this,
  202. asio::placeholders::error,
  203. asio::placeholders::bytes_transferred));
  204. }
  205. void
  206. SessionImpl::internalRead(const asio::error_code& error,
  207. size_t bytes_transferred)
  208. {
  209. if (!error) {
  210. assert(bytes_transferred == sizeof(data_length_));
  211. data_length_ = ntohl(data_length_);
  212. if (data_length_ == 0) {
  213. LOG_ERROR(logger, CC_ZERO_LENGTH);
  214. isc_throw(SessionError, "Invalid message length (0)");
  215. }
  216. user_handler_();
  217. } else {
  218. LOG_ERROR(logger, CC_ASYNC_READ_FAILED);
  219. isc_throw(SessionError, "asynchronous read failed");
  220. }
  221. }
  222. Session::Session(io_service& io_service) : impl_(new SessionImpl(io_service))
  223. {}
  224. Session::~Session() {
  225. delete impl_;
  226. }
  227. void
  228. Session::disconnect() {
  229. impl_->disconnect();
  230. }
  231. void
  232. Session::startRead(boost::function<void()> read_callback) {
  233. impl_->startRead(read_callback);
  234. }
  235. namespace { // maybe unnecessary.
  236. // This is a helper class to make the establish() method (below) exception-safe
  237. // with the RAII approach.
  238. class SessionHolder {
  239. public:
  240. SessionHolder(SessionImpl* obj) : impl_obj_(obj) {}
  241. ~SessionHolder()
  242. {
  243. if (impl_obj_ != NULL) {
  244. impl_obj_->disconnect();
  245. }
  246. }
  247. void clear() { impl_obj_ = NULL; }
  248. SessionImpl* impl_obj_;
  249. };
  250. }
  251. void
  252. Session::establish(const char* socket_file) {
  253. if (socket_file == NULL) {
  254. socket_file = getenv("BIND10_MSGQ_SOCKET_FILE");
  255. }
  256. if (socket_file == NULL) {
  257. socket_file = BIND10_MSGQ_SOCKET_FILE;
  258. }
  259. impl_->establish(*socket_file);
  260. // once established, encapsulate the implementation object so that we
  261. // can safely release the internal resource when exception happens
  262. // below.
  263. SessionHolder session_holder(impl_);
  264. //
  265. // send a request for our local name, and wait for a response
  266. //
  267. ConstElementPtr get_lname_msg =
  268. Element::fromJSON("{ \"type\": \"getlname\" }");
  269. sendmsg(get_lname_msg);
  270. ConstElementPtr routing, msg;
  271. recvmsg(routing, msg, false);
  272. impl_->lname_ = msg->get("lname")->stringValue();
  273. // At this point there's no risk of resource leak.
  274. session_holder.clear();
  275. }
  276. //
  277. // Convert to wire format and send this via the stream socket with its length
  278. // prefix.
  279. //
  280. void
  281. Session::sendmsg(ConstElementPtr msg) {
  282. std::string header_wire = msg->toWire();
  283. unsigned int length = 2 + header_wire.length();
  284. unsigned int length_net = htonl(length);
  285. unsigned short header_length = header_wire.length();
  286. unsigned short header_length_net = htons(header_length);
  287. impl_->writeData(&length_net, sizeof(length_net));
  288. impl_->writeData(&header_length_net, sizeof(header_length_net));
  289. impl_->writeData(header_wire.data(), header_length);
  290. }
  291. void
  292. Session::sendmsg(ConstElementPtr env, ConstElementPtr msg) {
  293. std::string header_wire = env->toWire();
  294. std::string body_wire = msg->toWire();
  295. unsigned int length = 2 + header_wire.length() + body_wire.length();
  296. unsigned int length_net = htonl(length);
  297. unsigned short header_length = header_wire.length();
  298. unsigned short header_length_net = htons(header_length);
  299. impl_->writeData(&length_net, sizeof(length_net));
  300. impl_->writeData(&header_length_net, sizeof(header_length_net));
  301. impl_->writeData(header_wire.data(), header_length);
  302. impl_->writeData(body_wire.data(), body_wire.length());
  303. }
  304. bool
  305. Session::recvmsg(ConstElementPtr& msg, bool nonblock, int seq) {
  306. ConstElementPtr l_env;
  307. return (recvmsg(l_env, msg, nonblock, seq));
  308. }
  309. bool
  310. Session::recvmsg(ConstElementPtr& env, ConstElementPtr& msg,
  311. bool nonblock, int seq)
  312. {
  313. size_t length = impl_->readDataLength();
  314. if (hasQueuedMsgs()) {
  315. ConstElementPtr q_el;
  316. for (int i = 0; i < impl_->queue_->size(); i++) {
  317. q_el = impl_->queue_->get(i);
  318. if (( seq == -1 &&
  319. !q_el->get(0)->contains("reply")
  320. ) || (
  321. q_el->get(0)->contains("reply") &&
  322. q_el->get(0)->get("reply")->intValue() == seq
  323. )
  324. ) {
  325. env = q_el->get(0);
  326. msg = q_el->get(1);
  327. impl_->queue_->remove(i);
  328. return (true);
  329. }
  330. }
  331. }
  332. unsigned short header_length_net;
  333. impl_->readData(&header_length_net, sizeof(header_length_net));
  334. unsigned short header_length = ntohs(header_length_net);
  335. if (header_length > length || length < 2) {
  336. LOG_ERROR(logger, CC_INVALID_LENGTHS).arg(length).arg(header_length);
  337. isc_throw(SessionError, "Length parameters invalid: total=" << length
  338. << ", header=" << header_length);
  339. }
  340. // remove the header-length bytes from the total length
  341. length -= 2;
  342. std::vector<char> buffer(length);
  343. impl_->readData(&buffer[0], length);
  344. std::string header_wire = std::string(&buffer[0], header_length);
  345. std::string body_wire = std::string(&buffer[0] + header_length,
  346. length - header_length);
  347. std::stringstream header_wire_stream;
  348. header_wire_stream << header_wire;
  349. ConstElementPtr l_env =
  350. Element::fromWire(header_wire_stream, header_length);
  351. std::stringstream body_wire_stream;
  352. body_wire_stream << body_wire;
  353. ConstElementPtr l_msg =
  354. Element::fromWire(body_wire_stream, length - header_length);
  355. if ((seq == -1 &&
  356. !l_env->contains("reply")
  357. ) || (
  358. l_env->contains("reply") &&
  359. l_env->get("reply")->intValue() == seq
  360. )
  361. ) {
  362. env = l_env;
  363. msg = l_msg;
  364. return (true);
  365. } else {
  366. ElementPtr q_el = Element::createList();
  367. q_el->add(l_env);
  368. q_el->add(l_msg);
  369. impl_->queue_->add(q_el);
  370. return (recvmsg(env, msg, nonblock, seq));
  371. }
  372. // XXXMLG handle non-block here, and return false for short reads
  373. }
  374. void
  375. Session::subscribe(std::string group, std::string instance) {
  376. ElementPtr env = Element::createMap();
  377. env->set("type", Element::create("subscribe"));
  378. env->set("group", Element::create(group));
  379. env->set("instance", Element::create(instance));
  380. sendmsg(env);
  381. }
  382. void
  383. Session::unsubscribe(std::string group, std::string instance) {
  384. ElementPtr env = Element::createMap();
  385. env->set("type", Element::create("unsubscribe"));
  386. env->set("group", Element::create(group));
  387. env->set("instance", Element::create(instance));
  388. sendmsg(env);
  389. }
  390. int
  391. Session::group_sendmsg(ConstElementPtr msg, std::string group,
  392. std::string instance, std::string to)
  393. {
  394. ElementPtr env = Element::createMap();
  395. long int nseq = ++impl_->sequence_;
  396. env->set("type", Element::create("send"));
  397. env->set("from", Element::create(impl_->lname_));
  398. env->set("to", Element::create(to));
  399. env->set("group", Element::create(group));
  400. env->set("instance", Element::create(instance));
  401. env->set("seq", Element::create(nseq));
  402. //env->set("msg", Element::create(msg->toWire()));
  403. sendmsg(env, msg);
  404. return (nseq);
  405. }
  406. bool
  407. Session::group_recvmsg(ConstElementPtr& envelope, ConstElementPtr& msg,
  408. bool nonblock, int seq)
  409. {
  410. return (recvmsg(envelope, msg, nonblock, seq));
  411. }
  412. int
  413. Session::reply(ConstElementPtr envelope, ConstElementPtr newmsg) {
  414. ElementPtr env = Element::createMap();
  415. long int nseq = ++impl_->sequence_;
  416. env->set("type", Element::create("send"));
  417. env->set("from", Element::create(impl_->lname_));
  418. env->set("to", Element::create(envelope->get("from")->stringValue()));
  419. env->set("group", Element::create(envelope->get("group")->stringValue()));
  420. env->set("instance", Element::create(envelope->get("instance")->stringValue()));
  421. env->set("seq", Element::create(nseq));
  422. env->set("reply", Element::create(envelope->get("seq")->intValue()));
  423. sendmsg(env, newmsg);
  424. return (nseq);
  425. }
  426. bool
  427. Session::hasQueuedMsgs() const {
  428. return (impl_->queue_->size() > 0);
  429. }
  430. void
  431. Session::setTimeout(size_t milliseconds) {
  432. impl_->setTimeout(milliseconds);
  433. }
  434. size_t
  435. Session::getTimeout() const {
  436. return (impl_->getTimeout());
  437. }
  438. }
  439. }