Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

s3_connector.py 19 KB

You have to be logged in to leave a comment. Sign In
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
  1. import os
  2. import sys
  3. from io import StringIO, BytesIO
  4. from typing import List
  5. import botocore
  6. from super_gradients.common import AWSConnector
  7. from super_gradients.common import explicit_params_validation
  8. from super_gradients.common.abstractions.abstract_logger import ILogger
  9. class KeyNotExistInBucketError(Exception):
  10. pass
  11. class S3Connector(ILogger):
  12. """
  13. S3Connector - S3 Connection Manager
  14. """
  15. def __init__(self, env: str, bucket_name: str):
  16. """
  17. :param s3_bucket:
  18. """
  19. super().__init__()
  20. self.env = env
  21. self.bucket_name = bucket_name
  22. self.s3_client = AWSConnector.get_aws_client_for_service_name(profile_name=env, service_name='s3')
  23. self.s3_resource = AWSConnector.get_aws_resource_for_service_name(profile_name=env, service_name='s3')
  24. @explicit_params_validation(validation_type='NoneOrEmpty')
  25. def check_key_exists(self, s3_key_to_check: str) -> bool:
  26. """
  27. check_key_exists - Checks if an S3 key exists
  28. :param s3_key_to_check:
  29. :return:
  30. """
  31. try:
  32. self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key_to_check)
  33. except botocore.exceptions.ClientError as ex:
  34. if ex.response['Error']['Code'] == "404":
  35. return False
  36. else:
  37. self._logger.error(
  38. 'Failed to check key: ' + str(s3_key_to_check) + ' existence in bucket' + str(self.bucket_name))
  39. return None
  40. else:
  41. return True
  42. @explicit_params_validation(validation_type='NoneOrEmpty')
  43. def get_object_by_etag(self, bucket_relative_file_name: str, etag: str) -> object:
  44. """
  45. get_object_by_etag - Gets S3 object by it's ETag heder if it. exists
  46. :param bucket_relative_file_name: The name of the file in the bucket (relative)
  47. :param etag: The ETag of the object in S3
  48. :return:
  49. """
  50. try:
  51. etag = etag.strip('"')
  52. s3_object = self.s3_client.get_object(Bucket=self.bucket_name, Key=bucket_relative_file_name, IfMatch=etag)
  53. return s3_object
  54. except botocore.exceptions.ClientError as ex:
  55. if ex.response['Error']['Code'] == "404":
  56. return False
  57. else:
  58. self._logger.error(
  59. 'Failed to check ETag: ' + str(etag) + ' existence in bucket ' + str(self.bucket_name))
  60. return
  61. @explicit_params_validation(validation_type='NoneOrEmpty')
  62. def create_bucket(self) -> bool:
  63. """
  64. Creates a bucket with the initialized bucket name.
  65. :return: The new bucket response
  66. :raises ClientError: If the creation failed for any reason.
  67. """
  68. try:
  69. # TODO: Change bucket_owner_arn to the company's proper IAM Role
  70. self._logger.info('Creating Bucket: ' + self.bucket_name)
  71. create_bucket_response = self.s3_client.create_bucket(
  72. ACL='private',
  73. Bucket=self.bucket_name
  74. )
  75. self._logger.info(f'Successfully created bucket: {create_bucket_response}')
  76. # Changing the bucket public access block to be private (disable public access)
  77. self._logger.debug('Disabling public access to the bucket...')
  78. self.s3_client.put_public_access_block(
  79. PublicAccessBlockConfiguration={
  80. 'BlockPublicAcls': True,
  81. 'IgnorePublicAcls': True,
  82. 'BlockPublicPolicy': True,
  83. 'RestrictPublicBuckets': True
  84. },
  85. Bucket=self.bucket_name,
  86. )
  87. return create_bucket_response
  88. except botocore.exceptions.ClientError as err:
  89. self._logger.fatal(f'Failed to create bucket "{self.bucket_name}": {err}')
  90. raise
  91. @explicit_params_validation(validation_type='NoneOrEmpty')
  92. def delete_bucket(self):
  93. """
  94. Deletes a bucket with the initialized bucket name.
  95. :return: True if succeeded.
  96. :raises ClientError: If the creation failed for any reason.
  97. """
  98. try:
  99. self._logger.info('Deleting Bucket: ' + self.bucket_name + ' from S3')
  100. bucket = self.s3_resource.Bucket(self.bucket_name)
  101. bucket.objects.all().delete()
  102. bucket.delete()
  103. self._logger.debug('Successfully Deleted Bucket: ' + self.bucket_name + ' from S3')
  104. except botocore.exceptions.ClientError as ex:
  105. self._logger.fatal(f'Failed to delete bucket {self.bucket_name}: {ex}')
  106. raise ex
  107. return True
  108. @explicit_params_validation(validation_type='NoneOrEmpty')
  109. def get_object_metadata(self, s3_key: str):
  110. try:
  111. return self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key)
  112. except botocore.exceptions.ClientError as ex:
  113. if ex.response['Error']['Code'] == '404':
  114. msg = '[' + sys._getframe().f_code.co_name + '] - Key does not exist in bucket)'
  115. self._logger.error(msg)
  116. raise KeyNotExistInBucketError(msg)
  117. raise ex
  118. @explicit_params_validation(validation_type='NoneOrEmpty')
  119. def delete_key(self, s3_key_to_delete: str) -> bool:
  120. """
  121. delete_key - Deletes a Key from an S3 Bucket
  122. :param s3_key_to_delete:
  123. :return: True/False if the operation succeeded/failed
  124. """
  125. try:
  126. self._logger.debug('Deleting Key: ' + s3_key_to_delete + ' from S3 bucket: ' + self.bucket_name)
  127. obj_status = self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key_to_delete)
  128. except botocore.exceptions.ClientError as ex:
  129. if ex.response['Error']['Code'] == '404':
  130. self._logger.error('[' + sys._getframe().f_code.co_name + '] - Key does not exist in bucket)')
  131. return False
  132. if obj_status['ContentLength']:
  133. self._logger.debug(
  134. '[' + sys._getframe().f_code.co_name + '] - Deleting file s3://' + self.bucket_name + s3_key_to_delete)
  135. self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_key_to_delete)
  136. return True
  137. @explicit_params_validation(validation_type='NoneOrEmpty')
  138. def upload_file_from_stream(self, file, key: str):
  139. """
  140. upload_file - Uploads a file to S3 via boto3 interface
  141. *Please Notice* - This method is for working with files, not objects
  142. :param key: The key (filename) to create in the S3 bucket
  143. :param filen: File to upload
  144. :return True/False if the operation succeeded/failed
  145. """
  146. try:
  147. self._logger.debug('Uploading Key: ' + key + ' to S3 bucket: ' + self.bucket_name)
  148. buffer = BytesIO(file)
  149. self.upload_buffer(key, buffer)
  150. return True
  151. except Exception as ex:
  152. self._logger.critical(
  153. '[' + sys._getframe().f_code.co_name + '] - Caught Exception while trying to upload file ' + str(
  154. key) + 'to S3' + str(ex))
  155. return False
  156. @explicit_params_validation(validation_type='NoneOrEmpty')
  157. def upload_file(self, filename_to_upload: str, key: str):
  158. """
  159. upload_file - Uploads a file to S3 via boto3 interface
  160. *Please Notice* - This method is for working with files, not objects
  161. :param key: The key (filename) to create in the S3 bucket
  162. :param filename_to_upload: Filename of the file to upload
  163. :return True/False if the operation succeeded/failed
  164. """
  165. try:
  166. self._logger.debug('Uploading Key: ' + key + ' to S3 bucket: ' + self.bucket_name)
  167. self.s3_client.upload_file(Bucket=self.bucket_name, Filename=filename_to_upload, Key=key)
  168. return True
  169. except Exception as ex:
  170. self._logger.critical(
  171. '[' + sys._getframe().f_code.co_name + '] - Caught Exception while trying to upload file ' + str(
  172. filename_to_upload) + 'to S3' + str(ex))
  173. return False
  174. @explicit_params_validation(validation_type='NoneOrEmpty')
  175. def download_key(self, target_path: str, key_to_download: str) -> bool:
  176. """
  177. download_file - Downloads a key from S3 using boto3 to the provided filename
  178. Please Notice* - This method is for working with files, not objects
  179. :param key_to_download: The key (filename) to download from the S3 bucket
  180. :param target_path: Filename of the file to download the content of the key to
  181. :return: True/False if the operation succeeded/failed
  182. """
  183. try:
  184. self._logger.debug('Uploading Key: ' + key_to_download + ' from S3 bucket: ' + self.bucket_name)
  185. self.s3_client.download_file(Bucket=self.bucket_name, Filename=target_path, Key=key_to_download)
  186. except botocore.exceptions.ClientError as ex:
  187. if ex.response['Error']['Code'] == '404':
  188. self._logger.error('[' + sys._getframe().f_code.co_name + '] - Key does exist in bucket)')
  189. else:
  190. self._logger.critical(
  191. '[' + sys._getframe().f_code.co_name + '] - Caught Exception while trying to download key ' + str(
  192. key_to_download) + ' from S3 ' + str(ex))
  193. return False
  194. return True
  195. @explicit_params_validation(validation_type='NoneOrEmpty')
  196. def download_keys_by_prefix(self, s3_bucket_path_prefix: str, local_download_dir: str,
  197. s3_file_path_prefix: str = ''):
  198. """
  199. download_keys_by_prefix - Download all of the keys who match the provided in-bucket path prefix and file prefix
  200. :param s3_bucket_path_prefix: The S3 "folder" to download from
  201. :param local_download_dir: The local directory to download the files to
  202. :param s3_file_path_prefix: The specific prefix of the files we want to download
  203. :return:
  204. """
  205. if not os.path.isdir(local_download_dir):
  206. raise ValueError('[' + sys._getframe().f_code.co_name + '] - Provided directory does not exist')
  207. paginator = self.s3_client.get_paginator('list_objects')
  208. prefix = s3_bucket_path_prefix if not s3_file_path_prefix else s3_bucket_path_prefix + '/' + s3_file_path_prefix
  209. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=prefix)
  210. for item in page_iterator.search('Contents'):
  211. if item is not None:
  212. if item['Key'] == s3_bucket_path_prefix:
  213. continue
  214. key_to_download = item['Key']
  215. local_filename = key_to_download.split('/')[-1]
  216. self.download_key(target_path=local_download_dir + '/' + local_filename,
  217. key_to_download=key_to_download)
  218. @explicit_params_validation(validation_type='NoneOrEmpty')
  219. def download_file_by_path(self, s3_file_path: str, local_download_dir: str):
  220. """
  221. :param s3_file_path: str - path ot s3 file e.g./ "s3://x/y.zip"
  222. :param local_download_dir: path to download
  223. :return:
  224. """
  225. if not os.path.isdir(local_download_dir):
  226. raise ValueError('[' + sys._getframe().f_code.co_name + '] - Provided directory does not exist')
  227. local_filename = s3_file_path.split('/')[-1]
  228. self.download_key(target_path=local_download_dir + '/' + local_filename,
  229. key_to_download=s3_file_path)
  230. return local_filename
  231. @explicit_params_validation(validation_type='NoneOrEmpty')
  232. def empty_folder_content_by_path_prefix(self, s3_bucket_path_prefix) -> list:
  233. """
  234. empty_folder_content_by_path_prefix - Deletes all of the files in the specified bucket path
  235. :param s3_bucket_path_prefix: The "folder" to empty
  236. :returns: Errors list
  237. """
  238. paginator = self.s3_client.get_paginator('list_objects')
  239. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=s3_bucket_path_prefix)
  240. files_dict_to_delete = dict(Objects=[])
  241. errors_list = []
  242. for item in page_iterator.search('Contents'):
  243. if item is not None:
  244. if item['Key'] == s3_bucket_path_prefix:
  245. continue
  246. files_dict_to_delete['Objects'].append(dict(Key=item['Key']))
  247. # IF OBJECTS LIMIT HAS BEEN REACHED, FLUSH
  248. if len(files_dict_to_delete['Objects']) >= 1000:
  249. self._delete_files_left_in_list(errors_list, files_dict_to_delete)
  250. files_dict_to_delete = dict(Objects=[])
  251. # DELETE THE FILES LEFT IN THE LIST
  252. if len(files_dict_to_delete['Objects']):
  253. self._delete_files_left_in_list(errors_list, files_dict_to_delete)
  254. return errors_list
  255. def _delete_files_left_in_list(self, errors_list, files_dict_to_delete):
  256. try:
  257. s3_response = self.s3_client.delete_objects(Bucket=self.bucket_name, Delete=files_dict_to_delete)
  258. except Exception as ex:
  259. self._logger.critical(
  260. '[' + sys._getframe().f_code.co_name + '] - Caught Exception while trying to delete keys ' + 'from S3 ' + str(
  261. ex))
  262. if 'Errors' in s3_response:
  263. errors_list.append(s3_response['Errors'])
  264. @explicit_params_validation(validation_type='NoneOrEmpty')
  265. def upload_buffer(self, new_key_name: str, buffer_to_write: StringIO):
  266. """
  267. Uploads a buffer into a file in S3 with the provided key name.
  268. :bucket: The name of the bucket
  269. :new_key_name: The name of the file to create in s3
  270. :buffer_to_write: A buffer that contains the file contents.
  271. """
  272. self.s3_resource.Object(self.bucket_name, new_key_name).put(Body=buffer_to_write.getvalue())
  273. @explicit_params_validation(validation_type='NoneOrEmpty')
  274. def list_bucket_objects(self, prefix: str = None) -> List[dict]:
  275. """
  276. Gets a list of dictionaries, representing files in the S3 bucket that is passed in the constructor (self.bucket).
  277. :param prefix: A prefix filter for the files names.
  278. :return: the objects, dict as received from botocore.
  279. """
  280. paginator = self.s3_client.get_paginator('list_objects')
  281. if prefix:
  282. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=prefix)
  283. else:
  284. page_iterator = paginator.paginate(Bucket=self.bucket_name)
  285. bucket_objects = []
  286. for item in page_iterator.search('Contents'):
  287. if not item or item['Key'] == self.bucket_name:
  288. continue
  289. bucket_objects.append(item)
  290. return bucket_objects
  291. @explicit_params_validation(validation_type='NoneOrEmpty')
  292. def create_presigned_upload_url(self,
  293. object_name: str,
  294. fields=None,
  295. conditions=None,
  296. expiration=3600):
  297. """Generate a presigned URL S3 POST request to upload a file
  298. :param bucket_name: string
  299. :param object_name: string
  300. :param fields: Dictionary of prefilled form fields
  301. :param conditions: List of conditions to include in the policy
  302. :param expiration: Time in seconds for the presigned URL to remain valid
  303. :return: Dictionary with the following keys:
  304. url: URL to post to
  305. fields: Dictionary of form fields and values to submit with the POST request
  306. """
  307. # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html#generating-a-presigned-url-to-upload-a-file
  308. file_already_exist = self.check_key_exists(object_name)
  309. if file_already_exist:
  310. raise FileExistsError(f"The key {object_name} already exists in bucket {self.bucket_name}")
  311. response = self.s3_client.generate_presigned_post(self.bucket_name,
  312. object_name,
  313. Fields=fields,
  314. Conditions=conditions,
  315. ExpiresIn=expiration)
  316. return response
  317. @explicit_params_validation(validation_type='NoneOrEmpty')
  318. def create_presigned_download_url(self, bucket_name: str, object_name: str, expiration=3600):
  319. """Generate a presigned URL S3 Get request to download a file
  320. :param bucket_name: string
  321. :param object_name: string
  322. :param expiration: Time in seconds for the presigned URL to remain valid
  323. :return: URL encoded with the credentials in the query, to be fetched using any HTTP client.
  324. """
  325. # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html
  326. response = self.s3_client.generate_presigned_url('get_object',
  327. Params={'Bucket': bucket_name,
  328. 'Key': object_name},
  329. ExpiresIn=expiration)
  330. return response
  331. @staticmethod
  332. def convert_content_length_to_mb(content_length):
  333. return round(float(f'{content_length / (1e+6):2f}'), 2)
  334. @explicit_params_validation(validation_type='NoneOrEmpty')
  335. def copy_key(self,
  336. destination_bucket_name: str,
  337. source_key: str,
  338. destination_key: str):
  339. self._logger.info(
  340. f'Copying the bucket object {self.bucket_name}:{source_key} to {destination_bucket_name}/{destination_key}')
  341. copy_source = {
  342. 'Bucket': self.bucket_name,
  343. 'Key': source_key
  344. }
  345. # Copying the key
  346. bucket = self.s3_resource.Bucket(destination_bucket_name)
  347. bucket.copy(copy_source, destination_key)
  348. return True
  349. # @explicit_params_validation(validation_type='NoneOrEmpty')
  350. # def list_common_prefixes(self) -> List[str]:
  351. # """
  352. # Gets a list of dictionaries, representing directories in the S3 bucket that is passed in the constructor (self.bucket).
  353. # :return: The names of the directories in the bucket.
  354. # """
  355. # paginator = self.s3_client.get_paginator('list_objects_v2')
  356. # page_iterator = paginator.paginate(Bucket=self.bucket_name)
  357. # prefixes = set()
  358. # for item in page_iterator.search('Contents'):
  359. # if not item:
  360. # continue
  361. #
  362. # if len(item.split('/') == 1):
  363. # prefixes.append(item)
  364. # return prefixes
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...