ZhiQiang Fan | 39f9722 | 2013-09-20 04:49:44 +0800 | [diff] [blame] | 1 | # Copyright 2012 OpenStack Foundation |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 2 | # All Rights Reserved. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 | # not use this file except in compliance with the License. You may obtain |
| 6 | # a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | # License for the specific language governing permissions and limitations |
| 14 | # under the License. |
| 15 | |
Monty Taylor | b2ca5ca | 2013-04-28 18:00:21 -0700 | [diff] [blame] | 16 | import contextlib |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 17 | import os |
| 18 | import re |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 19 | |
Matthew Treinish | a83a16e | 2012-12-07 13:44:02 -0500 | [diff] [blame] | 20 | import boto |
Monty Taylor | b2ca5ca | 2013-04-28 18:00:21 -0700 | [diff] [blame] | 21 | import boto.s3.key |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 22 | |
Doug Hellmann | 583ce2c | 2015-03-11 14:55:46 +0000 | [diff] [blame] | 23 | from oslo_log import log as logging |
Mitsuhiko Yamazaki | 46818aa | 2013-04-18 17:49:17 +0900 | [diff] [blame] | 24 | |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 25 | LOG = logging.getLogger(__name__) |
| 26 | |
| 27 | |
| 28 | def s3_upload_dir(bucket, path, prefix="", connection_data=None): |
| 29 | if isinstance(bucket, basestring): |
Monty Taylor | b2ca5ca | 2013-04-28 18:00:21 -0700 | [diff] [blame] | 30 | with contextlib.closing(boto.connect_s3(**connection_data)) as conn: |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 31 | bucket = conn.lookup(bucket) |
| 32 | for root, dirs, files in os.walk(path): |
| 33 | for fil in files: |
Monty Taylor | b2ca5ca | 2013-04-28 18:00:21 -0700 | [diff] [blame] | 34 | with contextlib.closing(boto.s3.key.Key(bucket)) as key: |
Attila Fazekas | a23f500 | 2012-10-23 19:32:45 +0200 | [diff] [blame] | 35 | source = root + os.sep + fil |
| 36 | target = re.sub("^" + re.escape(path) + "?/", prefix, source) |
| 37 | if os.sep != '/': |
| 38 | target = re.sub(re.escape(os.sep), '/', target) |
| 39 | key.key = target |
| 40 | LOG.info("Uploading %s to %s/%s", source, bucket.name, target) |
| 41 | key.set_contents_from_filename(source) |