Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(186)

Side by Side Diff: third_party/gsutil/boto/ec2/cloudwatch/__init__.py

Issue 12042069: Scripts to download files from google storage based on sha1 sums (Closed) Base URL: https://chromium.googlesource.com/chromium/tools/depot_tools.git@master
Patch Set: Removed gsutil/tests and gsutil/docs Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright (c) 2006-2011 Mitch Garnaat http://garnaat.org/
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the
5 # "Software"), to deal in the Software without restriction, including
6 # without limitation the rights to use, copy, modify, merge, publish, dis-
7 # tribute, sublicense, and/or sell copies of the Software, and to permit
8 # persons to whom the Software is furnished to do so, subject to the fol-
9 # lowing conditions:
10 #
11 # The above copyright notice and this permission notice shall be included
12 # in all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16 # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17 # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 # IN THE SOFTWARE.
21 #
22 """
23 This module provides an interface to the Elastic Compute Cloud (EC2)
24 CloudWatch service from AWS.
25 """
26 from boto.compat import json
27 from boto.connection import AWSQueryConnection
28 from boto.ec2.cloudwatch.metric import Metric
29 from boto.ec2.cloudwatch.alarm import MetricAlarm, MetricAlarms, AlarmHistoryIte m
30 from boto.ec2.cloudwatch.datapoint import Datapoint
31 from boto.regioninfo import RegionInfo
32 import boto
33
34 RegionData = {
35 'us-east-1': 'monitoring.us-east-1.amazonaws.com',
36 'us-west-1': 'monitoring.us-west-1.amazonaws.com',
37 'us-west-2': 'monitoring.us-west-2.amazonaws.com',
38 'sa-east-1': 'monitoring.sa-east-1.amazonaws.com',
39 'eu-west-1': 'monitoring.eu-west-1.amazonaws.com',
40 'ap-northeast-1': 'monitoring.ap-northeast-1.amazonaws.com',
41 'ap-southeast-1': 'monitoring.ap-southeast-1.amazonaws.com',
42 'ap-southeast-2': 'monitoring.ap-southeast-2.amazonaws.com',
43 }
44
45
46 def regions():
47 """
48 Get all available regions for the CloudWatch service.
49
50 :rtype: list
51 :return: A list of :class:`boto.RegionInfo` instances
52 """
53 regions = []
54 for region_name in RegionData:
55 region = RegionInfo(name=region_name,
56 endpoint=RegionData[region_name],
57 connection_cls=CloudWatchConnection)
58 regions.append(region)
59 return regions
60
61
62 def connect_to_region(region_name, **kw_params):
63 """
64 Given a valid region name, return a
65 :class:`boto.ec2.cloudwatch.CloudWatchConnection`.
66
67 :param str region_name: The name of the region to connect to.
68
69 :rtype: :class:`boto.ec2.CloudWatchConnection` or ``None``
70 :return: A connection to the given region, or None if an invalid region
71 name is given
72 """
73 for region in regions():
74 if region.name == region_name:
75 return region.connect(**kw_params)
76 return None
77
78
79 class CloudWatchConnection(AWSQueryConnection):
80
81 APIVersion = boto.config.get('Boto', 'cloudwatch_version', '2010-08-01')
82 DefaultRegionName = boto.config.get('Boto', 'cloudwatch_region_name',
83 'us-east-1')
84 DefaultRegionEndpoint = boto.config.get('Boto',
85 'cloudwatch_region_endpoint',
86 'monitoring.us-east-1.amazonaws.com' )
87
88 def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
89 is_secure=True, port=None, proxy=None, proxy_port=None,
90 proxy_user=None, proxy_pass=None, debug=0,
91 https_connection_factory=None, region=None, path='/',
92 security_token=None, validate_certs=True):
93 """
94 Init method to create a new connection to EC2 Monitoring Service.
95
96 B{Note:} The host argument is overridden by the host specified in the
97 boto configuration file.
98 """
99 if not region:
100 region = RegionInfo(self, self.DefaultRegionName,
101 self.DefaultRegionEndpoint)
102 self.region = region
103
104 # Ugly hack to get around both a bug in Python and a
105 # misconfigured SSL cert for the eu-west-1 endpoint
106 if self.region.name == 'eu-west-1':
107 validate_certs = False
108
109 AWSQueryConnection.__init__(self, aws_access_key_id,
110 aws_secret_access_key,
111 is_secure, port, proxy, proxy_port,
112 proxy_user, proxy_pass,
113 self.region.endpoint, debug,
114 https_connection_factory, path,
115 security_token,
116 validate_certs=validate_certs)
117
118 def _required_auth_capability(self):
119 return ['ec2']
120
121 def build_dimension_param(self, dimension, params):
122 prefix = 'Dimensions.member'
123 i = 0
124 for dim_name in dimension:
125 dim_value = dimension[dim_name]
126 if dim_value:
127 if isinstance(dim_value, basestring):
128 dim_value = [dim_value]
129 for value in dim_value:
130 params['%s.%d.Name' % (prefix, i+1)] = dim_name
131 params['%s.%d.Value' % (prefix, i+1)] = value
132 i += 1
133 else:
134 params['%s.%d.Name' % (prefix, i+1)] = dim_name
135 i += 1
136
137 def build_list_params(self, params, items, label):
138 if isinstance(items, basestring):
139 items = [items]
140 for index, item in enumerate(items):
141 i = index + 1
142 if isinstance(item, dict):
143 for k, v in item.iteritems():
144 params[label % (i, 'Name')] = k
145 if v is not None:
146 params[label % (i, 'Value')] = v
147 else:
148 params[label % i] = item
149
150 def build_put_params(self, params, name, value=None, timestamp=None,
151 unit=None, dimensions=None, statistics=None):
152 args = (name, value, unit, dimensions, statistics, timestamp)
153 length = max(map(lambda a: len(a) if isinstance(a, list) else 1, args))
154
155 def aslist(a):
156 if isinstance(a, list):
157 if len(a) != length:
158 raise Exception('Must specify equal number of elements; expe cted %d.' % length)
159 return a
160 return [a] * length
161
162 for index, (n, v, u, d, s, t) in enumerate(zip(*map(aslist, args))):
163 metric_data = {'MetricName': n}
164
165 if timestamp:
166 metric_data['Timestamp'] = t.isoformat()
167
168 if unit:
169 metric_data['Unit'] = u
170
171 if dimensions:
172 self.build_dimension_param(d, metric_data)
173
174 if statistics:
175 metric_data['StatisticValues.Maximum'] = s['maximum']
176 metric_data['StatisticValues.Minimum'] = s['minimum']
177 metric_data['StatisticValues.SampleCount'] = s['samplecount']
178 metric_data['StatisticValues.Sum'] = s['sum']
179 if value != None:
180 msg = 'You supplied a value and statistics for a metric.'
181 msg += 'Posting statistics and not value.'
182 boto.log.warn(msg)
183 elif value != None:
184 metric_data['Value'] = v
185 else:
186 raise Exception('Must specify a value or statistics to put.')
187
188 for key, value in metric_data.iteritems():
189 params['MetricData.member.%d.%s' % (index + 1, key)] = value
190
191 def get_metric_statistics(self, period, start_time, end_time, metric_name,
192 namespace, statistics, dimensions=None,
193 unit=None):
194 """
195 Get time-series data for one or more statistics of a given metric.
196
197 :type period: integer
198 :param period: The granularity, in seconds, of the returned datapoints.
199 Period must be at least 60 seconds and must be a multiple
200 of 60. The default value is 60.
201
202 :type start_time: datetime
203 :param start_time: The time stamp to use for determining the
204 first datapoint to return. The value specified is
205 inclusive; results include datapoints with the time stamp
206 specified.
207
208 :type end_time: datetime
209 :param end_time: The time stamp to use for determining the
210 last datapoint to return. The value specified is
211 exclusive; results will include datapoints up to the time
212 stamp specified.
213
214 :type metric_name: string
215 :param metric_name: The metric name.
216
217 :type namespace: string
218 :param namespace: The metric's namespace.
219
220 :type statistics: list
221 :param statistics: A list of statistics names Valid values:
222 Average | Sum | SampleCount | Maximum | Minimum
223
224 :type dimensions: dict
225 :param dimensions: A dictionary of dimension key/values where
226 the key is the dimension name and the value
227 is either a scalar value or an iterator
228 of values to be associated with that
229 dimension.
230
231 :type unit: string
232 :param unit: The unit for the metric. Value values are:
233 Seconds | Microseconds | Milliseconds | Bytes | Kilobytes |
234 Megabytes | Gigabytes | Terabytes | Bits | Kilobits |
235 Megabits | Gigabits | Terabits | Percent | Count |
236 Bytes/Second | Kilobytes/Second | Megabytes/Second |
237 Gigabytes/Second | Terabytes/Second | Bits/Second |
238 Kilobits/Second | Megabits/Second | Gigabits/Second |
239 Terabits/Second | Count/Second | None
240
241 :rtype: list
242 """
243 params = {'Period': period,
244 'MetricName': metric_name,
245 'Namespace': namespace,
246 'StartTime': start_time.isoformat(),
247 'EndTime': end_time.isoformat()}
248 self.build_list_params(params, statistics, 'Statistics.member.%d')
249 if dimensions:
250 self.build_dimension_param(dimensions, params)
251 if unit:
252 params['Unit'] = unit
253 return self.get_list('GetMetricStatistics', params,
254 [('member', Datapoint)])
255
256 def list_metrics(self, next_token=None, dimensions=None,
257 metric_name=None, namespace=None):
258 """
259 Returns a list of the valid metrics for which there is recorded
260 data available.
261
262 :type next_token: str
263 :param next_token: A maximum of 500 metrics will be returned
264 at one time. If more results are available, the ResultSet
265 returned will contain a non-Null next_token attribute.
266 Passing that token as a parameter to list_metrics will
267 retrieve the next page of metrics.
268
269 :type dimensions: dict
270 :param dimensions: A dictionary containing name/value
271 pairs that will be used to filter the results. The key in
272 the dictionary is the name of a Dimension. The value in
273 the dictionary is either a scalar value of that Dimension
274 name that you want to filter on, a list of values to
275 filter on or None if you want all metrics with that
276 Dimension name.
277
278 :type metric_name: str
279 :param metric_name: The name of the Metric to filter against. If None,
280 all Metric names will be returned.
281
282 :type namespace: str
283 :param namespace: A Metric namespace to filter against (e.g. AWS/EC2).
284 If None, Metrics from all namespaces will be returned.
285 """
286 params = {}
287 if next_token:
288 params['NextToken'] = next_token
289 if dimensions:
290 self.build_dimension_param(dimensions, params)
291 if metric_name:
292 params['MetricName'] = metric_name
293 if namespace:
294 params['Namespace'] = namespace
295
296 return self.get_list('ListMetrics', params, [('member', Metric)])
297
298 def put_metric_data(self, namespace, name, value=None, timestamp=None,
299 unit=None, dimensions=None, statistics=None):
300 """
301 Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
302 associates the data points with the specified metric. If the specified
303 metric does not exist, Amazon CloudWatch creates the metric. If a list
304 is specified for some, but not all, of the arguments, the remaining
305 arguments are repeated a corresponding number of times.
306
307 :type namespace: str
308 :param namespace: The namespace of the metric.
309
310 :type name: str or list
311 :param name: The name of the metric.
312
313 :type value: float or list
314 :param value: The value for the metric.
315
316 :type timestamp: datetime or list
317 :param timestamp: The time stamp used for the metric. If not specified,
318 the default value is set to the time the metric data was received.
319
320 :type unit: string or list
321 :param unit: The unit of the metric. Valid Values: Seconds |
322 Microseconds | Milliseconds | Bytes | Kilobytes |
323 Megabytes | Gigabytes | Terabytes | Bits | Kilobits |
324 Megabits | Gigabits | Terabits | Percent | Count |
325 Bytes/Second | Kilobytes/Second | Megabytes/Second |
326 Gigabytes/Second | Terabytes/Second | Bits/Second |
327 Kilobits/Second | Megabits/Second | Gigabits/Second |
328 Terabits/Second | Count/Second | None
329
330 :type dimensions: dict
331 :param dimensions: Add extra name value pairs to associate
332 with the metric, i.e.:
333 {'name1': value1, 'name2': (value2, value3)}
334
335 :type statistics: dict or list
336 :param statistics: Use a statistic set instead of a value, for example::
337
338 {'maximum': 30, 'minimum': 1, 'samplecount': 100, 'sum': 10000}
339 """
340 params = {'Namespace': namespace}
341 self.build_put_params(params, name, value=value, timestamp=timestamp,
342 unit=unit, dimensions=dimensions, statistics=statistics)
343
344 return self.get_status('PutMetricData', params, verb="POST")
345
346 def describe_alarms(self, action_prefix=None, alarm_name_prefix=None,
347 alarm_names=None, max_records=None, state_value=None,
348 next_token=None):
349 """
350 Retrieves alarms with the specified names. If no name is specified, all
351 alarms for the user are returned. Alarms can be retrieved by using only
352 a prefix for the alarm name, the alarm state, or a prefix for any
353 action.
354
355 :type action_prefix: string
356 :param action_name: The action name prefix.
357
358 :type alarm_name_prefix: string
359 :param alarm_name_prefix: The alarm name prefix. AlarmNames cannot
360 be specified if this parameter is specified.
361
362 :type alarm_names: list
363 :param alarm_names: A list of alarm names to retrieve information for.
364
365 :type max_records: int
366 :param max_records: The maximum number of alarm descriptions
367 to retrieve.
368
369 :type state_value: string
370 :param state_value: The state value to be used in matching alarms.
371
372 :type next_token: string
373 :param next_token: The token returned by a previous call to
374 indicate that there is more data.
375
376 :rtype list
377 """
378 params = {}
379 if action_prefix:
380 params['ActionPrefix'] = action_prefix
381 if alarm_name_prefix:
382 params['AlarmNamePrefix'] = alarm_name_prefix
383 elif alarm_names:
384 self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
385 if max_records:
386 params['MaxRecords'] = max_records
387 if next_token:
388 params['NextToken'] = next_token
389 if state_value:
390 params['StateValue'] = state_value
391
392 result = self.get_list('DescribeAlarms', params,
393 [('MetricAlarms', MetricAlarms)])
394 ret = result[0]
395 ret.next_token = result.next_token
396 return ret
397
398 def describe_alarm_history(self, alarm_name=None,
399 start_date=None, end_date=None,
400 max_records=None, history_item_type=None,
401 next_token=None):
402 """
403 Retrieves history for the specified alarm. Filter alarms by date range
404 or item type. If an alarm name is not specified, Amazon CloudWatch
405 returns histories for all of the owner's alarms.
406
407 Amazon CloudWatch retains the history of deleted alarms for a period of
408 six weeks. If an alarm has been deleted, its history can still be
409 queried.
410
411 :type alarm_name: string
412 :param alarm_name: The name of the alarm.
413
414 :type start_date: datetime
415 :param start_date: The starting date to retrieve alarm history.
416
417 :type end_date: datetime
418 :param end_date: The starting date to retrieve alarm history.
419
420 :type history_item_type: string
421 :param history_item_type: The type of alarm histories to retreive
422 (ConfigurationUpdate | StateUpdate | Action)
423
424 :type max_records: int
425 :param max_records: The maximum number of alarm descriptions
426 to retrieve.
427
428 :type next_token: string
429 :param next_token: The token returned by a previous call to indicate
430 that there is more data.
431
432 :rtype list
433 """
434 params = {}
435 if alarm_name:
436 params['AlarmName'] = alarm_name
437 if start_date:
438 params['StartDate'] = start_date.isoformat()
439 if end_date:
440 params['EndDate'] = end_date.isoformat()
441 if history_item_type:
442 params['HistoryItemType'] = history_item_type
443 if max_records:
444 params['MaxRecords'] = max_records
445 if next_token:
446 params['NextToken'] = next_token
447 return self.get_list('DescribeAlarmHistory', params,
448 [('member', AlarmHistoryItem)])
449
450 def describe_alarms_for_metric(self, metric_name, namespace, period=None,
451 statistic=None, dimensions=None, unit=None):
452 """
453 Retrieves all alarms for a single metric. Specify a statistic, period,
454 or unit to filter the set of alarms further.
455
456 :type metric_name: string
457 :param metric_name: The name of the metric
458
459 :type namespace: string
460 :param namespace: The namespace of the metric.
461
462 :type period: int
463 :param period: The period in seconds over which the statistic
464 is applied.
465
466 :type statistic: string
467 :param statistic: The statistic for the metric.
468
469 :param dimension_filters: A dictionary containing name/value
470 pairs that will be used to filter the results. The key in
471 the dictionary is the name of a Dimension. The value in
472 the dictionary is either a scalar value of that Dimension
473 name that you want to filter on, a list of values to
474 filter on or None if you want all metrics with that
475 Dimension name.
476
477 :type unit: string
478
479 :rtype list
480 """
481 params = {'MetricName': metric_name,
482 'Namespace': namespace}
483 if period:
484 params['Period'] = period
485 if statistic:
486 params['Statistic'] = statistic
487 if dimensions:
488 self.build_dimension_param(dimensions, params)
489 if unit:
490 params['Unit'] = unit
491 return self.get_list('DescribeAlarmsForMetric', params,
492 [('member', MetricAlarm)])
493
494 def put_metric_alarm(self, alarm):
495 """
496 Creates or updates an alarm and associates it with the specified Amazon
497 CloudWatch metric. Optionally, this operation can associate one or more
498 Amazon Simple Notification Service resources with the alarm.
499
500 When this operation creates an alarm, the alarm state is immediately
501 set to INSUFFICIENT_DATA. The alarm is evaluated and its StateValue is
502 set appropriately. Any actions associated with the StateValue is then
503 executed.
504
505 When updating an existing alarm, its StateValue is left unchanged.
506
507 :type alarm: boto.ec2.cloudwatch.alarm.MetricAlarm
508 :param alarm: MetricAlarm object.
509 """
510 params = {
511 'AlarmName': alarm.name,
512 'MetricName': alarm.metric,
513 'Namespace': alarm.namespace,
514 'Statistic': alarm.statistic,
515 'ComparisonOperator': alarm.comparison,
516 'Threshold': alarm.threshold,
517 'EvaluationPeriods': alarm.evaluation_periods,
518 'Period': alarm.period,
519 }
520 if alarm.actions_enabled is not None:
521 params['ActionsEnabled'] = alarm.actions_enabled
522 if alarm.alarm_actions:
523 self.build_list_params(params, alarm.alarm_actions,
524 'AlarmActions.member.%s')
525 if alarm.description:
526 params['AlarmDescription'] = alarm.description
527 if alarm.dimensions:
528 self.build_dimension_param(alarm.dimensions, params)
529 if alarm.insufficient_data_actions:
530 self.build_list_params(params, alarm.insufficient_data_actions,
531 'InsufficientDataActions.member.%s')
532 if alarm.ok_actions:
533 self.build_list_params(params, alarm.ok_actions,
534 'OKActions.member.%s')
535 if alarm.unit:
536 params['Unit'] = alarm.unit
537 alarm.connection = self
538 return self.get_status('PutMetricAlarm', params)
539 create_alarm = put_metric_alarm
540 update_alarm = put_metric_alarm
541
542 def delete_alarms(self, alarms):
543 """
544 Deletes all specified alarms. In the event of an error, no
545 alarms are deleted.
546
547 :type alarms: list
548 :param alarms: List of alarm names.
549 """
550 params = {}
551 self.build_list_params(params, alarms, 'AlarmNames.member.%s')
552 return self.get_status('DeleteAlarms', params)
553
554 def set_alarm_state(self, alarm_name, state_reason, state_value,
555 state_reason_data=None):
556 """
557 Temporarily sets the state of an alarm. When the updated StateValue
558 differs from the previous value, the action configured for the
559 appropriate state is invoked. This is not a permanent change. The next
560 periodic alarm check (in about a minute) will set the alarm to its
561 actual state.
562
563 :type alarm_name: string
564 :param alarm_name: Descriptive name for alarm.
565
566 :type state_reason: string
567 :param state_reason: Human readable reason.
568
569 :type state_value: string
570 :param state_value: OK | ALARM | INSUFFICIENT_DATA
571
572 :type state_reason_data: string
573 :param state_reason_data: Reason string (will be jsonified).
574 """
575 params = {'AlarmName': alarm_name,
576 'StateReason': state_reason,
577 'StateValue': state_value}
578 if state_reason_data:
579 params['StateReasonData'] = json.dumps(state_reason_data)
580
581 return self.get_status('SetAlarmState', params)
582
583 def enable_alarm_actions(self, alarm_names):
584 """
585 Enables actions for the specified alarms.
586
587 :type alarms: list
588 :param alarms: List of alarm names.
589 """
590 params = {}
591 self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
592 return self.get_status('EnableAlarmActions', params)
593
594 def disable_alarm_actions(self, alarm_names):
595 """
596 Disables actions for the specified alarms.
597
598 :type alarms: list
599 :param alarms: List of alarm names.
600 """
601 params = {}
602 self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
603 return self.get_status('DisableAlarmActions', params)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698