rpc_engine.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef LIB_RPC_RPC_ENGINE_H_
  19. #define LIB_RPC_RPC_ENGINE_H_
  20. #include "hdfspp/options.h"
  21. #include "hdfspp/status.h"
  22. #include "common/retry_policy.h"
  23. #include <google/protobuf/message_lite.h>
  24. #include <google/protobuf/io/coded_stream.h>
  25. #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
  26. #include <asio/ip/tcp.hpp>
  27. #include <asio/deadline_timer.hpp>
  28. #include <atomic>
  29. #include <memory>
  30. #include <unordered_map>
  31. #include <vector>
  32. #include <mutex>
  33. namespace hdfs {
  34. /*
  35. * NOTE ABOUT LOCKING MODELS
  36. *
  37. * To prevent deadlocks, anything that might acquire multiple locks must
  38. * acquire the lock on the RpcEngine first, then the RpcConnection. Callbacks
  39. * will never be called while holding any locks, so the components are free
  40. * to take locks when servicing a callback.
  41. *
  42. * An RpcRequest or RpcConnection should never call any methods on the RpcEngine
  43. * except for those that are exposed through the LockFreeRpcEngine interface.
  44. */
  45. typedef const std::function<void(const Status &)> RpcCallback;
  46. class LockFreeRpcEngine;
  47. class RpcConnection;
  48. /*
  49. * Internal bookkeeping for an outstanding request from the consumer.
  50. *
  51. * Threading model: not thread-safe; should only be accessed from a single
  52. * thread at a time
  53. */
  54. class Request {
  55. public:
  56. typedef std::function<void(::google::protobuf::io::CodedInputStream *is,
  57. const Status &status)> Handler;
  58. Request(LockFreeRpcEngine *engine, const std::string &method_name,
  59. const std::string &request, Handler &&callback);
  60. Request(LockFreeRpcEngine *engine, const std::string &method_name,
  61. const ::google::protobuf::MessageLite *request, Handler &&callback);
  62. // Null request (with no actual message) used to track the state of an
  63. // initial Connect call
  64. Request(LockFreeRpcEngine *engine, Handler &&handler);
  65. int call_id() const { return call_id_; }
  66. ::asio::deadline_timer &timer() { return timer_; }
  67. int IncrementRetryCount() { return retry_count_++; }
  68. void GetPacket(std::string *res) const;
  69. void OnResponseArrived(::google::protobuf::io::CodedInputStream *is,
  70. const Status &status);
  71. private:
  72. LockFreeRpcEngine *const engine_;
  73. const std::string method_name_;
  74. const int call_id_;
  75. ::asio::deadline_timer timer_;
  76. std::string payload_;
  77. const Handler handler_;
  78. int retry_count_;
  79. };
  80. /*
  81. * Encapsulates a persistent connection to the NameNode, and the sending of
  82. * RPC requests and evaluating their responses.
  83. *
  84. * Can have multiple RPC requests in-flight simultaneously, but they are
  85. * evaluated in-order on the server side in a blocking manner.
  86. *
  87. * Threading model: public interface is thread-safe
  88. * All handlers passed in to method calls will be called from an asio thread,
  89. * and will not be holding any internal RpcConnection locks.
  90. */
  91. class RpcConnection : public std::enable_shared_from_this<RpcConnection> {
  92. public:
  93. RpcConnection(LockFreeRpcEngine *engine);
  94. virtual ~RpcConnection();
  95. // Note that a single server can have multiple endpoints - especially both
  96. // an ipv4 and ipv6 endpoint
  97. virtual void Connect(const std::vector<::asio::ip::tcp::endpoint> &server,
  98. RpcCallback &handler) = 0;
  99. virtual void ConnectAndFlush(const std::vector<::asio::ip::tcp::endpoint> &server) = 0;
  100. virtual void Handshake(RpcCallback &handler) = 0;
  101. virtual void Disconnect() = 0;
  102. void StartReading();
  103. void AsyncRpc(const std::string &method_name,
  104. const ::google::protobuf::MessageLite *req,
  105. std::shared_ptr<::google::protobuf::MessageLite> resp,
  106. const RpcCallback &handler);
  107. void AsyncRawRpc(const std::string &method_name, const std::string &request,
  108. std::shared_ptr<std::string> resp, RpcCallback &&handler);
  109. // Enqueue requests before the connection is connected. Will be flushed
  110. // on connect
  111. void PreEnqueueRequests(std::vector<std::shared_ptr<Request>> requests);
  112. LockFreeRpcEngine *engine() { return engine_; }
  113. ::asio::io_service &io_service();
  114. protected:
  115. struct Response {
  116. enum ResponseState {
  117. kReadLength,
  118. kReadContent,
  119. kParseResponse,
  120. } state_;
  121. unsigned length_;
  122. std::vector<char> data_;
  123. std::unique_ptr<::google::protobuf::io::ArrayInputStream> ar;
  124. std::unique_ptr<::google::protobuf::io::CodedInputStream> in;
  125. Response() : state_(kReadLength), length_(0) {}
  126. };
  127. LockFreeRpcEngine *const engine_;
  128. virtual void OnSendCompleted(const ::asio::error_code &ec,
  129. size_t transferred) = 0;
  130. virtual void OnRecvCompleted(const ::asio::error_code &ec,
  131. size_t transferred) = 0;
  132. virtual void FlushPendingRequests()=0; // Synchronously write the next request
  133. void AsyncFlushPendingRequests(); // Queue requests to be flushed at a later time
  134. std::shared_ptr<std::string> PrepareHandshakePacket();
  135. static std::string SerializeRpcRequest(
  136. const std::string &method_name,
  137. const ::google::protobuf::MessageLite *req);
  138. void HandleRpcResponse(std::shared_ptr<Response> response);
  139. void HandleRpcTimeout(std::shared_ptr<Request> req,
  140. const ::asio::error_code &ec);
  141. void CommsError(const Status &status);
  142. void ClearAndDisconnect(const ::asio::error_code &ec);
  143. std::shared_ptr<Request> RemoveFromRunningQueue(int call_id);
  144. std::shared_ptr<Response> response_;
  145. // Connection can have deferred connection, especially when we're pausing
  146. // during retry
  147. bool connected_;
  148. // The request being sent over the wire; will also be in requests_on_fly_
  149. std::shared_ptr<Request> request_over_the_wire_;
  150. // Requests to be sent over the wire
  151. std::vector<std::shared_ptr<Request>> pending_requests_;
  152. // Requests that are waiting for responses
  153. typedef std::unordered_map<int, std::shared_ptr<Request>> RequestOnFlyMap;
  154. RequestOnFlyMap requests_on_fly_;
  155. // Lock for mutable parts of this class that need to be thread safe
  156. std::mutex connection_state_lock_;
  157. };
  158. /*
  159. * These methods of the RpcEngine will never acquire locks, and are safe for
  160. * RpcConnections to call while holding a ConnectionLock.
  161. */
  162. class LockFreeRpcEngine {
  163. public:
  164. /* Enqueues a CommsError without acquiring a lock*/
  165. virtual void AsyncRpcCommsError(const Status &status,
  166. std::vector<std::shared_ptr<Request>> pendingRequests) = 0;
  167. virtual const RetryPolicy * retry_policy() const = 0;
  168. virtual int NextCallId() = 0;
  169. virtual const std::string &client_name() const = 0;
  170. virtual const std::string &user_name() const = 0;
  171. virtual const std::string &protocol_name() const = 0;
  172. virtual int protocol_version() const = 0;
  173. virtual ::asio::io_service &io_service() = 0;
  174. virtual const Options &options() const = 0;
  175. };
  176. /*
  177. * An engine for reliable communication with a NameNode. Handles connection,
  178. * retry, and (someday) failover of the requested messages.
  179. *
  180. * Threading model: thread-safe. All callbacks will be called back from
  181. * an asio pool and will not hold any internal locks
  182. */
  183. class RpcEngine : public LockFreeRpcEngine {
  184. public:
  185. enum { kRpcVersion = 9 };
  186. enum {
  187. kCallIdAuthorizationFailed = -1,
  188. kCallIdInvalid = -2,
  189. kCallIdConnectionContext = -3,
  190. kCallIdPing = -4
  191. };
  192. RpcEngine(::asio::io_service *io_service, const Options &options,
  193. const std::string &client_name, const std::string &user_name,
  194. const char *protocol_name, int protocol_version);
  195. void Connect(const std::vector<::asio::ip::tcp::endpoint> &server, RpcCallback &handler);
  196. void AsyncRpc(const std::string &method_name,
  197. const ::google::protobuf::MessageLite *req,
  198. const std::shared_ptr<::google::protobuf::MessageLite> &resp,
  199. const std::function<void(const Status &)> &handler);
  200. Status Rpc(const std::string &method_name,
  201. const ::google::protobuf::MessageLite *req,
  202. const std::shared_ptr<::google::protobuf::MessageLite> &resp);
  203. /**
  204. * Send raw bytes as RPC payload. This is intended to be used in JNI
  205. * bindings only.
  206. **/
  207. Status RawRpc(const std::string &method_name, const std::string &req,
  208. std::shared_ptr<std::string> resp);
  209. void Start();
  210. void Shutdown();
  211. /* Enqueues a CommsError without acquiring a lock*/
  212. void AsyncRpcCommsError(const Status &status,
  213. std::vector<std::shared_ptr<Request>> pendingRequests) override;
  214. void RpcCommsError(const Status &status,
  215. std::vector<std::shared_ptr<Request>> pendingRequests);
  216. const RetryPolicy * retry_policy() const override { return retry_policy_.get(); }
  217. int NextCallId() override { return ++call_id_; }
  218. void TEST_SetRpcConnection(std::shared_ptr<RpcConnection> conn);
  219. const std::string &client_name() const override { return client_name_; }
  220. const std::string &user_name() const override { return user_name_; }
  221. const std::string &protocol_name() const override { return protocol_name_; }
  222. int protocol_version() const override { return protocol_version_; }
  223. ::asio::io_service &io_service() override { return *io_service_; }
  224. const Options &options() const override { return options_; }
  225. static std::string GetRandomClientName();
  226. protected:
  227. std::shared_ptr<RpcConnection> conn_;
  228. virtual std::shared_ptr<RpcConnection> NewConnection();
  229. virtual std::unique_ptr<const RetryPolicy> MakeRetryPolicy(const Options &options);
  230. // Remember all of the last endpoints in case we need to reconnect and retry
  231. std::vector<::asio::ip::tcp::endpoint> last_endpoints_;
  232. private:
  233. ::asio::io_service * const io_service_;
  234. const Options options_;
  235. const std::string client_name_;
  236. const std::string user_name_;
  237. const std::string protocol_name_;
  238. const int protocol_version_;
  239. const std::unique_ptr<const RetryPolicy> retry_policy_; //null --> no retry
  240. std::atomic_int call_id_;
  241. ::asio::deadline_timer retry_timer;
  242. std::mutex engine_state_lock_;
  243. };
  244. }
  245. #endif