session.cc 17 KB

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