gotime_aws 2.5.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,244 @@
1
+ module Aws
2
+
3
+
4
+ # This is the interface for Amazon CloudWatch.
5
+
6
+ class Mon < Aws::AwsBase
7
+ include Aws::AwsBaseInterface
8
+
9
+
10
+ #Amazon EC2 API version being used
11
+ API_VERSION = "2009-05-15"
12
+ DEFAULT_HOST = "monitoring.amazonaws.com"
13
+ DEFAULT_PATH = '/'
14
+ DEFAULT_PROTOCOL = 'https'
15
+ DEFAULT_PORT = 443
16
+
17
+ # Available measures for EC2 instances:
18
+ # NetworkIn NetworkOut DiskReadOps DiskWriteOps DiskReadBytes DiskWriteBytes CPUUtilization
19
+ measures =%w(NetworkIn NetworkOut DiskReadOps DiskWriteOps DiskReadBytes DiskWriteBytes CPUUtilization)
20
+
21
+
22
+ def self.connection_name
23
+ :mon_connection
24
+ end
25
+
26
+ @@bench = Aws::AwsBenchmarkingBlock.new
27
+ def self.bench
28
+ @@bench
29
+ end
30
+
31
+ def self.bench_xml
32
+ @@bench.xml
33
+ end
34
+
35
+ def self.bench_ec2
36
+ @@bench.service
37
+ end
38
+
39
+ # Current API version (sometimes we have to check it outside the GEM).
40
+ @@api = ENV['EC2_API_VERSION'] || API_VERSION
41
+
42
+ def self.api
43
+ @@api
44
+ end
45
+
46
+
47
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
48
+ init({:name => 'MON',
49
+ :default_host => ENV['MON_URL'] ? URI.parse(ENV['MON_URL']).host : DEFAULT_HOST,
50
+ :default_port => ENV['MON_URL'] ? URI.parse(ENV['MON_URL']).port : DEFAULT_PORT,
51
+ :default_service => ENV['MON_URL'] ? URI.parse(ENV['MON_URL']).path : DEFAULT_PATH,
52
+ :default_protocol => ENV['MON_URL'] ? URI.parse(ENV['MON_URL']).scheme : DEFAULT_PROTOCOL,
53
+ :api_version => API_VERSION},
54
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
55
+ aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
56
+ params)
57
+ end
58
+
59
+
60
+ def generate_request(action, params={})
61
+ service_hash = {"Action" => action,
62
+ "AWSAccessKeyId" => @aws_access_key_id,
63
+ "Version" => @@api}
64
+ service_hash.update(params)
65
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], @params[:service])
66
+
67
+ # use POST method if the length of the query string is too large
68
+ if service_params.size > 2000
69
+ if signature_version == '2'
70
+ # resign the request because HTTP verb is included into signature
71
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], @params[:service])
72
+ end
73
+ request = Net::HTTP::Post.new(service)
74
+ request.body = service_params
75
+ request['Content-Type'] = 'application/x-www-form-urlencoded'
76
+ else
77
+ request = Net::HTTP::Get.new("#{@params[:service]}?#{service_params}")
78
+ end
79
+
80
+ #puts "\n\n --------------- QUERY REQUEST TO AWS -------------- \n\n"
81
+ #puts "#{@params[:service]}?#{service_params}\n\n"
82
+
83
+ # prepare output hash
84
+ {:request => request,
85
+ :server => @params[:server],
86
+ :port => @params[:port],
87
+ :protocol => @params[:protocol]}
88
+ end
89
+
90
+
91
+ # Sends request to Amazon and parses the response
92
+ # Raises AwsError if any banana happened
93
+ # todo: remove this and switch to using request_info2
94
+ def request_info(request, parser, options={})
95
+ conn = get_conn(self.class.connection_name, @params, @logger)
96
+ request_info_impl(conn, @@bench, request, parser, options)
97
+ end
98
+
99
+ #-----------------------------------------------------------------
100
+ # REQUESTS
101
+ #-----------------------------------------------------------------
102
+
103
+ def list_metrics(options={})
104
+
105
+ next_token = options[:next_token] || nil
106
+
107
+ params = {}
108
+ params['NextToken'] = next_token unless next_token.nil?
109
+
110
+ @logger.info("list Metrics ")
111
+
112
+ link = generate_request("ListMetrics", params)
113
+ resp = request_info(link, QMonListMetrics.new(:logger => @logger))
114
+
115
+ rescue Exception
116
+ on_exception
117
+ end
118
+
119
+
120
+ # measureName: CPUUtilization (Units: Percent), NetworkIn (Units: Bytes), NetworkOut (Units: Bytes), DiskWriteOps (Units: Count)
121
+ # DiskReadBytes (Units: Bytes), DiskReadOps (Units: Count), DiskWriteBytes (Units: Bytes)
122
+ # stats: array containing one or more of Minimum, Maximum, Sum, Average, Samples
123
+ # start_time : Timestamp to start
124
+ # end_time: Timestamp to end
125
+ # unit: Either Seconds, Percent, Bytes, Bits, Count, Bytes, Bits/Second, Count/Second, and None
126
+ #
127
+ # Optional parameters:
128
+ # period: Integer 60 or multiple of 60
129
+ # dimensions: Hash containing keys ImageId, AutoScalingGroupName, InstanceId, InstanceType
130
+ # customUnit: nil. not supported currently.
131
+ # namespace: AWS/EC2
132
+
133
+ def get_metric_statistics (measure_name, stats, start_time, end_time, unit, options={})
134
+
135
+ period = options[:period] || 60
136
+ dimensions = options[:dimensions] || nil
137
+ custom_unit = options[:custom_unit] || nil
138
+ namespace = options[:namespace] || "AWS/EC2"
139
+
140
+ params = {}
141
+ params['MeasureName'] = measure_name
142
+ i =1
143
+ stats.each do |s|
144
+ params['Statistics.member.'+i.to_s] = s
145
+ i = i+1
146
+ end
147
+ params['Period'] = period
148
+ if (dimensions != nil)
149
+ i = 1
150
+ dimensions.each do |k, v|
151
+ params['Dimensions.member.'+i.to_s+".Name."+i.to_s] = k
152
+ params['Dimensions.member.'+i.to_s+".Value."+i.to_s] = v
153
+ i = i+1
154
+ end
155
+ end
156
+ params['StartTime'] = start_time
157
+ params['EndTime'] = end_time
158
+ params['Unit'] = unit
159
+ #params['CustomUnit'] = customUnit always nil
160
+ params['Namespace'] = namespace
161
+
162
+ link = generate_request("GetMetricStatistics", params)
163
+ resp = request_info(link, QMonGetMetricStatistics.new(:logger => @logger))
164
+
165
+ rescue Exception
166
+ on_exception
167
+ end
168
+
169
+
170
+ #-----------------------------------------------------------------
171
+ # PARSERS: Instances
172
+ #-----------------------------------------------------------------
173
+
174
+
175
+ class QMonGetMetricStatistics < Aws::AwsParser
176
+
177
+ def reset
178
+ @result = []
179
+ end
180
+
181
+ def tagstart(name, attributes)
182
+ @metric = {} if name == 'member'
183
+ end
184
+
185
+ def tagend(name)
186
+ case name
187
+ when 'Timestamp' then
188
+ @metric[:timestamp] = @text
189
+ when 'Samples' then
190
+ @metric[:samples] = @text
191
+ when 'Unit' then
192
+ @metric[:unit] = @text
193
+ when 'Average' then
194
+ @metric[:average] = @text
195
+ when 'Minimum' then
196
+ @metric[:minimum] = @text
197
+ when 'Maximum' then
198
+ @metric[:maximum] = @text
199
+ when 'Sum' then
200
+ @metric[:sum] = @text
201
+ when 'Value' then
202
+ @metric[:value] = @text
203
+ when 'member' then
204
+ @result << @metric
205
+ end
206
+ end
207
+ end
208
+
209
+ class QMonListMetrics < Aws::AwsParser
210
+
211
+ def reset
212
+ @result = []
213
+ @namespace = ""
214
+ @measure_name = ""
215
+ end
216
+
217
+ def tagstart(name, attributes)
218
+ @metric = {} if name == 'member'
219
+ end
220
+
221
+ def tagend(name)
222
+ case name
223
+ when 'MeasureName' then
224
+ @measure_name = @text
225
+ when 'Namespace' then
226
+ @namespace = @text
227
+ when 'Name' then
228
+ @metric[:name] = @text
229
+ when 'Value' then
230
+ @metric[:value] = @text
231
+ when 'member' then
232
+ @metric[:namespace] = @namespace
233
+ @metric[:measure_name] = @measure_name
234
+ @result << @metric
235
+ end
236
+ end
237
+ end
238
+
239
+
240
+ end
241
+
242
+
243
+ end
244
+
@@ -0,0 +1,366 @@
1
+ module Aws
2
+
3
+ require 'xmlsimple'
4
+
5
+ class Elb < AwsBase
6
+
7
+ include AwsBaseInterface
8
+
9
+
10
+ #Amazon ELB API version being used
11
+ API_VERSION = "2009-05-15"
12
+ DEFAULT_HOST = "elasticloadbalancing.amazonaws.com"
13
+ DEFAULT_PATH = '/'
14
+ DEFAULT_PROTOCOL = 'https'
15
+ DEFAULT_PORT = 443
16
+
17
+ def self.connection_name
18
+ :elb_connection
19
+ end
20
+
21
+ @@bench = AwsBenchmarkingBlock.new
22
+
23
+ def self.bench
24
+ @@bench
25
+ end
26
+
27
+ def self.bench_xml
28
+ @@bench.xml
29
+ end
30
+
31
+ def self.bench_ec2
32
+ @@bench.service
33
+ end
34
+
35
+ # Current API version (sometimes we have to check it outside the GEM).
36
+ @@api = ENV['ELB_API_VERSION'] || API_VERSION
37
+
38
+ def self.api
39
+ @@api
40
+ end
41
+
42
+
43
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
44
+ init({:name => 'ELB',
45
+ :default_host => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).host : DEFAULT_HOST,
46
+ :default_port => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).port : DEFAULT_PORT,
47
+ :default_service => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).path : DEFAULT_PATH,
48
+ :default_protocol => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).scheme : DEFAULT_PROTOCOL,
49
+ :api_version => API_VERSION},
50
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
51
+ aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
52
+ params)
53
+ end
54
+
55
+
56
+ # Sends request to Amazon and parses the response
57
+ # Raises AwsError if any banana happened
58
+ def request_info(request, parser, options={})
59
+ request_info2(request, parser, @params, self.class.connection_name, @logger, @@bench, options)
60
+ end
61
+
62
+ # todo: convert to xml-simple version and get rid of parser below
63
+ def do_request(action, params, options={})
64
+ link = generate_request(action, params)
65
+ resp = request_info_xml_simple(self.class.connection_name, @params, link, @logger,
66
+ :group_tags =>{"LoadBalancersDescriptions"=>"LoadBalancersDescription",
67
+ "DBParameterGroups" =>"DBParameterGroup",
68
+ "DBSecurityGroups" =>"DBSecurityGroup",
69
+ "EC2SecurityGroups" =>"EC2SecurityGroup",
70
+ "IPRanges" =>"IPRange"},
71
+ :force_array =>["DBInstances",
72
+ "DBParameterGroups",
73
+ "DBSecurityGroups",
74
+ "EC2SecurityGroups",
75
+ "IPRanges"],
76
+ :pull_out_array =>options[:pull_out_array],
77
+ :pull_out_single=>options[:pull_out_single],
78
+ :wrapper =>options[:wrapper])
79
+ end
80
+
81
+
82
+ #-----------------------------------------------------------------
83
+ # REQUESTS
84
+ #-----------------------------------------------------------------
85
+
86
+ #
87
+ # name: name of load balancer
88
+ # availability_zones: array of zones
89
+ # listeners: array of hashes containing :load_balancer_port, :instance_port, :protocol
90
+ # eg: {:load_balancer_port=>80, :instance_port=>8080, :protocol=>"HTTP"}
91
+ def create_load_balancer(name, availability_zones, listeners)
92
+ params = hash_params('AvailabilityZones.member', availability_zones)
93
+ i = 1
94
+ listeners.each do |l|
95
+ params["Listeners.member.#{i}.Protocol"] = "#{l[:protocol]}"
96
+ params["Listeners.member.#{i}.LoadBalancerPort"] = "#{l[:load_balancer_port]}"
97
+ params["Listeners.member.#{i}.InstancePort"] = "#{l[:instance_port]}"
98
+ i += 1
99
+ end
100
+ params['LoadBalancerName'] = name
101
+
102
+ @logger.info("Creating LoadBalancer called #{params['LoadBalancerName']}")
103
+
104
+ link = generate_request("CreateLoadBalancer", params)
105
+ resp = request_info(link, QElbCreateParser.new(:logger => @logger))
106
+
107
+ rescue Exception
108
+ on_exception
109
+ end
110
+
111
+
112
+ # name: name of load balancer
113
+ # instance_ids: array of instance_id's to add to load balancer
114
+ def register_instances_with_load_balancer(name, instance_ids)
115
+ params = {}
116
+ params['LoadBalancerName'] = name
117
+
118
+ i = 1
119
+ instance_ids.each do |l|
120
+ params["Instances.member.#{i}.InstanceId"] = "#{l}"
121
+ i += 1
122
+ end
123
+
124
+ @logger.info("Registering Instances #{instance_ids.join(',')} with Load Balancer '#{name}'")
125
+
126
+ link = generate_request("RegisterInstancesWithLoadBalancer", params)
127
+ resp = request_info(link, QElbRegisterInstancesParser.new(:logger => @logger))
128
+
129
+ rescue Exception
130
+ on_exception
131
+ end
132
+
133
+ def deregister_instances_from_load_balancer(name, instance_ids)
134
+ params = {}
135
+ params['LoadBalancerName'] = name
136
+
137
+ i = 1
138
+ instance_ids.each do |l|
139
+ params["Instances.member.#{i}.InstanceId"] = "#{l}"
140
+ i += 1
141
+ end
142
+
143
+ @logger.info("Deregistering Instances #{instance_ids.join(',')} from Load Balancer '#{name}'")
144
+
145
+ link = generate_request("DeregisterInstancesFromLoadBalancer", params) # Same response as register I believe
146
+ resp = request_info(link, QElbRegisterInstancesParser.new(:logger => @logger))
147
+
148
+ rescue Exception
149
+ on_exception
150
+ end
151
+
152
+
153
+ def describe_load_balancers(lparams={})
154
+ @logger.info("Describing Load Balancers")
155
+
156
+ params = {}
157
+ params.update(hash_params('LoadBalancerNames.member', lparams[:names])) if lparams[:names]
158
+
159
+ link = generate_request("DescribeLoadBalancers", params)
160
+
161
+ resp = request_info(link, QElbDescribeLoadBalancersParser.new(:logger => @logger))
162
+
163
+ rescue Exception
164
+ on_exception
165
+ end
166
+
167
+
168
+ def describe_instance_health(name, instance_ids=[])
169
+ instance_ids = [instance_ids] if instance_ids.is_a?(String)
170
+ # @logger.info("Describing Instance Health")
171
+ params = {}
172
+ params['LoadBalancerName'] = name
173
+
174
+ i = 1
175
+ instance_ids.each do |l|
176
+ params["Instances.member.#{i}.InstanceId"] = "#{l}"
177
+ i += 1
178
+ end
179
+
180
+ @logger.info("Describing Instances Health #{instance_ids.join(',')} with Load Balancer '#{name}'")
181
+
182
+ link = generate_request("DescribeInstanceHealth", params)
183
+ resp = request_info(link, QElbDescribeInstancesHealthParser.new(:logger => @logger))
184
+
185
+
186
+ rescue Exception
187
+ on_exception
188
+ end
189
+
190
+
191
+ def delete_load_balancer(name)
192
+ @logger.info("Deleting Load Balancer - " + name.to_s)
193
+
194
+ params = {}
195
+ params['LoadBalancerName'] = name
196
+
197
+ link = generate_request("DeleteLoadBalancer", params)
198
+
199
+ resp = request_info(link, QElbDeleteParser.new(:logger => @logger))
200
+
201
+ rescue Exception
202
+ on_exception
203
+ end
204
+
205
+
206
+ #-----------------------------------------------------------------
207
+ # PARSERS: Instances
208
+ #-----------------------------------------------------------------
209
+
210
+
211
+ class QElbCreateParser < AwsParser
212
+
213
+ def reset
214
+ @result = {}
215
+ end
216
+
217
+
218
+ def tagend(name)
219
+ case name
220
+ when 'DNSName' then
221
+ @result[:dns_name] = @text
222
+ end
223
+ end
224
+ end
225
+
226
+ class QElbDescribeLoadBalancersParser < AwsParser
227
+
228
+ def reset
229
+ @result = []
230
+ end
231
+
232
+ def tagstart(name, attributes)
233
+ # puts 'tagstart ' + name + ' -- ' + @xmlpath
234
+ if (name == 'member' && @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/Listeners')
235
+ @listener = {}
236
+ end
237
+ if (name == 'member' && @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/AvailabilityZones')
238
+ @availability_zone = {}
239
+ end
240
+ if (name == 'member' && @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/Instances')
241
+ @instance = {}
242
+ end
243
+ if (name == 'member' && @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions')
244
+ @member = {:listeners=>[], :availability_zones=>[], :health_check=>{}, :instances=>[]}
245
+ end
246
+
247
+ end
248
+
249
+
250
+ def tagend(name)
251
+ case name
252
+ when 'LoadBalancerName' then
253
+ @member[:load_balancer_name] = @text
254
+ @member[:name] = @text
255
+ when 'CreatedTime' then
256
+ @member[:created_time] = Time.parse(@text)
257
+ @member[:created] = @member[:created_time]
258
+ when 'DNSName' then
259
+ @member[:dns_name] = @text
260
+ # Instances
261
+ when 'InstanceId' then
262
+ @instance[:instance_id] = @text
263
+ # Listeners
264
+ when 'Protocol' then
265
+ @listener[:protocol] = @text
266
+ when 'LoadBalancerPort' then
267
+ @listener[:load_balancer_port] = @text.to_i
268
+ when 'InstancePort' then
269
+ @listener[:instance_port] = @text.to_i
270
+ # HEALTH CHECK STUFF
271
+ when 'Interval' then
272
+ @member[:health_check][:interval] = @text.to_i
273
+ when 'Target' then
274
+ @member[:health_check][:target] = @text
275
+ when 'HealthyThreshold' then
276
+ @member[:health_check][:healthy_threshold] = @text.to_i
277
+ when 'Timeout' then
278
+ @member[:health_check][:timeout] = @text.to_i
279
+ when 'UnhealthyThreshold' then
280
+ @member[:health_check][:unhealthy_threshold] = @text.to_i
281
+ # AvailabilityZones
282
+ when 'member' then
283
+ if @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/Listeners'
284
+ @member[:listeners] << @listener
285
+ elsif @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/AvailabilityZones'
286
+ @availability_zone = @text
287
+ @member[:availability_zones] << @availability_zone
288
+ elsif @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions/member/Instances'
289
+ @member[:instances] << @instance
290
+ elsif @xmlpath == 'DescribeLoadBalancersResponse/DescribeLoadBalancersResult/LoadBalancerDescriptions'
291
+ @result << @member
292
+ end
293
+
294
+ end
295
+ end
296
+ end
297
+
298
+ class QElbRegisterInstancesParser < AwsParser
299
+
300
+ def reset
301
+ @result = []
302
+ end
303
+
304
+ def tagstart(name, attributes)
305
+ # puts 'tagstart ' + name + ' -- ' + @xmlpath
306
+ if (name == 'member' &&
307
+ (@xmlpath == 'RegisterInstancesWithLoadBalancerResponse/RegisterInstancesWithLoadBalancerResult/Instances' ||
308
+ @xmlpath == 'DeregisterInstancesFromLoadBalancerResponse/DeregisterInstancesFromLoadBalancerResult/Instances')
309
+ )
310
+ @member = {}
311
+ end
312
+
313
+ end
314
+
315
+ def tagend(name)
316
+ case name
317
+ when 'InstanceId' then
318
+ @member[:instance_id] = @text
319
+ when 'member' then
320
+ @result << @member
321
+ end
322
+ end
323
+ #
324
+ end
325
+
326
+ class QElbDescribeInstancesHealthParser < AwsParser
327
+
328
+ def reset
329
+ @result = []
330
+ end
331
+
332
+ def tagstart(name, attributes)
333
+ # puts 'tagstart ' + name + ' -- ' + @xmlpath
334
+ if (name == 'member' && @xmlpath == 'DescribeInstanceHealthResponse/DescribeInstanceHealthResult/InstanceStates')
335
+ @member = {}
336
+ end
337
+ end
338
+
339
+ def tagend(name)
340
+ case name
341
+ when 'Description' then
342
+ @member[:description] = @text
343
+ when 'State' then
344
+ @member[:state] = @text
345
+ when 'InstanceId' then
346
+ @member[:instance_id] = @text
347
+ when 'ReasonCode' then
348
+ @member[:reason_code] = @text
349
+ when 'member' then
350
+ @result << @member
351
+ end
352
+ end
353
+ #
354
+ end
355
+
356
+ class QElbDeleteParser < AwsParser
357
+ def reset
358
+ @result = true
359
+ end
360
+ end
361
+
362
+
363
+ end
364
+
365
+
366
+ end
data/lib/gotime_aws.rb ADDED
@@ -0,0 +1,33 @@
1
+
2
+ require 'benchmark'
3
+ require 'net/https'
4
+ require 'uri'
5
+ require 'time'
6
+ require "cgi"
7
+ require "base64"
8
+ require "rexml/document"
9
+ require "openssl"
10
+ require "digest/sha1"
11
+
12
+ require 'rubygems'
13
+ require 'right_http_connection'
14
+
15
+ $:.unshift(File.dirname(__FILE__))
16
+ require 'awsbase/require_relative'
17
+ require 'awsbase/benchmark_fix'
18
+ require 'awsbase/awsbase'
19
+ require 'awsbase/aws_response_array'
20
+ require 'ec2/ec2'
21
+ require 'ec2/mon_interface'
22
+ require 's3/s3_interface'
23
+ require 's3/s3'
24
+ require 'sqs/sqs_interface'
25
+ require 'sqs/sqs'
26
+ require 'sdb/sdb_interface'
27
+ require 'acf/acf_interface'
28
+ require 'elb/elb_interface'
29
+ require 'rds/rds'
30
+ require 'iam/iam'
31
+ require 'ses/ses'
32
+
33
+