TGooch44 commented on a change in pull request #277: Moving/Renaming hadoop 
module to filesystem
URL: https://github.com/apache/incubator-iceberg/pull/277#discussion_r309675119
 
 

 ##########
 File path: python/iceberg/core/filesystem/s3_filesystem.py
 ##########
 @@ -0,0 +1,274 @@
+# 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.
+
+import io
+import logging
+import re
+import time
+from urllib.parse import urlparse
+
+import boto3
+from botocore.credentials import RefreshableCredentials
+from botocore.session import get_session
+from retrying import retry
+
+from .file_status import FileStatus
+from .file_system import FileSystem
+
+_logger = logging.getLogger(__name__)
+
+
+S3_CLIENT = dict()
+BOTO_STS_CLIENT = boto3.client('sts')
+ROLE_ARN = None
+AUTOREFRESH_SESSION = None
+
+
+@retry(wait_incrementing_start=100, wait_exponential_multiplier=4,
+       wait_exponential_max=5000, stop_max_delay=600000, 
stop_max_attempt_number=7)
+def get_s3(obj="resource"):
+    global AUTOREFRESH_SESSION
+    global ROLE_ARN
+    if ROLE_ARN not in S3_CLIENT:
+        S3_CLIENT[ROLE_ARN] = dict()
+
+    if ROLE_ARN == "default":
+        if AUTOREFRESH_SESSION is None:
+            AUTOREFRESH_SESSION = boto3.Session()
+        S3_CLIENT["default"]["resource"] = AUTOREFRESH_SESSION.resource('s3')
+        S3_CLIENT["default"]["client"] = AUTOREFRESH_SESSION.client('s3')
+    else:
+        if AUTOREFRESH_SESSION is None:
+            sess = get_session()
+            sess._credentials = 
RefreshableCredentials.create_from_metadata(metadata=refresh_sts_session_keys(),
+                                                                            
refresh_using=refresh_sts_session_keys,
+                                                                            
method="sts-assume-role")
+            AUTOREFRESH_SESSION = boto3.Session(botocore_session=sess)
+
+        S3_CLIENT[ROLE_ARN]["resource"] = AUTOREFRESH_SESSION.resource("s3")
+        S3_CLIENT[ROLE_ARN]["client"] = AUTOREFRESH_SESSION.client("s3")
+
+    return S3_CLIENT.get(ROLE_ARN, dict()).get(obj)
+
+
+def refresh_sts_session_keys():
+    params = {"RoleArn": ROLE_ARN,
+              "RoleSessionName": 
"iceberg_python_client_{}".format(int(time.time() * 1000.00))}
+
+    sts_creds = BOTO_STS_CLIENT.assume_role(**params).get("Credentials")
+    credentials = {"access_key": sts_creds.get("AccessKeyId"),
+                   "secret_key": sts_creds.get("SecretAccessKey"),
+                   "token": sts_creds.get("SessionToken"),
+                   "expiry_time": sts_creds.get("Expiration").isoformat()}
+    return credentials
+
+
+def url_to_bucket_key_name_tuple(url):
+    parsed_url = urlparse(url)
+    return parsed_url.netloc, parsed_url.path[1:], 
parsed_url.path.split("/")[-1]
+
+
+class S3FileSystem(FileSystem):
+    fs_inst = None
+
+    @staticmethod
+    def get_instance():
+        if S3FileSystem.fs_inst is None:
+            S3FileSystem()
+        return S3FileSystem.fs_inst
+
+    def __init__(self):
+        if S3FileSystem.fs_inst is None:
+            S3FileSystem.fs_inst = self
+
+    def set_conf(self, conf):
+        global ROLE_ARN
+        if conf is not None:
+            ROLE_ARN = conf.get("hive.aws_iam_role", "default")
+
+    def exists(self, path):
+        bucket, key, _ = 
url_to_bucket_key_name_tuple(S3FileSystem.normalize_s3_path(path))
+
+        res = get_s3(obj="client").list_objects_v2(Bucket=bucket,
+                                                   Prefix=key)
+        for obj in res.get('Contents', []):
+            return True
+
+        return False
+
+    def open(self, path, mode='rb'):
+        return S3File(path, mode=mode)
+
+    def delete(self, path):
+        bucket, key, _ = 
url_to_bucket_key_name_tuple(S3FileSystem.normalize_s3_path(path))
+        get_s3().Object(bucket_name=bucket,
+                        key=key).delete()
+
+    def stat(self, path):
+        is_dir = False
+        st = dict()
+        length = -1
+        try:
+            st = self.info(S3FileSystem.normalize_s3_path(path))
+        except RuntimeError:
+            # must be a directory or subsequent du will fail
+            du = self.du(S3FileSystem.normalize_s3_path(path))
+            if len(du) > 0:
+                is_dir = True
+
+            length = sum([val for key, val in 
du("s3://netflix-dataplatform-code/tgooch/test_write2.txt").items()])
+
+        return FileStatus(path=path, length=st.get("ContentLength", length), 
is_dir=is_dir,
+                          blocksize=None, 
modification_time=st.get("LastModified"), access_time=None,
+                          permission=None, owner=None, group=None)
+
+    @staticmethod
+    def du(url):
+        bucket, key, _ = url_to_bucket_key_name_tuple(url)
+        kwargs = {"Bucket": bucket,
+                  "Prefix": key}
+        du_items = {}
+        while True:
+            resp = get_s3().list_objects_v2(**kwargs)
 
 Review comment:
   I added the delimiter to the kwargs here, although I'm not sure that's quite 
right, the linux du command will list sub-directories and folders by default. 
With delimiter set, it will not here.  I'll share a notebook with you and take 
a look and let me know what you think

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to