rpc_engine.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. #include "rpc_engine.h"
  19. #include "rpc_connection_impl.h"
  20. #include "common/util.h"
  21. #include "common/logging.h"
  22. #include "common/namenode_info.h"
  23. #include "common/optional_wrapper.h"
  24. #include <algorithm>
  25. #include <memory>
  26. #include <boost/date_time/posix_time/posix_time_duration.hpp>
  27. #include <openssl/rand.h>
  28. #include <openssl/err.h>
  29. namespace hdfs {
  30. template <class T>
  31. using optional = std::experimental::optional<T>;
  32. RpcEngine::RpcEngine(std::shared_ptr<IoService> io_service, const Options &options,
  33. const std::string &client_name, const std::string &user_name,
  34. const char *protocol_name, int protocol_version)
  35. : io_service_(io_service),
  36. options_(options),
  37. client_name_(client_name),
  38. client_id_(getRandomClientId()),
  39. protocol_name_(protocol_name),
  40. protocol_version_(protocol_version),
  41. call_id_(0),
  42. retry_timer(io_service->GetRaw()),
  43. event_handlers_(std::make_shared<LibhdfsEvents>()),
  44. connect_canceled_(false)
  45. {
  46. LOG_DEBUG(kRPC, << "RpcEngine::RpcEngine called");
  47. auth_info_.setUser(user_name);
  48. if (options.authentication == Options::kKerberos) {
  49. auth_info_.setMethod(AuthInfo::kKerberos);
  50. }
  51. }
  52. void RpcEngine::Connect(const std::string &cluster_name,
  53. const std::vector<ResolvedNamenodeInfo> servers,
  54. RpcCallback &handler) {
  55. std::lock_guard<std::mutex> state_lock(engine_state_lock_);
  56. LOG_DEBUG(kRPC, << "RpcEngine::Connect called");
  57. last_endpoints_ = servers[0].endpoints;
  58. cluster_name_ = cluster_name;
  59. LOG_TRACE(kRPC, << "Got cluster name \"" << cluster_name << "\" in RpcEngine::Connect")
  60. ha_persisted_info_.reset(new HANamenodeTracker(servers, io_service_, event_handlers_));
  61. if(!ha_persisted_info_->is_enabled()) {
  62. ha_persisted_info_.reset();
  63. }
  64. // Construct retry policy after we determine if config is HA
  65. retry_policy_ = MakeRetryPolicy(options_);
  66. conn_ = InitializeConnection();
  67. conn_->Connect(last_endpoints_, auth_info_, handler);
  68. }
  69. bool RpcEngine::CancelPendingConnect() {
  70. if(connect_canceled_) {
  71. LOG_DEBUG(kRPC, << "RpcEngine@" << this << "::CancelPendingConnect called more than once");
  72. return false;
  73. }
  74. connect_canceled_ = true;
  75. return true;
  76. }
  77. void RpcEngine::Shutdown() {
  78. LOG_DEBUG(kRPC, << "RpcEngine::Shutdown called");
  79. io_service_->PostLambda([this]() {
  80. std::lock_guard<std::mutex> state_lock(engine_state_lock_);
  81. conn_.reset();
  82. });
  83. }
  84. std::unique_ptr<const RetryPolicy> RpcEngine::MakeRetryPolicy(const Options &options) {
  85. LOG_DEBUG(kRPC, << "RpcEngine::MakeRetryPolicy called");
  86. if(ha_persisted_info_) {
  87. LOG_INFO(kRPC, << "Cluster is HA configued so policy will default to HA until a knob is implemented");
  88. return std::unique_ptr<RetryPolicy>(new FixedDelayWithFailover(options.rpc_retry_delay_ms,
  89. options.max_rpc_retries,
  90. options.failover_max_retries,
  91. options.failover_connection_max_retries));
  92. } else if (options.max_rpc_retries > 0) {
  93. return std::unique_ptr<RetryPolicy>(new FixedDelayRetryPolicy(options.rpc_retry_delay_ms,
  94. options.max_rpc_retries));
  95. } else {
  96. return nullptr;
  97. }
  98. }
  99. std::unique_ptr<std::string> RpcEngine::getRandomClientId() {
  100. /**
  101. * The server is requesting a 16-byte UUID:
  102. * https://github.com/c9n/hadoop/blob/master/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ClientId.java
  103. *
  104. * This function generates a 16-byte UUID (version 4):
  105. * https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
  106. **/
  107. std::vector<unsigned char>buf(16);
  108. if (RAND_bytes(&buf[0], static_cast<int>(buf.size())) != 1) {
  109. const auto *error = ERR_reason_error_string(ERR_get_error());
  110. LOG_ERROR(kRPC, << "Unable to generate random client ID, err : " << error);
  111. return nullptr;
  112. }
  113. //clear the first four bits of byte 6 then set the second bit
  114. buf[6] = (buf[6] & 0x0f) | 0x40;
  115. //clear the second bit of byte 8 and set the first bit
  116. buf[8] = (buf[8] & 0xbf) | 0x80;
  117. return std::unique_ptr<std::string>(
  118. new std::string(reinterpret_cast<const char *>(&buf[0]), buf.size()));
  119. }
  120. void RpcEngine::TEST_SetRpcConnection(std::shared_ptr<RpcConnection> conn) {
  121. conn_ = conn;
  122. retry_policy_ = MakeRetryPolicy(options_);
  123. }
  124. void RpcEngine::TEST_SetRetryPolicy(std::unique_ptr<const RetryPolicy> policy) {
  125. retry_policy_ = std::move(policy);
  126. }
  127. std::unique_ptr<const RetryPolicy> RpcEngine::TEST_GenerateRetryPolicyUsingOptions() {
  128. return MakeRetryPolicy(options_);
  129. }
  130. void RpcEngine::AsyncRpc(
  131. const std::string &method_name, const ::google::protobuf::MessageLite *req,
  132. const std::shared_ptr<::google::protobuf::MessageLite> &resp,
  133. const std::function<void(const Status &)> &handler) {
  134. std::lock_guard<std::mutex> state_lock(engine_state_lock_);
  135. LOG_TRACE(kRPC, << "RpcEngine::AsyncRpc called");
  136. // In case user-side code isn't checking the status of Connect before doing RPC
  137. if(connect_canceled_) {
  138. io_service_->PostLambda(
  139. [handler](){ handler(Status::Canceled()); }
  140. );
  141. return;
  142. }
  143. if (!conn_) {
  144. conn_ = InitializeConnection();
  145. conn_->ConnectAndFlush(last_endpoints_);
  146. }
  147. conn_->AsyncRpc(method_name, req, resp, handler);
  148. }
  149. std::shared_ptr<RpcConnection> RpcEngine::NewConnection()
  150. {
  151. LOG_DEBUG(kRPC, << "RpcEngine::NewConnection called");
  152. return std::make_shared<RpcConnectionImpl<boost::asio::ip::tcp::socket>>(shared_from_this());
  153. }
  154. std::shared_ptr<RpcConnection> RpcEngine::InitializeConnection()
  155. {
  156. std::shared_ptr<RpcConnection> newConn = NewConnection();
  157. newConn->SetEventHandlers(event_handlers_);
  158. newConn->SetClusterName(cluster_name_);
  159. newConn->SetAuthInfo(auth_info_);
  160. return newConn;
  161. }
  162. void RpcEngine::AsyncRpcCommsError(
  163. const Status &status,
  164. std::shared_ptr<RpcConnection> failedConnection,
  165. std::vector<std::shared_ptr<Request>> pendingRequests) {
  166. LOG_ERROR(kRPC, << "RpcEngine::AsyncRpcCommsError called; status=\"" << status.ToString() << "\" conn=" << failedConnection.get() << " reqs=" << std::to_string(pendingRequests.size()));
  167. io_service_->PostLambda([this, status, failedConnection, pendingRequests]() {
  168. RpcCommsError(status, failedConnection, pendingRequests);
  169. });
  170. }
  171. void RpcEngine::RpcCommsError(
  172. const Status &status,
  173. std::shared_ptr<RpcConnection> failedConnection,
  174. std::vector<std::shared_ptr<Request>> pendingRequests) {
  175. LOG_WARN(kRPC, << "RpcEngine::RpcCommsError called; status=\"" << status.ToString() << "\" conn=" << failedConnection.get() << " reqs=" << std::to_string(pendingRequests.size()));
  176. std::lock_guard<std::mutex> state_lock(engine_state_lock_);
  177. // If the failed connection is the current one, shut it down
  178. // It will be reconnected when there is work to do
  179. if (failedConnection == conn_) {
  180. LOG_INFO(kRPC, << "Disconnecting from failed RpcConnection");
  181. conn_.reset();
  182. }
  183. optional<RetryAction> head_action = optional<RetryAction>();
  184. // Filter out anything with too many retries already
  185. if(event_handlers_) {
  186. event_handlers_->call(FS_NN_PRE_RPC_RETRY_EVENT, "RpcCommsError",
  187. reinterpret_cast<int64_t>(this));
  188. }
  189. for (auto it = pendingRequests.begin(); it < pendingRequests.end();) {
  190. auto req = *it;
  191. LOG_DEBUG(kRPC, << req->GetDebugString());
  192. RetryAction retry = RetryAction::fail(""); // Default to fail
  193. if(connect_canceled_) {
  194. retry = RetryAction::fail("Operation canceled");
  195. } else if (status.notWorthRetry()) {
  196. retry = RetryAction::fail(status.ToString().c_str());
  197. } else if (retry_policy()) {
  198. retry = retry_policy()->ShouldRetry(status, req->IncrementRetryCount(), req->get_failover_count(), true);
  199. }
  200. if (retry.action == RetryAction::FAIL) {
  201. // If we've exceeded the maximum retry, take the latest error and pass it
  202. // on. There might be a good argument for caching the first error
  203. // rather than the last one, that gets messy
  204. io_service()->PostLambda([req, status]() {
  205. req->OnResponseArrived(nullptr, status); // Never call back while holding a lock
  206. });
  207. it = pendingRequests.erase(it);
  208. } else {
  209. if (!head_action) {
  210. head_action = retry;
  211. }
  212. ++it;
  213. }
  214. }
  215. // If we have reqests that need to be re-sent, ensure that we have a connection
  216. // and send the requests to it
  217. bool haveRequests = !pendingRequests.empty() &&
  218. head_action && head_action->action != RetryAction::FAIL;
  219. if (haveRequests) {
  220. LOG_TRACE(kRPC, << "Have " << std::to_string(pendingRequests.size()) << " requests to resend");
  221. bool needNewConnection = !conn_;
  222. if (needNewConnection) {
  223. LOG_DEBUG(kRPC, << "Creating a new NN conection");
  224. // If HA is enabled and we have valid HA info then fail over to the standby (hopefully now active)
  225. if(head_action->action == RetryAction::FAILOVER_AND_RETRY && ha_persisted_info_) {
  226. for(unsigned int i=0; i<pendingRequests.size();i++) {
  227. pendingRequests[i]->IncrementFailoverCount();
  228. }
  229. ResolvedNamenodeInfo new_active_nn_info;
  230. bool failoverInfoFound = ha_persisted_info_->GetFailoverAndUpdate(last_endpoints_, new_active_nn_info);
  231. if(!failoverInfoFound) {
  232. // This shouldn't be a common case, the set of endpoints was empty, likely due to DNS issues.
  233. // Another possibility is a network device has been added or removed due to a VM starting or stopping.
  234. LOG_ERROR(kRPC, << "Failed to find endpoints for the alternate namenode."
  235. << "Make sure Namenode hostnames can be found with a DNS lookup.");
  236. // Kill all pending RPC requests since there's nowhere for this to go
  237. Status badEndpointStatus = Status::Error("No endpoints found for namenode");
  238. for(unsigned int i=0; i<pendingRequests.size(); i++) {
  239. std::shared_ptr<Request> sharedCurrentRequest = pendingRequests[i];
  240. io_service()->PostLambda([sharedCurrentRequest, badEndpointStatus]() {
  241. sharedCurrentRequest->OnResponseArrived(nullptr, badEndpointStatus); // Never call back while holding a lock
  242. });
  243. }
  244. // Clear request vector. This isn't a recoverable error.
  245. pendingRequests.clear();
  246. }
  247. if(ha_persisted_info_->is_resolved()) {
  248. LOG_INFO(kRPC, << "Going to try connecting to alternate Namenode: " << new_active_nn_info.uri.str());
  249. last_endpoints_ = new_active_nn_info.endpoints;
  250. } else {
  251. LOG_WARN(kRPC, << "It looks HA is turned on, but unable to fail over. has info="
  252. << ha_persisted_info_->is_enabled() << " resolved=" << ha_persisted_info_->is_resolved());
  253. }
  254. }
  255. conn_ = InitializeConnection();
  256. conn_->PreEnqueueRequests(pendingRequests);
  257. if (head_action->delayMillis > 0) {
  258. auto weak_conn = std::weak_ptr<RpcConnection>(conn_);
  259. retry_timer.expires_from_now(
  260. boost::posix_time::milliseconds(head_action->delayMillis));
  261. retry_timer.async_wait([this, weak_conn](boost::system::error_code ec) {
  262. auto strong_conn = weak_conn.lock();
  263. if ( (!ec) && (strong_conn) ) {
  264. strong_conn->ConnectAndFlush(last_endpoints_);
  265. }
  266. });
  267. } else {
  268. conn_->ConnectAndFlush(last_endpoints_);
  269. }
  270. } else {
  271. // We have an existing connection (which might be closed; we don't know
  272. // until we hold the connection local) and should just add the new requests
  273. conn_->AsyncRpc(pendingRequests);
  274. }
  275. }
  276. }
  277. void RpcEngine::SetFsEventCallback(fs_event_callback callback) {
  278. event_handlers_->set_fs_callback(callback);
  279. }
  280. }