yuseok89 commented on code in PR #77788:
URL: https://github.com/apache/airflow/pull/77788#discussion_r4756863983


##########
providers/samba/src/airflow/providers/samba/fs/_smb_filesystem.py:
##########
@@ -0,0 +1,161 @@
+#
+# 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.
+from __future__ import annotations
+
+import datetime
+from stat import S_ISDIR
+from typing import Any
+
+import smbclient
+from fsspec import AbstractFileSystem
+from fsspec.implementations.smb import (
+    SMBFileOpener,
+    SMBFileSystem,
+    _as_temp_path,
+    _as_unc_path,
+    _share_has_path,
+)
+
+from airflow.providers.samba.hooks.samba import _get_auth_protocol
+
+
+class _SMBFileOpener(SMBFileOpener):
+    """``SMBFileOpener`` that also sends the session arguments when it commits 
or discards the file."""
+
+    def __init__(self, *args: Any, session_kwargs: dict[str, Any], **kwargs: 
Any) -> None:
+        self.session_kwargs = session_kwargs
+        super().__init__(*args, **session_kwargs, **kwargs)
+
+    def commit(self) -> None:
+        smbclient.replace(self.temp, self.path, port=self.port, 
**self.session_kwargs)
+
+    def discard(self) -> None:
+        smbclient.remove(self.temp, port=self.port, **self.session_kwargs)
+
+
+class _IsolatedSMBFileSystem(SMBFileSystem):
+    """
+    ``SMBFileSystem`` that keeps its own SMB connection and sends its 
credentials with every call.
+
+    fsspec registers a session once in smbclient's process-wide pool and then 
calls smbclient without
+    credentials, so smbclient uses the first session it finds for the server. 
Two connections to the same
+    server would then both act as whichever user connected first, and once the 
server drops the
+    connection, smbclient reconnects without credentials and every call fails. 
Like ``SambaHook``, this
+    filesystem keeps a pool of its own and passes the credentials on every 
call, which opens the session
+    on first use and again after the server drops it.
+    """
+
+    def __init__(self, *args: Any, auth_protocol: str = "negotiate", **kwargs: 
Any) -> None:
+        self.auth_protocol = _get_auth_protocol({}, auth_protocol)
+        self._connection_cache: dict[str, Any] = {}
+        super().__init__(*args, **kwargs)
+
+    @property
+    def _session_kwargs(self) -> dict[str, Any]:
+        return {
+            "username": self.username,
+            "password": self.password,
+            "encrypt": self.encrypt,
+            "connection_timeout": self.timeout,
+            "connection_cache": self._connection_cache,
+            "auth_protocol": self.auth_protocol,
+        }
+
+    def _connect(self) -> None:
+        """Do not register a session up front; each call opens it in this 
filesystem's own pool."""
+
+    def ls(self, path, detail=True, **kwargs):
+        return super().ls(path, detail=detail, **{**kwargs, 
**self._session_kwargs})
+
+    def info(self, path, **kwargs):
+        return super().info(path, **{**kwargs, **self._session_kwargs})
+
+    def created(self, path):
+        stats = smbclient.stat(_as_unc_path(self.host, path), port=self._port, 
**self._session_kwargs)
+        return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.UTC)
+
+    def modified(self, path):
+        stats = smbclient.stat(_as_unc_path(self.host, path), port=self._port, 
**self._session_kwargs)
+        return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.UTC)
+
+    def mkdir(self, path, create_parents=True, **kwargs):
+        return super().mkdir(path, create_parents=create_parents, **{**kwargs, 
**self._session_kwargs})
+
+    def makedirs(self, path, exist_ok=False):
+        if _share_has_path(path):
+            smbclient.makedirs(
+                _as_unc_path(self.host, path), exist_ok=exist_ok, 
port=self._port, **self._session_kwargs
+            )
+
+    def rmdir(self, path):
+        if _share_has_path(path):
+            smbclient.rmdir(_as_unc_path(self.host, path), port=self._port, 
**self._session_kwargs)
+
+    def _rm(self, path):
+        if _share_has_path(path):
+            wpath = _as_unc_path(self.host, path)
+            stats = smbclient.stat(wpath, port=self._port, 
**self._session_kwargs)
+            if S_ISDIR(stats.st_mode):
+                smbclient.rmdir(wpath, port=self._port, **self._session_kwargs)
+            else:
+                smbclient.remove(wpath, port=self._port, 
**self._session_kwargs)
+
+    def _open(self, path, mode="rb", block_size=-1, autocommit=True, 
cache_options=None, **kwargs):
+        if "w" in mode and autocommit is False:
+            if self.auto_mkdir:
+                self.makedirs(self._parent(path), exist_ok=True)
+            kwargs.pop("share_access", None)
+            return _SMBFileOpener(
+                _as_unc_path(self.host, path),
+                _as_temp_path(self.host, path, self.temppath),
+                mode,
+                port=self._port,
+                block_size=block_size if block_size is not None and block_size 
>= 0 else -1,
+                session_kwargs=self._session_kwargs,
+                **kwargs,
+            )
+        return super()._open(
+            path,
+            mode=mode,
+            block_size=block_size,
+            autocommit=autocommit,
+            cache_options=cache_options,
+            **{**kwargs, **self._session_kwargs},
+        )
+
+    # fsspec's SMB ``copy`` passes ``recursive`` on to smbclient, which 
rejects it, so copies go through
+    # the generic ``copy`` and a server-side ``cp_file`` instead.
+    copy = AbstractFileSystem.copy
+
+    def cp_file(self, path1, path2, **kwargs):
+        if self.isdir(path1):
+            self.makedirs(path2, exist_ok=True)
+            return
+        if self.auto_mkdir:
+            self.makedirs(self._parent(path2), exist_ok=True)
+        smbclient.copyfile(
+            _as_unc_path(self.host, path1),
+            _as_unc_path(self.host, path2),
+            port=self._port,
+            **self._session_kwargs,
+        )
+
+    def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs):

Review Comment:
   Switched `mv` to `smbclient.replace`, so a move or `replace()` onto an 
existing file overwrites it, as on the other filesystems you mentioned. Moving 
onto a folder that has files is still refused, so nothing gets removed there. 
`smbclient.replace` behaved that way on both Samba and Azure Files.



-- 
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