filehandle.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 "filehandle.h"
  19. #include "common/continuation/continuation.h"
  20. #include "common/logging.h"
  21. #include "connection/datanodeconnection.h"
  22. #include "reader/block_reader.h"
  23. #include "hdfspp/events.h"
  24. #include <future>
  25. #include <tuple>
  26. #include <boost/asio/buffer.hpp>
  27. #define FMT_THIS_ADDR "this=" << (void*)this
  28. namespace hdfs {
  29. using ::hadoop::hdfs::LocatedBlocksProto;
  30. FileHandle::~FileHandle() {}
  31. FileHandleImpl::FileHandleImpl(const std::string & cluster_name,
  32. const std::string & path,
  33. std::shared_ptr<IoService> io_service, const std::string &client_name,
  34. const std::shared_ptr<const struct FileInfo> file_info,
  35. std::shared_ptr<BadDataNodeTracker> bad_data_nodes,
  36. std::shared_ptr<LibhdfsEvents> event_handlers)
  37. : cluster_name_(cluster_name), path_(path), io_service_(io_service), client_name_(client_name), file_info_(file_info),
  38. bad_node_tracker_(bad_data_nodes), offset_(0), cancel_state_(CancelTracker::New()), event_handlers_(event_handlers), bytes_read_(0) {
  39. LOG_TRACE(kFileHandle, << "FileHandleImpl::FileHandleImpl("
  40. << FMT_THIS_ADDR << ", ...) called");
  41. }
  42. void FileHandleImpl::PositionRead(
  43. void *buf, size_t buf_size, uint64_t offset,
  44. const std::function<void(const Status &, size_t)> &handler) {
  45. LOG_DEBUG(kFileHandle, << "FileHandleImpl::PositionRead("
  46. << FMT_THIS_ADDR << ", buf=" << buf
  47. << ", buf_size=" << std::to_string(buf_size) << ") called");
  48. /* prevent usage after cancelation */
  49. if(cancel_state_->is_canceled()) {
  50. handler(Status::Canceled(), 0);
  51. return;
  52. }
  53. auto callback = [this, handler](const Status &status,
  54. const std::string &contacted_datanode,
  55. size_t bytes_read) {
  56. /* determine if DN gets marked bad */
  57. if (ShouldExclude(status)) {
  58. bad_node_tracker_->AddBadNode(contacted_datanode);
  59. }
  60. bytes_read_ += bytes_read;
  61. handler(status, bytes_read);
  62. };
  63. AsyncPreadSome(offset, boost::asio::buffer(buf, buf_size), bad_node_tracker_, callback);
  64. }
  65. Status FileHandleImpl::PositionRead(void *buf, size_t buf_size, off_t offset, size_t *bytes_read) {
  66. LOG_DEBUG(kFileHandle, << "FileHandleImpl::[sync]PositionRead("
  67. << FMT_THIS_ADDR << ", buf=" << buf
  68. << ", buf_size=" << std::to_string(buf_size)
  69. << ", offset=" << offset << ") called");
  70. auto callstate = std::make_shared<std::promise<std::tuple<Status, size_t>>>();
  71. std::future<std::tuple<Status, size_t>> future(callstate->get_future());
  72. /* wrap async call with promise/future to make it blocking */
  73. auto callback = [callstate](const Status &s, size_t bytes) {
  74. callstate->set_value(std::make_tuple(s,bytes));
  75. };
  76. PositionRead(buf, buf_size, offset, callback);
  77. /* wait for async to finish */
  78. auto returnstate = future.get();
  79. auto stat = std::get<0>(returnstate);
  80. if (!stat.ok()) {
  81. return stat;
  82. }
  83. *bytes_read = std::get<1>(returnstate);
  84. return stat;
  85. }
  86. Status FileHandleImpl::Read(void *buf, size_t buf_size, size_t *bytes_read) {
  87. LOG_DEBUG(kFileHandle, << "FileHandleImpl::Read("
  88. << FMT_THIS_ADDR << ", buf=" << buf
  89. << ", buf_size=" << std::to_string(buf_size) << ") called");
  90. Status stat = PositionRead(buf, buf_size, offset_, bytes_read);
  91. if(!stat.ok()) {
  92. return stat;
  93. }
  94. offset_ += *bytes_read;
  95. return Status::OK();
  96. }
  97. Status FileHandleImpl::Seek(off_t *offset, std::ios_base::seekdir whence) {
  98. LOG_DEBUG(kFileHandle, << "FileHandleImpl::Seek("
  99. << ", offset=" << *offset << ", ...) called");
  100. if(cancel_state_->is_canceled()) {
  101. return Status::Canceled();
  102. }
  103. off_t new_offset = -1;
  104. switch (whence) {
  105. case std::ios_base::beg:
  106. new_offset = *offset;
  107. break;
  108. case std::ios_base::cur:
  109. new_offset = offset_ + *offset;
  110. break;
  111. case std::ios_base::end:
  112. new_offset = file_info_->file_length_ + *offset;
  113. break;
  114. default:
  115. /* unsupported */
  116. return Status::InvalidArgument("Invalid Seek whence argument");
  117. }
  118. if(!CheckSeekBounds(new_offset)) {
  119. return Status::InvalidArgument("Seek offset out of bounds");
  120. }
  121. offset_ = new_offset;
  122. *offset = offset_;
  123. return Status::OK();
  124. }
  125. /* return false if seek will be out of bounds */
  126. bool FileHandleImpl::CheckSeekBounds(ssize_t desired_position) {
  127. ssize_t file_length = file_info_->file_length_;
  128. if (desired_position < 0 || desired_position > file_length) {
  129. return false;
  130. }
  131. return true;
  132. }
  133. /*
  134. * Note that this method must be thread-safe w.r.t. the unsafe operations occurring
  135. * on the FileHandle
  136. */
  137. void FileHandleImpl::AsyncPreadSome(
  138. size_t offset, const MutableBuffer &buffer,
  139. std::shared_ptr<NodeExclusionRule> excluded_nodes,
  140. const std::function<void(const Status &, const std::string &, size_t)> handler) {
  141. using ::hadoop::hdfs::DatanodeInfoProto;
  142. using ::hadoop::hdfs::LocatedBlockProto;
  143. LOG_DEBUG(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
  144. << FMT_THIS_ADDR << ", ...) called");
  145. if(cancel_state_->is_canceled()) {
  146. handler(Status::Canceled(), "", 0);
  147. return;
  148. }
  149. if(offset == file_info_->file_length_) {
  150. handler(Status::OK(), "", 0);
  151. return;
  152. } else if(offset > file_info_->file_length_){
  153. handler(Status::InvalidOffset("AsyncPreadSome: trying to begin a read past the EOF"), "", 0);
  154. return;
  155. }
  156. /**
  157. * Note: block and chosen_dn will end up pointing to things inside
  158. * the blocks_ vector. They shouldn't be directly deleted.
  159. **/
  160. auto block = std::find_if(
  161. file_info_->blocks_.begin(), file_info_->blocks_.end(), [offset](const LocatedBlockProto &p) {
  162. return p.offset() <= offset && offset < p.offset() + p.b().numbytes();
  163. });
  164. if (block == file_info_->blocks_.end()) {
  165. LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome(" << FMT_THIS_ADDR
  166. << ", ...) Cannot find corresponding blocks");
  167. handler(Status::InvalidArgument("Cannot find corresponding blocks"), "", 0);
  168. return;
  169. }
  170. /**
  171. * If user supplies a rule use it, otherwise use the tracker.
  172. * User is responsible for making sure one of them isn't null.
  173. **/
  174. std::shared_ptr<NodeExclusionRule> rule =
  175. excluded_nodes != nullptr ? excluded_nodes : bad_node_tracker_;
  176. auto datanodes = block->locs();
  177. auto it = std::find_if(datanodes.begin(), datanodes.end(),
  178. [rule](const DatanodeInfoProto &dn) {
  179. return !rule->IsBadNode(dn.id().datanodeuuid());
  180. });
  181. if (it == datanodes.end()) {
  182. LOG_WARN(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
  183. << FMT_THIS_ADDR << ", ...) No datanodes available");
  184. handler(Status::ResourceUnavailable("No datanodes available"), "", 0);
  185. return;
  186. }
  187. DatanodeInfoProto &chosen_dn = *it;
  188. std::string dnIpAddr = chosen_dn.id().ipaddr();
  189. std::string dnHostName = chosen_dn.id().hostname();
  190. uint64_t offset_within_block = offset - block->offset();
  191. uint64_t size_within_block = std::min<uint64_t>(
  192. block->b().numbytes() - offset_within_block, boost::asio::buffer_size(buffer));
  193. LOG_DEBUG(kFileHandle, << "FileHandleImpl::AsyncPreadSome("
  194. << FMT_THIS_ADDR << "), ...) Datanode hostname=" << dnHostName << ", IP Address=" << dnIpAddr
  195. << ", file path=\"" << path_ << "\", offset=" << std::to_string(offset) << ", read size=" << size_within_block);
  196. // This is where we will put the logic for re-using a DN connection; we can
  197. // steal the FileHandle's dn and put it back when we're done
  198. std::shared_ptr<DataNodeConnection> dn = CreateDataNodeConnection(io_service_, chosen_dn, &block->blocktoken());
  199. std::string dn_id = dn->uuid_;
  200. std::string client_name = client_name_;
  201. // Wrap the DN in a block reader to handle the state and logic of the
  202. // block request protocol
  203. std::shared_ptr<BlockReader> reader;
  204. reader = CreateBlockReader(BlockReaderOptions(), dn, event_handlers_);
  205. // Lambdas cannot capture copies of member variables so we'll make explicit
  206. // copies for it
  207. auto event_handlers = event_handlers_;
  208. auto path = path_;
  209. auto cluster_name = cluster_name_;
  210. auto read_handler = [reader, event_handlers, cluster_name, path, dn_id, handler](const Status & status, size_t transferred) {
  211. event_response event_resp = event_handlers->call(FILE_DN_READ_EVENT, cluster_name.c_str(), path.c_str(), transferred);
  212. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  213. if (event_resp.response_type() == event_response::kTest_Error) {
  214. handler(event_resp.status(), dn_id, transferred);
  215. return;
  216. }
  217. #endif
  218. handler(status, dn_id, transferred);
  219. };
  220. auto connect_handler = [handler,event_handlers,cluster_name,path,read_handler,block,offset_within_block,size_within_block, buffer, reader, dn_id, client_name]
  221. (Status status, std::shared_ptr<DataNodeConnection> dn) {
  222. (void)dn;
  223. event_response event_resp = event_handlers->call(FILE_DN_CONNECT_EVENT, cluster_name.c_str(), path.c_str(), 0);
  224. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  225. if (event_resp.response_type() == event_response::kTest_Error) {
  226. status = event_resp.status();
  227. }
  228. #endif
  229. if (status.ok()) {
  230. reader->AsyncReadBlock(
  231. client_name, *block, offset_within_block,
  232. boost::asio::buffer(buffer, size_within_block), read_handler);
  233. } else {
  234. handler(status, dn_id, 0);
  235. }
  236. };
  237. dn->Connect(connect_handler);
  238. return;
  239. }
  240. std::shared_ptr<BlockReader> FileHandleImpl::CreateBlockReader(const BlockReaderOptions &options,
  241. std::shared_ptr<DataNodeConnection> dn,
  242. std::shared_ptr<LibhdfsEvents> event_handlers)
  243. {
  244. std::shared_ptr<BlockReader> reader = std::make_shared<BlockReaderImpl>(options, dn, cancel_state_, event_handlers);
  245. LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateBlockReader(" << FMT_THIS_ADDR
  246. << ", ..., dnconn=" << dn.get()
  247. << ") called. New BlockReader = " << reader.get());
  248. readers_.AddReader(reader);
  249. return reader;
  250. }
  251. std::shared_ptr<DataNodeConnection> FileHandleImpl::CreateDataNodeConnection(
  252. std::shared_ptr<IoService> io_service,
  253. const ::hadoop::hdfs::DatanodeInfoProto & dn,
  254. const hadoop::common::TokenProto * token) {
  255. LOG_TRACE(kFileHandle, << "FileHandleImpl::CreateDataNodeConnection("
  256. << FMT_THIS_ADDR << ", ...) called");
  257. return std::make_shared<DataNodeConnectionImpl>(io_service, dn, token, event_handlers_.get());
  258. }
  259. std::shared_ptr<LibhdfsEvents> FileHandleImpl::get_event_handlers() {
  260. return event_handlers_;
  261. }
  262. void FileHandleImpl::CancelOperations() {
  263. LOG_INFO(kFileHandle, << "FileHandleImpl::CancelOperations("
  264. << FMT_THIS_ADDR << ") called");
  265. cancel_state_->set_canceled();
  266. /* Push update to BlockReaders that may be hung in an asio call */
  267. std::vector<std::shared_ptr<BlockReader>> live_readers = readers_.GetLiveReaders();
  268. for(auto reader : live_readers) {
  269. reader->CancelOperation();
  270. }
  271. }
  272. void FileHandleImpl::SetFileEventCallback(file_event_callback callback) {
  273. std::shared_ptr<LibhdfsEvents> new_event_handlers;
  274. if (event_handlers_) {
  275. new_event_handlers = std::make_shared<LibhdfsEvents>(*event_handlers_);
  276. } else {
  277. new_event_handlers = std::make_shared<LibhdfsEvents>();
  278. }
  279. new_event_handlers->set_file_callback(callback);
  280. event_handlers_ = new_event_handlers;
  281. }
  282. bool FileHandle::ShouldExclude(const Status &s) {
  283. if (s.ok()) {
  284. return false;
  285. }
  286. switch (s.code()) {
  287. /* client side resource exhaustion */
  288. case Status::kResourceUnavailable:
  289. case Status::kOperationCanceled:
  290. return false;
  291. case Status::kInvalidArgument:
  292. case Status::kUnimplemented:
  293. case Status::kException:
  294. default:
  295. return true;
  296. }
  297. }
  298. uint64_t FileHandleImpl::get_bytes_read() { return bytes_read_.load(); }
  299. void FileHandleImpl::clear_bytes_read() { bytes_read_.store(0); }
  300. }