Skip to content

Instantly share code, notes, and snippets.

@advance512
Last active August 18, 2019 19:59
Show Gist options
  • Save advance512/6164734 to your computer and use it in GitHub Desktop.
Save advance512/6164734 to your computer and use it in GitHub Desktop.
S3 client that uses Tornado's asynchronous mechanisms. Allows the uploading and downloading of files asynchronously, including metadata support as well. Based on https://gist.github.com/taylanpince/5876491
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2011-2013 Everything.me. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY Everything.me ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of Everything.me.
__copyright__ = "Copyright 2011-2013 (c) everything.me. All rights reserved."
__author__="Alon Diamant"
__email__ = "alon@everything.me"
'''
S3 client that uses Tornado's asynchronous mechanisms.
Allows the uploading and downloading of files asynchronously, including metadata support as well.
Example:
s3 = S3AsyncClient('access_key', 'secret_key', 'somebucket')
result = yield s3.uploadFile("private_files/someFile.jpeg",
image_data,
contentType="image/jpeg",
metadata={"uploaded": upload_timestamp},
isPublic=False)
result = yield s3.downloadFile("private_files/someFile.jpeg")
Another example:
result = yield s3.uploadFile("public_files/someOtherFile.jpeg",
image_data,
contentType="image/jpeg",
metadata={"uploaded": upload_timestamp},
isPublic=True)
Now accessible in:
http://somebucket.s3.amazonaws.com/public_files/someOtherFile.jpeg
Based on https://gist.github.com/taylanpince/5876491
by Taylan Pince, taylanpince@gmail.com
'''
import hashlib, hmac, mimetypes, os, time
from base64 import b64encode, b64decode
from calendar import timegm
from datetime import datetime
from email.utils import formatdate
from urllib import quote, unquote
import logging
from lxml import etree
from tornado.gen import coroutine, Return
from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPClient
#=======================================================================================================================
# Module variables definition
#=======================================================================================================================
AWS_S3_BUCKET_URL = "http://%(bucket)s.s3.amazonaws.com/%(path)s"
AWS_S3_CONNECT_TIMEOUT = 10
AWS_S3_REQUEST_TIMEOUT = 90
#=======================================================================================================================
# Class definition
#=======================================================================================================================
class S3AsyncClient(object):
'''
AWS client that handles asynchronous uploads to S3 buckets
'''
#===================================================================================================================
# Public Interface
#===================================================================================================================
def __init__(self, access_key=None, secret_key=None, bucket=None):
'''
:param access_key: S3 access key
:param secret_key: S3 secret key
:param bucket: S3 bucket to use
'''
super(S3AsyncClient, self).__init__()
self.access_key = access_key
self.secret_key = secret_key
self.bucket = bucket
self._client = AsyncHTTPClient()
@coroutine
def uploadFile(self, path, data, contentType="application/octet-stream", metadata={}, isPublic=False):
"""
Asynchronously uploads the given file to the specified path.
:param path: Path of file to upload
:param data: File data
:param contentType: Content type of the file uploaded. Will affect HTTP access, so set this correctly.
:param metadata: Metadata to store with this file. Metadata key names will be stored in lowercase on the server.
Make sure there are no newlines in the values inputted.
:param isPublic: Whether to allow global HTTP access (as described in AWS_S3_BUCKET_URL) or not.
:return: True or False
"""
method = "PUT"
headers = {}
headers.update({
"Content-Length": str(len(data)),
"Content-MD5": self._calculateAWSMD5(data),
"X-Amz-Acl": "public-read" if isPublic else "private",
"Content-Type": contentType
})
# Add metadata headers
total_metadata_size = 0
for key, value in metadata.iteritems():
if "\n" in str(value): raise ValueError("Metadata values should not have newlines.")
headers['X-Amz-Meta-%s' % key] = quote(str(value))
total_metadata_size += len('X-Amz-Meta-%s' % key) + len(headers['X-Amz-Meta-%s' % key])
if total_metadata_size > 2048:
raise ValueError("S3 metadata size too large: %s! The S3 user-defined metadata is limited to 2 KB in size. "
"The size of the user-defined metadata is measured by taking the sum of the "
"number of bytes in the UTF-8 encoding of each key and value." % total_metadata_size)
# Sign the headers
self._signHeaders(method, path, headers)
try:
start_time = time.time()
response = yield self._client.fetch(
AWS_S3_BUCKET_URL % {
"bucket": self.bucket,
"path": path,
},
method=method,
body=data,
connect_timeout=AWS_S3_CONNECT_TIMEOUT,
request_timeout=AWS_S3_REQUEST_TIMEOUT,
headers=headers
)
if response.code != 200:
logging.error("Problem uploading file %s to S3: code=%s, body=%s",
path,
response.code,
response.body)
else:
raise Return(True)
except HTTPError as error:
if error.code == 599:
end_time = time.time()
total_time = end_time - start_time
logging.warning("Timeout uploading file %s to S3: %s seconds.", path, total_time)
else:
logging.error("Error uploading file %s to S3: %s", path, error)
raise Return(False)
@coroutine
def downloadFile(self, path):
"""
Asynchronously downloads the requested file.
Metadata will be returned as well.
:param path: Path of file to download
:return: (data, metadata) tuple, or None if it doesn't exist
"""
method = "GET"
headers = {}
# Sign the headers
self._signHeaders(method, path, headers)
try:
response = yield self._client.fetch(
AWS_S3_BUCKET_URL % {
"bucket": self.bucket,
"path": path,
},
method=method,
body=None,
connect_timeout=AWS_S3_CONNECT_TIMEOUT,
request_timeout=AWS_S3_REQUEST_TIMEOUT,
headers=headers
)
if response.code == 200:
# Get the metadata from the headers
metadata = {
key[11:].lower(): unquote(value)
for key, value in response.headers.iteritems()
if key.lower().startswith('x-amz-meta')
}
data = response.body
raise Return((data, metadata))
else:
logging.error("Problem downloading file from S3: code=%s, body=%s", response.code, response.body)
except HTTPError as error:
if error.code == 404:
#logging.error("The request file %s does not exist in S3. HTTP %s" %
# (path, error.code))
pass
elif error.code == 599:
logging.error("Downloading the requested file %s from S3 timed out. HTTP %s" %
(path, error.code))
else:
logging.exception("Error downloading file %s from S3: HTTP error %s" % (path, error.code))
raise Return(None)
@coroutine
def deleteFile(self, path):
"""
Asynchronously delete the requested file.
:param path: Path of file to delete
:return: True or False
"""
result = False
method = "DELETE"
headers = {}
# Sign the headers
self._signHeaders(method, path, headers)
try:
response = yield self._client.fetch(
AWS_S3_BUCKET_URL % {
"bucket": self.bucket,
"path": path,
},
method=method,
body=None,
connect_timeout=AWS_S3_CONNECT_TIMEOUT,
request_timeout=AWS_S3_REQUEST_TIMEOUT,
headers=headers
)
if response.code == 204:
result = True
else:
logging.error("Problem deleting file from S3: code=%s, body=%s", response.code, response.body)
except HTTPError as error:
logging.exception("Error downloading file %s from S3." % path)
raise Return(result)
@coroutine
def listFiles(self, path_prefix):
"""
Asynchronously gets a list of all files that begin with the inputted path prefix.
:param path_prefix: for example: "/public/image_" will match "/public/image_1.jpeg" etc
:return: Set of file paths found, or None if error
"""
# Based on http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
file_names = None
method = "GET"
headers = {}
url = AWS_S3_BUCKET_URL % { "bucket": self.bucket, "path": "?prefix=%s" % path_prefix }
# Sign the headers
self._signHeaders(method, "", headers)
try:
response = yield self._client.fetch(
url,
method=method,
body=None,
connect_timeout=AWS_S3_CONNECT_TIMEOUT,
request_timeout=AWS_S3_REQUEST_TIMEOUT,
headers=headers
)
if response.code == 200:
# Get the file names
file_names = [ val.text for val in etree.fromstring(response.body).iter("{*}Key") ]
else:
logging.error("Problem listing file from S3: code=%s, body=%s", response.code, response.body)
except HTTPError as error:
logging.exception("Error listing files that start with %s in S3." % path_prefix)
raise Return(file_names)
@coroutine
def deleteFiles(self, paths):
"""
Asynchronously delete all files in specified paths
:param paths: Set of paths to files to delete
:return: True or False
"""
raise NotImplementedError
# TODO: Fix the problem in the signing - this requires better tests.
# For now, listFiles + deleteFile will do the job.
'''
# Based on http://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html
result = False
method = "POST"
url = AWS_S3_BUCKET_URL % { "bucket": self.bucket, "path": "?delete" }
xml_parts = [ '<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>true</Quiet>' ]
for path in paths: xml_parts.append('<Object><Key>%s</Key></Object>' % path)
xml_parts.append('</Delete>')
body = ''.join(xml_parts)
headers = {}
headers.update({
"Content-Length": str(len(body)),
"Content-MD5": self._calculateAWSMD5(body)
})
# Sign the headers
self._signHeaders(method, "", headers)
try:
response = yield self._client.fetch(
url,
method=method,
body=body,
connect_timeout=AWS_S3_CONNECT_TIMEOUT,
request_timeout=AWS_S3_REQUEST_TIMEOUT,
headers=headers
)
if response.code == 200:
# TODO: Better checks whether the return XML actually says we failed miserably
result = True
else:
logging.error("Problem deleting files from S3: code=%s, body=%s", response.code, response.body)
except HTTPError as error:
logging.exception("Error downloading files %s from S3." % paths)
raise Return(result)
'''
#===================================================================================================================
# Private Methods
#===================================================================================================================
def _calculateAWSMD5(self, data):
"""
Make an AWS-style MD5 hash (digest in base64)
"""
hasher = hashlib.new("md5")
if hasattr(data, "read"):
data.seek(0)
while True:
chunk = data.read(8192)
if not chunk:
break
hasher.update(chunk)
data.seek(0)
else:
hasher.update(data)
return b64encode(hasher.digest()).decode("ascii")
def _urlquote(self, url):
"""
Quote URLs in AWS format
"""
if isinstance(url, unicode):
url = url.encode("utf-8")
return quote(url, "/")
def _getRFC822DateTime(self, t=None):
"""
Generate date in RFC822 format
"""
if t is None:
t = datetime.utcnow()
return formatdate(timegm(t.timetuple()), usegmt=True)
def _signHeaders(self, method, path, headers):
"""
Sign headers for AWS with authentication tokens. Updates the headers dictionary receives.
"""
date = self._getRFC822DateTime()
# Based on: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
amz_headers_set = [ "%s:%s" % (key.lower(), value)
for key, value in headers.iteritems()
if key.lower().startswith('x-amz') ]
amz_headers_set.sort()
amz_headers_string = "\n".join(amz_headers_set).rstrip()
signature_strings = \
[
"{method}",
"{content_md5}",
"{content_type}",
"{date}"
]
if len(amz_headers_string) > 0:
signature_strings.append(amz_headers_string)
signature_strings.append("/{bucket}/{path}")
signature = "\n".join(signature_strings).format(
method=method,
content_type=headers.get("Content-Type") or "",
content_md5=headers.get("Content-MD5") or "",
date=date,
bucket=self.bucket,
path=path
)
try:
auth_signature = b64encode(hmac.new(
self.secret_key.encode("utf-8"),
signature.encode("utf-8"),
hashlib.sha1
).digest()).strip()
except UnicodeDecodeError as e:
logging.info("Signature is: ***\n%s\n***", signature)
logging.exception("Problem with signature encoding...")
headers.update({
"Date": date,
"Authorization": "AWS %(access_key)s:%(auth_signature)s" % {
"access_key": self.access_key,
"auth_signature": auth_signature,
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment