session.cc 17 KB

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