forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.py
413 lines (358 loc) · 14.1 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
import asyncio
import os
from contextlib import AsyncExitStack
from functools import partial
import aioboto3
import fastjsonschema
from aiobotocore.config import AioConfig
from botocore.exceptions import ClientError
from fastjsonschema import JsonSchemaValueException
from connectors.filtering.validation import (
AdvancedRulesValidator,
SyncRuleValidationResult,
)
from connectors.logger import logger
from connectors.source import BaseDataSource
from connectors.utils import hash_id
DEFAULT_PAGE_SIZE = 100
DEFAULT_MAX_RETRY_ATTEMPTS = 5
DEFAULT_CONNECTION_TIMEOUT = 90
DEFAULT_READ_TIMEOUT = 90
if "AWS_ENDPOINT_URL" in os.environ:
AWS_ENDPOINT = f"{os.environ['AWS_ENDPOINT_URL']}:{os.environ['AWS_PORT']}"
else:
AWS_ENDPOINT = None
class S3Client:
"""Amazon S3 client to handle method calls made to S3"""
def __init__(self, configuration):
self.configuration = configuration
self._logger = logger
self.session = aioboto3.Session(
aws_access_key_id=self.configuration["aws_access_key_id"],
aws_secret_access_key=self.configuration["aws_secret_access_key"],
)
self.config = AioConfig(
read_timeout=self.configuration["read_timeout"],
connect_timeout=self.configuration["connect_timeout"],
retries={"max_attempts": self.configuration["max_attempts"]},
)
self.clients = {}
self.client_context = []
def set_logger(self, logger_):
self._logger = logger_
async def client(self, region=None):
"""This method creates context manager and client session object for s3.
Args:
region (str): Name of bucket region. Defaults to None
"""
region_name = region if region else "default"
if region_name in self.clients:
return self.clients[region_name]
if AWS_ENDPOINT is not None:
self._logger.debug(f"Creating a session against {AWS_ENDPOINT}")
# AsyncExitStack, supports asynchronous context managers, used to create client using enter_async_context and
# these context manager will be stored in client_context list also client will be stored in clients dict with their region
s3_context_stack = AsyncExitStack()
s3_client = await s3_context_stack.enter_async_context(
self.session.client(
service_name="s3",
config=self.config,
endpoint_url=AWS_ENDPOINT,
region_name=region,
)
)
self.client_context.append(s3_context_stack)
self.clients[region_name] = s3_client
return self.clients[region_name]
async def close_client(self):
"""Closes unclosed client session"""
for context in self.client_context:
await context.aclose()
async def fetch_buckets(self):
"""This method used to list all the buckets from Amazon S3"""
s3 = await self.client()
await s3.list_buckets()
async def get_bucket_list(self):
"""Returns bucket list from list_buckets response
Returns:
list: List of buckets
"""
if self.configuration["buckets"] == ["*"]:
s3 = await self.client()
bucket_list = await s3.list_buckets()
buckets = [bucket["Name"] for bucket in bucket_list["Buckets"]]
else:
buckets = self.configuration["buckets"]
return buckets
async def get_bucket_objects(self, bucket, **kwargs):
"""Returns bucket list from list_buckets response
Args:
bucket (str): Name of bucket
Yields:
obj_summary: Bucket objects metadata
s3_client: S3 client object
"""
page_size = self.configuration["page_size"]
region_name = await self.get_bucket_region(bucket)
s3_client = await self.client(region=region_name)
async with self.session.resource(
service_name="s3",
config=self.config,
endpoint_url=AWS_ENDPOINT,
region_name=region_name,
) as s3:
try:
bucket_obj = await s3.Bucket(bucket)
await asyncio.sleep(0)
if kwargs.get("prefix"):
objects = bucket_obj.objects.filter(
Prefix=kwargs["prefix"]
).page_size(page_size)
else:
objects = bucket_obj.objects.page_size(page_size)
async for obj_summary in objects:
yield obj_summary, s3_client
except Exception as exception:
self._logger.warning(
f"Something went wrong while fetching documents from {bucket}. Error: {exception}"
)
async def get_bucket_region(self, bucket_name):
"""This method return the name of region for a bucket.
Args
bucket_name (str): Name of bucket
Returns:
region: Name of region
"""
region = None
try:
s3 = await self.client()
response = await s3.get_bucket_location(
Bucket=bucket_name,
)
region = response.get("LocationConstraint")
except ClientError:
self._logger.warning(f"Unable to fetch the region for {bucket_name}")
return region
class S3AdvancedRulesValidator(AdvancedRulesValidator):
RULES_OBJECT_SCHEMA_DEFINITION = {
"type": "object",
"properties": {
"bucket": {"type": "string", "minLength": 1},
"prefix": {"type": "string"},
"extension": {"type": "array"},
},
"required": ["bucket"],
"additionalProperties": False,
}
SCHEMA_DEFINITION = {"type": "array", "items": RULES_OBJECT_SCHEMA_DEFINITION}
SCHEMA = fastjsonschema.compile(definition=SCHEMA_DEFINITION)
def __init__(self, source):
self.source = source
async def validate(self, advanced_rules):
if len(advanced_rules) == 0:
return SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
)
try:
S3AdvancedRulesValidator.SCHEMA(advanced_rules)
return SyncRuleValidationResult.valid_result(
rule_id=SyncRuleValidationResult.ADVANCED_RULES
)
except JsonSchemaValueException as e:
return SyncRuleValidationResult(
rule_id=SyncRuleValidationResult.ADVANCED_RULES,
is_valid=False,
validation_message=e.message,
)
class S3DataSource(BaseDataSource):
"""Amazon S3"""
name = "Amazon S3"
service_type = "s3"
advanced_rules_enabled = True
def __init__(self, configuration):
"""Set up the connection to the Amazon S3.
Args:
configuration (DataSourceConfiguration): Object of DataSourceConfiguration class.
"""
super().__init__(configuration=configuration)
self.s3_client = S3Client(configuration=configuration)
def _set_internal_logger(self):
self.s3_client.set_logger(self._logger)
def advanced_rules_validators(self):
return [S3AdvancedRulesValidator(self)]
async def ping(self):
"""Verify the connection with AWS"""
try:
await self.s3_client.fetch_buckets()
self._logger.info("Successfully connected to AWS.")
except Exception:
self._logger.exception("Error while connecting to AWS.")
raise
async def format_document(self, bucket_name, bucket_object):
"""Prepare document for bucket object.
Args:
bucket_name: Name of bucket
bucket_object: Response of bucket objects
Returns:
document: Modified document.
"""
doc_id = hash_id(f"{bucket_name}/{bucket_object.key}")
owner = await bucket_object.owner
document = {
"_id": doc_id,
"filename": bucket_object.key,
"size_in_bytes": await bucket_object.size,
"bucket": bucket_name,
"owner": owner.get("DisplayName") if owner else "",
"storage_class": await bucket_object.storage_class,
"_timestamp": (await bucket_object.last_modified).isoformat(),
}
return document
async def advanced_sync(self, rule):
async def process_object(obj_summary, s3_client):
document = await self.format_document(
bucket_name=bucket, bucket_object=obj_summary
)
return document, partial(
self.get_content, doc=document, s3_client=s3_client
)
bucket = rule["bucket"]
prefix = rule.get("prefix", "")
async for obj_summary, s3_client in self.s3_client.get_bucket_objects(
bucket=bucket, prefix=prefix
):
if not rule.get("extension"):
yield await process_object(obj_summary, s3_client)
elif self.get_file_extension(obj_summary.key) in rule.get("extension", []):
yield await process_object(obj_summary, s3_client)
async def get_docs(self, filtering=None):
"""Get documents from Amazon S3
Returns:
dictionary: Document of file content
Yields:
dictionary: Document from Amazon S3.
"""
if filtering and filtering.has_advanced_rules():
for rule in filtering.get_advanced_rules():
async for document, attachment in self.advanced_sync(rule=rule):
yield document, attachment
else:
bucket_list = await self.s3_client.get_bucket_list()
for bucket in bucket_list:
async for obj_summary, s3_client in self.s3_client.get_bucket_objects(
bucket=bucket
):
document = await self.format_document(
bucket_name=bucket, bucket_object=obj_summary
)
yield (
document,
partial(
self.get_content,
doc=document,
s3_client=s3_client,
),
)
async def get_content(self, doc, s3_client, timestamp=None, doit=None):
if not (doit):
return
filename = doc["filename"]
file_size = doc["size_in_bytes"]
file_extension = self.get_file_extension(filename)
if not self.can_file_be_downloaded(file_extension, filename, file_size):
return
bucket = doc["bucket"]
document = {
"_id": doc["id"],
"_timestamp": doc["_timestamp"],
}
# s3 has a unique download method so we can't utilize
# the generic download_and_extract_file func
async with self.create_temp_file(file_extension) as async_buffer:
await s3_client.download_fileobj(
Bucket=bucket, Key=filename, Fileobj=async_buffer
)
await async_buffer.close()
document = await self.handle_file_content_extraction(
document, filename, async_buffer.name
)
return document
async def close(self):
"""Closes unclosed client session"""
await self.s3_client.close_client()
@classmethod
def get_default_configuration(cls):
"""Get the default configuration for Amazon S3.
Returns:
dictionary: Default configuration.
"""
return {
"buckets": {
"display": "textarea",
"label": "AWS Buckets",
"order": 1,
"tooltip": "AWS Buckets are ignored when Advanced Sync Rules are used.",
"type": "list",
},
"aws_access_key_id": {
"label": "AWS Access Key Id",
"order": 2,
"type": "str",
},
"aws_secret_access_key": {
"label": "AWS Secret Key",
"order": 3,
"sensitive": True,
"type": "str",
},
"read_timeout": {
"default_value": DEFAULT_READ_TIMEOUT,
"display": "numeric",
"label": "Read timeout",
"order": 4,
"required": False,
"type": "int",
"ui_restrictions": ["advanced"],
},
"connect_timeout": {
"default_value": DEFAULT_CONNECTION_TIMEOUT,
"display": "numeric",
"label": "Connection timeout",
"order": 5,
"required": False,
"type": "int",
"ui_restrictions": ["advanced"],
},
"max_attempts": {
"default_value": DEFAULT_MAX_RETRY_ATTEMPTS,
"display": "numeric",
"label": "Maximum retry attempts",
"order": 6,
"required": False,
"type": "int",
"ui_restrictions": ["advanced"],
},
"page_size": {
"default_value": DEFAULT_PAGE_SIZE,
"display": "numeric",
"label": "Maximum size of page",
"order": 7,
"required": False,
"type": "int",
"ui_restrictions": ["advanced"],
},
"use_text_extraction_service": {
"display": "toggle",
"label": "Use text extraction service",
"order": 8,
"tooltip": "Requires a separate deployment of the Elastic Text Extraction Service. Requires that pipeline settings disable text extraction.",
"type": "bool",
"ui_restrictions": ["advanced"],
"value": False,
},
}