3 # Copyright (C) 2010 The Regents of the University of California
4 # Written by Michael Vrable <mvrable@cs.ucsd.edu>
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 # 3. Neither the name of the University nor the names of its contributors
15 # may be used to endorse or promote products derived from this software
16 # without specific prior written permission.
18 # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 """A simple test API for accessing Windows Azure blob storage.
32 Parts of the code are modeled after boto (a library for accessing Amazon Web
33 Services), but this code is far less general and is meant only as a
36 import base64, hashlib, hmac, httplib, os, time
38 # The version of the Azure API we implement; sent in the x-ms-version header.
39 API_VERSION = '2009-09-19'
45 def add_auth_headers(headers, method, path):
46 header_order = ['Content-Encoding', 'Content-Language', 'Content-Length',
47 'Content-MD5', 'Content-Type', 'Date', 'If-Modified-Since',
48 'If-Match', 'If-None-Match', 'If-Unmodified-Since',
51 if not headers.has_key('Date'):
52 headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
54 if not headers.has_key('x-ms-version'):
55 headers['x-ms-version'] = API_VERSION
57 StringToSign = method + "\n"
58 for h in header_order:
60 StringToSign += headers[h] + "\n"
64 # Add Canonicalized Headers
66 for (k, v) in headers.items():
68 if k.startswith('x-ms-'):
69 canonized.append((k, v))
71 for (k, v) in canonized:
72 StringToSign += "%s:%s\n" % (k, v)
74 # Add CanonicalizedHeaders Resource
75 account_name = os.environ['AZURE_ACCOUNT_NAME']
76 account_name = 'bluesky'
77 resource = "/" + account_name
81 (path, params) = path.split('?', 1)
82 params = [p.split('=') for p in params.split("&")]
83 params = dict((k.lower(), uri_decode(v)) for (k, v) in params)
85 for k in sorted(params):
86 resource += "\n%s:%s" % (k, params[k])
87 StringToSign += resource
89 # print "String to sign:", repr(StringToSign)
91 secret_key = os.environ['AZURE_SECRET_KEY']
92 secret_key = base64.b64decode(secret_key)
93 h = hmac.new(secret_key, digestmod=hashlib.sha256)
94 h.update(StringToSign)
96 signature = base64.b64encode(h.digest())
97 headers['Authorization'] = "SharedKey %s:%s" % (account_name, signature)
101 self.host = os.environ['AZURE_ACCOUNT_NAME'] + ".blob.core.windows.net"
102 self.conn = httplib.HTTPConnection(self.host)
104 def make_request(self, path, method='GET', body="", headers={}):
105 headers = headers.copy()
106 headers['Content-Length'] = str(len(body))
108 headers['Content-MD5'] \
109 = base64.b64encode(hashlib.md5(body).digest())
110 add_auth_headers(headers, method, path)
112 # req = "%s %s HTTP/1.1\r\nHost: %s\r\n" % (method, path, host)
113 # req = req + ''.join("%s: %s\r\n" % h for h in headers.items()) + "\r\n"
116 self.conn.request(method, path, body, headers)
117 response = self.conn.getresponse()
118 print "Response:", response.status
119 print "Headers:", response.getheaders()
120 body = response.read()
122 if __name__ == '__main__':
123 # generate_request("/?comp=list")
127 conn.make_request('/benchmark/file-1M-' + str(i), 'PUT', buf,
128 {'x-ms-blob-type': 'BlockBlob'})
132 conn.make_request('/benchmark/file-1M-' + str(i), 'GET')