Permalink
Browse files

PEP8 cleanup.

  • Loading branch information...
1 parent b408397 commit ac5f6ada5ea399ec0a53b73f051772847fddd350 @garnaat garnaat committed Mar 28, 2012
Showing with 641 additions and 551 deletions.
  1. +8 −6 boto/ec2/__init__.py
  2. +1 −2 boto/ec2/address.py
  3. +26 −19 boto/ec2/autoscale/__init__.py
  4. +6 −4 boto/ec2/autoscale/activity.py
  5. +13 −10 boto/ec2/autoscale/group.py
  6. +0 −1 boto/ec2/autoscale/instance.py
  7. +3 −1 boto/ec2/autoscale/launchconfig.py
  8. +17 −5 boto/ec2/autoscale/policy.py
  9. +0 −1 boto/ec2/autoscale/scheduled.py
  10. +8 −8 boto/ec2/autoscale/tag.py
  11. +9 −6 boto/ec2/blockdevicemapping.py
  12. +5 −5 boto/ec2/bundleinstance.py
  13. +75 −74 boto/ec2/cloudwatch/__init__.py
  14. +21 −18 boto/ec2/cloudwatch/alarm.py
  15. +1 −1 boto/ec2/cloudwatch/datapoint.py
  16. +1 −1 boto/ec2/cloudwatch/dimension.py
  17. +2 −3 boto/ec2/cloudwatch/listelement.py
  18. +1 −3 boto/ec2/cloudwatch/metric.py
  19. +140 −119 boto/ec2/connection.py
  20. +5 −4 boto/ec2/ec2object.py
  21. +63 −61 boto/ec2/elb/__init__.py
  22. +6 −6 boto/ec2/elb/healthcheck.py
  23. +1 −3 boto/ec2/elb/instancestate.py
  24. +4 −5 boto/ec2/elb/listelement.py
  25. +29 −18 boto/ec2/elb/loadbalancer.py
  26. +0 −1 boto/ec2/elb/policies.py
  27. +1 −1 boto/ec2/elb/securitygroup.py
  28. +2 −2 boto/ec2/group.py
  29. +57 −42 boto/ec2/image.py
  30. +12 −7 boto/ec2/instance.py
  31. +3 −5 boto/ec2/instanceinfo.py
  32. +13 −8 boto/ec2/instancestatus.py
  33. +6 −8 boto/ec2/keypair.py
  34. +4 −4 boto/ec2/launchspecification.py
  35. +8 −10 boto/ec2/networkinterface.py
  36. +3 −4 boto/ec2/placementgroup.py
  37. +3 −2 boto/ec2/regioninfo.py
  38. +7 −4 boto/ec2/reservedinstance.py
  39. +10 −6 boto/ec2/securitygroup.py
  40. +6 −7 boto/ec2/snapshot.py
  41. +4 −4 boto/ec2/spotdatafeedsubscription.py
  42. +4 −5 boto/ec2/spotinstancerequest.py
  43. +3 −4 boto/ec2/spotpricehistory.py
  44. +4 −6 boto/ec2/tag.py
  45. +27 −21 boto/ec2/volume.py
  46. +13 −8 boto/ec2/volumestatus.py
  47. +6 −8 boto/ec2/zone.py
View
14 boto/ec2/__init__.py
@@ -14,7 +14,7 @@
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
@@ -25,29 +25,31 @@
"""
from boto.ec2.connection import EC2Connection
+
def regions(**kw_params):
"""
Get all available regions for the EC2 service.
You may pass any of the arguments accepted by the EC2Connection
object's constructor as keyword arguments and they will be
passed along to the EC2Connection object.
-
+
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
"""
c = EC2Connection(**kw_params)
return c.get_all_regions()
+
def connect_to_region(region_name, **kw_params):
"""
- Given a valid region name, return a
+ Given a valid region name, return a
:class:`boto.ec2.connection.EC2Connection`.
Any additional parameters after the region_name are passed on to
the connect method of the region object.
:type: str
:param region_name: The name of the region to connect to.
-
+
:rtype: :class:`boto.ec2.connection.EC2Connection` or ``None``
:return: A connection to the given region, or None if an invalid region
name is given
@@ -56,7 +58,8 @@ def connect_to_region(region_name, **kw_params):
if region.name == region_name:
return region.connect(**kw_params)
return None
-
+
+
def get_region(region_name, **kw_params):
"""
Find and return a :class:`boto.ec2.regioninfo.RegionInfo` object
@@ -73,4 +76,3 @@ def get_region(region_name, **kw_params):
if region.name == region_name:
return region
return None
-
View
3 boto/ec2/address.py
@@ -25,6 +25,7 @@
from boto.ec2.ec2object import EC2Object
+
class Address(EC2Object):
def __init__(self, connection=None, public_ip=None, instance_id=None):
@@ -63,5 +64,3 @@ def associate(self, instance_id):
def disassociate(self):
return self.connection.disassociate_address(self.public_ip)
-
-
View
45 boto/ec2/autoscale/__init__.py
@@ -34,7 +34,8 @@
from boto.ec2.autoscale.launchconfig import LaunchConfiguration
from boto.ec2.autoscale.group import AutoScalingGroup, ProcessType
from boto.ec2.autoscale.activity import Activity
-from boto.ec2.autoscale.policy import AdjustmentType, MetricCollectionTypes, ScalingPolicy
+from boto.ec2.autoscale.policy import AdjustmentType, MetricCollectionTypes
+from boto.ec2.autoscale.policy import ScalingPolicy
from boto.ec2.autoscale.instance import Instance
from boto.ec2.autoscale.scheduled import ScheduledUpdateGroupAction
from boto.ec2.autoscale.tag import Tag
@@ -48,6 +49,7 @@
'ap-northeast-1': 'autoscaling.ap-northeast-1.amazonaws.com',
'ap-southeast-1': 'autoscaling.ap-southeast-1.amazonaws.com'}
+
def regions():
"""
Get all available regions for the Auto Scaling service.
@@ -63,6 +65,7 @@ def regions():
regions.append(region)
return regions
+
def connect_to_region(region_name, **kw_params):
"""
Given a valid region name, return a
@@ -79,11 +82,12 @@ def connect_to_region(region_name, **kw_params):
return region.connect(**kw_params)
return None
+
class AutoScaleConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'autoscale_version', '2011-01-01')
DefaultRegionEndpoint = boto.config.get('Boto', 'autoscale_endpoint',
'autoscaling.amazonaws.com')
- DefaultRegionName = boto.config.get('Boto', 'autoscale_region_name',
+ DefaultRegionName = boto.config.get('Boto', 'autoscale_region_name',
'us-east-1')
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
@@ -129,16 +133,16 @@ def build_list_params(self, params, items, label):
['us-east-1b',...]
"""
# different from EC2 list params
- for i in xrange(1, len(items)+1):
- if isinstance(items[i-1], dict):
- for k, v in items[i-1].items():
+ for i in xrange(1, len(items) + 1):
+ if isinstance(items[i - 1], dict):
+ for k, v in items[i - 1].items():
if isinstance(v, dict):
for kk, vv in v.items():
params['%s.member.%d.%s.%s' % (label, i, k, kk)] = vv
else:
params['%s.member.%d.%s' % (label, i, k)] = v
- elif isinstance(items[i-1], basestring):
- params['%s.member.%d' % (label, i)] = items[i-1]
+ elif isinstance(items[i - 1], basestring):
+ params['%s.member.%d' % (label, i)] = items[i - 1]
def _update_group(self, op, as_group):
params = {'AutoScalingGroupName': as_group.name,
@@ -189,7 +193,8 @@ def create_launch_configuration(self, launch_config):
"""
Creates a new Launch Configuration.
- :type launch_config: :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration`
+ :type launch_config:
+ :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration`
:param launch_config: LaunchConfiguration object.
"""
params = {'ImageId': launch_config.image_id,
@@ -333,7 +338,7 @@ def get_all_activities(self, autoscale_group, activity_ids=None,
name = autoscale_group
if isinstance(autoscale_group, AutoScalingGroup):
name = autoscale_group.name
- params = {'AutoScalingGroupName' : name}
+ params = {'AutoScalingGroupName': name}
if max_records:
params['MaxRecords'] = max_records
if next_token:
@@ -488,12 +493,13 @@ def suspend_processes(self, as_group, scaling_processes=None):
:param as_group: The auto scaling group to suspend processes on.
:type scaling_processes: list
- :param scaling_processes: Processes you want to suspend. If omitted, all
- processes will be suspended.
+ :param scaling_processes: Processes you want to suspend. If
+ omitted, all processes will be suspended.
"""
params = {'AutoScalingGroupName': as_group}
if scaling_processes:
- self.build_list_params(params, scaling_processes, 'ScalingProcesses')
+ self.build_list_params(params, scaling_processes,
+ 'ScalingProcesses')
return self.get_status('SuspendProcesses', params)
def resume_processes(self, as_group, scaling_processes=None):
@@ -510,7 +516,8 @@ def resume_processes(self, as_group, scaling_processes=None):
params = {'AutoScalingGroupName': as_group}
if scaling_processes:
- self.build_list_params(params, scaling_processes, 'ScalingProcesses')
+ self.build_list_params(params, scaling_processes,
+ 'ScalingProcesses')
return self.get_status('ResumeProcesses', params)
def create_scheduled_group_action(self, as_group, name, time,
@@ -646,8 +653,10 @@ def get_all_tags(self, filters=None, max_records=None, next_token=None):
"""
Lists the Auto Scaling group tags.
- This action supports pagination by returning a token if there are more
- pages to retrieve. To get the next page, call this action again with the returned token as the NextToken parameter.
+ This action supports pagination by returning a token if there
+ are more pages to retrieve. To get the next page, call this
+ action again with the returned token as the NextToken
+ parameter.
:type filters: dict
:param filters: The value of the filter type used to identify
@@ -677,7 +686,7 @@ def create_or_update_tags(self, tags):
"""
params = {}
for i, tag in enumerate(tags):
- tag.build_params(params, i+1)
+ tag.build_params(params, i + 1)
return self.get_status('CreateOrUpdateTags', params, verb='POST')
def delete_tags(self, tags):
@@ -689,7 +698,5 @@ def delete_tags(self, tags):
"""
params = {}
for i, tag in enumerate(tags):
- tag.build_params(params, i+1)
+ tag.build_params(params, i + 1)
return self.get_status('DeleteTags', params, verb='POST')
-
-
View
10 boto/ec2/autoscale/activity.py
@@ -51,12 +51,15 @@ def endElement(self, name, value, connection):
self.group_name = value
elif name == 'StartTime':
try:
- self.start_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
+ self.start_time = datetime.strptime(value,
+ '%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
- self.start_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
+ self.start_time = datetime.strptime(value,
+ '%Y-%m-%dT%H:%M:%SZ')
elif name == 'EndTime':
try:
- self.end_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
+ self.end_time = datetime.strptime(value,
+ '%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
self.end_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
elif name == 'Progress':
@@ -71,4 +74,3 @@ def endElement(self, name, value, connection):
self.status_code = value
else:
setattr(self, name, value)
-
View
23 boto/ec2/autoscale/group.py
@@ -26,6 +26,7 @@
from boto.ec2.autoscale.instance import Instance
from boto.ec2.autoscale.tag import Tag
+
class ProcessType(object):
def __init__(self, connection=None):
self.connection = connection
@@ -86,7 +87,8 @@ def __init__(self, connection=None, name=None,
load_balancers=None, default_cooldown=None,
health_check_type=None, health_check_period=None,
placement_group=None, vpc_zone_identifier=None,
- desired_capacity=None, min_size=None, max_size=None, **kwargs):
+ desired_capacity=None, min_size=None, max_size=None,
+ **kwargs):
"""
Creates a new AutoScalingGroup with the specified name.
@@ -136,11 +138,11 @@ def __init__(self, connection=None, name=None,
:type vpc_zone_identifier: str
:param vpc_zone_identifier: The subnet identifier of the Virtual
Private Cloud.
-
+
:rtype: :class:`boto.ec2.autoscale.group.AutoScalingGroup`
:return: An autoscale group.
"""
- self.name = name or kwargs.get('group_name') # backwards compatibility
+ self.name = name or kwargs.get('group_name') # b/w compatibility
self.connection = connection
self.min_size = int(min_size) if min_size is not None else None
self.max_size = int(max_size) if max_size is not None else None
@@ -169,10 +171,10 @@ def __init__(self, connection=None, name=None,
# backwards compatible access to 'cooldown' param
def _get_cooldown(self):
return self.default_cooldown
-
+
def _set_cooldown(self, val):
self.default_cooldown = val
-
+
cooldown = property(_get_cooldown, _set_cooldown)
def __repr__(self):
@@ -190,7 +192,8 @@ def startElement(self, name, attrs, connection):
self.enabled_metrics = ResultSet([('member', EnabledMetric)])
return self.enabled_metrics
elif name == 'SuspendedProcesses':
- self.suspended_processes = ResultSet([('member', SuspendedProcess)])
+ self.suspended_processes = ResultSet([('member',
+ SuspendedProcess)])
return self.suspended_processes
elif name == 'Tags':
self.tags = ResultSet([('member', Tag)])
@@ -233,8 +236,8 @@ def set_capacity(self, capacity):
"""
Set the desired capacity for the group.
"""
- params = {'AutoScalingGroupName' : self.name,
- 'DesiredCapacity' : capacity}
+ params = {'AutoScalingGroupName': self.name,
+ 'DesiredCapacity': capacity}
req = self.connection.get_object('SetDesiredCapacity', params,
Request)
self.connection.last_request = req
@@ -261,7 +264,8 @@ def delete(self, force_delete=False):
Delete this auto-scaling group if no instances attached or no
scaling activities in progress.
"""
- return self.connection.delete_auto_scaling_group(self.name, force_delete)
+ return self.connection.delete_auto_scaling_group(self.name,
+ force_delete)
def get_activities(self, activity_ids=None, max_records=50):
"""
@@ -303,4 +307,3 @@ def endElement(self, name, value, connection):
self.granularity = value
else:
setattr(self, name, value)
-
View
1 boto/ec2/autoscale/instance.py
@@ -57,4 +57,3 @@ def endElement(self, name, value, connection):
self.group_name = value
else:
setattr(self, name, value)
-
View
4 boto/ec2/autoscale/launchconfig.py
@@ -26,6 +26,8 @@
import base64
# this should use the corresponding object from boto.ec2
+
+
class Ebs(object):
def __init__(self, connection=None, snapshot_id=None, volume_size=None):
self.connection = connection
@@ -84,6 +86,7 @@ def endElement(self, name, value, connection):
elif name == 'VirtualName':
self.virtual_name = value
+
class LaunchConfiguration(object):
def __init__(self, connection=None, name=None, image_id=None,
key_name=None, security_groups=None, user_data=None,
@@ -187,4 +190,3 @@ def endElement(self, name, value, connection):
def delete(self):
""" Delete this launch configuration. """
return self.connection.delete_launch_configuration(self.name)
-
View
22 boto/ec2/autoscale/policy.py
@@ -23,6 +23,7 @@
from boto.resultset import ResultSet
from boto.ec2.elb.listelement import ListElement
+
class Alarm(object):
def __init__(self, connection=None):
self.connection = connection
@@ -62,19 +63,26 @@ def endElement(self, name, value, connection):
class MetricCollectionTypes(object):
class BaseType(object):
+
arg = ''
+
def __init__(self, connection):
self.connection = connection
self.val = None
+
def __repr__(self):
return '%s:%s' % (self.arg, self.val)
+
def startElement(self, name, attrs, connection):
return
+
def endElement(self, name, value, connection):
if name == self.arg:
self.val = value
+
class Metric(BaseType):
arg = 'Metric'
+
class Granularity(BaseType):
arg = 'Granularity'
@@ -84,7 +92,8 @@ def __init__(self, connection=None):
self.granularities = []
def __repr__(self):
- return 'MetricCollectionTypes:<%s, %s>' % (self.metrics, self.granularities)
+ return 'MetricCollectionTypes:<%s, %s>' % (self.metrics,
+ self.granularities)
def startElement(self, name, attrs, connection):
if name == 'Granularities':
@@ -107,16 +116,20 @@ def __init__(self, connection=None, **kwargs):
:param name: Name of scaling policy.
:type adjustment_type: str
- :param adjustment_type: Specifies the type of adjustment. Valid values are `ChangeInCapacity`, `ExactCapacity` and `PercentChangeInCapacity`.
+ :param adjustment_type: Specifies the type of adjustment.
+ Valid values are `ChangeInCapacity`, `ExactCapacity`
+ and `PercentChangeInCapacity`.
:type as_name: str or int
:param as_name: Name or ARN of the Auto Scaling Group.
:type scaling_adjustment: int
- :param scaling_adjustment: Value of adjustment (type specified in `adjustment_type`).
+ :param scaling_adjustment: Value of adjustment (type specified
+ in `adjustment_type`).
:type cooldown: int
- :param cooldown: Time (in seconds) before Alarm related Scaling Activities can start after the previous Scaling Activity ends.
+ :param cooldown: Time (in seconds) before Alarm related Scaling
+ Activities can start after the previous Scaling Activity ends.
"""
self.name = kwargs.get('name', None)
@@ -152,4 +165,3 @@ def endElement(self, name, value, connection):
def delete(self):
return self.connection.delete_policy(self.name, self.as_name)
-
View
1 boto/ec2/autoscale/scheduled.py
@@ -57,4 +57,3 @@ def endElement(self, name, value, connection):
self.time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
else:
setattr(self, name, value)
-
View
16 boto/ec2/autoscale/tag.py
@@ -20,6 +20,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
+
class Tag(object):
"""
A name/value tag on an AutoScalingGroup resource.
@@ -32,7 +33,7 @@ class Tag(object):
:ivar resource_type: The only supported resource type at this time
is "auto-scaling-group".
"""
-
+
def __init__(self, connection=None, key=None, value=None,
propagate_at_launch=False, resource_id=None,
resource_type='auto-scaling-group'):
@@ -70,15 +71,14 @@ def build_params(self, params, i):
to identify this Tag in a request.
"""
prefix = 'Tags.member.%d.' % i
- params[prefix+'ResourceId'] = self.resource_id
- params[prefix+'ResourceType'] = self.resource_type
- params[prefix+'Key'] = self.key
- params[prefix+'Value'] = self.value
+ params[prefix + 'ResourceId'] = self.resource_id
+ params[prefix + 'ResourceType'] = self.resource_type
+ params[prefix + 'Key'] = self.key
+ params[prefix + 'Value'] = self.value
if self.propagate_at_launch:
- params[prefix+'PropagateAtLaunch'] = 'true'
+ params[prefix + 'PropagateAtLaunch'] = 'true'
else:
- params[prefix+'PropagateAtLaunch'] = 'false'
+ params[prefix + 'PropagateAtLaunch'] = 'false'
def delete(self):
return self.connection.delete_tags([self])
-
View
15 boto/ec2/blockdevicemapping.py
@@ -14,12 +14,13 @@
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
+
class BlockDeviceType(object):
"""
Represents parameters for a block device.
@@ -49,13 +50,13 @@ def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
- if name =='volumeId':
+ if name == 'volumeId':
self.volume_id = value
elif name == 'virtualName':
self.ephemeral_name = value
- elif name =='NoDevice':
+ elif name == 'NoDevice':
self.no_device = (value == 'true')
- elif name =='snapshotId':
+ elif name == 'snapshotId':
self.snapshot_id = value
elif name == 'volumeSize':
self.size = int(value)
@@ -74,13 +75,15 @@ def endElement(self, name, value, connection):
# for backwards compatibility
EBSBlockDeviceType = BlockDeviceType
+
class BlockDeviceMapping(dict):
"""
Represents a collection of BlockDeviceTypes when creating ec2 instances.
- Example:
+ Example:
dev_sda1 = BlockDeviceType()
- dev_sda1.size = 100 # change root volume to 100GB instead of default for ami
+ dev_sda1.size = 100 # change root volume to 100GB instead of
+ default for ami
bdm = BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
reservation = image.run(..., block_device_map=bdm, ...)
View
10 boto/ec2/bundleinstance.py
@@ -14,19 +14,20 @@
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
-Represents an EC2 Bundle Task
+Represents an EC2 Bundle Task
"""
from boto.ec2.ec2object import EC2Object
+
class BundleInstanceTask(EC2Object):
-
+
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.id = None
@@ -38,7 +39,7 @@ def __init__(self, connection=None):
self.prefix = None
self.upload_policy = None
self.upload_policy_signature = None
- self.update_time = None
+ self.update_time = None
self.code = None
self.message = None
@@ -75,4 +76,3 @@ def endElement(self, name, value, connection):
self.message = value
else:
setattr(self, name, value)
-
View
149 boto/ec2/cloudwatch/__init__.py
@@ -26,21 +26,23 @@
from boto.connection import AWSQueryConnection
from boto.ec2.cloudwatch.metric import Metric
-from boto.ec2.cloudwatch.alarm import MetricAlarm, MetricAlarms, AlarmHistoryItem
+from boto.ec2.cloudwatch.alarm import MetricAlarm, MetricAlarms
+from boto.ec2.cloudwatch.alarm import AlarmHistoryItem
from boto.ec2.cloudwatch.datapoint import Datapoint
from boto.regioninfo import RegionInfo
import boto
import boto.compat as compat
RegionData = {
- 'us-east-1' : 'monitoring.us-east-1.amazonaws.com',
- 'us-west-1' : 'monitoring.us-west-1.amazonaws.com',
- 'us-west-2' : 'monitoring.us-west-2.amazonaws.com',
- 'sa-east-1' : 'monitoring.sa-east-1.amazonaws.com',
- 'eu-west-1' : 'monitoring.eu-west-1.amazonaws.com',
- 'ap-northeast-1' : 'monitoring.ap-northeast-1.amazonaws.com',
- 'ap-southeast-1' : 'monitoring.ap-southeast-1.amazonaws.com'}
+ 'us-east-1': 'monitoring.us-east-1.amazonaws.com',
+ 'us-west-1': 'monitoring.us-west-1.amazonaws.com',
+ 'us-west-2': 'monitoring.us-west-2.amazonaws.com',
+ 'sa-east-1': 'monitoring.sa-east-1.amazonaws.com',
+ 'eu-west-1': 'monitoring.eu-west-1.amazonaws.com',
+ 'ap-northeast-1': 'monitoring.ap-northeast-1.amazonaws.com',
+ 'ap-southeast-1': 'monitoring.ap-southeast-1.amazonaws.com'}
+
def regions():
"""
@@ -57,6 +59,7 @@ def regions():
regions.append(region)
return regions
+
def connect_to_region(region_name, **kw_params):
"""
Given a valid region name, return a
@@ -83,7 +86,6 @@ class CloudWatchConnection(AWSQueryConnection):
'cloudwatch_region_endpoint',
'monitoring.us-east-1.amazonaws.com')
-
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
@@ -100,7 +102,7 @@ def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
self.region = region
AWSQueryConnection.__init__(self, aws_access_key_id,
- aws_secret_access_key,
+ aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
@@ -117,25 +119,25 @@ def build_dimension_param(self, dimension, params):
if isinstance(dim_value, basestring):
dim_value = [dim_value]
for j, value in enumerate(dim_value):
- params['%s.%d.Name.%d' % (prefix, i+1, j+1)] = dim_name
- params['%s.%d.Value.%d' % (prefix, i+1, j+1)] = value
+ params['%s.%d.Name.%d' % (prefix, i + 1, j + 1)] = dim_name
+ params['%s.%d.Value.%d' % (prefix, i + 1, j + 1)] = value
else:
- params['%s.%d.Name' % (prefix, i+1)] = dim_name
-
+ params['%s.%d.Name' % (prefix, i + 1)] = dim_name
+
def build_list_params(self, params, items, label):
if isinstance(items, basestring):
items = [items]
for index, item in enumerate(items):
i = index + 1
if isinstance(item, dict):
- for k,v in item.iteritems():
+ for k, v in item.items():
params[label % (i, 'Name')] = k
if v is not None:
params[label % (i, 'Value')] = v
else:
params[label % i] = item
- def build_put_params(self, params, name, value=None, timestamp=None,
+ def build_put_params(self, params, name, value=None, timestamp=None,
unit=None, dimensions=None, statistics=None):
args = (name, value, unit, dimensions, statistics)
length = max(map(lambda a: len(a) if isinstance(a, list) else 1, args))
@@ -152,13 +154,13 @@ def aslist(a):
if timestamp:
metric_data['Timestamp'] = timestamp.isoformat()
-
+
if unit:
metric_data['Unit'] = u
-
+
if dimensions:
self.build_dimension_param(d, metric_data)
-
+
if statistics:
metric_data['StatisticValues.Maximum'] = s['maximum']
metric_data['StatisticValues.Minimum'] = s['minimum']
@@ -184,8 +186,8 @@ def get_metric_statistics(self, period, start_time, end_time, metric_name,
:type period: integer
:param period: The granularity, in seconds, of the returned datapoints.
- Period must be at least 60 seconds and must be a multiple
- of 60. The default value is 60.
+ Period must be at least 60 seconds and must be a
+ multiple of 60. The default value is 60.
:type start_time: datetime
:param start_time: The time stamp to use for determining the first
@@ -217,11 +219,11 @@ def get_metric_statistics(self, period, start_time, end_time, metric_name,
dimension.
:rtype: list
"""
- params = {'Period' : period,
- 'MetricName' : metric_name,
- 'Namespace' : namespace,
- 'StartTime' : start_time.isoformat(),
- 'EndTime' : end_time.isoformat()}
+ params = {'Period': period,
+ 'MetricName': metric_name,
+ 'Namespace': namespace,
+ 'StartTime': start_time.isoformat(),
+ 'EndTime': end_time.isoformat()}
self.build_list_params(params, statistics, 'Statistics.member.%d')
if dimensions:
self.build_dimension_param(dimensions, params)
@@ -243,22 +245,21 @@ def list_metrics(self, next_token=None, dimensions=None,
next page of metrics.
:type dimension: dict
- :param dimension_filters: A dictionary containing name/value pairs
- that will be used to filter the results.
- The key in the dictionary is the name of
- a Dimension. The value in the dictionary
- is either a scalar value of that Dimension
- name that you want to filter on, a list
- of values to filter on or None if
- you want all metrics with that Dimension name.
+ :param dimension_filters: A dictionary containing name/value
+ pairs that will be used to filter the results. The key in
+ the dictionary is the name of a Dimension. The value in
+ the dictionary is either a scalar value of that Dimension
+ name that you want to filter on, a list of values to
+ filter on or None if you want all metrics with that
+ Dimension name.
:type metric_name: str
:param metric_name: The name of the Metric to filter against. If None,
all Metric names will be returned.
:type namespace: str
:param namespace: A Metric namespace to filter against (e.g. AWS/EC2).
- If None, Metrics from all namespaces will be returned.
+ If None, Metrics from all namespaces will be returned.
"""
params = {}
if next_token:
@@ -269,17 +270,18 @@ def list_metrics(self, next_token=None, dimensions=None,
params['MetricName'] = metric_name
if namespace:
params['Namespace'] = namespace
-
+
return self.get_list('ListMetrics', params, [('member', Metric)])
-
- def put_metric_data(self, namespace, name, value=None, timestamp=None,
+
+ def put_metric_data(self, namespace, name, value=None, timestamp=None,
unit=None, dimensions=None, statistics=None):
"""
- Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
- associates the data points with the specified metric. If the specified
- metric does not exist, Amazon CloudWatch creates the metric. If a list
- is specified for some, but not all, of the arguments, the remaining
- arguments are repeated a corresponding number of times.
+ Publishes metric data points to Amazon CloudWatch. Amazon
+ Cloudwatch associates the data points with the specified
+ metric. If the specified metric does not exist, Amazon
+ CloudWatch creates the metric. If a list is specified for
+ some, but not all, of the arguments, the remaining arguments
+ are repeated a corresponding number of times.
:type namespace: str
:param namespace: The namespace of the metric.
@@ -291,26 +293,28 @@ def put_metric_data(self, namespace, name, value=None, timestamp=None,
:param value: The value for the metric.
:type timestamp: datetime or list
- :param timestamp: The time stamp used for the metric. If not specified,
- the default value is set to the time the metric data was received.
-
+ :param timestamp: The time stamp used for the metric. If not
+ specified, the default value is set to the time the metric
+ data was received.
+
:type unit: string or list
- :param unit: The unit of the metric. Valid Values: Seconds |
+ :param unit: The unit of the metric. Valid Values: Seconds |
Microseconds | Milliseconds | Bytes | Kilobytes |
Megabytes | Gigabytes | Terabytes | Bits | Kilobits |
Megabits | Gigabits | Terabits | Percent | Count |
Bytes/Second | Kilobytes/Second | Megabytes/Second |
Gigabytes/Second | Terabytes/Second | Bits/Second |
Kilobits/Second | Megabits/Second | Gigabits/Second |
Terabits/Second | Count/Second | None
-
+
:type dimensions: dict
- :param dimensions: Add extra name value pairs to associate
+ :param dimensions: Add extra name value pairs to associate
with the metric, i.e.:
{'name1': value1, 'name2': (value2, value3)}
-
+
:type statistics: dict or list
- :param statistics: Use a statistic set instead of a value, for example::
+ :param statistics: Use a statistic set instead of a value,
+ for example::
{'maximum': 30, 'minimum': 1, 'samplecount': 100, 'sum': 10000}
"""
@@ -320,7 +324,6 @@ def put_metric_data(self, namespace, name, value=None, timestamp=None,
return self.get_status('PutMetricData', params)
-
def describe_alarms(self, action_prefix=None, alarm_name_prefix=None,
alarm_names=None, max_records=None, state_value=None,
next_token=None):
@@ -440,21 +443,20 @@ def describe_alarms_for_metric(self, metric_name, namespace, period=None,
:type statistic: string
:param statistic: The statistic for the metric.
- :param dimension_filters: A dictionary containing name/value pairs
- that will be used to filter the results.
- The key in the dictionary is the name of
- a Dimension. The value in the dictionary
- is either a scalar value of that Dimension
- name that you want to filter on, a list
- of values to filter on or None if
- you want all metrics with that Dimension name.
+ :param dimension_filters: A dictionary containing name/value
+ pairs that will be used to filter the results. The key in
+ the dictionary is the name of a Dimension. The value in
+ the dictionary is either a scalar value of that Dimension
+ name that you want to filter on, a list of values to
+ filter on or None if you want all metrics with that
+ Dimension name.
:type unit: string
:rtype list
"""
- params = {'MetricName' : metric_name,
- 'Namespace' : namespace}
+ params = {'MetricName': metric_name,
+ 'Namespace': namespace}
if period:
params['Period'] = period
if statistic:
@@ -483,14 +485,14 @@ def put_metric_alarm(self, alarm):
:param alarm: MetricAlarm object.
"""
params = {
- 'AlarmName' : alarm.name,
- 'MetricName' : alarm.metric,
- 'Namespace' : alarm.namespace,
- 'Statistic' : alarm.statistic,
- 'ComparisonOperator' : alarm.comparison,
- 'Threshold' : alarm.threshold,
- 'EvaluationPeriods' : alarm.evaluation_periods,
- 'Period' : alarm.period,
+ 'AlarmName': alarm.name,
+ 'MetricName': alarm.metric,
+ 'Namespace': alarm.namespace,
+ 'Statistic': alarm.statistic,
+ 'ComparisonOperator': alarm.comparison,
+ 'Threshold': alarm.threshold,
+ 'EvaluationPeriods': alarm.evaluation_periods,
+ 'Period': alarm.period,
}
if alarm.actions_enabled is not None:
params['ActionsEnabled'] = alarm.actions_enabled
@@ -547,9 +549,9 @@ def set_alarm_state(self, alarm_name, state_reason, state_value,
:type state_reason_data: string
:param state_reason_data: Reason string (will be jsonified).
"""
- params = {'AlarmName' : alarm_name,
- 'StateReason' : state_reason,
- 'StateValue' : state_value}
+ params = {'AlarmName': alarm_name,
+ 'StateReason': state_reason,
+ 'StateValue': state_value}
if state_reason_data:
params['StateReasonData'] = compat.json.dumps(state_reason_data)
@@ -576,4 +578,3 @@ def disable_alarm_actions(self, alarm_names):
params = {}
self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
return self.get_status('DisableAlarmActions', params)
-
View
39 boto/ec2/cloudwatch/alarm.py
@@ -52,10 +52,10 @@ class MetricAlarm(object):
INSUFFICIENT_DATA = 'INSUFFICIENT_DATA'
_cmp_map = {
- '>=' : 'GreaterThanOrEqualToThreshold',
- '>' : 'GreaterThanThreshold',
- '<' : 'LessThanThreshold',
- '<=' : 'LessThanOrEqualToThreshold',
+ '>=': 'GreaterThanOrEqualToThreshold',
+ '>': 'GreaterThanThreshold',
+ '<': 'LessThanThreshold',
+ '<=': 'LessThanOrEqualToThreshold',
}
_rev_cmp_map = dict((v, k) for (k, v) in _cmp_map.items())
@@ -115,17 +115,18 @@ def __init__(self, connection=None, name=None, metric=None,
:type dimensions: list of dicts
:param description: Dimensions of alarm, such as:
[{'InstanceId':['i-0123456,i-0123457']}]
-
+
:type alarm_actions: list of strs
:param alarm_actions: A list of the ARNs of the actions to take in
ALARM state
-
+
:type insufficient_data_actions: list of strs
:param insufficient_data_actions: A list of the ARNs of the actions to
take in INSUFFICIENT_DATA state
-
+
:type ok_actions: list of strs
- :param ok_actions: A list of the ARNs of the actions to take in OK state
+ :param ok_actions: A list of the ARNs of the actions to take in
+ OK state
"""
self.name = name
self.connection = connection
@@ -236,24 +237,25 @@ def enable_actions(self):
def disable_actions(self):
return self.connection.disable_alarm_actions([self.name])
- def describe_history(self, start_date=None, end_date=None, max_records=None,
- history_item_type=None, next_token=None):
+ def describe_history(self, start_date=None, end_date=None,
+ max_records=None, history_item_type=None,
+ next_token=None):
return self.connection.describe_alarm_history(self.name, start_date,
end_date, max_records,
history_item_type,
next_token)
def add_alarm_action(self, action_arn=None):
"""
- Adds an alarm action, represented as an SNS topic, to this alarm.
+ Adds an alarm action, represented as an SNS topic, to this alarm.
What do do when alarm is triggered.
:type action_arn: str
- :param action_arn: SNS topics to which notification should be
+ :param action_arn: SNS topics to which notification should be
sent if the alarm goes to state ALARM.
"""
if not action_arn:
- return # Raise exception instead?
+ return # Raise exception instead?
self.actions_enabled = 'true'
self.alarm_actions.append(action_arn)
@@ -263,21 +265,21 @@ def add_insufficient_data_action(self, action_arn=None):
this alarm. What to do when the insufficient_data state is reached.
:type action_arn: str
- :param action_arn: SNS topics to which notification should be
+ :param action_arn: SNS topics to which notification should be
sent if the alarm goes to state INSUFFICIENT_DATA.
"""
if not action_arn:
return
self.actions_enabled = 'true'
self.insufficient_data_actions.append(action_arn)
-
+
def add_ok_action(self, action_arn=None):
"""
Adds an ok action, represented as an SNS topic, to this alarm. What
to do when the ok state is reached.
:type action_arn: str
- :param action_arn: SNS topics to which notification should be
+ :param action_arn: SNS topics to which notification should be
sent if the alarm goes to state INSUFFICIENT_DATA.
"""
if not action_arn:
@@ -288,12 +290,14 @@ def add_ok_action(self, action_arn=None):
def delete(self):
self.connection.delete_alarms([self.name])
+
class AlarmHistoryItem(object):
def __init__(self, connection=None):
self.connection = connection
def __repr__(self):
- return 'AlarmHistory:%s[%s at %s]' % (self.name, self.summary, self.timestamp)
+ return 'AlarmHistory:%s[%s at %s]' % (self.name, self.summary,
+ self.timestamp)
def startElement(self, name, attrs, connection):
pass
@@ -309,4 +313,3 @@ def endElement(self, name, value, connection):
self.summary = value
elif name == 'Timestamp':
self.timestamp = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
-
View
2 boto/ec2/cloudwatch/datapoint.py
@@ -21,6 +21,7 @@
#
from datetime import datetime
+
class Datapoint(dict):
def __init__(self, connection=None):
@@ -37,4 +38,3 @@ def endElement(self, name, value, connection):
self[name] = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
elif name != 'member':
self[name] = value
-
View
2 boto/ec2/cloudwatch/dimension.py
@@ -20,6 +20,7 @@
# IN THE SOFTWARE.
#
+
class Dimension(dict):
def startElement(self, name, attrs, connection):
@@ -35,4 +36,3 @@ def endElement(self, name, value, connection):
self[self._name] = [value]
else:
setattr(self, name, value)
-
View
5 boto/ec2/cloudwatch/listelement.py
@@ -14,11 +14,12 @@
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
+
class ListElement(list):
def startElement(self, name, attrs, connection):
@@ -27,5 +28,3 @@ def startElement(self, name, attrs, connection):
def endElement(self, name, value, connection):
if name == 'member':
self.append(value)
-
-
View
4 boto/ec2/cloudwatch/metric.py
@@ -23,6 +23,7 @@
from boto.ec2.cloudwatch.alarm import MetricAlarm
from boto.ec2.cloudwatch.dimension import Dimension
+
class Metric(object):
Statistics = ['Minimum', 'Maximum', 'Sum', 'Average', 'SampleCount']
@@ -92,6 +93,3 @@ def describe_alarms(self, period=None, statistic=None,
statistic,
dimensions,
unit)
-
-
-
View
259 boto/ec2/connection.py
@@ -58,6 +58,7 @@
#boto.set_stream_logger('ec2')
+
class EC2Connection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'ec2_version', '2012-03-01')
@@ -118,7 +119,7 @@ def build_filter_params(self, params, filters):
value = [value]
j = 1
for v in value:
- params['Filter.%d.Value.%d' % (i,j)] = v
+ params['Filter.%d.Value.%d' % (i, j)] = v
j += 1
i += 1
@@ -183,7 +184,7 @@ def get_all_kernels(self, kernel_ids=None, owners=None):
self.build_list_params(params, kernel_ids, 'ImageId')
if owners:
self.build_list_params(params, owners, 'Owner')
- filter = {'image-type' : 'kernel'}
+ filter = {'image-type': 'kernel'}
self.build_filter_params(params, filter)
return self.get_list('DescribeImages', params,
[('item', Image)], verb='POST')
@@ -207,7 +208,7 @@ def get_all_ramdisks(self, ramdisk_ids=None, owners=None):
self.build_list_params(params, ramdisk_ids, 'ImageId')
if owners:
self.build_list_params(params, owners, 'Owner')
- filter = {'image-type' : 'ramdisk'}
+ filter = {'image-type': 'ramdisk'}
self.build_filter_params(params, filter)
return self.get_list('DescribeImages', params,
[('item', Image)], verb='POST')
@@ -224,7 +225,7 @@ def get_image(self, image_id):
"""
try:
return self.get_all_images(image_ids=[image_id])[0]
- except IndexError: # None of those images available
+ except IndexError: # None of those images available
return None
def register_image(self, name=None, description=None, image_location=None,
@@ -308,7 +309,7 @@ def deregister_image(self, image_id, delete_snapshot=False):
break
result = self.get_status('DeregisterImage',
- {'ImageId':image_id}, verb='POST')
+ {'ImageId': image_id}, verb='POST')
if result and snapshot_id:
return result and self.delete_snapshot(snapshot_id)
return result
@@ -339,8 +340,8 @@ def create_image(self, instance_id, name,
:rtype: string
:return: The new image id
"""
- params = {'InstanceId' : instance_id,
- 'Name' : name}
+ params = {'InstanceId': instance_id,
+ 'Name': name}
if description:
params['Description'] = description
if no_reboot:
@@ -368,8 +369,8 @@ def get_image_attribute(self, image_id, attribute='launchPermission'):
:return: An ImageAttribute object representing the value of the
attribute requested
"""
- params = {'ImageId' : image_id,
- 'Attribute' : attribute}
+ params = {'ImageId': image_id,
+ 'Attribute': attribute}
return self.get_object('DescribeImageAttribute', params,
ImageAttribute, verb='POST')
@@ -400,9 +401,9 @@ def modify_image_attribute(self, image_id, attribute='launchPermission',
product code can be associated with an AMI. Once
set, the product code cannot be changed or reset.
"""
- params = {'ImageId' : image_id,
- 'Attribute' : attribute,
- 'OperationType' : operation}
+ params = {'ImageId': image_id,
+ 'Attribute': attribute,
+ 'OperationType': operation}
if user_ids:
self.build_list_params(params, user_ids, 'UserId')
if groups:
@@ -424,8 +425,8 @@ def reset_image_attribute(self, image_id, attribute='launchPermission'):
:rtype: bool
:return: Whether the operation succeeded or not
"""
- params = {'ImageId' : image_id,
- 'Attribute' : attribute}
+ params = {'ImageId': image_id,
+ 'Attribute': attribute}
return self.get_status('ResetImageAttribute', params, verb='POST')
# Instance methods
@@ -533,7 +534,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
:param max_count: The maximum number of instances to launch
:type key_name: string
- :param key_name: The name of the key pair with which to launch instances
+ :param key_name: The name of the key pair with which to launch
+ instances
:type security_groups: list of strings
:param security_groups: The names of the security groups with which to
@@ -557,7 +559,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
* t1.micro
:type placement: string
- :param placement: The availability zone in which to launch the instances
+ :param placement: The availability zone in which to launch the
+ instances
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the
@@ -568,7 +571,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
instances
:type monitoring_enabled: bool
- :param monitoring_enabled: Enable CloudWatch monitoring on the instance.
+ :param monitoring_enabled: Enable CloudWatch monitoring on the
+ instance.
:type subnet_id: string
:param subnet_id: The subnet ID within which to launch the instances
@@ -603,7 +607,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
:type placement_group: string
:param placement_group: If specified, this is the name of the placement
- group in which the instance(s) will be launched.
+ group in which the instance(s) will be
+ launched.
:type client_token: string
:param client_token: Unique, case-sensitive identifier you provide
@@ -618,8 +623,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
:param security_group_ids: The ID of the VPC security groups with
which to associate instances
"""
- params = {'ImageId':image_id,
- 'MinCount':min_count,
+ params = {'ImageId': image_id,
+ 'MinCount': min_count,
'MaxCount': max_count}
if key_name:
params['KeyName'] = key_name
@@ -668,7 +673,8 @@ def run_instances(self, image_id, min_count=1, max_count=1,
params['InstanceInitiatedShutdownBehavior'] = val
if client_token:
params['ClientToken'] = client_token
- return self.get_object('RunInstances', params, Reservation, verb='POST')
+ return self.get_object('RunInstances', params, Reservation,
+ verb='POST')
def terminate_instances(self, instance_ids=None):
"""
@@ -751,8 +757,8 @@ def reboot_instances(self, instance_ids=None):
return self.get_status('RebootInstances', params)
def confirm_product_instance(self, product_code, instance_id):
- params = {'ProductCode' : product_code,
- 'InstanceId' : instance_id}
+ params = {'ProductCode': product_code,
+ 'InstanceId': instance_id}
rs = self.get_object('ConfirmProductInstance', params,
ResultSet, verb='POST')
return (rs.status, rs.ownerId)
@@ -779,7 +785,7 @@ def get_instance_attribute(self, instance_id, attribute):
:return: An InstanceAttribute object representing the value of the
attribute requested
"""
- params = {'InstanceId' : instance_id}
+ params = {'InstanceId': instance_id}
if attribute:
params['Attribute'] = attribute
return self.get_object('DescribeInstanceAttribute', params,
@@ -817,9 +823,9 @@ def modify_instance_attribute(self, instance_id, attribute, value):
value = 'true'
else:
value = 'false'
- params = {'InstanceId' : instance_id,
- 'Attribute' : attribute,
- 'Value' : value}
+ params = {'InstanceId': instance_id,
+ 'Attribute': attribute,
+ 'Value': value}
return self.get_status('ModifyInstanceAttribute', params, verb='POST')
def reset_instance_attribute(self, instance_id, attribute):
@@ -836,8 +842,8 @@ def reset_instance_attribute(self, instance_id, attribute):
:rtype: bool
:return: Whether the operation succeeded or not
"""
- params = {'InstanceId' : instance_id,
- 'Attribute' : attribute}
+ params = {'InstanceId': instance_id,
+ 'Attribute': attribute}
return self.get_status('ResetInstanceAttribute', params, verb='POST')
# Spot Instances
@@ -866,7 +872,8 @@ def get_all_spot_instance_requests(self, request_ids=None,
"""
params = {}
if request_ids:
- self.build_list_params(params, request_ids, 'SpotInstanceRequestId')
+ self.build_list_params(params, request_ids,
+ 'SpotInstanceRequestId')
if filters:
if 'launch.group-id' in filters:
lgid = filters.get('launch.group-id')
@@ -965,7 +972,8 @@ def request_spot_instances(self, price, image_id, count=1, type='one-time',
availability zone.
:type key_name: string
- :param key_name: The name of the key pair with which to launch instances
+ :param key_name: The name of the key pair with which to
+ launch instances
:type security_groups: list of strings
:param security_groups: The names of the security groups with which to
@@ -989,7 +997,8 @@ def request_spot_instances(self, price, image_id, count=1, type='one-time',
* t1.micro
:type placement: string
- :param placement: The availability zone in which to launch the instances
+ :param placement: The availability zone in which to launch
+ the instances
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the
@@ -1000,15 +1009,16 @@ def request_spot_instances(self, price, image_id, count=1, type='one-time',
instances
:type monitoring_enabled: bool
- :param monitoring_enabled: Enable CloudWatch monitoring on the instance.
+ :param monitoring_enabled: Enable CloudWatch monitoring on
+ the instance.
:type subnet_id: string
:param subnet_id: The subnet ID within which to launch the instances
for VPC.
:type placement_group: string
:param placement_group: If specified, this is the name of the placement
- group in which the instance(s) will be launched.
+ group in which the instance(s) will be launched.
:type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
:param block_device_map: A BlockDeviceMapping data structure
@@ -1019,9 +1029,9 @@ def request_spot_instances(self, price, image_id, count=1, type='one-time',
:return: The :class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`
associated with the request for machines
"""
- params = {'LaunchSpecification.ImageId':image_id,
- 'Type' : type,
- 'SpotPrice' : price}
+ params = {'LaunchSpecification.ImageId': image_id,
+ 'Type': type,
+ 'SpotPrice': price}
if count:
params['InstanceCount'] = count
if valid_from:
@@ -1079,7 +1089,8 @@ def cancel_spot_instance_requests(self, request_ids):
"""
params = {}
if request_ids:
- self.build_list_params(params, request_ids, 'SpotInstanceRequestId')
+ self.build_list_params(params, request_ids,
+ 'SpotInstanceRequestId')
return self.get_list('CancelSpotInstanceRequests', params,
[('item', Instance)], verb='POST')
@@ -1111,7 +1122,7 @@ def create_spot_datafeed_subscription(self, bucket, prefix):
:rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`
:return: The datafeed subscription object or None
"""
- params = {'Bucket' : bucket}
+ params = {'Bucket': bucket}
if prefix:
params['Prefix'] = prefix
return self.get_object('CreateSpotDatafeedSubscription',
@@ -1162,7 +1173,8 @@ def get_all_zones(self, zones=None, filters=None):
# Address methods
- def get_all_addresses(self, addresses=None, filters=None, allocation_ids=None):
+ def get_all_addresses(self, addresses=None, filters=None,
+ allocation_ids=None):
"""
Get all EIP's associated with the current credentials.
@@ -1182,9 +1194,9 @@ def get_all_addresses(self, addresses=None, filters=None, allocation_ids=None):
for details.
:type allocation_ids: list
- :param allocation_ids: Optional list of allocation IDs. If this list is
- present, only the Addresses associated with the given
- allocation IDs will be returned.
+ :param allocation_ids: Optional list of allocation IDs. If this
+ list is present, only the Addresses associated with the given
+ allocation IDs will be returned.
:rtype: list of :class:`boto.ec2.address.Address`
:return: The requested Address objects
@@ -1196,7 +1208,8 @@ def get_all_addresses(self, addresses=None, filters=None, allocation_ids=None):
self.build_list_params(params, allocation_ids, 'AllocationId')
if filters:
self.build_filter_params(params, filters)
- return self.get_list('DescribeAddresses', params, [('item', Address)], verb='POST')
+ return self.get_list('DescribeAddresses', params,
+ [('item', Address)], verb='POST')
def allocate_address(self, domain=None):
"""
@@ -1212,7 +1225,8 @@ def allocate_address(self, domain=None):
return self.get_object('AllocateAddress', params, Address, verb='POST')
- def associate_address(self, instance_id, public_ip=None, allocation_id=None):
+ def associate_address(self, instance_id, public_ip=None,
+ allocation_id=None):
"""
Associate an Elastic IP address with a currently running instance.
This requires one of ``public_ip`` or ``allocation_id`` depending
@@ -1230,7 +1244,7 @@ def associate_address(self, instance_id, public_ip=None, allocation_id=None):
:rtype: bool
:return: True if successful
"""
- params = { 'InstanceId' : instance_id }
+ params = {'InstanceId': instance_id}
if public_ip is not None:
params['PublicIp'] = public_ip
@@ -1387,7 +1401,7 @@ def get_volume_attribute(self, volume_id,
:rtype: list of :class:`boto.ec2.volume.VolumeAttribute`
:return: The requested Volume attribute
"""
- params = {'VolumeId': volume_id, 'Attribute' : attribute}
+ params = {'VolumeId': volume_id, 'Attribute': attribute}
return self.get_object('DescribeVolumeAttribute', params,
VolumeAttribute, verb='POST')
@@ -1421,11 +1435,12 @@ def create_volume(self, size, zone, snapshot=None):
:param zone: The availability zone in which the Volume will be created.
:type snapshot: string or :class:`boto.ec2.snapshot.Snapshot`
- :param snapshot: The snapshot from which the new Volume will be created.
+ :param snapshot: The snapshot from which the new Volume will
+ be created.
"""
if isinstance(zone, Zone):
zone = zone.name
- params = {'AvailabilityZone' : zone}
+ params = {'AvailabilityZone': zone}
if size:
params['Size'] = size
if snapshot:
@@ -1465,9 +1480,9 @@ def attach_volume(self, volume_id, instance_id, device):
:rtype: bool
:return: True if successful
"""
- params = {'InstanceId' : instance_id,
- 'VolumeId' : volume_id,
- 'Device' : device}
+ params = {'InstanceId': instance_id,
+ 'VolumeId': volume_id,
+ 'Device': device}
return self.get_status('AttachVolume', params, verb='POST')
def detach_volume(self, volume_id, instance_id=None,
@@ -1487,18 +1502,19 @@ def detach_volume(self, volume_id, instance_id=None,
volume is exposted (e.g. /dev/sdh)
:type force: bool
- :param force: Forces detachment if the previous detachment attempt did
- not occur cleanly. This option can lead to data loss or
- a corrupted file system. Use this option only as a last
- resort to detach a volume from a failed instance. The
- instance will not have an opportunity to flush file system
- caches nor file system meta data. If you use this option,
- you must perform file system check and repair procedures.
+ :param force: Forces detachment if the previous detachment
+ attempt did not occur cleanly. This option can lead to
+ data loss or a corrupted file system. Use this option only
+ as a last resort to detach a volume from a failed
+ instance. The instance will not have an opportunity to
+ flush file system caches nor file system meta data. If you
+ use this option, you must perform file system check and
+ repair procedures.
:rtype: bool
:return: True if successful
"""
- params = {'VolumeId' : volume_id}
+ params = {'VolumeId': volume_id}
if instance_id:
params['InstanceId'] = instance_id
if device:
@@ -1521,16 +1537,16 @@ def get_all_snapshots(self, snapshot_ids=None,
these snapshot ids will be returned.
:type owner: str
- :param owner: If present, only the snapshots owned by the specified user
- will be returned. Valid values are:
+ :param owner: If present, only the snapshots owned by the
+ specified user will be returned. Valid values are:
- * self
- * amazon
- * AWS Account ID
+ * self
+ * amazon
+ * AWS Account ID
:type restorable_by: str
- :param restorable_by: If present, only the snapshots that are restorable
- by the specified account id will be returned.
+ :param restorable_by: If present, only the snapshots that
+ are restorable by the specified account id will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
@@ -1571,7 +1587,7 @@ def create_snapshot(self, volume_id, description=None):
:rtype: bool
:return: True if successful
"""
- params = {'VolumeId' : volume_id}
+ params = {'VolumeId': volume_id}
if description:
params['Description'] = description[0:255]
snapshot = self.get_object('CreateSnapshot', params,
@@ -1586,8 +1602,8 @@ def delete_snapshot(self, snapshot_id):
params = {'SnapshotId': snapshot_id}
return self.get_status('DeleteSnapshot', params, verb='POST')
- def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
- weekly_backups = 4):
+ def trim_snapshots(self, hourly_backups=8, daily_backups=7,
+ weekly_backups=4):
"""
Trim excess snapshots, based on when they were taken. More current
snapshots are retained, with the number retained decreasing as you
@@ -1631,7 +1647,7 @@ def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
now = datetime.utcnow()
last_hour = datetime(now.year, now.month, now.day, now.hour)
last_midnight = datetime(now.year, now.month, now.day)
- last_sunday = datetime(now.year, now.month, now.day) - timedelta(days = (now.weekday() + 1) % 7)
+ last_sunday = datetime(now.year, now.month, now.day) - timedelta(days=(now.weekday() + 1) % 7)
start_of_month = datetime(now.year, now.month, 1)
target_backup_times = []
@@ -1640,15 +1656,15 @@ def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
oldest_snapshot_date = datetime(2007, 1, 1)
for hour in range(0, hourly_backups):
- target_backup_times.append(last_hour - timedelta(hours = hour))
+ target_backup_times.append(last_hour - timedelta(hours=hour))
for day in range(0, daily_backups):
- target_backup_times.append(last_midnight - timedelta(days = day))
+ target_backup_times.append(last_midnight - timedelta(days=day))
for week in range(0, weekly_backups):
- target_backup_times.append(last_sunday - timedelta(weeks = week))
+ target_backup_times.append(last_sunday - timedelta(weeks=week))
- one_day = timedelta(days = 1)
+ one_day = timedelta(days=1)
while start_of_month > oldest_snapshot_date:
# append the start of the month to the list of
# snapshot dates to save:
@@ -1674,8 +1690,8 @@ def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
# get all the snapshots, sort them by date and time, and
# organize them into one array for each volume:
- all_snapshots = self.get_all_snapshots(owner = 'self')
- all_snapshots.sort(cmp = lambda x, y: cmp(x.start_time, y.start_time))
+ all_snapshots = self.get_all_snapshots(owner='self')
+ all_snapshots.sort(cmp=lambda x, y: cmp(x.start_time, y.start_time))
snaps_for_each_volume = {}
for snap in all_snapshots:
# the snapshot name and the volume name are the same.
@@ -1695,7 +1711,7 @@ def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
# time period and deleting the rest:
for volume_name in snaps_for_each_volume:
snaps = snaps_for_each_volume[volume_name]
- snaps = snaps[:-1] # never delete the newest snapshot
+ snaps = snaps[:-1] # never delete the newest snapshot
time_period_number = 0
snap_found_for_this_time_period = False
for snap in snaps:
@@ -1733,7 +1749,6 @@ def trim_snapshots(self, hourly_backups = 8, daily_backups = 7,
time_period_number += 1
snap_found_for_this_time_period = False
-
def get_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission'):
"""
@@ -1751,7 +1766,7 @@ def get_snapshot_attribute(self, snapshot_id,
:rtype: list of :class:`boto.ec2.snapshotattribute.SnapshotAttribute`
:return: The requested Snapshot attribute
"""
- params = {'Attribute' : attribute}
+ params = {'Attribute': attribute}
if snapshot_id:
params['SnapshotId'] = snapshot_id
return self.get_object('DescribeSnapshotAttribute', params,
@@ -1782,9 +1797,9 @@ def modify_snapshot_attribute(self, snapshot_id,
value at this time is 'all'.
"""
- params = {'SnapshotId' : snapshot_id,
- 'Attribute' : attribute,
- 'OperationType' : operation}
+ params = {'SnapshotId': snapshot_id,
+ 'Attribute': attribute,
+ 'OperationType': operation}
if user_ids:
self.build_list_params(params, user_ids, 'UserId')
if groups:
@@ -1805,8 +1820,8 @@ def reset_snapshot_attribute(self, snapshot_id,
:rtype: bool
:return: Whether the operation succeeded or not
"""
- params = {'SnapshotId' : snapshot_id,
- 'Attribute' : attribute}
+ params = {'SnapshotId': snapshot_id,
+ 'Attribute': attribute}
return self.get_status('ResetSnapshotAttribute', params, verb='POST')
# Keypair methods
@@ -1872,7 +1887,7 @@ def create_key_pair(self, key_name):
The material attribute of the new KeyPair object
will contain the the unencrypted PEM encoded RSA private key.
"""
- params = {'KeyName':key_name}
+ params = {'KeyName': key_name}
return self.get_object('CreateKeyPair', params, KeyPair, verb='POST')
def delete_key_pair(self, key_name):
@@ -1882,7 +1897,7 @@ def delete_key_pair(self, key_name):
:type key_name: string
:param key_name: The name of the keypair to delete
"""
- params = {'KeyName':key_name}
+ params = {'KeyName': key_name}
return self.get_status('DeleteKeyPair', params, verb='POST')
def import_key_pair(self, key_name, public_key_material):
@@ -1918,8 +1933,8 @@ def import_key_pair(self, key_name, public_key_material):
will contain the the unencrypted PEM encoded RSA private key.
"""
public_key_material = base64.b64encode(public_key_material)
- params = {'KeyName' : key_name,
- 'PublicKeyMaterial' : public_key_material}
+ params = {'KeyName': key_name,
+ 'PublicKeyMaterial': public_key_material}
return self.get_object('ImportKeyPair', params, KeyPair, verb='POST')
# SecurityGroup methods
@@ -2057,7 +2072,7 @@ def authorize_security_group_deprecated(self, group_name,
:rtype: bool
:return: True if successful.
"""
- params = {'GroupName':group_name}
+ params = {'GroupName': group_name}
if src_security_group_name:
params['SourceSecurityGroupName'] = src_security_group_name
if src_security_group_owner_id:
@@ -2075,7 +2090,8 @@ def authorize_security_group_deprecated(self, group_name,
def authorize_security_group(self, group_name=None,
src_security_group_name=None,
src_security_group_owner_id=None,
- ip_protocol=None, from_port=None, to_port=None,
+ ip_protocol=None,
+ from_port=None, to_port=None,
cidr_ip=None, group_id=None,
src_security_group_group_id=None):
"""
@@ -2156,7 +2172,7 @@ def authorize_security_group(self, group_name=None,
if type(cidr_ip) != list:
cidr_ip = [cidr_ip]
for i, single_cidr_ip in enumerate(cidr_ip):
- params['IpPermissions.1.IpRanges.%d.CidrIp' % (i+1)] = \
+ params['IpPermissions.1.IpRanges.%d.CidrIp' % (i + 1)] = \
single_cidr_ip
return self.get_status('AuthorizeSecurityGroupIngress',
@@ -2250,7 +2266,7 @@ def revoke_security_group_deprecated(self, group_name,
:rtype: bool
:return: True if successful.
"""
- params = {'GroupName':group_name}
+ params = {'GroupName': group_name}
if src_security_group_name:
params['SourceSecurityGroupName'] = src_security_group_name
if src_security_group_owner_id:
@@ -2265,7 +2281,8 @@ def revoke_security_group_deprecated(self, group_name,
params['CidrIp'] = cidr_ip
return self.get_status('RevokeSecurityGroupIngress', params)
- def revoke_security_group(self, group_name=None, src_security_group_name=None,
+ def revoke_security_group(self, group_name=None,
+ src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, group_id=None,
@@ -2343,10 +2360,11 @@ def revoke_security_group_egress(self,
src_group_id=None,
cidr_ip=None):
"""
- Remove an existing egress rule from an existing VPC security group.
- You need to pass in an ip_protocol, from_port and to_port range only
- if the protocol you are using is port-based. You also need to pass in either
- a src_group_id or cidr_ip.
+ Remove an existing egress rule from an existing VPC security
+ group. You need to pass in an ip_protocol, from_port and
+ to_port range only if the protocol you are using is
+ port-based. You also need to pass in either a src_group_id or
+ cidr_ip.
:type group_name: string
:param group_id: The name of the security group you are removing
@@ -2362,7 +2380,8 @@ def revoke_security_group_egress(self,
:param to_port: The ending port number you are disabling
:type src_group_id: src_group_id
- :param src_group_id: The source security group you are revoking access to.
+ :param src_group_id: The source security group you are
+ revoking access to.
:type cidr_ip: string
:param cidr_ip: The CIDR block you are revoking access to.
@@ -2417,7 +2436,7 @@ def get_all_regions(self, region_names=None, filters=None):
self.build_list_params(params, region_names, 'RegionName')
if filters:
self.build_filter_params(params, filters)
- regions = self.get_list('DescribeRegions', params,
+ regions = self.get_list('DescribeRegions', params,
[('item', RegionInfo)], verb='POST')
for region in regions:
region.connection_cls = EC2Connection
@@ -2462,7 +2481,8 @@ def get_all_reserved_instances_offerings(self, reserved_instances_id=None,
for details.
:rtype: list
- :return: A list of :class:`boto.ec2.reservedinstance.ReservedInstancesOffering`
+ :return: A list of
+ :class:`boto.ec2.reservedinstance.ReservedInstancesOffering`
"""
params = {}
if reserved_instances_id:
@@ -2533,8 +2553,8 @@ def purchase_reserved_instance_offering(self,
:return: The newly created Reserved Instance
"""
params = {
- 'ReservedInstancesOfferingId' : reserved_instances_offering_id,
- 'InstanceCount' : instance_count}
+ 'ReservedInstancesOfferingId': reserved_instances_offering_id,
+ 'InstanceCount': instance_count}
return self.get_object('PurchaseReservedInstancesOffering', params,
ReservedInstance, verb='POST')
@@ -2624,10 +2644,10 @@ def bundle_instance(self, instance_id,
user's image into Amazon S3.
"""
- params = {'InstanceId' : instance_id,
- 'Storage.S3.Bucket' : s3_bucket,
- 'Storage.S3.Prefix' : s3_prefix,
- 'Storage.S3.UploadPolicy' : s3_upload_policy}
+ params = {'InstanceId': instance_id,
+ 'Storage.S3.Bucket': s3_bucket,
+ 'Storage.S3.Prefix': s3_prefix,
+ 'Storage.S3.UploadPolicy': s3_upload_policy}
s3auth = boto.auth.get_auth_handler(None, boto.config,
self.provider, ['s3'])
params['Storage.S3.AWSAccessKeyId'] = self.aws_access_key_id
@@ -2673,7 +2693,7 @@ def cancel_bundle_task(self, bundle_id):
:param bundle_id: The identifier of the bundle task to cancel.
"""
- params = {'BundleId' : bundle_id}
+ params = {'BundleId': bundle_id}
return self.get_object('CancelBundleTask', params,
BundleInstanceTask, verb='POST')
@@ -2686,7 +2706,7 @@ def get_password_data(self, instance_id):
password for.
"""
- params = {'InstanceId' : instance_id}
+ params = {'InstanceId': instance_id}
rs = self.get_object('GetPasswordData', params, ResultSet, verb='POST')
return rs.passwordData
@@ -2740,7 +2760,8 @@ def create_placement_group(self, name, strategy='cluster'):</