session.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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(io_service& io_service) : impl_(new SessionImpl(io_service))
  226. {}
  227. Session::~Session() {
  228. delete impl_;
  229. }
  230. void
  231. Session::disconnect() {
  232. impl_->disconnect();
  233. }
  234. void
  235. Session::startRead(boost::function<void()> read_callback) {
  236. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_START_READ);
  237. impl_->startRead(read_callback);
  238. }
  239. namespace { // maybe unnecessary.
  240. // This is a helper class to make the establish() method (below) exception-safe
  241. // with the RAII approach.
  242. class SessionHolder {
  243. public:
  244. SessionHolder(SessionImpl* obj) : impl_obj_(obj) {}
  245. ~SessionHolder()
  246. {
  247. if (impl_obj_ != NULL) {
  248. impl_obj_->disconnect();
  249. }
  250. }
  251. void clear() { impl_obj_ = NULL; }
  252. SessionImpl* impl_obj_;
  253. };
  254. }
  255. void
  256. Session::establish(const char* socket_file) {
  257. if (socket_file == NULL) {
  258. socket_file = getenv("BIND10_MSGQ_SOCKET_FILE");
  259. }
  260. if (socket_file == NULL) {
  261. socket_file = BIND10_MSGQ_SOCKET_FILE;
  262. }
  263. impl_->establish(*socket_file);
  264. // once established, encapsulate the implementation object so that we
  265. // can safely release the internal resource when exception happens
  266. // below.
  267. SessionHolder session_holder(impl_);
  268. //
  269. // send a request for our local name, and wait for a response
  270. //
  271. ConstElementPtr get_lname_msg =
  272. Element::fromJSON("{ \"type\": \"getlname\" }");
  273. sendmsg(get_lname_msg);
  274. ConstElementPtr routing, msg;
  275. recvmsg(routing, msg, false);
  276. impl_->lname_ = msg->get("lname")->stringValue();
  277. // At this point there's no risk of resource leak.
  278. session_holder.clear();
  279. }
  280. //
  281. // Convert to wire format and send this via the stream socket with its length
  282. // prefix.
  283. //
  284. void
  285. Session::sendmsg(ConstElementPtr msg) {
  286. std::string header_wire = msg->toWire();
  287. unsigned int length = 2 + header_wire.length();
  288. unsigned int length_net = htonl(length);
  289. unsigned short header_length = header_wire.length();
  290. unsigned short header_length_net = htons(header_length);
  291. impl_->writeData(&length_net, sizeof(length_net));
  292. impl_->writeData(&header_length_net, sizeof(header_length_net));
  293. impl_->writeData(header_wire.data(), header_length);
  294. }
  295. void
  296. Session::sendmsg(ConstElementPtr env, ConstElementPtr msg) {
  297. std::string header_wire = env->toWire();
  298. std::string body_wire = msg->toWire();
  299. unsigned int length = 2 + header_wire.length() + body_wire.length();
  300. unsigned int length_net = htonl(length);
  301. unsigned short header_length = header_wire.length();
  302. unsigned short header_length_net = htons(header_length);
  303. impl_->writeData(&length_net, sizeof(length_net));
  304. impl_->writeData(&header_length_net, sizeof(header_length_net));
  305. impl_->writeData(header_wire.data(), header_length);
  306. impl_->writeData(body_wire.data(), body_wire.length());
  307. }
  308. bool
  309. Session::recvmsg(ConstElementPtr& msg, bool nonblock, int seq) {
  310. ConstElementPtr l_env;
  311. return (recvmsg(l_env, msg, nonblock, seq));
  312. }
  313. bool
  314. Session::recvmsg(ConstElementPtr& env, ConstElementPtr& msg,
  315. bool nonblock, int seq)
  316. {
  317. size_t length = impl_->readDataLength();
  318. if (hasQueuedMsgs()) {
  319. ConstElementPtr q_el;
  320. for (int i = 0; i < impl_->queue_->size(); i++) {
  321. q_el = impl_->queue_->get(i);
  322. if (( seq == -1 &&
  323. !q_el->get(0)->contains("reply")
  324. ) || (
  325. q_el->get(0)->contains("reply") &&
  326. q_el->get(0)->get("reply")->intValue() == seq
  327. )
  328. ) {
  329. env = q_el->get(0);
  330. msg = q_el->get(1);
  331. impl_->queue_->remove(i);
  332. return (true);
  333. }
  334. }
  335. }
  336. unsigned short header_length_net;
  337. impl_->readData(&header_length_net, sizeof(header_length_net));
  338. unsigned short header_length = ntohs(header_length_net);
  339. if (header_length > length || length < 2) {
  340. LOG_ERROR(logger, CC_INVALID_LENGTHS).arg(length).arg(header_length);
  341. isc_throw(SessionError, "Length parameters invalid: total=" << length
  342. << ", header=" << header_length);
  343. }
  344. // remove the header-length bytes from the total length
  345. length -= 2;
  346. std::vector<char> buffer(length);
  347. impl_->readData(&buffer[0], length);
  348. std::string header_wire = std::string(&buffer[0], header_length);
  349. std::string body_wire = std::string(&buffer[0] + header_length,
  350. length - header_length);
  351. std::stringstream header_wire_stream;
  352. header_wire_stream << header_wire;
  353. ConstElementPtr l_env =
  354. Element::fromWire(header_wire_stream, header_length);
  355. std::stringstream body_wire_stream;
  356. body_wire_stream << body_wire;
  357. ConstElementPtr l_msg =
  358. Element::fromWire(body_wire_stream, length - header_length);
  359. if ((seq == -1 &&
  360. !l_env->contains("reply")
  361. ) || (
  362. l_env->contains("reply") &&
  363. l_env->get("reply")->intValue() == seq
  364. )
  365. ) {
  366. env = l_env;
  367. msg = l_msg;
  368. return (true);
  369. } else {
  370. ElementPtr q_el = Element::createList();
  371. q_el->add(l_env);
  372. q_el->add(l_msg);
  373. impl_->queue_->add(q_el);
  374. return (recvmsg(env, msg, nonblock, seq));
  375. }
  376. // XXXMLG handle non-block here, and return false for short reads
  377. }
  378. void
  379. Session::subscribe(std::string group, std::string instance) {
  380. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_SUBSCRIBE).arg(group);
  381. ElementPtr env = Element::createMap();
  382. env->set("type", Element::create("subscribe"));
  383. env->set("group", Element::create(group));
  384. env->set("instance", Element::create(instance));
  385. sendmsg(env);
  386. }
  387. void
  388. Session::unsubscribe(std::string group, std::string instance) {
  389. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_UNSUBSCRIBE).arg(group);
  390. ElementPtr env = Element::createMap();
  391. env->set("type", Element::create("unsubscribe"));
  392. env->set("group", Element::create(group));
  393. env->set("instance", Element::create(instance));
  394. sendmsg(env);
  395. }
  396. int
  397. Session::group_sendmsg(ConstElementPtr msg, std::string group,
  398. std::string instance, std::string to)
  399. {
  400. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_GROUP_SEND).arg(msg->str()).
  401. arg(group);
  402. ElementPtr env = Element::createMap();
  403. long int nseq = ++impl_->sequence_;
  404. env->set("type", Element::create("send"));
  405. env->set("from", Element::create(impl_->lname_));
  406. env->set("to", Element::create(to));
  407. env->set("group", Element::create(group));
  408. env->set("instance", Element::create(instance));
  409. env->set("seq", Element::create(nseq));
  410. //env->set("msg", Element::create(msg->toWire()));
  411. sendmsg(env, msg);
  412. return (nseq);
  413. }
  414. bool
  415. Session::group_recvmsg(ConstElementPtr& envelope, ConstElementPtr& msg,
  416. bool nonblock, int seq)
  417. {
  418. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_GROUP_RECEIVE);
  419. bool result(recvmsg(envelope, msg, nonblock, seq));
  420. if (result) {
  421. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_GROUP_RECEIVED).
  422. arg(envelope->str()).arg(msg->str());
  423. } else {
  424. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_NO_MESSAGE);
  425. }
  426. return (result);
  427. }
  428. int
  429. Session::reply(ConstElementPtr envelope, ConstElementPtr newmsg) {
  430. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_REPLY).arg(envelope->str()).
  431. arg(newmsg->str());
  432. ElementPtr env = Element::createMap();
  433. long int nseq = ++impl_->sequence_;
  434. env->set("type", Element::create("send"));
  435. env->set("from", Element::create(impl_->lname_));
  436. env->set("to", Element::create(envelope->get("from")->stringValue()));
  437. env->set("group", Element::create(envelope->get("group")->stringValue()));
  438. env->set("instance", Element::create(envelope->get("instance")->stringValue()));
  439. env->set("seq", Element::create(nseq));
  440. env->set("reply", Element::create(envelope->get("seq")->intValue()));
  441. sendmsg(env, newmsg);
  442. return (nseq);
  443. }
  444. bool
  445. Session::hasQueuedMsgs() const {
  446. return (impl_->queue_->size() > 0);
  447. }
  448. void
  449. Session::setTimeout(size_t milliseconds) {
  450. LOG_DEBUG(logger, DBG_TRACE_DETAILED, CC_SET_TIMEOUT).arg(milliseconds);
  451. impl_->setTimeout(milliseconds);
  452. }
  453. size_t
  454. Session::getTimeout() const {
  455. return (impl_->getTimeout());
  456. }
  457. }
  458. }