Debian Codegraph @

ansible_collections/community/aws/plugins/modules/s3_sync.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: s3_sync
10 version_added: 1.0.0
11 short_description: Efficiently upload multiple files to S3
12 description:
13 - The S3 module is great, but it is very slow for a large volume of files- even a dozen will be noticeable. In addition to speed, it handles globbing,
14 inclusions/exclusions, mime types, expiration mapping, recursion, cache control and smart directory mapping.
15 options:
16 mode:
17 description:
18 - sync direction.
19 default: 'push'
20 choices: [ 'push' ]
21 type: str
22 file_change_strategy:
23 description:
24 - Difference determination method to allow changes-only syncing. Unlike rsync, files are not patched- they are fully skipped or fully uploaded.
25 - date_size will upload if file sizes don't match or if local file modified date is newer than s3's version
26 - checksum will compare etag values based on s3's implementation of chunked md5s.
27 - force will always upload all files.
28 required: false
29 default: 'date_size'
30 choices: [ 'force', 'checksum', 'date_size' ]
31 type: str
32 bucket:
33 description:
34 - Bucket name.
35 required: true
36 type: str
37 key_prefix:
38 description:
39 - In addition to file path, prepend s3 path with this prefix. Module will add slash at end of prefix if necessary.
40 required: false
41 type: str
42 default: ''
43 file_root:
44 description:
45 - File/directory path for synchronization. This is a local path.
46 - This root path is scrubbed from the key name, so subdirectories will remain as keys.
47 required: true
48 type: path
49 permission:
50 description:
51 - Canned ACL to apply to synced files.
52 - Changing this ACL only changes newly synced files, it does not trigger a full reupload.
53 required: false
54 choices:
55 - 'private'
56 - 'public-read'
57 - 'public-read-write'
58 - 'authenticated-read'
59 - 'aws-exec-read'
60 - 'bucket-owner-read'
61 - 'bucket-owner-full-control'
62 type: str
63 mime_map:
64 description:
65 - >
66 Dict entry from extension to MIME type. This will override any default/sniffed MIME type.
67 For example C({".txt": "application/text", ".yml": "application/text"})
68 required: false
69 type: dict
70 include:
71 description:
72 - Shell pattern-style file matching.
73 - Used before exclude to determine eligible files (for instance, only C("*.gif"))
74 - For multiple patterns, comma-separate them.
75 required: false
76 default: "*"
77 type: str
78 exclude:
79 description:
80 - Shell pattern-style file matching.
81 - Used after include to remove files (for instance, skip C("*.txt"))
82 - For multiple patterns, comma-separate them.
83 required: false
84 default: ".*"
85 type: str
86 cache_control:
87 description:
88 - Cache-Control header set on uploaded objects.
89 - Directives are separated by commas.
90 required: false
91 type: str
92 default: ''
93 storage_class:
94 description:
95 - Storage class to be associated to each object added to the S3 bucket.
96 required: false
97 choices:
98 - 'STANDARD'
99 - 'REDUCED_REDUNDANCY'
100 - 'STANDARD_IA'
101 - 'ONEZONE_IA'
102 - 'INTELLIGENT_TIERING'
103 - 'GLACIER'
104 - 'DEEP_ARCHIVE'
105 - 'OUTPOSTS'
106 default: 'STANDARD'
107 type: str
108 version_added: 1.5.0
109 delete:
110 description:
111 - Remove remote files that exist in bucket but are not present in the file root.
112 required: false
113 default: false
114 type: bool
115
116 author:
117 - Ted Timmons (@tedder)
118 extends_documentation_fragment:
119 - amazon.aws.common.modules
120 - amazon.aws.region.modules
121 - amazon.aws.boto3
122 """
123
124 EXAMPLES = r"""
125 - name: basic upload
126 community.aws.s3_sync:
127 bucket: tedder
128 file_root: roles/s3/files/
129
130 - name: basic upload using the glacier storage class
131 community.aws.s3_sync:
132 bucket: tedder
133 file_root: roles/s3/files/
134 storage_class: GLACIER
135
136 - name: basic individual file upload
137 community.aws.s3_sync:
138 bucket: tedder
139 file_root: roles/s3/files/file_name
140
141 - name: all the options
142 community.aws.s3_sync:
143 bucket: tedder
144 file_root: roles/s3/files
145 mime_map:
146 .yml: application/text
147 .json: application/text
148 key_prefix: config_files/web
149 file_change_strategy: force
150 permission: public-read
151 cache_control: "public, max-age=31536000"
152 storage_class: "GLACIER"
153 include: "*"
154 exclude: "*.txt,.*"
155 """
156
157 RETURN = r"""
158 filelist_initial:
159 description: file listing (dicts) from initial globbing
160 returned: always
161 type: list
162 sample: [{
163 "bytes": 151,
164 "chopped_path": "policy.json",
165 "fullpath": "roles/cf/files/policy.json",
166 "modified_epoch": 1477416706
167 }]
168 filelist_local_etag:
169 description: file listing (dicts) including calculated local etag
170 returned: always
171 type: list
172 sample: [{
173 "bytes": 151,
174 "chopped_path": "policy.json",
175 "fullpath": "roles/cf/files/policy.json",
176 "mime_type": "application/json",
177 "modified_epoch": 1477416706,
178 "s3_path": "s3sync/policy.json"
179 }]
180 filelist_s3:
181 description: file listing (dicts) including information about previously-uploaded versions
182 returned: always
183 type: list
184 sample: [{
185 "bytes": 151,
186 "chopped_path": "policy.json",
187 "fullpath": "roles/cf/files/policy.json",
188 "mime_type": "application/json",
189 "modified_epoch": 1477416706,
190 "s3_path": "s3sync/policy.json"
191 }]
192 filelist_typed:
193 description: file listing (dicts) with calculated or overridden mime types
194 returned: always
195 type: list
196 sample: [{
197 "bytes": 151,
198 "chopped_path": "policy.json",
199 "fullpath": "roles/cf/files/policy.json",
200 "mime_type": "application/json",
201 "modified_epoch": 1477416706
202 }]
203 filelist_actionable:
204 description: file listing (dicts) of files that will be uploaded after the strategy decision
205 returned: always
206 type: list
207 sample: [{
208 "bytes": 151,
209 "chopped_path": "policy.json",
210 "fullpath": "roles/cf/files/policy.json",
211 "mime_type": "application/json",
212 "modified_epoch": 1477931256,
213 "s3_path": "s3sync/policy.json",
214 "whysize": "151 / 151",
215 "whytime": "1477931256 / 1477929260"
216 }]
217 uploads:
218 description: file listing (dicts) of files that were actually uploaded
219 returned: always
220 type: list
221 sample: [{
222 "bytes": 151,
223 "chopped_path": "policy.json",
224 "fullpath": "roles/cf/files/policy.json",
225 "s3_path": "s3sync/policy.json",
226 "whysize": "151 / 151",
227 "whytime": "1477931637 / 1477931489"
228 }]
229
230 """
231
232 import datetime
233 import fnmatch
234 import mimetypes
235 import os
236 import stat as osstat # os.stat constants
237
238 try:
239 from dateutil import tz
240
241 HAS_DATEUTIL = True
242 except ImportError:
243 HAS_DATEUTIL = False
244
245 try:
246 import botocore
247 except ImportError:
248 pass # Handled by AnsibleAWSModule
249
250 from ansible.module_utils._text import to_text
251
252 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
253
254 from ansible_collections.community.aws.plugins.module_utils.etag import calculate_multipart_etag
255 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
256
257
258 def gather_files(fileroot, include=None, exclude=None):
259 ret = []
260
261 if os.path.isfile(fileroot):
262 fullpath = fileroot
263 fstat = os.stat(fullpath)
264 path_array = fileroot.split("/")
265 chopped_path = path_array[-1]
266 f_size = fstat[osstat.ST_SIZE]
267 f_modified_epoch = fstat[osstat.ST_MTIME]
268 ret.append(
269 {
270 "fullpath": fullpath,
271 "chopped_path": chopped_path,
272 "modified_epoch": f_modified_epoch,
273 "bytes": f_size,
274 }
275 )
276
277 else:
278 for dirpath, dirnames, filenames in os.walk(fileroot):
279 for fn in filenames:
280 fullpath = os.path.join(dirpath, fn)
281 # include/exclude
282 if include:
283 found = False
284 for x in include.split(","):
285 if fnmatch.fnmatch(fn, x):
286 found = True
287 if not found:
288 # not on the include list, so we don't want it.
289 continue
290
291 if exclude:
292 found = False
293 for x in exclude.split(","):
294 if fnmatch.fnmatch(fn, x):
295 found = True
296 if found:
297 # skip it, even if previously included.
298 continue
299
300 chopped_path = os.path.relpath(fullpath, start=fileroot)
301 fstat = os.stat(fullpath)
302 f_size = fstat[osstat.ST_SIZE]
303 f_modified_epoch = fstat[osstat.ST_MTIME]
304 ret.append(
305 {
306 "fullpath": fullpath,
307 "chopped_path": chopped_path,
308 "modified_epoch": f_modified_epoch,
309 "bytes": f_size,
310 }
311 )
312 # dirpath = path *to* the directory
313 # dirnames = subdirs *in* our directory
314 # filenames
315 return ret
316
317
318 def calculate_s3_path(filelist, key_prefix=""):
319 ret = []
320 for fileentry in filelist:
321 # don't modify the input dict
322 retentry = fileentry.copy()
323 retentry["s3_path"] = os.path.join(key_prefix, fileentry["chopped_path"])
324 ret.append(retentry)
325 return ret
326
327
328 def calculate_local_etag(filelist, key_prefix=""):
329 """Really, "calculate md5", but since AWS uses their own format, we'll just call
330 it a "local etag". TODO optimization: only calculate if remote key exists."""
331 ret = []
332 for fileentry in filelist:
333 # don't modify the input dict
334 retentry = fileentry.copy()
335 retentry["local_etag"] = calculate_multipart_etag(fileentry["fullpath"])
336 ret.append(retentry)
337 return ret
338
339
340 def determine_mimetypes(filelist, override_map):
341 ret = []
342 for fileentry in filelist:
343 retentry = fileentry.copy()
344 localfile = fileentry["fullpath"]
345
346 # reminder: file extension is '.txt', not 'txt'.
347 file_extension = os.path.splitext(localfile)[1]
348 if override_map and override_map.get(file_extension):
349 # override? use it.
350 retentry["mime_type"] = override_map[file_extension]
351 else:
352 # else sniff it
353 retentry["mime_type"], retentry["encoding"] = mimetypes.guess_type(localfile, strict=False)
354
355 # might be None or '' from one of the above. Not a great type but better than nothing.
356 if not retentry["mime_type"]:
357 retentry["mime_type"] = "application/octet-stream"
358
359 ret.append(retentry)
360
361 return ret
362
363
364 def head_s3(s3, bucket, s3keys):
365 retkeys = []
366 for entry in s3keys:
367 retentry = entry.copy()
368 try:
369 retentry["s3_head"] = s3.head_object(Bucket=bucket, Key=entry["s3_path"])
370 # 404 (Missing) - File doesn't exist, we'll need to upload
371 # 403 (Denied) - Sometimes we can write but not read, assume we'll need to upload
372 except is_boto3_error_code(["404", "403"]):
373 pass
374 retkeys.append(retentry)
375 return retkeys
376
377
378 def filter_list(s3, bucket, s3filelist, strategy):
379 keeplist = list(s3filelist)
380
381 for e in keeplist:
382 e["_strategy"] = strategy
383
384 # init/fetch info from S3 if we're going to use it for comparisons
385 if not strategy == "force":
386 keeplist = head_s3(s3, bucket, s3filelist)
387
388 # now actually run the strategies
389 if strategy == "checksum":
390 for entry in keeplist:
391 if entry.get("s3_head"):
392 # since we have a remote s3 object, compare the values.
393 if entry["s3_head"]["ETag"] == entry["local_etag"]:
394 # files match, so remove the entry
395 entry["skip_flag"] = True
396 else:
397 # file etags don't match, keep the entry.
398 pass
399 else: # we don't have an etag, so we'll keep it.
400 pass
401 elif strategy == "date_size":
402 for entry in keeplist:
403 if entry.get("s3_head"):
404 # fstat = entry['stat']
405 local_modified_epoch = entry["modified_epoch"]
406 local_size = entry["bytes"]
407
408 # py2's datetime doesn't have a timestamp() field, so we have to revert to something more awkward.
409 # remote_modified_epoch = entry['s3_head']['LastModified'].timestamp()
410 remote_modified_datetime = entry["s3_head"]["LastModified"]
411 delta = remote_modified_datetime - datetime.datetime(1970, 1, 1, tzinfo=tz.tzutc())
412 remote_modified_epoch = delta.seconds + (delta.days * 86400)
413
414 remote_size = entry["s3_head"]["ContentLength"]
415
416 entry["whytime"] = f"{local_modified_epoch} / {remote_modified_epoch}"
417 entry["whysize"] = f"{local_size} / {remote_size}"
418
419 if local_modified_epoch <= remote_modified_epoch and local_size == remote_size:
420 entry["skip_flag"] = True
421 else:
422 entry["why"] = "no s3_head"
423 # else: probably 'force'. Basically we don't skip with any with other strategies.
424 else:
425 pass
426
427 # prune 'please skip' entries, if any.
428 return [x for x in keeplist if not x.get("skip_flag")]
429
430
431 def upload_files(s3, bucket, filelist, params):
432 ret = []
433 for entry in filelist:
434 args = {"ContentType": entry["mime_type"]}
435 if params.get("permission"):
436 args["ACL"] = params["permission"]
437 if params.get("cache_control"):
438 args["CacheControl"] = params["cache_control"]
439 if params.get("storage_class"):
440 args["StorageClass"] = params["storage_class"]
441 # if this fails exception is caught in main()
442 s3.upload_file(entry["fullpath"], bucket, entry["s3_path"], ExtraArgs=args, Callback=None, Config=None)
443 ret.append(entry)
444 return ret
445
446
447 def remove_files(s3, sourcelist, params):
448 bucket = params.get("bucket")
449 key_prefix = params.get("key_prefix")
450 paginator = s3.get_paginator("list_objects_v2")
451 current_keys = set(
452 x["Key"] for x in paginator.paginate(Bucket=bucket, Prefix=key_prefix).build_full_result().get("Contents", [])
453 )
454 keep_keys = set(to_text(source_file["s3_path"]) for source_file in sourcelist)
455 delete_keys = list(current_keys - keep_keys)
456
457 # can delete 1000 objects at a time
458 groups_of_keys = [delete_keys[i:i + 1000] for i in range(0, len(delete_keys), 1000)] # fmt:skip
459 for keys in groups_of_keys:
460 s3.delete_objects(Bucket=bucket, Delete={"Objects": [{"Key": key} for key in keys]})
461
462 return delete_keys
463
464
465 def main():
466 argument_spec = dict(
467 mode=dict(choices=["push"], default="push"),
468 file_change_strategy=dict(choices=["force", "date_size", "checksum"], default="date_size"),
469 bucket=dict(required=True),
470 key_prefix=dict(required=False, default="", no_log=False),
471 file_root=dict(required=True, type="path"),
472 permission=dict(
473 required=False,
474 choices=[
475 "private",
476 "public-read",
477 "public-read-write",
478 "authenticated-read",
479 "aws-exec-read",
480 "bucket-owner-read",
481 "bucket-owner-full-control",
482 ],
483 ),
484 mime_map=dict(required=False, type="dict"),
485 exclude=dict(required=False, default=".*"),
486 include=dict(required=False, default="*"),
487 cache_control=dict(required=False, default=""),
488 delete=dict(required=False, type="bool", default=False),
489 storage_class=dict(
490 required=False,
491 default="STANDARD",
492 choices=[
493 "STANDARD",
494 "REDUCED_REDUNDANCY",
495 "STANDARD_IA",
496 "ONEZONE_IA",
497 "INTELLIGENT_TIERING",
498 "GLACIER",
499 "DEEP_ARCHIVE",
500 "OUTPOSTS",
501 ],
502 ),
503 # future options: encoding, metadata, retries
504 )
505
506 module = AnsibleAWSModule(
507 argument_spec=argument_spec,
508 )
509
510 if not HAS_DATEUTIL:
511 module.fail_json(msg="dateutil required for this module")
512
513 result = {}
514 mode = module.params["mode"]
515
516 try:
517 s3 = module.client("s3")
518 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
519 module.fail_json_aws(e, msg="Failed to connect to AWS")
520
521 if mode == "push":
522 try:
523 result["filelist_initial"] = gather_files(
524 module.params["file_root"], exclude=module.params["exclude"], include=module.params["include"]
525 )
526 result["filelist_typed"] = determine_mimetypes(result["filelist_initial"], module.params.get("mime_map"))
527 result["filelist_s3"] = calculate_s3_path(result["filelist_typed"], module.params["key_prefix"])
528 try:
529 result["filelist_local_etag"] = calculate_local_etag(result["filelist_s3"])
530 except ValueError as e:
531 if module.params["file_change_strategy"] == "checksum":
532 module.fail_json_aws(
533 e,
534 "Unable to calculate checksum. If running in FIPS mode, you may need to use another file_change_strategy",
535 )
536 result["filelist_local_etag"] = result["filelist_s3"].copy()
537 result["filelist_actionable"] = filter_list(
538 s3, module.params["bucket"], result["filelist_local_etag"], module.params["file_change_strategy"]
539 )
540 result["uploads"] = upload_files(s3, module.params["bucket"], result["filelist_actionable"], module.params)
541
542 if module.params["delete"]:
543 result["removed"] = remove_files(s3, result["filelist_local_etag"], module.params)
544
545 # mark changed if we actually upload something.
546 if result.get("uploads") or result.get("removed"):
547 result["changed"] = True
548 # result.update(filelist=actionable_filelist)
549 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
550 module.fail_json_aws(e, msg="Failed to push file")
551
552 module.exit_json(**result)
553
554
555 if __name__ == "__main__":
556 main()