Debian Codegraph @

test/test_s3.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from io import BytesIO
5 import unittest
6 import os
7 import tempfile
8 import math
9 import shutil
10 import time
11 from test import NativeResourceTest
12 from concurrent.futures import Future
13 from multiprocessing import Process
14 import multiprocessing as mp
15 import sys
16 import gc
17
18 from awscrt.http import HttpHeaders, HttpRequest
19 from awscrt.auth import AwsCredentials
20 from awscrt.s3 import (
21 S3ChecksumAlgorithm,
22 S3ChecksumConfig,
23 S3ChecksumLocation,
24 S3Client,
25 S3RequestType,
26 S3ResponseError,
27 CrossProcessLock,
28 S3FileIoOptions,
29 create_default_s3_signing_config,
30 get_optimized_platforms,
31 )
32 from awscrt.io import (
33 ClientBootstrap,
34 ClientTlsContext,
35 DefaultHostResolver,
36 EventLoopGroup,
37 TlsConnectionOptions,
38 TlsContextOptions,
39 )
40 from awscrt.auth import (
41 AwsCredentialsProvider,
42 AwsSignatureType,
43 AwsSignedBodyHeaderType,
44 AwsSignedBodyValue,
45 AwsSigningAlgorithm,
46 AwsSigningConfig,
47 )
48 from awscrt.common import join_all_native_threads
49
50 MB = 1024 ** 2
51 GB = 1024 ** 3
52 S3EXPRESS_ENDPOINT = "crts-east1--use1-az4--x-s3.s3express-use1-az4.us-east-1.amazonaws.com"
53
54 cross_process_lock_name = "instance_lock_test"
55
56
57 def cross_proc_task():
58 try:
59 lock = CrossProcessLock(cross_process_lock_name)
60 lock.acquire()
61 lock.release()
62 exit(0)
63 except RuntimeError as e:
64 exit(-1)
65
66
67 def release_lock_task():
68 # remove the global lock
69 global CRT_S3_PROCESS_LOCK
70 CRT_S3_PROCESS_LOCK = None
71 exit(0)
72
73
74 class CrossProcessLockTest(NativeResourceTest):
75
76 def setUp(self):
77 self.nonce = time.time()
78 super().setUp()
79
80 def test_with_statement(self):
81 nonce_str = f'lock_a_{self.nonce}'
82 with CrossProcessLock(nonce_str) as lock:
83 try:
84 new_lock = CrossProcessLock(nonce_str)
85 new_lock.acquire()
86 self.fail("Acquiring a lock by the same nonce should fail when it's already held")
87 except RuntimeError as e:
88 unique_nonce_str = f'lock_b{self.nonce}'
89 new_lock = CrossProcessLock(unique_nonce_str)
90 new_lock.acquire()
91 new_lock.release()
92
93 lock_after_with_same_nonce = CrossProcessLock(nonce_str)
94 lock_after_with_same_nonce.acquire()
95 lock_after_with_same_nonce.release()
96
97 def test_cross_proc(self):
98 with CrossProcessLock(cross_process_lock_name) as lock:
99 process = Process(target=cross_proc_task)
100 process.start()
101 process.join()
102 # acquiring this lock in a sub-process should fail since we
103 # already hold the lock in this process.
104 self.assertNotEqual(0, process.exitcode)
105 # now that we've released the lock above, the same sub-process path
106 # should now succeed.
107 unlocked_process = Process(target=cross_proc_task)
108 unlocked_process.start()
109 unlocked_process.join()
110 self.assertEqual(0, unlocked_process.exitcode)
111
112 @unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support fork")
113 def test_fork_shares_lock(self):
114 # mock the use case from boto3 where a global lock used and the workaround with fork.
115 global CRT_S3_PROCESS_LOCK
116 CRT_S3_PROCESS_LOCK = CrossProcessLock(cross_process_lock_name)
117 CRT_S3_PROCESS_LOCK.acquire()
118 mp.set_start_method('fork', force=True)
119 # the first forked process release the forked lock.
120 # when the process forked, the child process also has the lock and it could release the lock before
121 # the parent process. Make sure when this happens, the lock is still held by the parent process.
122 release_process = Process(target=release_lock_task)
123 release_process.start()
124 release_process.join()
125
126 # create another process try to acquire the lock, it should fail as the
127 # lock should still be held with the main process.
128 process = Process(target=cross_proc_task)
129 process.start()
130 process.join()
131 # acquiring this lock in a sub-process should fail since we
132 # already hold the lock in this process.
133 self.assertNotEqual(0, process.exitcode)
134 del CRT_S3_PROCESS_LOCK
135
136
137 class FileCreator(object):
138 def __init__(self):
139 self.rootdir = tempfile.mkdtemp()
140
141 def remove_all(self):
142 shutil.rmtree(self.rootdir)
143
144 def create_file(self, filename, contents, mode='w'):
145 """Creates a file in a tmpdir
146 ``filename`` should be a relative path, e.g. "foo/bar/baz.txt"
147 It will be translated into a full path in a tmp dir.
148 ``mode`` is the mode the file should be opened either as ``w`` or
149 `wb``.
150 Returns the full path to the file.
151 """
152 full_path = os.path.join(self.rootdir, filename)
153 if not os.path.isdir(os.path.dirname(full_path)):
154 os.makedirs(os.path.dirname(full_path))
155 with open(full_path, mode) as f:
156 f.write(contents)
157 return full_path
158
159 def create_file_with_size(self, filename, filesize):
160 filename = self.create_file(filename, contents='')
161 chunksize = 8192
162 with open(filename, 'wb') as f:
163 for i in range(int(math.ceil(filesize / float(chunksize)))):
164 f.write(b'a' * chunksize)
165 return filename
166
167 def append_file(self, filename, contents):
168 """Append contents to a file
169 ``filename`` should be a relative path, e.g. "foo/bar/baz.txt"
170 It will be translated into a full path in a tmp dir.
171 Returns the full path to the file.
172 """
173 full_path = os.path.join(self.rootdir, filename)
174 if not os.path.isdir(os.path.dirname(full_path)):
175 os.makedirs(os.path.dirname(full_path))
176 with open(full_path, 'a') as f:
177 f.write(contents)
178 return full_path
179
180 def full_path(self, filename):
181 """Translate relative path to full path in temp dir.
182 f.full_path('foo/bar.txt') -> /tmp/asdfasd/foo/bar.txt
183 """
184 return os.path.join(self.rootdir, filename)
185
186
187 def s3_client_new(
188 secure,
189 region,
190 part_size=0,
191 is_cancel_test=False,
192 enable_s3express=False,
193 mem_limit=None,
194 network_interface_names=None):
195
196 if is_cancel_test:
197 # for cancellation tests, make things slow, so it's less likely that
198 # stuff succeeds on other threads before the cancellation is processed.
199 num_threads = 1
200 throughput_target_gbps = 0.000028 # 28 Kbps beeepdiiingeep beeeeeekskhskshhKKKKchCH
201 else:
202 # else use defaults
203 num_threads = None
204 throughput_target_gbps = None
205
206 event_loop_group = EventLoopGroup(num_threads)
207 host_resolver = DefaultHostResolver(event_loop_group)
208 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
209 credential_provider = AwsCredentialsProvider.new_default_chain(bootstrap)
210 signing_config = create_default_s3_signing_config(region=region, credential_provider=credential_provider)
211 tls_option = None
212 if secure:
213 opt = TlsContextOptions()
214 ctx = ClientTlsContext(opt)
215 tls_option = TlsConnectionOptions(ctx)
216 s3_client = S3Client(
217 bootstrap=bootstrap,
218 region=region,
219 signing_config=signing_config,
220 tls_connection_options=tls_option,
221 part_size=part_size,
222 throughput_target_gbps=throughput_target_gbps,
223 enable_s3express=enable_s3express,
224 memory_limit=mem_limit,
225 network_interface_names=network_interface_names)
226 return s3_client
227
228
229 class FakeReadStream(object):
230 def __init__(self, read_future):
231 self._future = read_future
232
233 def read(self, length):
234 fake_string = "x" * length
235 fake_data = bytes(fake_string, 'utf-8')
236 if not self._future.done():
237 self._future.set_result(None)
238 return fake_data
239
240
241 class S3ClientTest(NativeResourceTest):
242
243 def setUp(self):
244 self.region = "us-west-2"
245 self.timeout = 10 # seconds
246 super().setUp()
247
248 def test_sanity(self):
249 s3_client = s3_client_new(False, self.region)
250 self.assertIsNotNone(s3_client)
251
252 def test_sanity_secure(self):
253 s3_client = s3_client_new(True, self.region)
254 self.assertIsNotNone(s3_client)
255
256 def test_sanity_network_interface_names(self):
257 # This is just a sanity test to ensure that we are passing the parameter correctly.
258 with self.assertRaises(Exception):
259 s3_client_new(True, self.region, network_interface_names=("eth0", "invalid-network-interface"))
260
261 def test_wait_shutdown(self):
262 s3_client = s3_client_new(False, self.region)
263 self.assertIsNotNone(s3_client)
264
265 shutdown_event = s3_client.shutdown_event
266 del s3_client
267 self.assertTrue(shutdown_event.wait(self.timeout))
268
269 def test_get_optimized_platforms(self):
270 platform_list = get_optimized_platforms()
271 self.assertTrue(len(platform_list) > 0)
272 self.assertTrue("p4d.24xlarge" in platform_list)
273
274
275 @unittest.skipUnless(os.environ.get('AWS_TEST_S3'), 'set env var to run test: AWS_TEST_S3')
276 class S3RequestTest(NativeResourceTest):
277 def setUp(self):
278 super().setUp()
279 # TODO: use env-vars to customize how these tests are run, instead of relying on hard-coded values
280 self.get_test_object_path = "/get_object_test_10MB.txt"
281 self.put_test_object_path = "/put_object_test_py_10MB.txt"
282 self.region = "us-west-2"
283 self.bucket_name = "aws-crt-canary-bucket"
284 self.timeout = 100 # seconds
285 self.num_threads = 0
286 self.special_path = "put_object_test_10MB@$%.txt"
287 self.non_ascii_file_name = "ÉxÅmple.txt"
288 self.part_size = 5 * MB
289
290 self.response_headers = None
291 self.response_status_code = None
292 self.received_body_len = 0
293 self.transferred_len = 0
294 self.data_len = 0
295 self.progress_invoked = 0
296 self.done_error = None
297 self.done_status_code = None
298 self.done_error_headers = None
299 self.done_error_body = None
300 self.done_error_operation_name = None
301 self.done_did_validate_checksum = None
302 self.done_checksum_validation_algorithm = None
303
304 self.files = FileCreator()
305 self.temp_put_obj_file_path = self.files.create_file_with_size("temp_put_obj_10mb", 10 * MB)
306 self.s3express_preload_cache = [('key_1', AwsCredentials("accesskey_1", "secretAccessKey", "sessionToken")),
307 ('key_2', AwsCredentials("accesskey_2", "secretAccessKey", "sessionToken"))]
308
309 def tearDown(self):
310 self.files.remove_all()
311 self.s3express_preload_cache = None
312 super().tearDown()
313
314 def _build_endpoint_string(self, region, bucket_name, enable_s3express=False):
315 if enable_s3express:
316 return S3EXPRESS_ENDPOINT
317 return bucket_name + ".s3." + region + ".amazonaws.com"
318
319 def _get_object_request(self, object_path, enable_s3express=False):
320 headers = HttpHeaders([("host", self._build_endpoint_string(self.region, self.bucket_name, enable_s3express))])
321 request = HttpRequest("GET", object_path, headers)
322 return request
323
324 def _put_object_request(
325 self,
326 input_stream,
327 content_len,
328 path=None,
329 unknown_content_length=False,
330 enable_s3express=False):
331 # if send file path is set, the body_stream of http request will be ignored (using file handler from C instead)
332 headers = HttpHeaders([("host", self._build_endpoint_string(self.region, self.bucket_name, enable_s3express)),
333 ("Content-Type", "text/plain")])
334 if unknown_content_length is False:
335 headers.add("Content-Length", str(content_len))
336 if path is None:
337 path = self.put_test_object_path
338 request = HttpRequest("PUT", path, headers, input_stream)
339 return request
340
341 def _on_request_headers(self, status_code, headers, **kargs):
342 self.response_status_code = status_code
343 self.response_headers = headers
344
345 def _on_request_body(self, chunk, offset, **kargs):
346 self.received_body_len = self.received_body_len + len(chunk)
347
348 def _on_request_done(
349 self,
350 error,
351 error_headers,
352 error_body,
353 error_operation_name,
354 status_code,
355 did_validate_checksum,
356 checksum_validation_algorithm,
357 **kwargs):
358 self.done_error = error
359 self.done_error_headers = error_headers
360 self.done_error_body = error_body
361 self.done_error_operation_name = error_operation_name
362 self.done_status_code = status_code
363 self.done_did_validate_checksum = did_validate_checksum
364 self.done_checksum_validation_algorithm = checksum_validation_algorithm
365
366 def _on_progress(self, progress):
367 self.transferred_len += progress
368
369 def _validate_successful_response(self, is_put_object):
370 self.assertEqual(self.response_status_code, 200, "status code is not 200")
371 self.assertEqual(self.done_status_code, self.response_status_code,
372 "status-code from on_done doesn't match code from on_headers")
373 self.assertIsNone(self.done_error)
374 self.assertIsNone(self.done_error_headers)
375 self.assertIsNone(self.done_error_body)
376 self.assertIsNone(self.done_error_operation_name)
377 self.assertIsInstance(self.done_did_validate_checksum, bool)
378 if self.done_did_validate_checksum:
379 self.assertIsInstance(self.done_checksum_validation_algorithm, S3ChecksumAlgorithm)
380 else:
381 self.assertIsNone(self.done_checksum_validation_algorithm)
382 headers = HttpHeaders(self.response_headers)
383 self.assertIsNone(headers.get("Content-Range"))
384 body_length = headers.get("Content-Length")
385 if not is_put_object:
386 self.assertIsNotNone(body_length, "Content-Length is missing from headers")
387 if body_length:
388 self.assertEqual(
389 int(body_length),
390 self.received_body_len,
391 "Received body length does not match the Content-Length header")
392
393 def _test_s3_put_get_object(
394 self,
395 request,
396 request_type,
397 exception_name=None,
398 enable_s3express=False,
399 mem_limit=None,
400 **kwargs):
401 s3_client = s3_client_new(
402 False,
403 self.region,
404 self.part_size,
405 enable_s3express=enable_s3express,
406 mem_limit=mem_limit)
407 signing_config = None
408 if enable_s3express:
409 signing_config = AwsSigningConfig(
410 algorithm=AwsSigningAlgorithm.V4_S3EXPRESS)
411
412 s3_request = s3_client.make_request(
413 request=request,
414 type=request_type,
415 signing_config=signing_config,
416 on_headers=self._on_request_headers,
417 on_body=self._on_request_body,
418 on_done=self._on_request_done,
419 **kwargs)
420
421 finished_future = s3_request.finished_future
422 shutdown_event = s3_request.shutdown_event
423 s3_request = None
424 self.assertTrue(shutdown_event.wait(self.timeout))
425
426 if exception_name is None:
427 try:
428 finished_future.result()
429 self._validate_successful_response(request_type is S3RequestType.PUT_OBJECT)
430 except S3ResponseError as e:
431 print(e.status_code)
432 print(e.headers)
433 print(e.body)
434 raise e
435 else:
436 e = finished_future.exception()
437 self.assertEqual(e.name, exception_name)
438 self.assertEqual(e, self.done_error)
439
440 def test_get_object(self):
441 request = self._get_object_request(self.get_test_object_path)
442 self._test_s3_put_get_object(request, S3RequestType.GET_OBJECT)
443
444 def test_get_object_mem_limit(self):
445 request = self._get_object_request(self.get_test_object_path)
446 self._test_s3_put_get_object(request, S3RequestType.GET_OBJECT, mem_limit=2 * GB)
447
448 def test_put_object(self):
449 put_body_stream = open(self.temp_put_obj_file_path, "rb")
450 content_length = os.stat(self.temp_put_obj_file_path).st_size
451 request = self._put_object_request(put_body_stream, content_length)
452 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT)
453 put_body_stream.close()
454
455 def test_put_object_mem_limit(self):
456 put_body_stream = open(self.temp_put_obj_file_path, "rb")
457 content_length = os.stat(self.temp_put_obj_file_path).st_size
458 request = self._put_object_request(put_body_stream, content_length)
459 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT, mem_limit=2 * GB)
460 put_body_stream.close()
461
462 def test_put_object_unknown_content_length(self):
463 put_body_stream = open(self.temp_put_obj_file_path, "rb")
464 content_length = os.stat(self.temp_put_obj_file_path).st_size
465 request = self._put_object_request(put_body_stream, content_length, unknown_content_length=True)
466 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT)
467 put_body_stream.close()
468
469 def test_put_object_unknown_content_length_single_part(self):
470 data_bytes = "test crt python single part upload".encode(encoding='utf-8')
471 put_body_stream = BytesIO(data_bytes)
472 request = self._put_object_request(put_body_stream, len(data_bytes), unknown_content_length=True)
473 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT)
474 put_body_stream.close()
475
476 def test_get_object_s3express(self):
477 self.region = "us-east-1"
478 request = self._get_object_request("/crt-download-10MB", enable_s3express=True)
479 self._test_s3_put_get_object(request, S3RequestType.GET_OBJECT, enable_s3express=True)
480
481 def test_put_object_s3express(self):
482 self.region = "us-east-1"
483 put_body_stream = open(self.temp_put_obj_file_path, "rb")
484 content_length = os.stat(self.temp_put_obj_file_path).st_size
485 request = self._put_object_request(put_body_stream, content_length, enable_s3express=True)
486 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT, enable_s3express=True)
487 put_body_stream.close()
488
489 def test_put_object_multiple_times(self):
490 s3_client = s3_client_new(False, self.region, 5 * MB)
491 finished_futures = []
492 for i in range(3):
493 tempfile = self.files.create_file_with_size("temp_file_{}".format(str(i)), 10 * MB)
494 path = "/put_object_test_py_10MB_{}.txt".format(str(i))
495 content_length = os.stat(tempfile).st_size
496 request = self._put_object_request(None, content_length, path=path)
497 s3_request = s3_client.make_request(
498 request=request,
499 type=S3RequestType.PUT_OBJECT,
500 send_filepath=tempfile,
501 on_headers=self._on_request_headers,
502 on_body=self._on_request_body,
503 on_done=self._on_request_done)
504 finished_futures.append(s3_request.finished_future)
505 # request keeps connection alive. delete pointer so connection can shut down
506 del s3_request
507 try:
508 for future in finished_futures:
509 future.result(self.timeout)
510 except Exception as e:
511 # failed
512 self.assertTrue(False)
513
514 client_shutdown_event = s3_client.shutdown_event
515 del s3_client
516 self.assertTrue(client_shutdown_event.wait(self.timeout))
517
518 def test_put_object_request_override_part_size(self):
519 s3_client = s3_client_new(False, self.region, 5 * MB)
520
521 tempfile = self.files.create_file_with_size("temp_file_override", 10 * MB)
522 path = "/put_object_test_py_10MB_override.txt"
523 content_length = os.stat(tempfile).st_size
524 request = self._put_object_request(None, content_length, path=path)
525 # Override the threshold to 10 MB, which will result in a single part upload
526 s3_request = s3_client.make_request(
527 request=request,
528 type=S3RequestType.PUT_OBJECT,
529 send_filepath=tempfile,
530 on_headers=self._on_request_headers,
531 on_body=self._on_request_body,
532 on_done=self._on_request_done,
533 multipart_upload_threshold=10 * MB)
534 try:
535 s3_request.finished_future.result(self.timeout)
536 except Exception as e:
537 # failed
538 self.assertTrue(False)
539
540 # Etag headers for a MPU will be formatted with `-[part number]`
541 etag = HttpHeaders(self.response_headers).get("Etag")
542 # make sure we uploaded as single part as we override the threshold
543 self.assertFalse("-" in etag)
544
545 del s3_request
546 client_shutdown_event = s3_client.shutdown_event
547 del s3_client
548 self.assertTrue(client_shutdown_event.wait(self.timeout))
549
550 def test_get_object_filepath(self):
551 request = self._get_object_request(self.get_test_object_path)
552 request_type = S3RequestType.GET_OBJECT
553 s3_client = s3_client_new(False, self.region, 5 * MB)
554 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
555 file.close()
556 s3_request = s3_client.make_request(
557 request=request,
558 type=request_type,
559 recv_filepath=file.name,
560 on_headers=self._on_request_headers,
561 on_progress=self._on_progress,
562 on_done=self._on_request_done)
563 finished_future = s3_request.finished_future
564
565 # Regression test: Let S3Request get GC'd early.
566 # The download should continue without problems.
567 # We once had a bug where the file would get closed too early:
568 # https://github.com/awslabs/aws-crt-python/pull/506
569 del s3_request
570
571 finished_future.result(self.timeout)
572
573 # Result check
574 self.data_len = int(HttpHeaders(self.response_headers).get("Content-Length"))
575 file_stats = os.stat(file.name)
576 file_len = file_stats.st_size
577 self.assertEqual(
578 file_len,
579 self.transferred_len,
580 "the length of written file does not match the transferred length reported")
581 self.assertEqual(
582 self.data_len,
583 self.transferred_len,
584 "the transferred length reported does not match the content-length header")
585 self.assertEqual(self.response_status_code, 200, "status code is not 200")
586 # TODO verify the content of written file
587 os.remove(file.name)
588
589 def test_put_object_filepath(self):
590 content_length = os.stat(self.temp_put_obj_file_path).st_size
591 request = self._put_object_request(None, content_length)
592 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT, send_filepath=self.temp_put_obj_file_path)
593
594 def test_put_object_filepath_with_fio_options(self):
595 content_length = os.stat(self.temp_put_obj_file_path).st_size
596 request = self._put_object_request(None, content_length)
597 fio_options = S3FileIoOptions(should_stream=True, disk_throughput_gbps=10.0, direct_io=True)
598 self._test_s3_put_get_object(
599 request,
600 S3RequestType.PUT_OBJECT,
601 send_filepath=self.temp_put_obj_file_path,
602 fio_options=fio_options)
603
604 def test_put_object_filepath_unknown_content_length(self):
605 content_length = os.stat(self.temp_put_obj_file_path).st_size
606 request = self._put_object_request(None, content_length, unknown_content_length=True)
607 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT, send_filepath=self.temp_put_obj_file_path)
608
609 def test_put_object_filepath_move(self):
610 # remove the input file when request done
611 tempfile = self.files.create_file_with_size("temp_file", 10 * MB)
612 content_length = os.stat(tempfile).st_size
613 request = self._put_object_request(None, content_length)
614 s3_client = s3_client_new(False, self.region, 5 * MB)
615 request_type = S3RequestType.PUT_OBJECT
616 done_future = Future()
617
618 def on_done_remove_file(**kwargs):
619 self._on_request_done(**kwargs)
620 os.remove(tempfile)
621 done_future.set_result(None)
622
623 s3_client.make_request(
624 request=request,
625 type=request_type,
626 send_filepath=tempfile,
627 on_headers=self._on_request_headers,
628 on_progress=self._on_progress,
629 on_done=on_done_remove_file)
630 done_future.result(self.timeout)
631
632 # check result
633 self.assertEqual(
634 content_length,
635 self.transferred_len,
636 "the transferred length reported does not match body we sent")
637 self._validate_successful_response(request_type is S3RequestType.PUT_OBJECT)
638
639 def upload_with_global_client(self):
640 global CRT_S3_CLIENT
641 if CRT_S3_CLIENT is None:
642 CRT_S3_CLIENT = s3_client_new(False, self.region, 5 * MB)
643 put_body_stream = open(self.temp_put_obj_file_path, "rb")
644 content_length = os.stat(self.temp_put_obj_file_path).st_size
645 request = self._put_object_request(put_body_stream, content_length)
646 s3_request = CRT_S3_CLIENT.make_request(
647 request=request,
648 type=S3RequestType.PUT_OBJECT,
649 on_headers=self._on_request_headers,
650 on_body=self._on_request_body,
651 on_done=self._on_request_done)
652
653 shutdown_event = s3_request.shutdown_event
654 s3_request = None
655 self.assertTrue(shutdown_event.wait(self.timeout))
656 put_body_stream.close()
657
658 def fork_s3_client(self):
659 try:
660 # init_logging(LogLevel.Trace, f"aws-crt-python{os.getpid()}.log")
661 self.upload_with_global_client()
662 global CRT_S3_CLIENT
663 del CRT_S3_CLIENT
664 exit(0)
665 except Exception as e:
666 print(f"fork_s3_client error: {e}")
667 exit(-1)
668
669 def before_fork(self):
670 global CRT_S3_CLIENT
671 try:
672 if CRT_S3_CLIENT is not None:
673 # The client is not safe to use after fork, so we need to release it.
674 # make sure the client is shutdown properly before fork
675 # also wait for every thread to be joined, incase of some thread is in the middle of cleanup.
676 shutdown_event = CRT_S3_CLIENT.shutdown_event
677 CRT_S3_CLIENT = None
678 gc.collect()
679 self.assertTrue(shutdown_event.wait(self.timeout))
680 self.assertTrue(join_all_native_threads(timeout_sec=10))
681 except Exception as e:
682 print(f"before_fork error: {e}")
683 # fail hard as exceptions raised from the fork handler will be ignored.
684 sys.stdout.flush()
685 sys.stderr.flush()
686 os._exit(-1)
687
688 @unittest.skipIf(sys.platform.startswith('win') or sys.platform == 'darwin',
689 "Test skipped on Windows and macOS. Windows doesn't support fork. macOS has background threads crashes the forked process.")
690 def test_fork_workaround(self):
691 # mock the boto3 use case where a global client is used and the
692 # workaround for fork is to release the client from the fork handler.
693 global CRT_S3_CLIENT
694 CRT_S3_CLIENT = s3_client_new(False, self.region, 5 * MB)
695 self.upload_with_global_client()
696 # fork the process and use the global S3 client for the transfer.
697 # to workaround the background thread issue that cleaned after fork,
698 # we need to make sure the client is shutdown properly
699 # and all background threads has joined before fork, see `self.before_fork`
700 # And in the sub-process, we can recreate the global S3 client and use it.
701 os.register_at_fork(before=self.before_fork)
702 mp.set_start_method('fork', force=True)
703 process = Process(target=self.fork_s3_client)
704 process.start()
705 process.join()
706 self.assertEqual(0, process.exitcode)
707 self.upload_with_global_client()
708 del CRT_S3_CLIENT
709
710 def _round_trip_with_checksums_helper(
711 self,
712 algo=S3ChecksumAlgorithm.CRC32,
713 mpu=True,
714 provide_full_object_checksum=False):
715 if not mpu:
716 # increase the part size for the client to use single part upload
717 self.part_size = 20 * MB
718
719 put_body_stream = open(self.temp_put_obj_file_path, "rb")
720 content_length = os.stat(self.temp_put_obj_file_path).st_size
721 # construct different path to prevent race condition between tests
722 path = '/hello-world-' + algo.name
723 if mpu:
724 path += "-mpu"
725 if provide_full_object_checksum:
726 path += "-full-object"
727
728 if algo == S3ChecksumAlgorithm.CRC32:
729 checksum_header_name = 'x-amz-checksum-crc32'
730 checksum_str = 'a9ccsg=='
731 elif algo == S3ChecksumAlgorithm.CRC64NVME:
732 checksum_header_name = 'x-amz-checksum-crc64nvme'
733 checksum_str = 'tPMvgM0jSDQ='
734 else:
735 raise Exception("Checksum algo not supported by test helper")
736
737 # upload, with client adding checksum
738 upload_request = self._put_object_request(put_body_stream, content_length, path=path)
739 upload_checksum_config = S3ChecksumConfig(
740 algorithm=algo,
741 location=S3ChecksumLocation.TRAILER)
742 if provide_full_object_checksum:
743 upload_request.headers.add(checksum_header_name, checksum_str)
744 # checksum will be provided from the header, don't set the checksum configs
745 upload_checksum_config = None
746
747 self._test_s3_put_get_object(upload_request, S3RequestType.PUT_OBJECT,
748 checksum_config=upload_checksum_config)
749
750 # download, with client validating checksum
751 download_request = self._get_object_request(path)
752 download_checksum_config = S3ChecksumConfig(validate_response=True)
753 self._test_s3_put_get_object(download_request, S3RequestType.GET_OBJECT,
754 checksum_config=download_checksum_config)
755 self.assertTrue(self.done_did_validate_checksum)
756 self.assertEqual(self.done_checksum_validation_algorithm, algo)
757 self.assertEqual(HttpHeaders(self.response_headers).get(checksum_header_name),
758 checksum_str)
759 put_body_stream.close()
760
761 def test_round_trip_with_trailing_checksum(self):
762 self._round_trip_with_checksums_helper(S3ChecksumAlgorithm.CRC32, mpu=False)
763
764 def test_round_trip_with_full_object_checksum_mpu(self):
765 self._round_trip_with_checksums_helper(
766 S3ChecksumAlgorithm.CRC64NVME,
767 mpu=True,
768 provide_full_object_checksum=True)
769
770 def test_round_trip_with_full_object_checksum_single_part(self):
771 self._round_trip_with_checksums_helper(
772 S3ChecksumAlgorithm.CRC64NVME,
773 mpu=False,
774 provide_full_object_checksum=True)
775
776 def test_round_trip_with_full_object_checksum_mpu_crc32(self):
777 self._round_trip_with_checksums_helper(S3ChecksumAlgorithm.CRC32, mpu=True, provide_full_object_checksum=True)
778
779 def test_round_trip_with_full_object_checksum_single_part_crc32(self):
780 self._round_trip_with_checksums_helper(S3ChecksumAlgorithm.CRC32, mpu=False, provide_full_object_checksum=True)
781
782 def _on_progress_cancel_after_first_chunk(self, progress):
783 self.transferred_len += progress
784 self.progress_invoked += 1
785 self.s3_request.cancel()
786
787 def test_multipart_get_object_cancel(self):
788 # a 5 GB file
789 request = self._get_object_request("/get_object_test_5120MB.txt")
790 s3_client = s3_client_new(False, self.region, 5 * MB, is_cancel_test=True)
791 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
792 file.close()
793 self.s3_request = s3_client.make_request(
794 request=request,
795 recv_filepath=file.name,
796 type=S3RequestType.GET_OBJECT,
797 on_headers=self._on_request_headers,
798 on_progress=self._on_progress_cancel_after_first_chunk,
799 on_done=self._on_request_done)
800 finished_future = self.s3_request.finished_future
801 e = finished_future.exception(self.timeout)
802 self.assertEqual(e.name, "AWS_ERROR_S3_CANCELED")
803
804 # Result check
805 self.data_len = int(HttpHeaders(self.response_headers).get("Content-Length"))
806 self.assertLess(
807 self.transferred_len,
808 self.data_len,
809 "the cancel failed to block all the following body")
810
811 # The on_finish callback may invoke the progress
812 self.assertLessEqual(self.progress_invoked, 2)
813 shutdown_event = self.s3_request.shutdown_event
814 self.s3_request = None
815 self.assertTrue(shutdown_event.wait(self.timeout))
816 os.remove(file.name)
817
818 def test_get_object_quick_cancel(self):
819 # a 5 GB file
820 request = self._get_object_request("/get_object_test_5120MB.txt")
821 s3_client = s3_client_new(False, self.region, 5 * MB, is_cancel_test=True)
822 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
823 file.close()
824 s3_request = s3_client.make_request(
825 request=request,
826 recv_filepath=file.name,
827 type=S3RequestType.GET_OBJECT,
828 on_headers=self._on_request_headers,
829 on_progress=self._on_progress,
830 on_done=self._on_request_done)
831 s3_request.cancel()
832 finished_future = s3_request.finished_future
833 e = finished_future.exception(self.timeout)
834 self.assertEqual(e.name, "AWS_ERROR_S3_CANCELED")
835 shutdown_event = s3_request.shutdown_event
836 s3_request = None
837 self.assertTrue(shutdown_event.wait(self.timeout))
838 os.remove(file.name)
839
840 def _put_object_cancel_helper(self, cancel_after_read):
841 read_future = Future()
842 put_body_stream = FakeReadStream(read_future)
843 data_len = 10 * GB # some fake length
844 headers = HttpHeaders([("host", self._build_endpoint_string(self.region, self.bucket_name)),
845 ("Content-Type", "text/plain"), ("Content-Length", str(data_len))])
846 http_request = HttpRequest("PUT", "/cancelled_request", headers, put_body_stream)
847 s3_client = s3_client_new(False, self.region, 8 * MB, is_cancel_test=True)
848 s3_request = s3_client.make_request(
849 request=http_request,
850 type=S3RequestType.PUT_OBJECT,
851 on_headers=self._on_request_headers,
852 on_done=self._on_request_done)
853
854 if cancel_after_read:
855 read_future.result(self.timeout)
856 s3_request.cancel()
857 finished_future = s3_request.finished_future
858 e = finished_future.exception(self.timeout)
859 self.assertEqual(e.name, "AWS_ERROR_S3_CANCELED")
860
861 shutdown_event = s3_request.shutdown_event
862 s3_request = None
863 self.assertTrue(shutdown_event.wait(self.timeout))
864 # TODO If CLI installed, run the following command to ensure the cancel succeed.
865 # aws s3api list-multipart-uploads --bucket aws-crt-canary-bucket --prefix 'cancelled_request'
866 # Nothing should printout
867
868 def test_multipart_put_object_cancel(self):
869 return self._put_object_cancel_helper(True)
870
871 def test_put_object_quick_cancel(self):
872 return self._put_object_cancel_helper(False)
873
874 def test_singlepart_upload_with_invalid_request(self):
875 # send upload with incorrect Content-MD5
876 # need to do single-part upload so the Content-MD5 header is sent along as-is.
877 content_length = 100
878 file_path = self.files.create_file_with_size("temp_file", content_length)
879 put_body_stream = open(file_path, "r+b")
880 request = self._put_object_request(put_body_stream, content_length)
881 request.headers.set("Content-MD5", "something")
882 self._test_s3_put_get_object(request, S3RequestType.PUT_OBJECT, "AWS_ERROR_S3_INVALID_RESPONSE_STATUS")
883
884 # check that data from on_done callback came through correctly
885 self.assertIsInstance(self.done_error, S3ResponseError)
886 self.assertEqual(self.done_status_code, 400)
887 self.assertEqual(self.done_error.status_code, 400)
888 self.assertIsNotNone(self.done_error_headers)
889 self.assertTrue(any(h[0].lower() == 'x-amz-request-id' for h in self.done_error_headers))
890 self.assertListEqual(self.done_error_headers, self.done_error.headers)
891 self.assertIsNotNone(self.done_error_body)
892 self.assertEqual(self.done_error_operation_name, "PutObject")
893 self.assertEqual(self.done_error_operation_name, self.done_error.operation_name)
894 self.assertTrue(b"InvalidDigest" in self.done_error_body)
895 self.assertEqual(self.done_error_body, self.done_error.body)
896
897 put_body_stream.close()
898
899 def test_default_request_failure(self):
900 # send invalid DEFAULT S3Request
901 # ensure error info (including custom operation_name) comes through correctly
902 s3_client = S3Client(region=self.region)
903
904 # send invalid request to S3.
905 http_request = HttpRequest(method="GET", path="/obviously-invalid-path-object-does-not-exist")
906 http_request.headers.add("host", self._build_endpoint_string(self.region, self.bucket_name))
907 http_request.headers.add("content-length", "0")
908 s3_request = s3_client.make_request(
909 type=S3RequestType.DEFAULT,
910 request=http_request,
911 operation_name="MyNewOperationName")
912
913 exception = s3_request.finished_future.exception(self.timeout)
914 self.assertIsInstance(exception, S3ResponseError)
915 self.assertEqual(exception.operation_name, "MyNewOperationName")
916
917 def test_on_headers_callback_failure(self):
918 def _explode(**kwargs):
919 raise RuntimeError("Error in on_headers callback")
920
921 request = self._get_object_request(self.get_test_object_path)
922 s3_client = s3_client_new(False, self.region, 5 * MB)
923 s3_request = s3_client.make_request(
924 request=request,
925 type=S3RequestType.GET_OBJECT,
926 on_headers=_explode,
927 on_body=self._on_request_body,
928 )
929
930 finished_future = s3_request.finished_future
931 shutdown_event = s3_request.shutdown_event
932 s3_request = None
933 self.assertTrue(shutdown_event.wait(self.timeout))
934
935 e = finished_future.exception()
936 # check that data from on_done callback came through correctly
937 self.assertIsInstance(e, RuntimeError)
938 self.assertEqual(str(e), "Error in on_headers callback")
939
940 def test_on_body_callback_failure(self):
941 def _explode(**kwargs):
942 raise RuntimeError("Error in on_body callback")
943
944 request = self._get_object_request(self.get_test_object_path)
945 s3_client = s3_client_new(False, self.region, 5 * MB)
946 s3_request = s3_client.make_request(
947 request=request,
948 type=S3RequestType.GET_OBJECT,
949 on_headers=self._on_request_headers,
950 on_body=_explode,
951 )
952
953 finished_future = s3_request.finished_future
954 shutdown_event = s3_request.shutdown_event
955 s3_request = None
956 self.assertTrue(shutdown_event.wait(self.timeout))
957
958 e = finished_future.exception()
959 # check that data from on_done callback came through correctly
960 self.assertIsInstance(e, RuntimeError)
961 self.assertEqual(str(e), "Error in on_body callback")
962
963 def test_special_filepath_upload(self):
964 # remove the input file when request done
965 content_length = 10 * MB
966 special_path = self.files.create_file_with_size(self.special_path, content_length)
967
968 request = self._put_object_request(None, content_length)
969 s3_client = s3_client_new(False, self.region, 5 * MB)
970 request_type = S3RequestType.PUT_OBJECT
971
972 event_loop_group = EventLoopGroup()
973 host_resolver = DefaultHostResolver(event_loop_group)
974 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
975 credential_provider = AwsCredentialsProvider.new_default_chain(bootstrap)
976 # Let signer to normalize uri path for us.
977 signing_config = AwsSigningConfig(
978 algorithm=AwsSigningAlgorithm.V4,
979 signature_type=AwsSignatureType.HTTP_REQUEST_HEADERS,
980 service="s3",
981 signed_body_header_type=AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA_256,
982 signed_body_value=AwsSignedBodyValue.UNSIGNED_PAYLOAD,
983 region=self.region,
984 credentials_provider=credential_provider,
985 use_double_uri_encode=False,
986 should_normalize_uri_path=True,
987 )
988
989 s3_request = s3_client.make_request(
990 request=request,
991 type=request_type,
992 send_filepath=special_path,
993 signing_config=signing_config,
994 on_headers=self._on_request_headers,
995 on_progress=self._on_progress,
996 on_done=self._on_request_done)
997 finished_future = s3_request.finished_future
998 finished_future.result(self.timeout)
999
1000 # check result
1001 self.assertEqual(
1002 content_length,
1003 self.transferred_len,
1004 "the transferred length reported does not match body we sent")
1005 self._validate_successful_response(request_type is S3RequestType.PUT_OBJECT)
1006 os.remove(special_path)
1007
1008 def test_non_ascii_filepath_upload(self):
1009 # remove the input file when request done
1010 content_length = 10 * MB
1011 non_ascii_file_path = self.files.create_file_with_size(self.non_ascii_file_name, content_length)
1012 request = self._put_object_request(None, content_length)
1013 s3_client = s3_client_new(False, self.region, 5 * MB)
1014 request_type = S3RequestType.PUT_OBJECT
1015
1016 s3_request = s3_client.make_request(
1017 request=request,
1018 type=request_type,
1019 send_filepath=non_ascii_file_path,
1020 on_headers=self._on_request_headers,
1021 on_progress=self._on_progress,
1022 on_done=self._on_request_done)
1023 finished_future = s3_request.finished_future
1024 finished_future.result(self.timeout)
1025
1026 # check result
1027 self.assertEqual(
1028 content_length,
1029 self.transferred_len,
1030 "the transferred length reported does not match body we sent")
1031 self._validate_successful_response(request_type is S3RequestType.PUT_OBJECT)
1032
1033 def test_non_ascii_filepath_download(self):
1034 non_ascii_file_path = self.files.create_file_with_size(self.non_ascii_file_name, 0)
1035 request = self._get_object_request(self.get_test_object_path)
1036 request_type = S3RequestType.GET_OBJECT
1037 s3_client = s3_client_new(False, self.region, 5 * MB)
1038 s3_request = s3_client.make_request(
1039 request=request,
1040 type=request_type,
1041 recv_filepath=non_ascii_file_path,
1042 on_headers=self._on_request_headers,
1043 on_progress=self._on_progress,
1044 on_done=self._on_request_done)
1045 finished_future = s3_request.finished_future
1046 finished_future.result(self.timeout)
1047
1048 # Result check
1049 self.data_len = int(HttpHeaders(self.response_headers).get("Content-Length"))
1050 file_stats = os.stat(non_ascii_file_path)
1051 file_len = file_stats.st_size
1052 self.assertEqual(
1053 file_len,
1054 self.transferred_len,
1055 "the length of written file does not match the transferred length reported")
1056 self.assertEqual(
1057 self.data_len,
1058 self.transferred_len,
1059 "the transferred length reported does not match the content-length header")
1060 self.assertEqual(self.response_status_code, 200, "status code is not 200")
1061
1062
1063 if __name__ == '__main__':
1064 unittest.main()