test_server_unix_socket.cc 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright (C) 2017 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <asiolink/asio_wrapper.h>
  7. #include <asiolink/testutils/test_server_unix_socket.h>
  8. #include <boost/bind.hpp>
  9. #include <boost/enable_shared_from_this.hpp>
  10. #include <boost/shared_ptr.hpp>
  11. #include <functional>
  12. #include <set>
  13. #include <sstream>
  14. using namespace boost::asio::local;
  15. namespace isc {
  16. namespace asiolink {
  17. namespace test {
  18. /// @brief ASIO unix domain socket.
  19. typedef stream_protocol::socket UnixSocket;
  20. /// @brief Pointer to the ASIO unix domain socket.
  21. typedef boost::shared_ptr<UnixSocket> UnixSocketPtr;
  22. /// @brief Callback function invoked when response is sent from the server.
  23. typedef std::function<void()> SentResponseCallback;
  24. /// @brief Connection to the server over unix domain socket.
  25. ///
  26. /// It reads the data over the socket, sends responses and closes a socket.
  27. class Connection : public boost::enable_shared_from_this<Connection> {
  28. public:
  29. /// @brief Constructor.
  30. ///
  31. /// It starts asynchronous read operation.
  32. ///
  33. /// @param unix_socket Pointer to the unix domain socket into which
  34. /// connection has been accepted.
  35. /// @param custom_response Custom response that the server should send.
  36. /// @param sent_response_callback Callback function to be invoked when
  37. /// server sends a response.
  38. Connection(const UnixSocketPtr& unix_socket,
  39. const std::string custom_response,
  40. SentResponseCallback sent_response_callback)
  41. : socket_(unix_socket), custom_response_(custom_response),
  42. sent_response_callback_(sent_response_callback) {
  43. }
  44. /// @brief Starts asynchronous read from the socket.
  45. void start() {
  46. socket_->async_read_some(boost::asio::buffer(&raw_buf_[0], raw_buf_.size()),
  47. boost::bind(&Connection::readHandler, shared_from_this(),
  48. boost::asio::placeholders::error,
  49. boost::asio::placeholders::bytes_transferred));
  50. }
  51. /// @brief Closes the socket.
  52. void stop() {
  53. socket_->close();
  54. }
  55. /// @brief Handler invoked when data have been received over the socket.
  56. ///
  57. /// This is the handler invoked when the data have been received over the
  58. /// socket. If custom response has been specified, this response is sent
  59. /// back to the client. Otherwise, the handler echoes back the request
  60. /// and prepends the word "received ". Finally, it calls a custom
  61. /// callback function (specified in the constructor) to notify that the
  62. /// response has been sent over the socket.
  63. ///
  64. /// @param bytes_transferred Number of bytes received.
  65. void
  66. readHandler(const boost::system::error_code& ec,
  67. size_t bytes_transferred) {
  68. // This is most likely due to the abort.
  69. if (ec) {
  70. return;
  71. }
  72. if (!custom_response_.empty()) {
  73. boost::asio::write(*socket_,
  74. boost::asio::buffer(custom_response_.c_str(), custom_response_.size()));
  75. } else {
  76. std::string received(&raw_buf_[0], bytes_transferred);
  77. std::string response("received " + received);
  78. boost::asio::write(*socket_,
  79. boost::asio::buffer(response.c_str(), response.size()));
  80. }
  81. start();
  82. // Invoke callback function to notify that the response has been sent.
  83. sent_response_callback_();
  84. }
  85. private:
  86. /// @brief Pointer to the unix domain socket.
  87. UnixSocketPtr socket_;
  88. /// @brief Custom response to be sent to the client.
  89. std::string custom_response_;
  90. /// @brief Receive buffer.
  91. std::array<char, 1024> raw_buf_;
  92. /// @brief Pointer to the callback function to be invoked when response
  93. /// has been sent.
  94. SentResponseCallback sent_response_callback_;
  95. };
  96. /// @brief Pointer to a Connection object.
  97. typedef boost::shared_ptr<Connection> ConnectionPtr;
  98. /// @brief Connection pool.
  99. ///
  100. /// Holds all connections established with the server and gracefully
  101. /// terminates these connections.
  102. class ConnectionPool {
  103. public:
  104. /// @brief Constructor.
  105. ///
  106. /// @param io_service Reference to the IO service.
  107. ConnectionPool(IOService& io_service)
  108. : io_service_(io_service), connections_(), next_socket_(),
  109. response_num_(0) {
  110. }
  111. /// @brief Destructor.
  112. ~ConnectionPool() {
  113. stopAll();
  114. }
  115. /// @brief Creates new unix domain socket and returns it.
  116. ///
  117. /// This convenience method creates a socket which can be used to accept
  118. /// new connections. If such socket already exists, it is returned.
  119. ///
  120. /// @return Pointer to the socket.
  121. UnixSocketPtr getSocket() {
  122. if (!next_socket_) {
  123. next_socket_.reset(new UnixSocket(io_service_.get_io_service()));
  124. }
  125. return (next_socket_);
  126. }
  127. /// @brief Starts new connection.
  128. ///
  129. /// The socket returned by the @ref ConnectionPool::getSocket is used to
  130. /// create new connection. Then, the @ref next_socket_ is reset, to force
  131. /// the @ref ConnectionPool::getSocket to generate a new socket for a
  132. /// next connection.
  133. ///
  134. /// @param custom_response Custom response to be sent to the client.
  135. void start(const std::string& custom_response) {
  136. ConnectionPtr conn(new Connection(next_socket_, custom_response, [this] {
  137. ++response_num_;
  138. }));
  139. conn->start();
  140. connections_.insert(conn);
  141. next_socket_.reset();
  142. }
  143. /// @brief Stops the given connection.
  144. ///
  145. /// @param conn Pointer to the connection to be stopped.
  146. void stop(const ConnectionPtr& conn) {
  147. conn->stop();
  148. connections_.erase(conn);
  149. }
  150. /// @brief Stops all connections.
  151. void stopAll() {
  152. for (auto conn = connections_.begin(); conn != connections_.end();
  153. ++conn) {
  154. (*conn)->stop();
  155. }
  156. connections_.clear();
  157. }
  158. /// @brief Returns number of responses sent so far.
  159. size_t getResponseNum() const {
  160. return (response_num_);
  161. }
  162. private:
  163. /// @brief Reference to the IO service.
  164. IOService& io_service_;
  165. /// @brief Container holding established connections.
  166. std::set<ConnectionPtr> connections_;
  167. /// @brief Holds pointer to the generated socket.
  168. ///
  169. /// This socket will be used by the next connection.
  170. UnixSocketPtr next_socket_;
  171. /// @brief Holds the number of sent responses.
  172. size_t response_num_;
  173. };
  174. TestServerUnixSocket::TestServerUnixSocket(IOService& io_service,
  175. const std::string& socket_file_path,
  176. const std::string& custom_response)
  177. : io_service_(io_service),
  178. server_endpoint_(socket_file_path),
  179. server_acceptor_(io_service_.get_io_service()),
  180. test_timer_(io_service_),
  181. custom_response_(custom_response),
  182. connection_pool_(new ConnectionPool(io_service)),
  183. stopped_(false),
  184. running_(false) {
  185. }
  186. TestServerUnixSocket::~TestServerUnixSocket() {
  187. server_acceptor_.close();
  188. }
  189. void
  190. TestServerUnixSocket::generateCustomResponse(const uint64_t response_size) {
  191. std::ostringstream s;
  192. s << "{";
  193. while (s.tellp() < response_size) {
  194. s << "\"param\": \"value\",";
  195. }
  196. s << "}";
  197. custom_response_ = s.str();
  198. }
  199. void
  200. TestServerUnixSocket::startTimer(const long test_timeout) {
  201. test_timer_.setup(boost::bind(&TestServerUnixSocket::timeoutHandler, this),
  202. test_timeout, IntervalTimer::ONE_SHOT);
  203. }
  204. void
  205. TestServerUnixSocket::stopServer() {
  206. test_timer_.cancel();
  207. server_acceptor_.cancel();
  208. connection_pool_->stopAll();
  209. }
  210. void
  211. TestServerUnixSocket::bindServerSocket(const bool use_thread) {
  212. server_acceptor_.open();
  213. server_acceptor_.bind(server_endpoint_);
  214. server_acceptor_.listen();
  215. accept();
  216. // When threads are in use, we need to post a handler which will be invoked
  217. // when the thread has already started and the IO service is running. The
  218. // main thread can move forward when it receives this signal from the handler.
  219. if (use_thread) {
  220. io_service_.post(boost::bind(&TestServerUnixSocket::signalRunning,
  221. this));
  222. }
  223. }
  224. void
  225. TestServerUnixSocket::acceptHandler(const boost::system::error_code& ec) {
  226. if (ec) {
  227. return;
  228. }
  229. connection_pool_->start(custom_response_);
  230. accept();
  231. }
  232. void
  233. TestServerUnixSocket::accept() {
  234. server_acceptor_.async_accept(*(connection_pool_->getSocket()),
  235. boost::bind(&TestServerUnixSocket::acceptHandler, this,
  236. boost::asio::placeholders::error));
  237. }
  238. void
  239. TestServerUnixSocket::signalRunning() {
  240. {
  241. isc::util::thread::Mutex::Locker lock(mutex_);
  242. running_ = true;
  243. }
  244. condvar_.signal();
  245. }
  246. void
  247. TestServerUnixSocket::waitForRunning() {
  248. isc::util::thread::Mutex::Locker lock(mutex_);
  249. while (!running_) {
  250. condvar_.wait(mutex_);
  251. }
  252. }
  253. void
  254. TestServerUnixSocket::timeoutHandler() {
  255. ADD_FAILURE() << "Timeout occurred while running the test!";
  256. io_service_.stop();
  257. stopped_ = true;
  258. }
  259. size_t
  260. TestServerUnixSocket::getResponseNum() const {
  261. return (connection_pool_->getResponseNum());
  262. }
  263. } // end of namespace isc::asiolink::test
  264. } // end of namespace isc::asiolink
  265. } // end of namespace isc