blob: 55c1b0a605c16e313691241251227d752d3ebe03 [file] [log] [blame]
ZhiQiang Fan39f97222013-09-20 04:49:44 +08001# Copyright 2012 OpenStack Foundation
Attila Fazekasa23f5002012-10-23 19:32:45 +02002# 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 Taylorb2ca5ca2013-04-28 18:00:21 -070016import contextlib
Attila Fazekasa23f5002012-10-23 19:32:45 +020017import os
18import re
Attila Fazekasa23f5002012-10-23 19:32:45 +020019
Matthew Treinisha83a16e2012-12-07 13:44:02 -050020import boto
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070021import boto.s3.key
Attila Fazekasa23f5002012-10-23 19:32:45 +020022
Doug Hellmann583ce2c2015-03-11 14:55:46 +000023from oslo_log import log as logging
Mitsuhiko Yamazaki46818aa2013-04-18 17:49:17 +090024
Attila Fazekasa23f5002012-10-23 19:32:45 +020025LOG = logging.getLogger(__name__)
26
27
28def s3_upload_dir(bucket, path, prefix="", connection_data=None):
29 if isinstance(bucket, basestring):
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070030 with contextlib.closing(boto.connect_s3(**connection_data)) as conn:
Attila Fazekasa23f5002012-10-23 19:32:45 +020031 bucket = conn.lookup(bucket)
32 for root, dirs, files in os.walk(path):
33 for fil in files:
Monty Taylorb2ca5ca2013-04-28 18:00:21 -070034 with contextlib.closing(boto.s3.key.Key(bucket)) as key:
Attila Fazekasa23f5002012-10-23 19:32:45 +020035 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)