filehandle.cc 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 "connection/datanodeconnection.h"
  21. #include "reader/block_reader.h"
  22. #include <future>
  23. #include <tuple>
  24. namespace hdfs {
  25. using ::hadoop::hdfs::LocatedBlocksProto;
  26. FileHandle::~FileHandle() {}
  27. FileHandleImpl::FileHandleImpl(::asio::io_service *io_service, const std::string &client_name,
  28. const std::shared_ptr<const struct FileInfo> file_info,
  29. std::shared_ptr<BadDataNodeTracker> bad_data_nodes)
  30. : io_service_(io_service), client_name_(client_name), file_info_(file_info),
  31. bad_node_tracker_(bad_data_nodes), offset_(0) {
  32. }
  33. void FileHandleImpl::PositionRead(
  34. void *buf, size_t nbyte, uint64_t offset,
  35. const std::function<void(const Status &, size_t)>
  36. &handler) {
  37. auto callback = [this, handler](const Status &status,
  38. const std::string &contacted_datanode,
  39. size_t bytes_read) {
  40. /* determine if DN gets marked bad */
  41. if (ShouldExclude(status)) {
  42. bad_node_tracker_->AddBadNode(contacted_datanode);
  43. }
  44. handler(status, bytes_read);
  45. };
  46. AsyncPreadSome(offset, asio::buffer(buf, nbyte), bad_node_tracker_, callback);
  47. }
  48. Status FileHandleImpl::PositionRead(void *buf, size_t *nbyte, off_t offset) {
  49. auto callstate = std::make_shared<std::promise<std::tuple<Status, size_t>>>();
  50. std::future<std::tuple<Status, size_t>> future(callstate->get_future());
  51. /* wrap async call with promise/future to make it blocking */
  52. auto callback = [callstate](const Status &s, size_t bytes) {
  53. callstate->set_value(std::make_tuple(s,bytes));
  54. };
  55. PositionRead(buf, *nbyte, offset, callback);
  56. /* wait for async to finish */
  57. auto returnstate = future.get();
  58. auto stat = std::get<0>(returnstate);
  59. if (!stat.ok()) {
  60. return stat;
  61. }
  62. *nbyte = std::get<1>(returnstate);
  63. return stat;
  64. }
  65. Status FileHandleImpl::Read(void *buf, size_t *nbyte) {
  66. Status stat = PositionRead(buf, nbyte, offset_);
  67. if(!stat.ok()) {
  68. return stat;
  69. }
  70. offset_ += *nbyte;
  71. return Status::OK();
  72. }
  73. Status FileHandleImpl::Seek(off_t *offset, std::ios_base::seekdir whence) {
  74. off_t new_offset = -1;
  75. switch (whence) {
  76. case std::ios_base::beg:
  77. new_offset = *offset;
  78. break;
  79. case std::ios_base::cur:
  80. new_offset = offset_ + *offset;
  81. break;
  82. case std::ios_base::end:
  83. new_offset = file_info_->file_length_ + *offset;
  84. break;
  85. default:
  86. /* unsupported */
  87. return Status::InvalidArgument("Invalid Seek whence argument");
  88. }
  89. if(!CheckSeekBounds(new_offset)) {
  90. return Status::InvalidArgument("Seek offset out of bounds");
  91. }
  92. offset_ = new_offset;
  93. *offset = offset_;
  94. return Status::OK();
  95. }
  96. /* return false if seek will be out of bounds */
  97. bool FileHandleImpl::CheckSeekBounds(ssize_t desired_position) {
  98. ssize_t file_length = file_info_->file_length_;
  99. if (desired_position < 0 || desired_position > file_length) {
  100. return false;
  101. }
  102. return true;
  103. }
  104. /*
  105. * Note that this method must be thread-safe w.r.t. the unsafe operations occurring
  106. * on the FileHandle
  107. */
  108. void FileHandleImpl::AsyncPreadSome(
  109. size_t offset, const MutableBuffers &buffers,
  110. std::shared_ptr<NodeExclusionRule> excluded_nodes,
  111. const std::function<void(const Status &, const std::string &, size_t)> handler) {
  112. using ::hadoop::hdfs::DatanodeInfoProto;
  113. using ::hadoop::hdfs::LocatedBlockProto;
  114. /**
  115. * Note: block and chosen_dn will end up pointing to things inside
  116. * the blocks_ vector. They shouldn't be directly deleted.
  117. **/
  118. auto block = std::find_if(
  119. file_info_->blocks_.begin(), file_info_->blocks_.end(), [offset](const LocatedBlockProto &p) {
  120. return p.offset() <= offset && offset < p.offset() + p.b().numbytes();
  121. });
  122. if (block == file_info_->blocks_.end()) {
  123. handler(Status::InvalidArgument("Cannot find corresponding blocks"), "", 0);
  124. return;
  125. }
  126. /**
  127. * If user supplies a rule use it, otherwise use the tracker.
  128. * User is responsible for making sure one of them isn't null.
  129. **/
  130. std::shared_ptr<NodeExclusionRule> rule =
  131. excluded_nodes != nullptr ? excluded_nodes : bad_node_tracker_;
  132. auto datanodes = block->locs();
  133. auto it = std::find_if(datanodes.begin(), datanodes.end(),
  134. [rule](const DatanodeInfoProto &dn) {
  135. return !rule->IsBadNode(dn.id().datanodeuuid());
  136. });
  137. if (it == datanodes.end()) {
  138. handler(Status::ResourceUnavailable("No datanodes available"), "", 0);
  139. return;
  140. }
  141. DatanodeInfoProto &chosen_dn = *it;
  142. uint64_t offset_within_block = offset - block->offset();
  143. uint64_t size_within_block = std::min<uint64_t>(
  144. block->b().numbytes() - offset_within_block, asio::buffer_size(buffers));
  145. // This is where we will put the logic for re-using a DN connection; we can
  146. // steal the FileHandle's dn and put it back when we're done
  147. std::shared_ptr<DataNodeConnection> dn = CreateDataNodeConnection(io_service_, chosen_dn, nullptr /*token*/);
  148. std::string dn_id = dn->uuid_;
  149. std::string client_name = client_name_;
  150. // Wrap the DN in a block reader to handle the state and logic of the
  151. // block request protocol
  152. std::shared_ptr<BlockReader> reader;
  153. reader = CreateBlockReader(BlockReaderOptions(), dn);
  154. auto read_handler = [reader, dn_id, handler](const Status & status, size_t transferred) {
  155. handler(status, dn_id, transferred);
  156. };
  157. dn->Connect([handler,read_handler,block,offset_within_block,size_within_block, buffers, reader, dn_id, client_name]
  158. (Status status, std::shared_ptr<DataNodeConnection> dn) {
  159. (void)dn;
  160. if (status.ok()) {
  161. reader->AsyncReadBlock(
  162. client_name, *block, offset_within_block,
  163. asio::buffer(buffers, size_within_block), read_handler);
  164. } else {
  165. handler(status, dn_id, 0);
  166. }
  167. });
  168. return;
  169. }
  170. std::shared_ptr<BlockReader> FileHandleImpl::CreateBlockReader(const BlockReaderOptions &options,
  171. std::shared_ptr<DataNodeConnection> dn)
  172. {
  173. return std::make_shared<BlockReaderImpl>(options, dn);
  174. }
  175. std::shared_ptr<DataNodeConnection> FileHandleImpl::CreateDataNodeConnection(
  176. ::asio::io_service * io_service,
  177. const ::hadoop::hdfs::DatanodeInfoProto & dn,
  178. const hadoop::common::TokenProto * token) {
  179. return std::make_shared<DataNodeConnectionImpl>(io_service, dn, token);
  180. }
  181. bool FileHandle::ShouldExclude(const Status &s) {
  182. if (s.ok()) {
  183. return false;
  184. }
  185. switch (s.code()) {
  186. /* client side resource exhaustion */
  187. case Status::kResourceUnavailable:
  188. return false;
  189. case Status::kInvalidArgument:
  190. case Status::kUnimplemented:
  191. case Status::kException:
  192. default:
  193. return true;
  194. }
  195. }
  196. }