-
Notifications
You must be signed in to change notification settings - Fork 61
/
s3.py
129 lines (110 loc) 路 4.71 KB
/
s3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#
# Copyright (c) 2022, Neptune Labs Sp. z o.o.
#
# Licensed 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 pathlib
import typing
from datetime import datetime
from urllib.parse import urlparse
import boto3
from botocore.exceptions import NoCredentialsError
from neptune.new.exceptions import (
NeptuneRemoteStorageAccessException,
NeptuneRemoteStorageCredentialsException,
NeptuneUnsupportedArtifactFunctionalityException,
)
from neptune.new.internal.artifacts.types import (
ArtifactDriver,
ArtifactFileData,
ArtifactFileType,
)
class S3ArtifactDriver(ArtifactDriver):
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
@staticmethod
def get_type() -> str:
return ArtifactFileType.S3.value
@classmethod
def matches(cls, path: str) -> bool:
return urlparse(path).scheme == "s3"
@classmethod
def _serialize_metadata(cls, metadata: typing.Dict[str, typing.Any]) -> typing.Dict[str, str]:
return {
"location": metadata["location"],
"last_modified": metadata["last_modified"].strftime(cls.DATETIME_FORMAT),
}
@classmethod
def _deserialize_metadata(cls, metadata: typing.Dict[str, str]) -> typing.Dict[str, typing.Any]:
return {
"location": metadata["location"],
"last_modified": datetime.strptime(metadata["last_modified"], cls.DATETIME_FORMAT),
}
@classmethod
def get_tracked_files(cls, path: str, destination: str = None) -> typing.List[ArtifactFileData]:
url = urlparse(path)
bucket_name, prefix = url.netloc, url.path.lstrip("/")
if "*" in prefix:
raise NeptuneUnsupportedArtifactFunctionalityException(
f"Wildcard characters (*,?) in location URI ({path}) are not supported."
)
# pylint: disable=no-member
remote_storage = boto3.resource("s3").Bucket(bucket_name)
stored_files: typing.List[ArtifactFileData] = list()
try:
for remote_object in remote_storage.objects.filter(Prefix=prefix):
# If prefix is path to file get only directories
if prefix == remote_object.key:
prefix = str(pathlib.PurePosixPath(prefix).parent)
remote_key = remote_object.key
destination = pathlib.PurePosixPath(destination or "")
relative_file_path = remote_key[len(prefix.lstrip(".")) :].lstrip("/")
file_path = destination / relative_file_path
stored_files.append(
ArtifactFileData(
file_path=str(file_path).lstrip("/"),
file_hash=remote_object.e_tag.strip('"'),
type=ArtifactFileType.S3.value,
size=remote_object.size,
metadata=cls._serialize_metadata(
{
"location": f's3://{bucket_name}/{remote_key.lstrip("/")}',
"last_modified": remote_object.last_modified,
}
),
)
)
except NoCredentialsError:
raise NeptuneRemoteStorageCredentialsException()
except (
remote_storage.meta.client.exceptions.NoSuchBucket,
remote_storage.meta.client.exceptions.NoSuchKey,
):
raise NeptuneRemoteStorageAccessException(location=path)
return stored_files
@classmethod
def download_file(cls, destination: pathlib.Path, file_definition: ArtifactFileData):
location = file_definition.metadata.get("location")
url = urlparse(location)
bucket_name, path = url.netloc, url.path.lstrip("/")
remote_storage = boto3.resource("s3")
try:
# pylint: disable=no-member
bucket = remote_storage.Bucket(bucket_name)
bucket.download_file(path, str(destination))
except NoCredentialsError:
raise NeptuneRemoteStorageCredentialsException()
except (
remote_storage.meta.client.exceptions.NoSuchBucket,
remote_storage.meta.client.exceptions.NoSuchKey,
):
raise NeptuneRemoteStorageAccessException(location=location)