comparison env/lib/python3.9/site-packages/boto/ec2/cloudwatch/__init__.py @ 0:4f3585e2f14b draft default tip

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