_table.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import io
  17. from typing import Iterable
  18. from pyarrow import fs
  19. from fate_arch.common import hdfs_utils
  20. from fate_arch.common.log import getLogger
  21. from fate_arch.storage import StorageEngine, HDFSStoreType
  22. from fate_arch.storage import StorageTableBase
  23. LOGGER = getLogger()
  24. class StorageTable(StorageTableBase):
  25. def __init__(
  26. self,
  27. address=None,
  28. name: str = None,
  29. namespace: str = None,
  30. partitions: int = 1,
  31. store_type: HDFSStoreType = HDFSStoreType.DISK,
  32. options=None,
  33. ):
  34. super(StorageTable, self).__init__(
  35. name=name,
  36. namespace=namespace,
  37. address=address,
  38. partitions=partitions,
  39. options=options,
  40. engine=StorageEngine.HDFS,
  41. store_type=store_type,
  42. )
  43. # tricky way to load libhdfs
  44. try:
  45. from pyarrow import HadoopFileSystem
  46. HadoopFileSystem(self.path)
  47. except Exception as e:
  48. LOGGER.warning(f"load libhdfs failed: {e}")
  49. self._hdfs_client = fs.HadoopFileSystem.from_uri(self.path)
  50. def check_address(self):
  51. return self._exist()
  52. def _put_all(
  53. self, kv_list: Iterable, append=True, assume_file_exist=False, **kwargs
  54. ):
  55. LOGGER.info(f"put in hdfs file: {self.file_path}")
  56. if append and (assume_file_exist or self._exist()):
  57. stream = self._hdfs_client.open_append_stream(
  58. path=self.file_path, compression=None
  59. )
  60. else:
  61. stream = self._hdfs_client.open_output_stream(
  62. path=self.file_path, compression=None
  63. )
  64. counter = self._meta.get_count() if self._meta.get_count() else 0
  65. with io.TextIOWrapper(stream) as writer:
  66. for k, v in kv_list:
  67. writer.write(hdfs_utils.serialize(k, v))
  68. writer.write(hdfs_utils.NEWLINE)
  69. counter = counter + 1
  70. self._meta.update_metas(count=counter)
  71. def _collect(self, **kwargs) -> list:
  72. for line in self._as_generator():
  73. yield hdfs_utils.deserialize(line.rstrip())
  74. def _read(self) -> list:
  75. for line in self._as_generator():
  76. yield line
  77. def _destroy(self):
  78. self._hdfs_client.delete_file(self.file_path)
  79. def _count(self):
  80. count = 0
  81. if self._meta.get_count():
  82. return self._meta.get_count()
  83. for _ in self._as_generator():
  84. count += 1
  85. return count
  86. def _save_as(
  87. self, address, partitions=None, name=None, namespace=None, **kwargs
  88. ):
  89. self._hdfs_client.copy_file(src=self.file_path, dst=address.path)
  90. table = StorageTable(
  91. address=address,
  92. partitions=partitions,
  93. name=name,
  94. namespace=namespace,
  95. **kwargs,
  96. )
  97. return table
  98. def close(self):
  99. pass
  100. @property
  101. def path(self) -> str:
  102. return f"{self._address.name_node}/{self._address.path}"
  103. @property
  104. def file_path(self) -> str:
  105. return f"{self._address.path}"
  106. def _exist(self):
  107. info = self._hdfs_client.get_file_info([self.file_path])[0]
  108. return info.type != fs.FileType.NotFound
  109. def _as_generator(self):
  110. LOGGER.info(f"as generator: {self.file_path}")
  111. info = self._hdfs_client.get_file_info([self.file_path])[0]
  112. if info.type == fs.FileType.NotFound:
  113. raise FileNotFoundError(f"file {self.file_path} not found")
  114. elif info.type == fs.FileType.File:
  115. for line in self._read_buffer_lines():
  116. yield line
  117. else:
  118. selector = fs.FileSelector(self.file_path)
  119. file_infos = self._hdfs_client.get_file_info(selector)
  120. for file_info in file_infos:
  121. if file_info.base_name == "_SUCCESS":
  122. continue
  123. assert (
  124. file_info.is_file
  125. ), f"{self.path} is directory contains a subdirectory: {file_info.path}"
  126. with io.TextIOWrapper(
  127. buffer=self._hdfs_client.open_input_stream(file_info.path),
  128. encoding="utf-8",
  129. ) as reader:
  130. for line in reader:
  131. yield line
  132. def _read_buffer_lines(self, path=None):
  133. if not path:
  134. path = self.file_path
  135. buffer = self._hdfs_client.open_input_file(path)
  136. offset = 0
  137. block_size = 1024 * 1024 * 10
  138. size = buffer.size()
  139. while offset < size:
  140. block_index = 1
  141. buffer_block = buffer.read_at(block_size, offset)
  142. if offset + block_size >= size:
  143. for line in self._read_lines(buffer_block):
  144. yield line
  145. break
  146. if buffer_block.endswith(b"\n"):
  147. for line in self._read_lines(buffer_block):
  148. yield line
  149. offset += block_size
  150. continue
  151. end_index = -1
  152. buffer_len = len(buffer_block)
  153. while not buffer_block[:end_index].endswith(b"\n"):
  154. if offset + block_index * block_size >= size:
  155. break
  156. end_index -= 1
  157. if abs(end_index) == buffer_len:
  158. block_index += 1
  159. buffer_block = buffer.read_at(block_index * block_size, offset)
  160. end_index = block_index * block_size
  161. for line in self._read_lines(buffer_block[:end_index]):
  162. yield line
  163. offset += len(buffer_block[:end_index])
  164. def _read_lines(self, buffer_block):
  165. with io.TextIOWrapper(buffer=io.BytesIO(buffer_block), encoding="utf-8") as reader:
  166. for line in reader:
  167. yield line