TheR1sing3un commented on code in PR #8031:
URL: https://github.com/apache/paimon/pull/8031#discussion_r3340090738


##########
paimon-python/pypaimon/filesystem/hdfs_native_file_io.py:
##########
@@ -0,0 +1,638 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""HDFS FileIO backed by the hdfs-native protocol client (no JVM, no 
libhdfs)."""
+
+import logging
+import os
+import xml.etree.ElementTree as ET
+from datetime import datetime, timezone
+from pathlib import PurePosixPath
+from typing import Dict, Optional
+from urllib.parse import urlparse
+
+import pyarrow
+import pyarrow.fs as pafs
+
+from pypaimon.common.file_io import FileIO
+from pypaimon.common.options import Options
+from pypaimon.common.options.config import HdfsOptions, SecurityOptions
+from pypaimon.common.uri_reader import UriReaderFactory
+from pypaimon.filesystem import _kerberos
+from pypaimon.schema.data_types import AtomicType, DataField, 
PyarrowFieldParser
+from pypaimon.write.blob_format_writer import BlobFormatWriter
+
+
+class _HdfsFileInfo:
+    """pafs.FileInfo-shaped adapter built from hdfs_native.FileStatus."""
+    __slots__ = ('path', 'size', 'type', 'mtime', 'base_name')
+
+    def __init__(self, path: str, size: Optional[int], file_type, mtime):
+        self.path = path
+        self.size = size
+        self.type = file_type
+        self.mtime = mtime
+        self.base_name = path.rsplit('/', 1)[-1] if path else ''
+
+
+class _HdfsWriterAdapter:
+    """File-like wrapper over hdfs_native.FileWriter."""
+
+    def __init__(self, fw):
+        self._fw = fw
+        self._pos = 0
+        self._closed = False
+
+    def write(self, buf) -> int:
+        n = self._fw.write(buf)
+        if n is None:
+            n = len(buf) if hasattr(buf, '__len__') else 0
+        self._pos += n
+        return n
+
+    def tell(self) -> int:
+        return self._pos
+
+    def flush(self):
+        pass
+
+    def close(self):
+        if not self._closed:
+            try:
+                self._fw.close()
+            finally:
+                self._closed = True
+
+    @property
+    def closed(self) -> bool:
+        return self._closed
+
+    def writable(self) -> bool:
+        return True
+
+    def readable(self) -> bool:
+        return False
+
+    def seekable(self) -> bool:
+        return False
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *exc):
+        self.close()
+        return False
+
+
+class _HdfsReaderAdapter:
+    """File-like wrapper over hdfs_native.FileReader.
+
+    Delegates read/seek/tell straight to the underlying reader (which is an
+    io.RawIOBase subclass with full seek/tell support). The wrapper only
+    exists so that exiting a `with` block guarantees the underlying handle
+    is closed — hdfs-native's own FileReader.__exit__ is a no-op.
+    """
+
+    def __init__(self, fr):
+        self._fr = fr
+        self._closed = False
+
+    def read(self, size: int = -1) -> bytes:
+        return self._fr.read(-1 if size is None else size)
+
+    def read1(self, size: int = -1) -> bytes:
+        return self.read(size)
+
+    def seek(self, pos: int, whence: int = 0) -> int:
+        self._fr.seek(pos, whence)
+        return self._fr.tell()
+
+    def tell(self) -> int:
+        return self._fr.tell()
+
+    def close(self):
+        if self._closed:
+            return
+        try:
+            close = getattr(self._fr, 'close', None)
+            if close is not None:
+                close()
+        finally:
+            self._closed = True
+
+    @property
+    def closed(self) -> bool:
+        return self._closed
+
+    def readable(self) -> bool:
+        return True
+
+    def writable(self) -> bool:
+        return False
+
+    def seekable(self) -> bool:
+        return True
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *exc):
+        self.close()
+        return False
+
+
+class HdfsNativeFileIO(FileIO):
+    """HDFS FileIO that speaks the HDFS RPC protocol directly.
+
+    No JVM, no libhdfs, no Hadoop install required. Hadoop xml is still
+    consumed if present (HADOOP_CONF_DIR or `hdfs.conf-dir` option) for
+    viewfs mount tables and HA NameNode lists; alternatively the same
+    key/values can be delivered via the catalog options channel (a REST
+    catalog can therefore push the cluster wiring with the response).
+    """
+
+    NATIVE_KEY_PREFIXES = HdfsOptions.HDFS_NATIVE_CONFIG_KEY_PREFIXES
+    NS_PREFIX = HdfsOptions.HDFS_CONFIG_PREFIX
+
+    def __init__(self, path: str, catalog_options: Options):
+        self.properties = catalog_options or Options({})
+        self.logger = logging.getLogger(__name__)
+        self.uri_reader_factory = UriReaderFactory(self.properties)
+
+        scheme, netloc, _ = self.parse_location(path)
+        if scheme not in {"hdfs", "viewfs"}:
+            raise ValueError(
+                f"HdfsNativeFileIO does not support scheme '{scheme}'"
+            )
+        self._scheme = scheme
+        self._netloc = netloc
+
+        try:
+            from hdfs_native import Client, WriteOptions
+        except ImportError as e:
+            raise ImportError(
+                "hdfs-native is not installed. "
+                "Install with: pip install 'pypaimon[hdfs]'"
+            ) from e
+        self._WriteOptions = WriteOptions
+
+        self._setup_kerberos()
+
+        config_dir = (
+            self.properties.get(HdfsOptions.HDFS_CONF_DIR)
+            or os.environ.get("HADOOP_CONF_DIR")
+        )
+        hadoop_xml = self._load_hadoop_xml(config_dir)
+
+        config = self._build_config_dict()
+        self._maybe_inject_viewfs_fallback(scheme, netloc, config, hadoop_xml)

Review Comment:
   nice suggestion! done!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to