Add proper per-file copyright notices/licenses and top-level license.
[bluesky.git] / cloudbench / azure.py
1 #!/usr/bin/python2.6
2 #
3 # Copyright (C) 2010  The Regents of the University of California
4 # Written by Michael Vrable <mvrable@cs.ucsd.edu>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
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.
17 #
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
28 # SUCH DAMAGE.
29
30 """A simple test API for accessing Windows Azure blob storage.
31
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
34 proof-of-concept."""
35
36 import base64, hashlib, hmac, httplib, os, time
37
38 # The version of the Azure API we implement; sent in the x-ms-version header.
39 API_VERSION = '2009-09-19'
40
41 def uri_decode(s):
42     # TODO
43     return s
44
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',
49                     'Range']
50
51     if not headers.has_key('Date'):
52         headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
53                                         time.gmtime())
54     if not headers.has_key('x-ms-version'):
55         headers['x-ms-version'] = API_VERSION
56
57     StringToSign = method + "\n"
58     for h in header_order:
59         if h in headers:
60             StringToSign += headers[h] + "\n"
61         else:
62             StringToSign += "\n"
63
64     # Add Canonicalized Headers
65     canonized = []
66     for (k, v) in headers.items():
67         k = k.lower()
68         if k.startswith('x-ms-'):
69             canonized.append((k, v))
70     canonized.sort()
71     for (k, v) in canonized:
72         StringToSign += "%s:%s\n" % (k, v)
73
74     # Add CanonicalizedHeaders Resource
75     account_name = os.environ['AZURE_ACCOUNT_NAME']
76     account_name = 'bluesky'
77     resource = "/" + account_name
78     if '?' not in path:
79         resource += path
80     else:
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)
84         resource += path
85         for k in sorted(params):
86             resource += "\n%s:%s" % (k, params[k])
87     StringToSign += resource
88
89     # print "String to sign:", repr(StringToSign)
90
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)
95
96     signature = base64.b64encode(h.digest())
97     headers['Authorization'] = "SharedKey %s:%s" % (account_name, signature)
98
99 class Connection:
100     def __init__(self):
101         self.host = os.environ['AZURE_ACCOUNT_NAME'] + ".blob.core.windows.net"
102         self.conn = httplib.HTTPConnection(self.host)
103
104     def make_request(self, path, method='GET', body="", headers={}):
105         headers = headers.copy()
106         headers['Content-Length'] = str(len(body))
107         if len(body) > 0:
108             headers['Content-MD5'] \
109                 = base64.b64encode(hashlib.md5(body).digest())
110         add_auth_headers(headers, method, path)
111
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"
114         # print req
115
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()
121
122 if __name__ == '__main__':
123     # generate_request("/?comp=list")
124     buf = 'A' * 1048576
125     conn = Connection()
126     for i in range(16):
127         conn.make_request('/benchmark/file-1M-' + str(i), 'PUT', buf,
128                           {'x-ms-blob-type': 'BlockBlob'})
129
130     conn = Connection()
131     for i in range(16):
132         conn.make_request('/benchmark/file-1M-' + str(i), 'GET')