filehandle.cc 12 KB

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