filehandle.cc 13 KB

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