filehandle.cc 12 KB

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