session.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. // $Id$
  15. #include <config.h>
  16. #include <cc/session_config.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. isc_throw(SessionError, se.what());
  108. }
  109. if (error_) {
  110. isc_throw(SessionError, "Unable to connect to message queue: " <<
  111. error_.message());
  112. }
  113. }
  114. void
  115. SessionImpl::disconnect() {
  116. socket_.close();
  117. data_length_ = 0;
  118. }
  119. void
  120. SessionImpl::writeData(const void* data, size_t datalen) {
  121. try {
  122. asio::write(socket_, asio::buffer(data, datalen));
  123. } catch (const asio::system_error& asio_ex) {
  124. isc_throw(SessionError, "ASIO write failed: " << asio_ex.what());
  125. }
  126. }
  127. size_t
  128. SessionImpl::readDataLength() {
  129. size_t ret_len = data_length_;
  130. if (ret_len == 0) {
  131. readData(&data_length_, sizeof(data_length_));
  132. if (data_length_ == 0) {
  133. isc_throw(SessionError, "ASIO read: data length is not ready");
  134. }
  135. ret_len = ntohl(data_length_);
  136. }
  137. data_length_ = 0;
  138. return (ret_len);
  139. }
  140. void
  141. SessionImpl::readData(void* data, size_t datalen) {
  142. boost::optional<asio::error_code> read_result;
  143. boost::optional<asio::error_code> timer_result;
  144. try {
  145. asio::async_read(socket_, asio::buffer(data, datalen),
  146. boost::bind(&setResult, &read_result, _1));
  147. asio::deadline_timer timer(socket_.io_service());
  148. if (getTimeout() != 0) {
  149. timer.expires_from_now(boost::posix_time::milliseconds(getTimeout()));
  150. timer.async_wait(boost::bind(&setResult, &timer_result, _1));
  151. }
  152. // wait until either we have read the data we want, the
  153. // timer expires, or one of the two is triggered with an error.
  154. // When one of them has a result, cancel the other, and wait
  155. // until the cancel is processed before we continue
  156. while (!read_result && !timer_result) {
  157. socket_.io_service().run_one();
  158. // Don't cancel the timer if we haven't set it
  159. if (read_result && getTimeout() != 0) {
  160. timer.cancel();
  161. while (!timer_result) {
  162. socket_.io_service().run_one();
  163. }
  164. } else if (timer_result) {
  165. socket_.cancel();
  166. while (!read_result) {
  167. socket_.io_service().run_one();
  168. }
  169. }
  170. }
  171. // asio::error_code evaluates to false if there was no error
  172. if (*read_result) {
  173. if (*read_result == asio::error::operation_aborted) {
  174. isc_throw(SessionTimeout,
  175. "Timeout while reading data from cc session");
  176. } else {
  177. isc_throw(SessionError,
  178. "Error while reading data from cc session: " <<
  179. read_result->message());
  180. }
  181. }
  182. } catch (const asio::system_error& asio_ex) {
  183. // to hide ASIO specific exceptions, we catch them explicitly
  184. // and convert it to SessionError.
  185. isc_throw(SessionError, "ASIO read failed: " << asio_ex.what());
  186. }
  187. }
  188. void
  189. SessionImpl::startRead(boost::function<void()> user_handler) {
  190. data_length_ = 0;
  191. user_handler_ = user_handler;
  192. asio::async_read(socket_, asio::buffer(&data_length_,
  193. sizeof(data_length_)),
  194. boost::bind(&SessionImpl::internalRead, this,
  195. asio::placeholders::error,
  196. asio::placeholders::bytes_transferred));
  197. }
  198. void
  199. SessionImpl::internalRead(const asio::error_code& error,
  200. size_t bytes_transferred)
  201. {
  202. if (!error) {
  203. assert(bytes_transferred == sizeof(data_length_));
  204. data_length_ = ntohl(data_length_);
  205. if (data_length_ == 0) {
  206. isc_throw(SessionError, "Invalid message length (0)");
  207. }
  208. user_handler_();
  209. } else {
  210. isc_throw(SessionError, "asynchronous read failed");
  211. }
  212. }
  213. Session::Session(io_service& io_service) : impl_(new SessionImpl(io_service))
  214. {}
  215. Session::~Session() {
  216. delete impl_;
  217. }
  218. void
  219. Session::disconnect() {
  220. impl_->disconnect();
  221. }
  222. void
  223. Session::startRead(boost::function<void()> read_callback) {
  224. impl_->startRead(read_callback);
  225. }
  226. namespace { // maybe unnecessary.
  227. // This is a helper class to make the establish() method (below) exception-safe
  228. // with the RAII approach.
  229. class SessionHolder {
  230. public:
  231. SessionHolder(SessionImpl* obj) : impl_obj_(obj) {}
  232. ~SessionHolder()
  233. {
  234. if (impl_obj_ != NULL) {
  235. impl_obj_->disconnect();
  236. }
  237. }
  238. void clear() { impl_obj_ = NULL; }
  239. SessionImpl* impl_obj_;
  240. };
  241. }
  242. void
  243. Session::establish(const char* socket_file) {
  244. if (socket_file == NULL) {
  245. socket_file = getenv("BIND10_MSGQ_SOCKET_FILE");
  246. }
  247. if (socket_file == NULL) {
  248. socket_file = BIND10_MSGQ_SOCKET_FILE;
  249. }
  250. impl_->establish(*socket_file);
  251. // once established, encapsulate the implementation object so that we
  252. // can safely release the internal resource when exception happens
  253. // below.
  254. SessionHolder session_holder(impl_);
  255. //
  256. // send a request for our local name, and wait for a response
  257. //
  258. ConstElementPtr get_lname_msg =
  259. Element::fromJSON("{ \"type\": \"getlname\" }");
  260. sendmsg(get_lname_msg);
  261. ConstElementPtr routing, msg;
  262. recvmsg(routing, msg, false);
  263. impl_->lname_ = msg->get("lname")->stringValue();
  264. // At this point there's no risk of resource leak.
  265. session_holder.clear();
  266. }
  267. //
  268. // Convert to wire format and send this via the stream socket with its length
  269. // prefix.
  270. //
  271. void
  272. Session::sendmsg(ConstElementPtr msg) {
  273. std::string header_wire = msg->toWire();
  274. unsigned int length = 2 + header_wire.length();
  275. unsigned int length_net = htonl(length);
  276. unsigned short header_length = header_wire.length();
  277. unsigned short header_length_net = htons(header_length);
  278. impl_->writeData(&length_net, sizeof(length_net));
  279. impl_->writeData(&header_length_net, sizeof(header_length_net));
  280. impl_->writeData(header_wire.data(), header_length);
  281. }
  282. void
  283. Session::sendmsg(ConstElementPtr env, ConstElementPtr msg) {
  284. std::string header_wire = env->toWire();
  285. std::string body_wire = msg->toWire();
  286. unsigned int length = 2 + header_wire.length() + body_wire.length();
  287. unsigned int length_net = htonl(length);
  288. unsigned short header_length = header_wire.length();
  289. unsigned short header_length_net = htons(header_length);
  290. impl_->writeData(&length_net, sizeof(length_net));
  291. impl_->writeData(&header_length_net, sizeof(header_length_net));
  292. impl_->writeData(header_wire.data(), header_length);
  293. impl_->writeData(body_wire.data(), body_wire.length());
  294. }
  295. bool
  296. Session::recvmsg(ConstElementPtr& msg, bool nonblock, int seq) {
  297. ConstElementPtr l_env;
  298. return (recvmsg(l_env, msg, nonblock, seq));
  299. }
  300. bool
  301. Session::recvmsg(ConstElementPtr& env, ConstElementPtr& msg,
  302. bool nonblock, int seq)
  303. {
  304. size_t length = impl_->readDataLength();
  305. if (hasQueuedMsgs()) {
  306. ConstElementPtr q_el;
  307. for (int i = 0; i < impl_->queue_->size(); i++) {
  308. q_el = impl_->queue_->get(i);
  309. if (( seq == -1 &&
  310. !q_el->get(0)->contains("reply")
  311. ) || (
  312. q_el->get(0)->contains("reply") &&
  313. q_el->get(0)->get("reply")->intValue() == seq
  314. )
  315. ) {
  316. env = q_el->get(0);
  317. msg = q_el->get(1);
  318. impl_->queue_->remove(i);
  319. return (true);
  320. }
  321. }
  322. }
  323. unsigned short header_length_net;
  324. impl_->readData(&header_length_net, sizeof(header_length_net));
  325. unsigned short header_length = ntohs(header_length_net);
  326. if (header_length > length || length < 2) {
  327. isc_throw(SessionError, "Length parameters invalid: total=" << length
  328. << ", header=" << header_length);
  329. }
  330. // remove the header-length bytes from the total length
  331. length -= 2;
  332. std::vector<char> buffer(length);
  333. impl_->readData(&buffer[0], length);
  334. std::string header_wire = std::string(&buffer[0], header_length);
  335. std::string body_wire = std::string(&buffer[0] + header_length,
  336. length - header_length);
  337. std::stringstream header_wire_stream;
  338. header_wire_stream << header_wire;
  339. ConstElementPtr l_env =
  340. Element::fromWire(header_wire_stream, header_length);
  341. std::stringstream body_wire_stream;
  342. body_wire_stream << body_wire;
  343. ConstElementPtr l_msg =
  344. Element::fromWire(body_wire_stream, length - header_length);
  345. if ((seq == -1 &&
  346. !l_env->contains("reply")
  347. ) || (
  348. l_env->contains("reply") &&
  349. l_env->get("reply")->intValue() == seq
  350. )
  351. ) {
  352. env = l_env;
  353. msg = l_msg;
  354. return (true);
  355. } else {
  356. ElementPtr q_el = Element::createList();
  357. q_el->add(l_env);
  358. q_el->add(l_msg);
  359. impl_->queue_->add(q_el);
  360. return (recvmsg(env, msg, nonblock, seq));
  361. }
  362. // XXXMLG handle non-block here, and return false for short reads
  363. }
  364. void
  365. Session::subscribe(std::string group, std::string instance) {
  366. ElementPtr env = Element::createMap();
  367. env->set("type", Element::create("subscribe"));
  368. env->set("group", Element::create(group));
  369. env->set("instance", Element::create(instance));
  370. sendmsg(env);
  371. }
  372. void
  373. Session::unsubscribe(std::string group, std::string instance) {
  374. ElementPtr env = Element::createMap();
  375. env->set("type", Element::create("unsubscribe"));
  376. env->set("group", Element::create(group));
  377. env->set("instance", Element::create(instance));
  378. sendmsg(env);
  379. }
  380. int
  381. Session::group_sendmsg(ConstElementPtr msg, std::string group,
  382. std::string instance, std::string to)
  383. {
  384. ElementPtr env = Element::createMap();
  385. long int nseq = ++impl_->sequence_;
  386. env->set("type", Element::create("send"));
  387. env->set("from", Element::create(impl_->lname_));
  388. env->set("to", Element::create(to));
  389. env->set("group", Element::create(group));
  390. env->set("instance", Element::create(instance));
  391. env->set("seq", Element::create(nseq));
  392. //env->set("msg", Element::create(msg->toWire()));
  393. sendmsg(env, msg);
  394. return (nseq);
  395. }
  396. bool
  397. Session::group_recvmsg(ConstElementPtr& envelope, ConstElementPtr& msg,
  398. bool nonblock, int seq)
  399. {
  400. return (recvmsg(envelope, msg, nonblock, seq));
  401. }
  402. int
  403. Session::reply(ConstElementPtr envelope, ConstElementPtr newmsg) {
  404. ElementPtr env = Element::createMap();
  405. long int nseq = ++impl_->sequence_;
  406. env->set("type", Element::create("send"));
  407. env->set("from", Element::create(impl_->lname_));
  408. env->set("to", Element::create(envelope->get("from")->stringValue()));
  409. env->set("group", Element::create(envelope->get("group")->stringValue()));
  410. env->set("instance", Element::create(envelope->get("instance")->stringValue()));
  411. env->set("seq", Element::create(nseq));
  412. env->set("reply", Element::create(envelope->get("seq")->intValue()));
  413. sendmsg(env, newmsg);
  414. return (nseq);
  415. }
  416. bool
  417. Session::hasQueuedMsgs() const {
  418. return (impl_->queue_->size() > 0);
  419. }
  420. void
  421. Session::setTimeout(size_t milliseconds) {
  422. impl_->setTimeout(milliseconds);
  423. }
  424. size_t
  425. Session::getTimeout() const {
  426. return (impl_->getTimeout());
  427. }
  428. }
  429. }