internuity-awsum 0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/parser.rb ADDED
@@ -0,0 +1,18 @@
1
+ require 'rexml/document'
2
+
3
+ module Awsum
4
+ class Parser #:nodoc:
5
+ def parse(xml_text)
6
+ REXML::Document.parse_stream(xml_text, self)
7
+ result
8
+ end
9
+
10
+ #--
11
+ #Methods to be overridden by each Parser implementation
12
+ def result ; end
13
+ def tag_start(tag, attributes) ; end
14
+ def text(text) ; end
15
+ def tag_end(tag) ; end
16
+ def xmldecl(*args) ; end
17
+ end
18
+ end
@@ -0,0 +1,214 @@
1
+ require 'base64'
2
+ require 'cgi'
3
+ require 'digest/md5'
4
+ require 'error'
5
+ require 'openssl'
6
+ require 'time'
7
+ require 'uri'
8
+
9
+ require 'net/https'
10
+ require 'net_fix'
11
+
12
+ module Awsum
13
+ module Requestable #:nodoc:
14
+
15
+ private
16
+ # Sends a request with query parameters
17
+ #
18
+ # Used for EC2 requests
19
+ def send_query_request(params)
20
+ standard_options = {
21
+ 'AWSAccessKeyId' => @access_key,
22
+ 'Version' => API_VERSION,
23
+ 'Timestamp' => Time.now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z'),
24
+ 'SignatureVersion' => SIGNATURE_VERSION,
25
+ 'SignatureMethod' => 'HmacSHA256'
26
+ }
27
+ params = standard_options.merge(params)
28
+
29
+ #Put parameters into query string format
30
+ params_string = params.delete_if{|k,v| v.nil?}.sort{|a,b|
31
+ a[0].to_s <=> b[0].to_s
32
+ }.collect{|key, val|
33
+ "#{CGI::escape(key.to_s)}=#{CGI::escape(val.to_s)}"
34
+ }.join('&')
35
+ params_string.gsub!('+', '%20')
36
+
37
+ #Create request signature
38
+ signature_string = "GET\n#{host}\n/\n#{params_string}"
39
+ signature = sign(signature_string, 'sha256')
40
+
41
+ #Attach signature to query string
42
+ params_string << "&Signature=#{CGI::escape(signature)}"
43
+
44
+ url = "https://#{host}/?#{params_string}"
45
+ response = process_request('GET', url)
46
+ if response.is_a?(Net::HTTPSuccess)
47
+ response
48
+ else
49
+ raise Awsum::Error.new(response)
50
+ end
51
+ end
52
+
53
+ # Sends a full request including headers and possible post data
54
+ #
55
+ # Used for S3 requests
56
+ def send_s3_request(method = 'GET', options = {}, &block)
57
+ bucket = options[:bucket] || ''
58
+ key = options[:key] || ''
59
+ parameters = options[:parameters] || {}
60
+ data = options[:data]
61
+ headers = {}
62
+ (options[:headers] || {}).each { |k,v| headers[k.downcase] = v }
63
+
64
+ #Add the host header
65
+ host_name = "#{bucket}#{bucket.blank? ? '' : '.'}#{host}"
66
+ headers['host'] = host_name
67
+
68
+ # Ensure required headers are in place
69
+ if !data.nil? && headers['content-md5'].nil?
70
+ if data.respond_to?(:read)
71
+ if data.respond_to?(:rewind)
72
+ digest = Digest::MD5.new
73
+ while chunk = data.read(1024 * 1024)
74
+ digest << chunk
75
+ end
76
+ data.rewind
77
+
78
+ headers['content-md5'] = Base64::encode64(digest.digest).gsub(/\n/, '')
79
+ end
80
+ else
81
+ headers['content-md5'] = Base64::encode64(Digest::MD5.digest(data)).gsub(/\n/, '')
82
+ end
83
+ end
84
+ if !data.nil? && headers['content-length'].nil?
85
+ headers['content-length'] = (data.respond_to?(:lstat) ? data.lstat.size : data.size).to_s
86
+ end
87
+ headers['date'] = Time.now.rfc822 if headers['date'].nil?
88
+ headers['content-type'] ||= ''
89
+ if !data.nil?
90
+ headers['expect'] = '100-continue'
91
+ end
92
+
93
+ signature_string = generate_rest_signature_string(method, bucket, key, parameters, headers)
94
+ puts "signature_string: \n#{signature_string}\n\n" if ENV['DEBUG']
95
+
96
+ signature = sign(signature_string)
97
+
98
+ headers['authorization'] = "AWS #{@access_key}:#{signature}"
99
+
100
+ url = "https://#{host_name}#{key[0..0] == '/' ? '' : '/'}#{key}#{parameters.size == 0 ? '' : "?#{parameters.collect{|k,v| v.nil? ? k.to_s : "#{CGI::escape(k.to_s)}=#{CGI::escape(v.to_s)}"}.join('&')}"}"
101
+
102
+ process_request(method, url, headers, data) do |response|
103
+ if response.is_a?(Net::HTTPSuccess)
104
+ if block_given?
105
+ block.call(response)
106
+ else
107
+ response
108
+ end
109
+ else
110
+ raise Awsum::Error.new(response)
111
+ end
112
+ end
113
+ end
114
+
115
+ def generate_rest_signature_string(method, bucket, key, parameters, headers)
116
+ canonicalized_amz_headers = headers.sort{|a,b| a[0].to_s.downcase <=> b[0].to_s.downcase }.collect{|k, v| "#{k.to_s.downcase}:#{(v.is_a?(Array) ? v.join(',') : v).gsub(/\n/, ' ')}" if k =~ /\Ax-amz-/i }.compact.join("\n")
117
+ canonicalized_resource = "#{bucket.blank? ? '' : '/'}#{bucket}#{key[0..0] == '/' ? '' : '/'}#{key}"
118
+ ['acl', 'torrent', 'logging', 'location'].each do |sub_resource|
119
+ if parameters.has_key?(sub_resource)
120
+ canonicalized_resource << "?#{sub_resource}"
121
+ break
122
+ end
123
+ end
124
+
125
+ signature_string = "#{method}\n#{headers['content-md5']}\n#{headers['content-type']}\n#{headers['x-amz-date'].nil? ? headers['date'] : ''}\n#{canonicalized_amz_headers}#{canonicalized_amz_headers.blank? ? '' : "\n"}#{canonicalized_resource}"
126
+ end
127
+
128
+ def generate_s3_signed_request_url(method, bucket, key, expires = nil)
129
+ signature_string = generate_rest_signature_string(method, bucket, key, {}, {'date' => expires})
130
+ signature = sign(signature_string)
131
+ "http://#{bucket}#{bucket.blank? ? '' : '.'}#{host}#{key[0..0] == '/' ? '' : '/'}#{key}?AWSAccessKeyId=#{@access_key}&Signature=#{CGI::escape(signature)}&Expires=#{expires}"
132
+ end
133
+
134
+ def process_request(method, url, headers = {}, data = nil, &block)
135
+ #TODO: Allow secure/non-secure
136
+ uri = URI.parse(url)
137
+ uri.scheme = 'https'
138
+ uri.port = 443
139
+
140
+ #puts uri.to_s
141
+
142
+ Net::HTTP.version_1_1
143
+ con = Net::HTTP.new(uri.host, uri.port)
144
+ con.use_ssl = true
145
+ con.verify_mode = OpenSSL::SSL::VERIFY_NONE
146
+ con.start do |http|
147
+ case method.upcase
148
+ when 'GET'
149
+ request = Net::HTTP::Get.new("#{uri.path}#{"?#{uri.query}" if uri.query}")
150
+ when 'POST'
151
+ request = Net::HTTP::Post.new("#{uri.path}#{"?#{uri.query}" if uri.query}")
152
+ when 'PUT'
153
+ request = Net::HTTP::Put.new("#{uri.path}#{"?#{uri.query}" if uri.query}")
154
+ when 'DELETE'
155
+ request = Net::HTTP::Delete.new("#{uri.path}#{"?#{uri.query}" if uri.query}")
156
+ when 'HEAD'
157
+ request = Net::HTTP::Head.new("#{uri.path}#{"?#{uri.query}" if uri.query}")
158
+ end
159
+ request.initialize_http_header(headers)
160
+
161
+ unless data.nil?
162
+ if data.respond_to?(:read)
163
+ request.body_stream = data
164
+ else
165
+ request.body = data
166
+ end
167
+ end
168
+
169
+ if block_given?
170
+ http.request(request) do |response|
171
+ handle_response response, &block
172
+ end
173
+ else
174
+ response = http.request(request)
175
+ handle_response response
176
+ end
177
+ end
178
+ end
179
+
180
+ def handle_response(response, &block)
181
+ case response
182
+ when Net::HTTPSuccess
183
+ if block_given?
184
+ block.call(response)
185
+ else
186
+ response
187
+ end
188
+ when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPTemporaryRedirect
189
+ new_uri = URI.parse(response['location'])
190
+ uri.host = new_uri.host
191
+ uri.path = "#{new_uri.path}#{uri.path unless uri.path = '/'}"
192
+ process_request(method, uri.to_s, headers, data, &block)
193
+ end
194
+ end
195
+
196
+ # Converts an array of paramters into <param_name>.<num> format
197
+ def array_to_params(arr, param_name)
198
+ arr = [arr] unless arr.is_a?(Array)
199
+ params = {}
200
+ arr.each_with_index do |value,i|
201
+ params["#{param_name}.#{i+1}"] = value
202
+ end
203
+ params
204
+ end
205
+
206
+ # Sign a string with a digest, wrap in HMAC digest and base64 encode
207
+ #
208
+ # ===Returns
209
+ # base64 encoded string with newlines removed
210
+ def sign(string, digest = 'sha1')
211
+ Base64::encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new(digest), @secret_key, string)).gsub(/\n/, '')
212
+ end
213
+ end
214
+ end
data/lib/support.rb ADDED
@@ -0,0 +1,94 @@
1
+ # Thanks to RightAws for this idea!
2
+ #
3
+ # If ActiveSupport is loaded, then great - use it. But we don't
4
+ # want a dependency on it, so if it's not present, define the few
5
+ # extensions that we want to use...
6
+ unless defined? ActiveSupport::CoreExtensions
7
+ # These are ActiveSupport-;like extensions to do a few handy things in the gems
8
+ # Derived from ActiveSupport, so the ActiveSupport copyright notice applies:
9
+ #
10
+ #
11
+ #
12
+ # Copyright (c) 2005 David Heinemeier Hansson
13
+ #
14
+ # Permission is hereby granted, free of charge, to any person obtaining
15
+ # a copy of this software and associated documentation files (the
16
+ # "Software"), to deal in the Software without restriction, including
17
+ # without limitation the rights to use, copy, modify, merge, publish,
18
+ # distribute, sublicense, and/or sell copies of the Software, and to
19
+ # permit persons to whom the Software is furnished to do so, subject to
20
+ # the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be
23
+ # included in all copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32
+ #++
33
+ #
34
+ #
35
+
36
+ class Object #:nodoc:
37
+ # "", " ", nil, [], and {} are blank
38
+ def blank?
39
+ if respond_to?(:empty?) && respond_to?(:strip)
40
+ empty? or strip.empty?
41
+ elsif respond_to?(:empty?)
42
+ empty?
43
+ else
44
+ !self
45
+ end
46
+ end
47
+ end
48
+
49
+ class NilClass #:nodoc:
50
+ def blank?
51
+ true
52
+ end
53
+ end
54
+
55
+ class FalseClass #:nodoc:
56
+ def blank?
57
+ true
58
+ end
59
+ end
60
+
61
+ class TrueClass #:nodoc:
62
+ def blank?
63
+ false
64
+ end
65
+ end
66
+
67
+ class Array #:nodoc:
68
+ alias_method :blank?, :empty?
69
+ end
70
+
71
+ class Hash #:nodoc:
72
+ alias_method :blank?, :empty?
73
+
74
+ # Return a new hash with all keys converted to symbols.
75
+ def symbolize_keys
76
+ inject({}) do |options, (key, value)|
77
+ options[key.to_sym] = value
78
+ options
79
+ end
80
+ end
81
+ end
82
+
83
+ class String #:nodoc:
84
+ def blank?
85
+ empty? || strip.empty?
86
+ end
87
+ end
88
+
89
+ class Numeric #:nodoc:
90
+ def blank?
91
+ false
92
+ end
93
+ end
94
+ end
data/test/dump.rb ADDED
@@ -0,0 +1,42 @@
1
+ require 'rubygems'
2
+
3
+ ROOT = File.join(File.dirname(__FILE__), '..')
4
+
5
+ $LOAD_PATH << File.join(ROOT, 'lib')
6
+ $LOAD_PATH << File.join(ROOT, 'lib', 'awsum')
7
+ require File.join(ROOT, 'lib', 'awsum.rb')
8
+
9
+ #Dumps the raw result of a call to the Awsum library
10
+ # Usage ruby dump.rb -a <access key> -s <secret key> -c <command to call>
11
+ #
12
+ # Awsum::Ec2 is available as ec2
13
+ # Awsum::S3 is available as s3
14
+ #
15
+ # Exampe
16
+ # ruby dump.rb -a ABC -s XYZ -c "ec2.images"
17
+
18
+ #Parse command line
19
+ access_key = nil
20
+ secret_key = nil
21
+ command = nil
22
+ ARGV.each_with_index do |arg, i|
23
+ case arg
24
+ when '-a'
25
+ access_key = ARGV[i+1]
26
+ when '-s'
27
+ secret_key = ARGV[i+1]
28
+ when '-c'
29
+ command = ARGV[i+1]
30
+ end
31
+ end
32
+
33
+ ENV['DEBUG'] = 'true'
34
+
35
+ ec2 = Awsum::Ec2.new(access_key, secret_key)
36
+ s3 = Awsum::S3.new(access_key, secret_key)
37
+ begin
38
+ result = eval(command)
39
+ puts result.inspect
40
+ rescue Awsum::Error => e
41
+ puts "ERROR: #{e.inspect}"
42
+ end
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0"?>
2
+ <AttachVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>3756a0c0-aa24-468d-9bd1-bfe2e54dd4cc</requestId>
4
+ <volumeId>vol-44d6322d</volumeId>
5
+ <instanceId>i-3f1cc856</instanceId>
6
+ <device>/dev/sdb</device>
7
+ <status>attaching</status>
8
+ <attachTime>2009-01-14T04:34:35.000Z</attachTime>
9
+ </AttachVolumeResponse>
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0"?>
2
+ <DescribeVolumesResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>f4786b8a-90e8-4570-a786-1076fba0eeae</requestId>
4
+ <volumeSet>
5
+ <item>
6
+ <volumeId>vol-44d6322d</volumeId>
7
+ <size>10</size>
8
+ <snapshotId/>
9
+ <availabilityZone>us-east-1b</availabilityZone>
10
+ <status>available</status>
11
+ <createTime>2009-01-14T03:57:08.000Z</createTime>
12
+ </item>
13
+ </volumeSet>
14
+ </DescribeVolumesResponse>
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0"?>
2
+ <CreateSnapshotResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>0c4677f0-5490-45bc-975a-3f2d4d8d499d</requestId>
4
+ <snapshotId>snap-747c911d</snapshotId>
5
+ <volumeId>vol-79d13510</volumeId>
6
+ <status>pending</status>
7
+ <startTime>2009-01-15T03:59:26.000Z</startTime>
8
+ <progress/>
9
+ </CreateSnapshotResponse>
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0"?>
2
+ <CreateVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>802160fa-0789-4441-9132-78d83702c3be</requestId>
4
+ <volumeId>vol-44d6322d</volumeId>
5
+ <size>10</size>
6
+ <snapshotId/>
7
+ <availabilityZone>us-east-1b</availabilityZone>
8
+ <status>creating</status>
9
+ <createTime>2009-01-14T03:57:08.000Z</createTime>
10
+ </CreateVolumeResponse>
@@ -0,0 +1,5 @@
1
+ <?xml version="1.0"?>
2
+ <DeleteSnapshotResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>0946c702-0474-428f-814b-3d5601ce53e4</requestId>
4
+ <return>true</return>
5
+ </DeleteSnapshotResponse>
@@ -0,0 +1,5 @@
1
+ <?xml version="1.0"?>
2
+ <DeleteVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>c12b4410-20f9-4ae0-bc70-73e252b687cf</requestId>
4
+ <return>true</return>
5
+ </DeleteVolumeResponse>
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0"?>
2
+ <DetachVolumeResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3
+ <requestId>7bd88374-377d-4954-8084-f0cd1ab8c873</requestId>
4
+ <volumeId>vol-44d6322d</volumeId>
5
+ <instanceId>i-3f1cc856</instanceId>
6
+ <device>/dev/sdb</device>
7
+ <status>detaching</status>
8
+ <attachTime>2009-01-15T03:28:05.000Z</attachTime>
9
+ </DetachVolumeResponse>