summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMitch Garnaat <mitch@garnaat.com>2012-03-28 07:53:02 -0700
committerMitch Garnaat <mitch@garnaat.com>2012-03-28 07:53:02 -0700
commitf240b19159e1f8211d96704a2b74baae3cb68e38 (patch)
tree6de193b1f15a935679fa22e78eb9a02ac0e671ee
parentcde748106613918951212b90a6eec8cb72ca8a57 (diff)
downloadboto-f240b19159e1f8211d96704a2b74baae3cb68e38.tar.gz
PEP8 cleanup and removing roboto which will be merged back into it's own package.
-rw-r--r--boto/rds/__init__.py938
-rw-r--r--boto/rds/connection.py951
-rw-r--r--boto/rds/dbinstance.py86
-rw-r--r--boto/rds/dbsecuritygroup.py4
-rw-r--r--boto/rds/dbsnapshot.py8
-rw-r--r--boto/rds/event.py6
-rw-r--r--boto/rds/parametergroup.py24
-rw-r--r--boto/rds/regioninfo.py5
-rw-r--r--boto/roboto/__init__.py1
-rw-r--r--boto/roboto/awsqueryrequest.py504
-rw-r--r--boto/roboto/awsqueryservice.py122
-rw-r--r--boto/roboto/param.py147
12 files changed, 1017 insertions, 1779 deletions
diff --git a/boto/rds/__init__.py b/boto/rds/__init__.py
index c739879d..00119028 100644
--- a/boto/rds/__init__.py
+++ b/boto/rds/__init__.py
@@ -20,15 +20,9 @@
# IN THE SOFTWARE.
#
-import urllib
-from boto.connection import AWSQueryConnection
-from boto.rds.dbinstance import DBInstance
-from boto.rds.dbsecuritygroup import DBSecurityGroup
-from boto.rds.parametergroup import ParameterGroup
-from boto.rds.dbsnapshot import DBSnapshot
-from boto.rds.event import Event
from boto.rds.regioninfo import RDSRegionInfo
+
def regions():
"""
Get all available regions for the RDS service.
@@ -52,9 +46,10 @@ def regions():
endpoint='rds.ap-southeast-1.amazonaws.com')
]
+
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.
@@ -70,930 +65,3 @@ def connect_to_region(region_name, **kw_params):
if region.name == region_name:
return region.connect(**kw_params)
return None
-
-#boto.set_stream_logger('rds')
-
-class RDSConnection(AWSQueryConnection):
-
- DefaultRegionName = 'us-east-1'
- DefaultRegionEndpoint = 'rds.us-east-1.amazonaws.com'
- APIVersion = '2011-04-01'
-
- 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,
- https_connection_factory=None, region=None, path='/'):
- if not region:
- region = RDSRegionInfo(self, self.DefaultRegionName,
- self.DefaultRegionEndpoint)
- self.region = region
- AWSQueryConnection.__init__(self, aws_access_key_id,
- aws_secret_access_key,
- is_secure, port, proxy, proxy_port,
- proxy_user, proxy_pass,
- self.region.endpoint, debug,
- https_connection_factory, path)
-
- def _required_auth_capability(self):
- return ['rds']
-
- # DB Instance methods
-
- def get_all_dbinstances(self, instance_id=None, max_records=None,
- marker=None):
- """
- Retrieve all the DBInstances in your account.
-
- :type instance_id: str
- :param instance_id: DB Instance identifier. If supplied, only
- information this instance will be returned.
- Otherwise, info about all DB Instances will
- be returned.
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: list
- :return: A list of :class:`boto.rds.dbinstance.DBInstance`
- """
- params = {}
- if instance_id:
- params['DBInstanceIdentifier'] = instance_id
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- return self.get_list('DescribeDBInstances', params,
- [('DBInstance', DBInstance)])
-
- def create_dbinstance(self, id, allocated_storage, instance_class,
- master_username, master_password, port=3306,
- engine='MySQL5.1', db_name=None, param_group=None,
- security_groups=None, availability_zone=None,
- preferred_maintenance_window=None,
- backup_retention_period=None,
- preferred_backup_window=None,
- multi_az=False,
- engine_version=None,
- auto_minor_version_upgrade=True):
- """
- Create a new DBInstance.
-
- :type id: str
- :param id: Unique identifier for the new instance.
- Must contain 1-63 alphanumeric characters.
- First character must be a letter.
- May not end with a hyphen or contain two consecutive hyphens
-
- :type allocated_storage: int
- :param allocated_storage: Initially allocated storage size, in GBs.
- Valid values are [5-1024]
-
- :type instance_class: str
- :param instance_class: The compute and memory capacity of
- the DBInstance. Valid values are:
-
- * db.m1.small
- * db.m1.large
- * db.m1.xlarge
- * db.m2.xlarge
- * db.m2.2xlarge
- * db.m2.4xlarge
-
- :type engine: str
- :param engine: Name of database engine. Must be MySQL5.1 for now.
-
- :type master_username: str
- :param master_username: Name of master user for the DBInstance.
- Must be 1-15 alphanumeric characters, first
- must be a letter.
-
- :type master_password: str
- :param master_password: Password of master user for the DBInstance.
- Must be 4-16 alphanumeric characters.
-
- :type port: int
- :param port: Port number on which database accepts connections.
- Valid values [1115-65535]. Defaults to 3306.
-
- :type db_name: str
- :param db_name: Name of a database to create when the DBInstance
- is created. Default is to create no databases.
-
- :type param_group: str
- :param param_group: Name of DBParameterGroup to associate with
- this DBInstance. If no groups are specified
- no parameter groups will be used.
-
- :type security_groups: list of str or list of DBSecurityGroup objects
- :param security_groups: List of names of DBSecurityGroup to authorize on
- this DBInstance.
-
- :type availability_zone: str
- :param availability_zone: Name of the availability zone to place
- DBInstance into.
-
- :type preferred_maintenance_window: str
- :param preferred_maintenance_window: The weekly time range (in UTC)
- during which maintenance can occur.
- Default is Sun:05:00-Sun:09:00
-
- :type backup_retention_period: int
- :param backup_retention_period: The number of days for which automated
- backups are retained. Setting this to
- zero disables automated backups.
-
- :type preferred_backup_window: str
- :param preferred_backup_window: The daily time range during which
- automated backups are created (if
- enabled). Must be in h24:mi-hh24:mi
- format (UTC).
-
- :type multi_az: bool
- :param multi_az: If True, specifies the DB Instance will be
- deployed in multiple availability zones.
-
- :type engine_version: str
- :param engine_version: Version number of the database engine to use.
-
- :type auto_minor_version_upgrade: bool
- :param auto_minor_version_upgrade: Indicates that minor engine
- upgrades will be applied
- automatically to the Read Replica
- during the maintenance window.
- Default is True.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The new db instance.
- """
- params = {'DBInstanceIdentifier': id,
- 'AllocatedStorage': allocated_storage,
- 'DBInstanceClass': instance_class,
- 'Engine': engine,
- 'MasterUsername': master_username,
- 'MasterUserPassword': master_password,
- 'Port': port,
- 'MultiAZ': str(multi_az).lower(),
- 'AutoMinorVersionUpgrade':
- str(auto_minor_version_upgrade).lower()}
- if db_name:
- params['DBName'] = db_name
- if param_group:
- params['DBParameterGroupName'] = param_group
- if security_groups:
- l = []
- for group in security_groups:
- if isinstance(group, DBSecurityGroup):
- l.append(group.name)
- else:
- l.append(group)
- self.build_list_params(params, l, 'DBSecurityGroups.member')
- if availability_zone:
- params['AvailabilityZone'] = availability_zone
- if preferred_maintenance_window:
- params['PreferredMaintenanceWindow'] = preferred_maintenance_window
- if backup_retention_period is not None:
- params['BackupRetentionPeriod'] = backup_retention_period
- if preferred_backup_window:
- params['PreferredBackupWindow'] = preferred_backup_window
- if engine_version:
- params['EngineVersion'] = engine_version
-
- return self.get_object('CreateDBInstance', params, DBInstance)
-
- def create_dbinstance_read_replica(self, id, source_id,
- instance_class=None,
- port=3306,
- availability_zone=None,
- auto_minor_version_upgrade=None):
- """
- Create a new DBInstance Read Replica.
-
- :type id: str
- :param id: Unique identifier for the new instance.
- Must contain 1-63 alphanumeric characters.
- First character must be a letter.
- May not end with a hyphen or contain two consecutive hyphens
-
- :type source_id: str
- :param source_id: Unique identifier for the DB Instance for which this
- DB Instance will act as a Read Replica.
-
- :type instance_class: str
- :param instance_class: The compute and memory capacity of the
- DBInstance. Default is to inherit from
- the source DB Instance.
-
- Valid values are:
-
- * db.m1.small
- * db.m1.large
- * db.m1.xlarge
- * db.m2.xlarge
- * db.m2.2xlarge
- * db.m2.4xlarge
-
- :type port: int
- :param port: Port number on which database accepts connections.
- Default is to inherit from source DB Instance.
- Valid values [1115-65535]. Defaults to 3306.
-
- :type availability_zone: str
- :param availability_zone: Name of the availability zone to place
- DBInstance into.
-
- :type auto_minor_version_upgrade: bool
- :param auto_minor_version_upgrade: Indicates that minor engine
- upgrades will be applied
- automatically to the Read Replica
- during the maintenance window.
- Default is to inherit this value
- from the source DB Instance.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The new db instance.
- """
- params = {'DBInstanceIdentifier' : id,
- 'SourceDBInstanceIdentifier' : source_id}
- if instance_class:
- params['DBInstanceClass'] = instance_class
- if port:
- params['Port'] = port
- if availability_zone:
- params['AvailabilityZone'] = availability_zone
- if auto_minor_version_upgrade is not None:
- if auto_minor_version_upgrade is True:
- params['AutoMinorVersionUpgrade'] = 'true'
- else:
- params['AutoMinorVersionUpgrade'] = 'false'
-
- return self.get_object('CreateDBInstanceReadReplica',
- params, DBInstance)
-
- def modify_dbinstance(self, id, param_group=None, security_groups=None,
- preferred_maintenance_window=None,
- master_password=None, allocated_storage=None,
- instance_class=None,
- backup_retention_period=None,
- preferred_backup_window=None,
- multi_az=False,
- apply_immediately=False):
- """
- Modify an existing DBInstance.
-
- :type id: str
- :param id: Unique identifier for the new instance.
-
- :type security_groups: list of str or list of DBSecurityGroup objects
- :param security_groups: List of names of DBSecurityGroup to authorize on
- this DBInstance.
-
- :type preferred_maintenance_window: str
- :param preferred_maintenance_window: The weekly time range (in UTC)
- during which maintenance can
- occur.
- Default is Sun:05:00-Sun:09:00
-
- :type master_password: str
- :param master_password: Password of master user for the DBInstance.
- Must be 4-15 alphanumeric characters.
-
- :type allocated_storage: int
- :param allocated_storage: The new allocated storage size, in GBs.
- Valid values are [5-1024]
-
- :type instance_class: str
- :param instance_class: The compute and memory capacity of the
- DBInstance. Changes will be applied at
- next maintenance window unless
- apply_immediately is True.
-
- Valid values are:
-
- * db.m1.small
- * db.m1.large
- * db.m1.xlarge
- * db.m2.xlarge
- * db.m2.2xlarge
- * db.m2.4xlarge
-
- :type apply_immediately: bool
- :param apply_immediately: If true, the modifications will be applied
- as soon as possible rather than waiting for
- the next preferred maintenance window.
-
- :type backup_retention_period: int
- :param backup_retention_period: The number of days for which automated
- backups are retained. Setting this to
- zero disables automated backups.
-
- :type preferred_backup_window: str
- :param preferred_backup_window: The daily time range during which
- automated backups are created (if
- enabled). Must be in h24:mi-hh24:mi
- format (UTC).
-
- :type multi_az: bool
- :param multi_az: If True, specifies the DB Instance will be
- deployed in multiple availability zones.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The modified db instance.
- """
- params = {'DBInstanceIdentifier' : id}
- if param_group:
- params['DBParameterGroupName'] = param_group
- if security_groups:
- l = []
- for group in security_groups:
- if isinstance(group, DBSecurityGroup):
- l.append(group.name)
- else:
- l.append(group)
- self.build_list_params(params, l, 'DBSecurityGroups.member')
- if preferred_maintenance_window:
- params['PreferredMaintenanceWindow'] = preferred_maintenance_window
- if master_password:
- params['MasterUserPassword'] = master_password
- if allocated_storage:
- params['AllocatedStorage'] = allocated_storage
- if instance_class:
- params['DBInstanceClass'] = instance_class
- if backup_retention_period is not None:
- params['BackupRetentionPeriod'] = backup_retention_period
- if preferred_backup_window:
- params['PreferredBackupWindow'] = preferred_backup_window
- if multi_az:
- params['MultiAZ'] = 'true'
- if apply_immediately:
- params['ApplyImmediately'] = 'true'
-
- return self.get_object('ModifyDBInstance', params, DBInstance)
-
- def delete_dbinstance(self, id, skip_final_snapshot=False,
- final_snapshot_id=''):
- """
- Delete an existing DBInstance.
-
- :type id: str
- :param id: Unique identifier for the new instance.
-
- :type skip_final_snapshot: bool
- :param skip_final_snapshot: This parameter determines whether a final
- db snapshot is created before the instance
- is deleted. If True, no snapshot
- is created. If False, a snapshot
- is created before deleting the instance.
-
- :type final_snapshot_id: str
- :param final_snapshot_id: If a final snapshot is requested, this
- is the identifier used for that snapshot.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The deleted db instance.
- """
- params = {'DBInstanceIdentifier' : id}
- if skip_final_snapshot:
- params['SkipFinalSnapshot'] = 'true'
- else:
- params['SkipFinalSnapshot'] = 'false'
- params['FinalDBSnapshotIdentifier'] = final_snapshot_id
- return self.get_object('DeleteDBInstance', params, DBInstance)
-
-
- def reboot_dbinstance(self, id):
- """
- Reboot DBInstance.
-
- :type id: str
- :param id: Unique identifier of the instance.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The rebooting db instance.
- """
- params = {'DBInstanceIdentifier' : id}
- return self.get_object('RebootDBInstance', params, DBInstance)
-
- # DBParameterGroup methods
-
- def get_all_dbparameter_groups(self, groupname=None, max_records=None,
- marker=None):
- """
- Get all parameter groups associated with your account in a region.
-
- :type groupname: str
- :param groupname: The name of the DBParameter group to retrieve.
- If not provided, all DBParameter groups will be returned.
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: list
- :return: A list of :class:`boto.ec2.parametergroup.ParameterGroup`
- """
- params = {}
- if groupname:
- params['DBParameterGroupName'] = groupname
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- return self.get_list('DescribeDBParameterGroups', params,
- [('DBParameterGroup', ParameterGroup)])
-
- def get_all_dbparameters(self, groupname, source=None,
- max_records=None, marker=None):
- """
- Get all parameters associated with a ParameterGroup
-
- :type groupname: str
- :param groupname: The name of the DBParameter group to retrieve.
-
- :type source: str
- :param source: Specifies which parameters to return.
- If not specified, all parameters will be returned.
- Valid values are: user|system|engine-default
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: :class:`boto.ec2.parametergroup.ParameterGroup`
- :return: The ParameterGroup
- """
- params = {'DBParameterGroupName' : groupname}
- if source:
- params['Source'] = source
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- pg = self.get_object('DescribeDBParameters', params, ParameterGroup)
- pg.name = groupname
- return pg
-
- def create_parameter_group(self, name, engine='MySQL5.1', description=''):
- """
- Create a new dbparameter group for your account.
-
- :type name: string
- :param name: The name of the new dbparameter group
-
- :type engine: str
- :param engine: Name of database engine.
-
- :type description: string
- :param description: The description of the new security group
-
- :rtype: :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
- :return: The newly created DBSecurityGroup
- """
- params = {'DBParameterGroupName': name,
- 'DBParameterGroupFamily': engine,
- 'Description' : description}
- return self.get_object('CreateDBParameterGroup', params, ParameterGroup)
-
- def modify_parameter_group(self, name, parameters=None):
- """
- Modify a parameter group for your account.
-
- :type name: string
- :param name: The name of the new parameter group
-
- :type parameters: list of :class:`boto.rds.parametergroup.Parameter`
- :param parameters: The new parameters
-
- :rtype: :class:`boto.rds.parametergroup.ParameterGroup`
- :return: The newly created ParameterGroup
- """
- params = {'DBParameterGroupName': name}
- for i in range(0, len(parameters)):
- parameter = parameters[i]
- parameter.merge(params, i+1)
- return self.get_list('ModifyDBParameterGroup', params,
- ParameterGroup, verb='POST')
-
- def reset_parameter_group(self, name, reset_all_params=False,
- parameters=None):
- """
- Resets some or all of the parameters of a ParameterGroup to the
- default value
-
- :type key_name: string
- :param key_name: The name of the ParameterGroup to reset
-
- :type parameters: list of :class:`boto.rds.parametergroup.Parameter`
- :param parameters: The parameters to reset. If not supplied,
- all parameters will be reset.
- """
- params = {'DBParameterGroupName':name}
- if reset_all_params:
- params['ResetAllParameters'] = 'true'
- else:
- params['ResetAllParameters'] = 'false'
- for i in range(0, len(parameters)):
- parameter = parameters[i]
- parameter.merge(params, i+1)
- return self.get_status('ResetDBParameterGroup', params)
-
- def delete_parameter_group(self, name):
- """
- Delete a DBSecurityGroup from your account.
-
- :type key_name: string
- :param key_name: The name of the DBSecurityGroup to delete
- """
- params = {'DBParameterGroupName':name}
- return self.get_status('DeleteDBParameterGroup', params)
-
- # DBSecurityGroup methods
-
- def get_all_dbsecurity_groups(self, groupname=None, max_records=None,
- marker=None):
- """
- Get all security groups associated with your account in a region.
-
- :type groupnames: list
- :param groupnames: A list of the names of security groups to retrieve.
- If not provided, all security groups will
- be returned.
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: list
- :return: A list of :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
- """
- params = {}
- if groupname:
- params['DBSecurityGroupName'] = groupname
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- return self.get_list('DescribeDBSecurityGroups', params,
- [('DBSecurityGroup', DBSecurityGroup)])
-
- def create_dbsecurity_group(self, name, description=None):
- """
- Create a new security group for your account.
- This will create the security group within the region you
- are currently connected to.
-
- :type name: string
- :param name: The name of the new security group
-
- :type description: string
- :param description: The description of the new security group
-
- :rtype: :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
- :return: The newly created DBSecurityGroup
- """
- params = {'DBSecurityGroupName':name}
- if description:
- params['DBSecurityGroupDescription'] = description
- group = self.get_object('CreateDBSecurityGroup', params,
- DBSecurityGroup)
- group.name = name
- group.description = description
- return group
-
- def delete_dbsecurity_group(self, name):
- """
- Delete a DBSecurityGroup from your account.
-
- :type key_name: string
- :param key_name: The name of the DBSecurityGroup to delete
- """
- params = {'DBSecurityGroupName':name}
- return self.get_status('DeleteDBSecurityGroup', params)
-
- def authorize_dbsecurity_group(self, group_name, cidr_ip=None,
- ec2_security_group_name=None,
- ec2_security_group_owner_id=None):
- """
- Add a new rule to an existing security group.
- You need to pass in either src_security_group_name and
- src_security_group_owner_id OR a CIDR block but not both.
-
- :type group_name: string
- :param group_name: The name of the security group you are adding
- the rule to.
-
- :type ec2_security_group_name: string
- :param ec2_security_group_name: The name of the EC2 security group
- you are granting access to.
-
- :type ec2_security_group_owner_id: string
- :param ec2_security_group_owner_id: The ID of the owner of the EC2
- security group you are granting
- access to.
-
- :type cidr_ip: string
- :param cidr_ip: The CIDR block you are providing access to.
- See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
-
- :rtype: bool
- :return: True if successful.
- """
- params = {'DBSecurityGroupName':group_name}
- if ec2_security_group_name:
- params['EC2SecurityGroupName'] = ec2_security_group_name
- if ec2_security_group_owner_id:
- params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
- if cidr_ip:
- params['CIDRIP'] = urllib.quote(cidr_ip)
- return self.get_object('AuthorizeDBSecurityGroupIngress', params,
- DBSecurityGroup)
-
- def revoke_dbsecurity_group(self, group_name, ec2_security_group_name=None,
- ec2_security_group_owner_id=None, cidr_ip=None):
- """
- Remove an existing rule from an existing security group.
- You need to pass in either ec2_security_group_name and
- ec2_security_group_owner_id OR a CIDR block.
-
- :type group_name: string
- :param group_name: The name of the security group you are removing
- the rule from.
-
- :type ec2_security_group_name: string
- :param ec2_security_group_name: The name of the EC2 security group
- from which you are removing access.
-
- :type ec2_security_group_owner_id: string
- :param ec2_security_group_owner_id: The ID of the owner of the EC2
- security from which you are
- removing access.
-
- :type cidr_ip: string
- :param cidr_ip: The CIDR block from which you are removing access.
- See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
-
- :rtype: bool
- :return: True if successful.
- """
- params = {'DBSecurityGroupName':group_name}
- if ec2_security_group_name:
- params['EC2SecurityGroupName'] = ec2_security_group_name
- if ec2_security_group_owner_id:
- params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
- if cidr_ip:
- params['CIDRIP'] = cidr_ip
- return self.get_object('RevokeDBSecurityGroupIngress', params,
- DBSecurityGroup)
-
- # For backwards compatibility. This method was improperly named
- # in previous versions. I have renamed it to match the others.
- revoke_security_group = revoke_dbsecurity_group
-
- # DBSnapshot methods
-
- def get_all_dbsnapshots(self, snapshot_id=None, instance_id=None,
- max_records=None, marker=None):
- """
- Get information about DB Snapshots.
-
- :type snapshot_id: str
- :param snapshot_id: The unique identifier of an RDS snapshot.
- If not provided, all RDS snapshots will be returned.
-
- :type instance_id: str
- :param instance_id: The identifier of a DBInstance. If provided,
- only the DBSnapshots related to that instance will
- be returned.
- If not provided, all RDS snapshots will be returned.
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: list
- :return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot`
- """
- params = {}
- if snapshot_id:
- params['DBSnapshotIdentifier'] = snapshot_id
- if instance_id:
- params['DBInstanceIdentifier'] = instance_id
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- return self.get_list('DescribeDBSnapshots', params,
- [('DBSnapshot', DBSnapshot)])
-
- def create_dbsnapshot(self, snapshot_id, dbinstance_id):
- """
- Create a new DB snapshot.
-
- :type snapshot_id: string
- :param snapshot_id: The identifier for the DBSnapshot
-
- :type dbinstance_id: string
- :param dbinstance_id: The source identifier for the RDS instance from
- which the snapshot is created.
-
- :rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
- :return: The newly created DBSnapshot
- """
- params = {'DBSnapshotIdentifier' : snapshot_id,
- 'DBInstanceIdentifier' : dbinstance_id}
- return self.get_object('CreateDBSnapshot', params, DBSnapshot)
-
- def delete_dbsnapshot(self, identifier):
- """
- Delete a DBSnapshot
-
- :type identifier: string
- :param identifier: The identifier of the DBSnapshot to delete
- """
- params = {'DBSnapshotIdentifier' : identifier}
- return self.get_object('DeleteDBSnapshot', params, DBSnapshot)
-
- def restore_dbinstance_from_dbsnapshot(self, identifier, instance_id,
- instance_class, port=None,
- availability_zone=None):
-
- """
- Create a new DBInstance from a DB snapshot.
-
- :type identifier: string
- :param identifier: The identifier for the DBSnapshot
-
- :type instance_id: string
- :param instance_id: The source identifier for the RDS instance from
- which the snapshot is created.
-
- :type instance_class: str
- :param instance_class: The compute and memory capacity of the
- DBInstance. Valid values are:
- db.m1.small | db.m1.large | db.m1.xlarge |
- db.m2.2xlarge | db.m2.4xlarge
-
- :type port: int
- :param port: Port number on which database accepts connections.
- Valid values [1115-65535]. Defaults to 3306.
-
- :type availability_zone: str
- :param availability_zone: Name of the availability zone to place
- DBInstance into.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The newly created DBInstance
- """
- params = {'DBSnapshotIdentifier' : identifier,
- 'DBInstanceIdentifier' : instance_id,
- 'DBInstanceClass' : instance_class}
- if port:
- params['Port'] = port
- if availability_zone:
- params['AvailabilityZone'] = availability_zone
- return self.get_object('RestoreDBInstanceFromDBSnapshot',
- params, DBInstance)
-
- def restore_dbinstance_from_point_in_time(self, source_instance_id,
- target_instance_id,
- use_latest=False,
- restore_time=None,
- dbinstance_class=None,
- port=None,
- availability_zone=None):
-
- """
- Create a new DBInstance from a point in time.
-
- :type source_instance_id: string
- :param source_instance_id: The identifier for the source DBInstance.
-
- :type target_instance_id: string
- :param target_instance_id: The identifier of the new DBInstance.
-
- :type use_latest: bool
- :param use_latest: If True, the latest snapshot availabile will
- be used.
-
- :type restore_time: datetime
- :param restore_time: The date and time to restore from. Only
- used if use_latest is False.
-
- :type instance_class: str
- :param instance_class: The compute and memory capacity of the
- DBInstance. Valid values are:
- db.m1.small | db.m1.large | db.m1.xlarge |
- db.m2.2xlarge | db.m2.4xlarge
-
- :type port: int
- :param port: Port number on which database accepts connections.
- Valid values [1115-65535]. Defaults to 3306.
-
- :type availability_zone: str
- :param availability_zone: Name of the availability zone to place
- DBInstance into.
-
- :rtype: :class:`boto.rds.dbinstance.DBInstance`
- :return: The newly created DBInstance
- """
- params = {'SourceDBInstanceIdentifier' : source_instance_id,
- 'TargetDBInstanceIdentifier' : target_instance_id}
- if use_latest:
- params['UseLatestRestorableTime'] = 'true'
- elif restore_time:
- params['RestoreTime'] = restore_time.isoformat()
- if dbinstance_class:
- params['DBInstanceClass'] = dbinstance_class
- if port:
- params['Port'] = port
- if availability_zone:
- params['AvailabilityZone'] = availability_zone
- return self.get_object('RestoreDBInstanceToPointInTime',
- params, DBInstance)
-
- # Events
-
- def get_all_events(self, source_identifier=None, source_type=None,
- start_time=None, end_time=None,
- max_records=None, marker=None):
- """
- Get information about events related to your DBInstances,
- DBSecurityGroups and DBParameterGroups.
-
- :type source_identifier: str
- :param source_identifier: If supplied, the events returned will be
- limited to those that apply to the identified
- source. The value of this parameter depends
- on the value of source_type. If neither
- parameter is specified, all events in the time
- span will be returned.
-
- :type source_type: str
- :param source_type: Specifies how the source_identifier should
- be interpreted. Valid values are:
- b-instance | db-security-group |
- db-parameter-group | db-snapshot
-
- :type start_time: datetime
- :param start_time: The beginning of the time interval for events.
- If not supplied, all available events will
- be returned.
-
- :type end_time: datetime
- :param end_time: The ending of the time interval for events.
- If not supplied, all available events will
- be returned.
-
- :type max_records: int
- :param max_records: The maximum number of records to be returned.
- If more results are available, a MoreToken will
- be returned in the response that can be used to
- retrieve additional records. Default is 100.
-
- :type marker: str
- :param marker: The marker provided by a previous request.
-
- :rtype: list
- :return: A list of class:`boto.rds.event.Event`
- """
- params = {}
- if source_identifier and source_type:
- params['SourceIdentifier'] = source_identifier
- params['SourceType'] = source_type
- if start_time:
- params['StartTime'] = start_time.isoformat()
- if end_time:
- params['EndTime'] = end_time.isoformat()
- if max_records:
- params['MaxRecords'] = max_records
- if marker:
- params['Marker'] = marker
- return self.get_list('DescribeEvents', params, [('Event', Event)])
-
-
diff --git a/boto/rds/connection.py b/boto/rds/connection.py
new file mode 100644
index 00000000..714c7d22
--- /dev/null
+++ b/boto/rds/connection.py
@@ -0,0 +1,951 @@
+# Copyright (c) 2009 Mitch Garnaat http://garnaat.org/
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish, dis-
+# tribute, sublicense, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the fol-
+# lowing conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# 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,
+# 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.
+#
+
+import urllib
+from boto.connection import AWSQueryConnection
+from boto.rds.dbinstance import DBInstance
+from boto.rds.dbsecuritygroup import DBSecurityGroup
+from boto.rds.parametergroup import ParameterGroup
+from boto.rds.dbsnapshot import DBSnapshot
+from boto.rds.event import Event
+from boto.rds.regioninfo import RDSRegionInfo
+
+#boto.set_stream_logger('rds')
+
+
+class RDSConnection(AWSQueryConnection):
+
+ DefaultRegionName = 'us-east-1'
+ DefaultRegionEndpoint = 'rds.us-east-1.amazonaws.com'
+ APIVersion = '2011-04-01'
+
+ 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,
+ https_connection_factory=None, region=None, path='/'):
+ if not region:
+ region = RDSRegionInfo(self, self.DefaultRegionName,
+ self.DefaultRegionEndpoint)
+ self.region = region
+ AWSQueryConnection.__init__(self, aws_access_key_id,
+ aws_secret_access_key,
+ is_secure, port, proxy, proxy_port,
+ proxy_user, proxy_pass,
+ self.region.endpoint, debug,
+ https_connection_factory, path)
+
+ def _required_auth_capability(self):
+ return ['rds']
+
+ # DB Instance methods
+
+ def get_all_dbinstances(self, instance_id=None, max_records=None,
+ marker=None):
+ """
+ Retrieve all the DBInstances in your account.
+
+ :type instance_id: str
+ :param instance_id: DB Instance identifier. If supplied, only
+ information this instance will be returned. Otherwise,
+ info about all DB Instances will be returned.
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: list
+ :return: A list of :class:`boto.rds.dbinstance.DBInstance`
+ """
+ params = {}
+ if instance_id:
+ params['DBInstanceIdentifier'] = instance_id
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ return self.get_list('DescribeDBInstances', params,
+ [('DBInstance', DBInstance)])
+
+ def create_dbinstance(self, id, allocated_storage, instance_class,
+ master_username, master_password, port=3306,
+ engine='MySQL5.1', db_name=None, param_group=None,
+ security_groups=None, availability_zone=None,
+ preferred_maintenance_window=None,
+ backup_retention_period=None,
+ preferred_backup_window=None,
+ multi_az=False,
+ engine_version=None,
+ auto_minor_version_upgrade=True):
+ """
+ Create a new DBInstance.
+
+ :type id: str
+ :param id: Unique identifier for the new instance. Must
+ contain 1-63 alphanumeric characters. First character
+ must be a letter. May not end with a hyphen or contain
+ two consecutive hyphens
+
+ :type allocated_storage: int
+ :param allocated_storage: Initially allocated storage size, in GBs.
+ Valid values are [5-1024]
+
+ :type instance_class: str
+ :param instance_class: The compute and memory capacity of
+ the DBInstance. Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
+
+ :type engine: str
+ :param engine: Name of database engine. Must be MySQL5.1 for now.
+
+ :type master_username: str
+ :param master_username: Name of master user for the DBInstance.
+ Must be 1-15 alphanumeric characters, first must be a letter.
+
+ :type master_password: str
+ :param master_password: Password of master user for the DBInstance.
+ Must be 4-16 alphanumeric characters.
+
+ :type port: int
+ :param port: Port number on which database accepts connections.
+ Valid values [1115-65535]. Defaults to 3306.
+
+ :type db_name: str
+ :param db_name: Name of a database to create when the DBInstance
+ is created. Default is to create no databases.
+
+ :type param_group: str
+ :param param_group: Name of DBParameterGroup to associate with
+ this DBInstance. If no groups are specified
+ no parameter groups will be used.
+
+ :type security_groups: list of str or list of DBSecurityGroup objects
+ :param security_groups: List of names of DBSecurityGroup to
+ authorize on this DBInstance.
+
+ :type availability_zone: str
+ :param availability_zone: Name of the availability zone to place
+ DBInstance into.
+
+ :type preferred_maintenance_window: str
+ :param preferred_maintenance_window: The weekly time range (in UTC)
+ during which maintenance can occur.
+ Default is Sun:05:00-Sun:09:00
+
+ :type backup_retention_period: int
+ :param backup_retention_period: The number of days for which automated
+ backups are retained. Setting this to
+ zero disables automated backups.
+
+ :type preferred_backup_window: str
+ :param preferred_backup_window: The daily time range during which
+ automated backups are created (if enabled). Must be in
+ h24:mi-hh24:mi format (UTC).
+
+ :type multi_az: bool
+ :param multi_az: If True, specifies the DB Instance will be
+ deployed in multiple availability zones.
+
+ :type engine_version: str
+ :param engine_version: Version number of the database engine to use.
+
+ :type auto_minor_version_upgrade: bool
+ :param auto_minor_version_upgrade: Indicates that minor engine
+ upgrades will be applied automatically to the Read Replica
+ during the maintenance window. Default is True.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The new db instance.
+ """
+ params = {'DBInstanceIdentifier': id,
+ 'AllocatedStorage': allocated_storage,
+ 'DBInstanceClass': instance_class,
+ 'Engine': engine,
+ 'MasterUsername': master_username,
+ 'MasterUserPassword': master_password,
+ 'Port': port,
+ 'MultiAZ': str(multi_az).lower(),
+ 'AutoMinorVersionUpgrade':
+ str(auto_minor_version_upgrade).lower()}
+ if db_name:
+ params['DBName'] = db_name
+ if param_group:
+ params['DBParameterGroupName'] = param_group
+ if security_groups:
+ l = []
+ for group in security_groups:
+ if isinstance(group, DBSecurityGroup):
+ l.append(group.name)
+ else:
+ l.append(group)
+ self.build_list_params(params, l, 'DBSecurityGroups.member')
+ if availability_zone:
+ params['AvailabilityZone'] = availability_zone
+ if preferred_maintenance_window:
+ params['PreferredMaintenanceWindow'] = preferred_maintenance_window
+ if backup_retention_period is not None:
+ params['BackupRetentionPeriod'] = backup_retention_period
+ if preferred_backup_window:
+ params['PreferredBackupWindow'] = preferred_backup_window
+ if engine_version:
+ params['EngineVersion'] = engine_version
+
+ return self.get_object('CreateDBInstance', params, DBInstance)
+
+ def create_dbinstance_read_replica(self, id, source_id,
+ instance_class=None,
+ port=3306,
+ availability_zone=None,
+ auto_minor_version_upgrade=None):
+ """
+ Create a new DBInstance Read Replica.
+
+ :type id: str
+ :param id: Unique identifier for the new instance. Must
+ contain 1-63 alphanumeric characters. First character
+ must be a letter. May not end with a hyphen or contain
+ two consecutive hyphens
+
+ :type source_id: str
+ :param source_id: Unique identifier for the DB Instance for which this
+ DB Instance will act as a Read Replica.
+
+ :type instance_class: str
+ :param instance_class: The compute and memory capacity of the
+ DBInstance. Default is to inherit from the source DB
+ Instance. Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
+
+ :type port: int
+ :param port: Port number on which database accepts connections.
+ Default is to inherit from source DB Instance.
+ Valid values [1115-65535]. Defaults to 3306.
+
+ :type availability_zone: str
+ :param availability_zone: Name of the availability zone to place
+ DBInstance into.
+
+ :type auto_minor_version_upgrade: bool
+ :param auto_minor_version_upgrade: Indicates that minor engine
+ upgrades will be applied automatically to the Read Replica
+ during the maintenance window. Default is to inherit this
+ value from the source DB Instance.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The new db instance.
+ """
+ params = {'DBInstanceIdentifier': id,
+ 'SourceDBInstanceIdentifier': source_id}
+ if instance_class:
+ params['DBInstanceClass'] = instance_class
+ if port:
+ params['Port'] = port
+ if availability_zone:
+ params['AvailabilityZone'] = availability_zone
+ if auto_minor_version_upgrade is not None:
+ if auto_minor_version_upgrade is True:
+ params['AutoMinorVersionUpgrade'] = 'true'
+ else:
+ params['AutoMinorVersionUpgrade'] = 'false'
+
+ return self.get_object('CreateDBInstanceReadReplica',
+ params, DBInstance)
+
+ def modify_dbinstance(self, id, param_group=None, security_groups=None,
+ preferred_maintenance_window=None,
+ master_password=None, allocated_storage=None,
+ instance_class=None,
+ backup_retention_period=None,
+ preferred_backup_window=None,
+ multi_az=False,
+ apply_immediately=False):
+ """
+ Modify an existing DBInstance.
+
+ :type id: str
+ :param id: Unique identifier for the new instance.
+
+ :type security_groups: list of str or list of DBSecurityGroup objects
+ :param security_groups: List of names of DBSecurityGroup to
+ authorize on this DBInstance.
+
+ :type preferred_maintenance_window: str
+ :param preferred_maintenance_window: The weekly time range (in UTC)
+ during which maintenance can occur.
+ Default is Sun:05:00-Sun:09:00
+
+ :type master_password: str
+ :param master_password: Password of master user for the DBInstance.
+ Must be 4-15 alphanumeric characters.
+
+ :type allocated_storage: int
+ :param allocated_storage: The new allocated storage size, in GBs.
+ Valid values are [5-1024]
+
+ :type instance_class: str
+ :param instance_class: The compute and memory capacity of the
+ DBInstance. Changes will be applied at
+ next maintenance window unless apply_immediately is True.
+ Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
+
+ :type apply_immediately: bool
+ :param apply_immediately: If true, the modifications will be applied
+ as soon as possible rather than waiting for
+ the next preferred maintenance window.
+
+ :type backup_retention_period: int
+ :param backup_retention_period: The number of days for which automated
+ backups are retained. Setting this to
+ zero disables automated backups.
+
+ :type preferred_backup_window: str
+ :param preferred_backup_window: The daily time range during
+ which automated backups are created (if enabled). Must be
+ in h24:mi-hh24:mi format (UTC).
+
+ :type multi_az: bool
+ :param multi_az: If True, specifies the DB Instance will be
+ deployed in multiple availability zones.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The modified db instance.
+ """
+ params = {'DBInstanceIdentifier': id}
+ if param_group:
+ params['DBParameterGroupName'] = param_group
+ if security_groups:
+ l = []
+ for group in security_groups:
+ if isinstance(group, DBSecurityGroup):
+ l.append(group.name)
+ else:
+ l.append(group)
+ self.build_list_params(params, l, 'DBSecurityGroups.member')
+ if preferred_maintenance_window:
+ params['PreferredMaintenanceWindow'] = preferred_maintenance_window
+ if master_password:
+ params['MasterUserPassword'] = master_password
+ if allocated_storage:
+ params['AllocatedStorage'] = allocated_storage
+ if instance_class:
+ params['DBInstanceClass'] = instance_class
+ if backup_retention_period is not None:
+ params['BackupRetentionPeriod'] = backup_retention_period
+ if preferred_backup_window:
+ params['PreferredBackupWindow'] = preferred_backup_window
+ if multi_az:
+ params['MultiAZ'] = 'true'
+ if apply_immediately:
+ params['ApplyImmediately'] = 'true'
+
+ return self.get_object('ModifyDBInstance', params, DBInstance)
+
+ def delete_dbinstance(self, id, skip_final_snapshot=False,
+ final_snapshot_id=''):
+ """
+ Delete an existing DBInstance.
+
+ :type id: str
+ :param id: Unique identifier for the new instance.
+
+ :type skip_final_snapshot: bool
+ :param skip_final_snapshot: This parameter determines whether
+ a final db snapshot is created before the instance is
+ deleted. If True, no snapshot is created. If False, a
+ snapshot is created before deleting the instance.
+
+ :type final_snapshot_id: str
+ :param final_snapshot_id: If a final snapshot is requested, this
+ is the identifier used for that snapshot.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The deleted db instance.
+ """
+ params = {'DBInstanceIdentifier': id}
+ if skip_final_snapshot:
+ params['SkipFinalSnapshot'] = 'true'
+ else:
+ params['SkipFinalSnapshot'] = 'false'
+ params['FinalDBSnapshotIdentifier'] = final_snapshot_id
+ return self.get_object('DeleteDBInstance', params, DBInstance)
+
+ def reboot_dbinstance(self, id):
+ """
+ Reboot DBInstance.
+
+ :type id: str
+ :param id: Unique identifier of the instance.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The rebooting db instance.
+ """
+ params = {'DBInstanceIdentifier': id}
+ return self.get_object('RebootDBInstance', params, DBInstance)
+
+ # DBParameterGroup methods
+
+ def get_all_dbparameter_groups(self, groupname=None, max_records=None,
+ marker=None):
+ """
+ Get all parameter groups associated with your account in a region.
+
+ :type groupname: str
+ :param groupname: The name of the DBParameter group to retrieve.
+ If not provided, all DBParameter groups will be returned.
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: list
+ :return: A list of :class:`boto.ec2.parametergroup.ParameterGroup`
+ """
+ params = {}
+ if groupname:
+ params['DBParameterGroupName'] = groupname
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ return self.get_list('DescribeDBParameterGroups', params,
+ [('DBParameterGroup', ParameterGroup)])
+
+ def get_all_dbparameters(self, groupname, source=None,
+ max_records=None, marker=None):
+ """
+ Get all parameters associated with a ParameterGroup
+
+ :type groupname: str
+ :param groupname: The name of the DBParameter group to retrieve.
+
+ :type source: str
+ :param source: Specifies which parameters to return.
+ If not specified, all parameters will be returned.
+ Valid values are: user|system|engine-default
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: :class:`boto.ec2.parametergroup.ParameterGroup`
+ :return: The ParameterGroup
+ """
+ params = {'DBParameterGroupName': groupname}
+ if source:
+ params['Source'] = source
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ pg = self.get_object('DescribeDBParameters', params, ParameterGroup)
+ pg.name = groupname
+ return pg
+
+ def create_parameter_group(self, name, engine='MySQL5.1', description=''):
+ """
+ Create a new dbparameter group for your account.
+
+ :type name: string
+ :param name: The name of the new dbparameter group
+
+ :type engine: str
+ :param engine: Name of database engine.
+
+ :type description: string
+ :param description: The description of the new security group
+
+ :rtype: :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
+ :return: The newly created DBSecurityGroup
+ """
+ params = {'DBParameterGroupName': name,
+ 'DBParameterGroupFamily': engine,
+ 'Description': description}
+ return self.get_object('CreateDBParameterGroup', params,
+ ParameterGroup)
+
+ def modify_parameter_group(self, name, parameters=None):
+ """
+ Modify a parameter group for your account.
+
+ :type name: string
+ :param name: The name of the new parameter group
+
+ :type parameters: list of :class:`boto.rds.parametergroup.Parameter`
+ :param parameters: The new parameters
+
+ :rtype: :class:`boto.rds.parametergroup.ParameterGroup`
+ :return: The newly created ParameterGroup
+ """
+ params = {'DBParameterGroupName': name}
+ for i in range(0, len(parameters)):
+ parameter = parameters[i]
+ parameter.merge(params, i + 1)
+ return self.get_list('ModifyDBParameterGroup', params,
+ ParameterGroup, verb='POST')
+
+ def reset_parameter_group(self, name, reset_all_params=False,
+ parameters=None):
+ """
+ Resets some or all of the parameters of a ParameterGroup to the
+ default value
+
+ :type key_name: string
+ :param key_name: The name of the ParameterGroup to reset
+
+ :type parameters: list of :class:`boto.rds.parametergroup.Parameter`
+ :param parameters: The parameters to reset. If not supplied,
+ all parameters will be reset.
+ """
+ params = {'DBParameterGroupName': name}
+ if reset_all_params:
+ params['ResetAllParameters'] = 'true'
+ else:
+ params['ResetAllParameters'] = 'false'
+ for i in range(0, len(parameters)):
+ parameter = parameters[i]
+ parameter.merge(params, i + 1)
+ return self.get_status('ResetDBParameterGroup', params)
+
+ def delete_parameter_group(self, name):
+ """
+ Delete a DBSecurityGroup from your account.
+
+ :type key_name: string
+ :param key_name: The name of the DBSecurityGroup to delete
+ """
+ params = {'DBParameterGroupName': name}
+ return self.get_status('DeleteDBParameterGroup', params)
+
+ # DBSecurityGroup methods
+
+ def get_all_dbsecurity_groups(self, groupname=None, max_records=None,
+ marker=None):
+ """
+ Get all security groups associated with your account in a region.
+
+ :type groupnames: list
+ :param groupnames: A list of the names of security groups to retrieve.
+ If not provided, all security groups will be returned.
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: list
+ :return: A list of :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
+ """
+ params = {}
+ if groupname:
+ params['DBSecurityGroupName'] = groupname
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ return self.get_list('DescribeDBSecurityGroups', params,
+ [('DBSecurityGroup', DBSecurityGroup)])
+
+ def create_dbsecurity_group(self, name, description=None):
+ """
+ Create a new security group for your account.
+ This will create the security group within the region you
+ are currently connected to.
+
+ :type name: string
+ :param name: The name of the new security group
+
+ :type description: string
+ :param description: The description of the new security group
+
+ :rtype: :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
+ :return: The newly created DBSecurityGroup
+ """
+ params = {'DBSecurityGroupName': name}
+ if description:
+ params['DBSecurityGroupDescription'] = description
+ group = self.get_object('CreateDBSecurityGroup', params,
+ DBSecurityGroup)
+ group.name = name
+ group.description = description
+ return group
+
+ def delete_dbsecurity_group(self, name):
+ """
+ Delete a DBSecurityGroup from your account.
+
+ :type key_name: string
+ :param key_name: The name of the DBSecurityGroup to delete
+ """
+ params = {'DBSecurityGroupName': name}
+ return self.get_status('DeleteDBSecurityGroup', params)
+
+ def authorize_dbsecurity_group(self, group_name, cidr_ip=None,
+ ec2_security_group_name=None,
+ ec2_security_group_owner_id=None):
+ """
+ Add a new rule to an existing security group.
+ You need to pass in either src_security_group_name and
+ src_security_group_owner_id OR a CIDR block but not both.
+
+ :type group_name: string
+ :param group_name: The name of the security group you are adding
+ the rule to.
+
+ :type ec2_security_group_name: string
+ :param ec2_security_group_name: The name of the EC2 security group
+ you are granting access to.
+
+ :type ec2_security_group_owner_id: string
+ :param ec2_security_group_owner_id: The ID of the owner of the EC2
+ security group you are granting access to.
+
+ :type cidr_ip: string
+ :param cidr_ip: The CIDR block you are providing access to.
+ See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
+
+ :rtype: bool
+ :return: True if successful.
+ """
+ params = {'DBSecurityGroupName': group_name}
+ if ec2_security_group_name:
+ params['EC2SecurityGroupName'] = ec2_security_group_name
+ if ec2_security_group_owner_id:
+ params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
+ if cidr_ip:
+ params['CIDRIP'] = urllib.quote(cidr_ip)
+ return self.get_object('AuthorizeDBSecurityGroupIngress', params,
+ DBSecurityGroup)
+
+ def revoke_dbsecurity_group(self, group_name,
+ ec2_security_group_name=None,
+ ec2_security_group_owner_id=None,
+ cidr_ip=None):
+ """
+ Remove an existing rule from an existing security group.
+ You need to pass in either ec2_security_group_name and
+ ec2_security_group_owner_id OR a CIDR block.
+
+ :type group_name: string
+ :param group_name: The name of the security group you are removing
+ the rule from.
+
+ :type ec2_security_group_name: string
+ :param ec2_security_group_name: The name of the EC2 security group
+ from which you are removing access.
+
+ :type ec2_security_group_owner_id: string
+ :param ec2_security_group_owner_id: The ID of the owner of the EC2
+ security from which you are removing access.
+
+ :type cidr_ip: string
+ :param cidr_ip: The CIDR block from which you are removing access.
+ See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
+
+ :rtype: bool
+ :return: True if successful.
+ """
+ params = {'DBSecurityGroupName': group_name}
+ if ec2_security_group_name:
+ params['EC2SecurityGroupName'] = ec2_security_group_name
+ if ec2_security_group_owner_id:
+ params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
+ if cidr_ip:
+ params['CIDRIP'] = cidr_ip
+ return self.get_object('RevokeDBSecurityGroupIngress', params,
+ DBSecurityGroup)
+
+ # For backwards compatibility. This method was improperly named
+ # in previous versions. I have renamed it to match the others.
+ revoke_security_group = revoke_dbsecurity_group
+
+ # DBSnapshot methods
+
+ def get_all_dbsnapshots(self, snapshot_id=None, instance_id=None,
+ max_records=None, marker=None):
+ """
+ Get information about DB Snapshots.
+
+ :type snapshot_id: str
+ :param snapshot_id: The unique identifier of an RDS snapshot.
+ If not provided, all RDS snapshots will be returned.
+
+ :type instance_id: str
+ :param instance_id: The identifier of a DBInstance. If
+ provided, only the DBSnapshots related to that instance
+ will be returned. If not provided, all RDS snapshots will
+ be returned.
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: list
+ :return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot`
+ """
+ params = {}
+ if snapshot_id:
+ params['DBSnapshotIdentifier'] = snapshot_id
+ if instance_id:
+ params['DBInstanceIdentifier'] = instance_id
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ return self.get_list('DescribeDBSnapshots', params,
+ [('DBSnapshot', DBSnapshot)])
+
+ def create_dbsnapshot(self, snapshot_id, dbinstance_id):
+ """
+ Create a new DB snapshot.
+
+ :type snapshot_id: string
+ :param snapshot_id: The identifier for the DBSnapshot
+
+ :type dbinstance_id: string
+ :param dbinstance_id: The source identifier for the RDS instance from
+ which the snapshot is created.
+
+ :rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
+ :return: The newly created DBSnapshot
+ """
+ params = {'DBSnapshotIdentifier': snapshot_id,
+ 'DBInstanceIdentifier': dbinstance_id}
+ return self.get_object('CreateDBSnapshot', params, DBSnapshot)
+
+ def delete_dbsnapshot(self, identifier):
+ """
+ Delete a DBSnapshot
+
+ :type identifier: string
+ :param identifier: The identifier of the DBSnapshot to delete
+ """
+ params = {'DBSnapshotIdentifier': identifier}
+ return self.get_object('DeleteDBSnapshot', params, DBSnapshot)
+
+ def restore_dbinstance_from_dbsnapshot(self, identifier, instance_id,
+ instance_class, port=None,
+ availability_zone=None):
+
+ """
+ Create a new DBInstance from a DB snapshot.
+
+ :type identifier: string
+ :param identifier: The identifier for the DBSnapshot
+
+ :type instance_id: string
+ :param instance_id: The source identifier for the RDS instance from
+ which the snapshot is created.
+
+ :type instance_class: str
+ :param instance_class: The compute and memory capacity of
+ the DBInstance. Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
+
+ :type port: int
+ :param port: Port number on which database accepts connections.
+ Valid values [1115-65535]. Defaults to 3306.
+
+ :type availability_zone: str
+ :param availability_zone: Name of the availability zone to place
+ DBInstance into.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The newly created DBInstance
+ """
+ params = {'DBSnapshotIdentifier': identifier,
+ 'DBInstanceIdentifier': instance_id,
+ 'DBInstanceClass': instance_class}
+ if port:
+ params['Port'] = port
+ if availability_zone:
+ params['AvailabilityZone'] = availability_zone
+ return self.get_object('RestoreDBInstanceFromDBSnapshot',
+ params, DBInstance)
+
+ def restore_dbinstance_from_point_in_time(self, source_instance_id,
+ target_instance_id,
+ use_latest=False,
+ restore_time=None,
+ dbinstance_class=None,
+ port=None,
+ availability_zone=None):
+
+ """
+ Create a new DBInstance from a point in time.
+
+ :type source_instance_id: string
+ :param source_instance_id: The identifier for the source DBInstance.
+
+ :type target_instance_id: string
+ :param target_instance_id: The identifier of the new DBInstance.
+
+ :type use_latest: bool
+ :param use_latest: If True, the latest snapshot availabile will
+ be used.
+
+ :type restore_time: datetime
+ :param restore_time: The date and time to restore from. Only
+ used if use_latest is False.
+
+ :type instance_class: str
+ :param instance_class: The compute and memory capacity of
+ the DBInstance. Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
+
+ :type port: int
+ :param port: Port number on which database accepts connections.
+ Valid values [1115-65535]. Defaults to 3306.
+
+ :type availability_zone: str
+ :param availability_zone: Name of the availability zone to place
+ DBInstance into.
+
+ :rtype: :class:`boto.rds.dbinstance.DBInstance`
+ :return: The newly created DBInstance
+ """
+ params = {'SourceDBInstanceIdentifier': source_instance_id,
+ 'TargetDBInstanceIdentifier': target_instance_id}
+ if use_latest:
+ params['UseLatestRestorableTime'] = 'true'
+ elif restore_time:
+ params['RestoreTime'] = restore_time.isoformat()
+ if dbinstance_class:
+ params['DBInstanceClass'] = dbinstance_class
+ if port:
+ params['Port'] = port
+ if availability_zone:
+ params['AvailabilityZone'] = availability_zone
+ return self.get_object('RestoreDBInstanceToPointInTime',
+ params, DBInstance)
+
+ # Events
+
+ def get_all_events(self, source_identifier=None, source_type=None,
+ start_time=None, end_time=None,
+ max_records=None, marker=None):
+ """
+ Get information about events related to your DBInstances,
+ DBSecurityGroups and DBParameterGroups.
+
+ :type source_identifier: str
+ :param source_identifier: If supplied, the events returned
+ will be limited to those that apply to the identified
+ source. The value of this parameter depends on the value
+ of source_type. If neither parameter is specified, all
+ events in the time span will be returned.
+
+ :type source_type: str
+ :param source_type: Specifies how the source_identifier should
+ be interpreted. Valid values are:
+
+ * b-instance
+ * db-security-group
+ * db-parameter-group
+ * db-snapshot
+
+ :type start_time: datetime
+ :param start_time: The beginning of the time interval for events.
+ If not supplied, all available events will be returned.
+
+ :type end_time: datetime
+ :param end_time: The ending of the time interval for events.
+ If not supplied, all available events will be returned.
+
+ :type max_records: int
+ :param max_records: The maximum number of records to be
+ returned. If more results are available, a MoreToken will
+ be returned in the response that can be used to retrieve
+ additional records. Default is 100.
+
+ :type marker: str
+ :param marker: The marker provided by a previous request.
+
+ :rtype: list
+ :return: A list of class:`boto.rds.event.Event`
+ """
+ params = {}
+ if source_identifier and source_type:
+ params['SourceIdentifier'] = source_identifier
+ params['SourceType'] = source_type
+ if start_time:
+ params['StartTime'] = start_time.isoformat()
+ if end_time:
+ params['EndTime'] = end_time.isoformat()
+ if max_records:
+ params['MaxRecords'] = max_records
+ if marker:
+ params['Marker'] = marker
+ return self.get_list('DescribeEvents', params, [('Event', Event)])
diff --git a/boto/rds/dbinstance.py b/boto/rds/dbinstance.py
index 02f9af6a..6ed675ff 100644
--- a/boto/rds/dbinstance.py
+++ b/boto/rds/dbinstance.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.
@@ -22,11 +22,12 @@
from boto.rds.dbsecuritygroup import DBSecurityGroup
from boto.rds.parametergroup import ParameterGroup
+
class DBInstance(object):
"""
Represents a RDS DBInstance
"""
-
+
def __init__(self, connection=None, id=None):
self.connection = connection
self.id = id
@@ -112,10 +113,10 @@ class DBInstance(object):
def snapshot(self, snapshot_id):
"""
Create a new DB snapshot of this DBInstance.
-
+
:type identifier: string
:param identifier: The identifier for the DBSnapshot
-
+
:rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
:return: The newly created DBSnapshot
"""
@@ -124,7 +125,7 @@ class DBInstance(object):
def reboot(self):
"""
Reboot this DBInstance
-
+
:rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
:return: The newly created DBSnapshot
"""
@@ -137,10 +138,9 @@ class DBInstance(object):
:type validate: bool
:param validate: By default, if EC2 returns no data about the
- instance the update method returns quietly. If
- the validate param is True, however, it will
- raise a ValueError exception if no data is
- returned from EC2.
+ instance the update method returns quietly. If the
+ validate param is True, however, it will raise a
+ ValueError exception if no data is returned from EC2.
"""
rs = self.connection.get_all_dbinstances(self.id)
if len(rs) > 0:
@@ -151,21 +151,19 @@ class DBInstance(object):
raise ValueError('%s is not a valid Instance ID' % self.id)
return self.status
-
def stop(self, skip_final_snapshot=False, final_snapshot_id=''):
"""
Delete this DBInstance.
:type skip_final_snapshot: bool
- :param skip_final_snapshot: This parameter determines whether a final
- db snapshot is created before the instance
- is deleted. If True, no snapshot is created.
- If False, a snapshot is created before
- deleting the instance.
+ :param skip_final_snapshot: This parameter determines whether
+ a final db snapshot is created before the instance is
+ deleted. If True, no snapshot is created. If False, a
+ snapshot is created before deleting the instance.
:type final_snapshot_id: str
:param final_snapshot_id: If a final snapshot is requested, this
- is the identifier used for that snapshot.
+ is the identifier used for that snapshot.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The deleted db instance.
@@ -186,57 +184,51 @@ class DBInstance(object):
Modify this DBInstance.
:type security_groups: list of str or list of DBSecurityGroup objects
- :param security_groups: List of names of DBSecurityGroup to authorize on
- this DBInstance.
+ :param security_groups: List of names of DBSecurityGroup to
+ authorize on this DBInstance.
:type preferred_maintenance_window: str
- :param preferred_maintenance_window: The weekly time range (in UTC)
- during which maintenance can
- occur.
- Default is Sun:05:00-Sun:09:00
+ :param preferred_maintenance_window: The weekly time range (in
+ UTC) during which maintenance can occur. Default is
+ Sun:05:00-Sun:09:00
:type master_password: str
:param master_password: Password of master user for the DBInstance.
- Must be 4-15 alphanumeric characters.
+ Must be 4-15 alphanumeric characters.
:type allocated_storage: int
:param allocated_storage: The new allocated storage size, in GBs.
- Valid values are [5-1024]
+ Valid values are [5-1024]
:type instance_class: str
- :param instance_class: The compute and memory capacity of the
- DBInstance. Changes will be applied at
- next maintenance window unless
- apply_immediately is True.
-
- Valid values are:
-
- * db.m1.small
- * db.m1.large
- * db.m1.xlarge
- * db.m2.xlarge
- * db.m2.2xlarge
- * db.m2.4xlarge
+ :param instance_class: The compute and memory capacity of
+ the DBInstance. Valid values are:
+
+ * db.m1.small
+ * db.m1.large
+ * db.m1.xlarge
+ * db.m2.xlarge
+ * db.m2.2xlarge
+ * db.m2.4xlarge
:type apply_immediately: bool
:param apply_immediately: If true, the modifications will be applied
- as soon as possible rather than waiting for
- the next preferred maintenance window.
+ as soon as possible rather than waiting for
+ the next preferred maintenance window.
:type backup_retention_period: int
:param backup_retention_period: The number of days for which automated
- backups are retained. Setting this to
- zero disables automated backups.
+ backups are retained. Setting this to
+ zero disables automated backups.
:type preferred_backup_window: str
:param preferred_backup_window: The daily time range during which
- automated backups are created (if
- enabled). Must be in h24:mi-hh24:mi
- format (UTC).
+ automated backups are created (if enabled).
+ Must be in h24:mi-hh24:mi format (UTC).
:type multi_az: bool
:param multi_az: If True, specifies the DB Instance will be
- deployed in multiple availability zones.
+ deployed in multiple availability zones.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The modified db instance.
@@ -252,7 +244,8 @@ class DBInstance(object):
preferred_backup_window,
multi_az,
apply_immediately)
-
+
+
class PendingModifiedValues(dict):
def startElement(self, name, attrs, connection):
@@ -261,4 +254,3 @@ class PendingModifiedValues(dict):
def endElement(self, name, value, connection):
if name != 'PendingModifiedValues':
self[name] = value
-
diff --git a/boto/rds/dbsecuritygroup.py b/boto/rds/dbsecuritygroup.py
index 1555ca07..c70ab759 100644
--- a/boto/rds/dbsecuritygroup.py
+++ b/boto/rds/dbsecuritygroup.py
@@ -24,6 +24,7 @@ Represents an DBSecurityGroup
"""
from boto.ec2.securitygroup import SecurityGroup
+
class DBSecurityGroup(object):
def __init__(self, connection=None, owner_id=None,
@@ -116,6 +117,7 @@ class DBSecurityGroup(object):
return self.connection.revoke_dbsecurity_group(
self.name, cidr_ip=cidr_ip)
+
class IPRange(object):
def __init__(self, parent=None):
@@ -137,6 +139,7 @@ class IPRange(object):
else:
setattr(self, name, value)
+
class EC2SecurityGroup(object):
def __init__(self, parent=None):
@@ -157,4 +160,3 @@ class EC2SecurityGroup(object):
self.owner_id = value
else:
setattr(self, name, value)
-
diff --git a/boto/rds/dbsnapshot.py b/boto/rds/dbsnapshot.py
index 78d0230c..19e29521 100644
--- a/boto/rds/dbsnapshot.py
+++ b/boto/rds/dbsnapshot.py
@@ -14,16 +14,17 @@
# 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 DBSnapshot(object):
"""
Represents a RDS DB Snapshot
"""
-
+
def __init__(self, connection=None, id=None):
self.connection = connection
self.id = id
@@ -69,6 +70,3 @@ class DBSnapshot(object):
self.time = value
else:
setattr(self, name, value)
-
-
-
diff --git a/boto/rds/event.py b/boto/rds/event.py
index a91f8f08..37599989 100644
--- a/boto/rds/event.py
+++ b/boto/rds/event.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 Event(object):
def __init__(self, connection=None):
@@ -28,7 +29,7 @@ class Event(object):
self.source_type = None
self.engine = None
self.date = None
-
+
def __repr__(self):
return '"%s"' % self.message
@@ -46,4 +47,3 @@ class Event(object):
self.date = value
else:
setattr(self, name, value)
-
diff --git a/boto/rds/parametergroup.py b/boto/rds/parametergroup.py
index e973467c..ab3c670d 100644
--- a/boto/rds/parametergroup.py
+++ b/boto/rds/parametergroup.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.
@@ -31,7 +31,7 @@ class ParameterGroup(dict):
self.description = None
self.engine = None
self._current_param = None
-
+
def __repr__(self):
return 'ParameterGroup:%s' % self.name
@@ -63,7 +63,7 @@ class ParameterGroup(dict):
def get_params(self):
pg = self.connection.get_all_dbparameters(self.name)
self.update(pg)
-
+
def add_param(self, name, value, apply_method):
param = Parameter()
param.name = name
@@ -71,18 +71,19 @@ class ParameterGroup(dict):
param.apply_method = apply_method
self.params.append(param)
+
class Parameter(object):
"""
Represents a RDS Parameter
"""
- ValidTypes = {'integer' : int,
- 'string' : str,
- 'boolean' : bool}
+ ValidTypes = {'integer': int,
+ 'string': str,
+ 'boolean': bool}
ValidSources = ['user', 'system', 'engine-default']
ValidApplyTypes = ['static', 'dynamic']
ValidApplyMethods = ['immediate', 'pending-reboot']
-
+
def __init__(self, group=None, name=None):
self.group = group
self.name = name
@@ -129,11 +130,11 @@ class Parameter(object):
def merge(self, d, i):
prefix = 'Parameters.member.%d.' % i
if self.name:
- d[prefix+'ParameterName'] = self.name
+ d[prefix + 'ParameterName'] = self.name
if self._value:
- d[prefix+'ParameterValue'] = self._value
+ d[prefix + 'ParameterValue'] = self._value
if self.apply_type:
- d[prefix+'ApplyMethod'] = self.apply_method
+ d[prefix + 'ApplyMethod'] = self.apply_method
def _set_string_value(self, value):
if not isinstance(value, compat.string_types):
@@ -152,7 +153,7 @@ class Parameter(object):
self._value = False
else:
raise ValueError('value must be boolean')
-
+
def set_value(self, value):
if self.type == 'string':
self._set_string_value(value)
@@ -187,4 +188,3 @@ class Parameter(object):
else:
self.apply_method = 'pending-reboot'
self.group.connection.modify_parameter_group(self.group.name, [self])
-
diff --git a/boto/rds/regioninfo.py b/boto/rds/regioninfo.py
index 7d186ae0..05a6661a 100644
--- a/boto/rds/regioninfo.py
+++ b/boto/rds/regioninfo.py
@@ -16,7 +16,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.
@@ -24,9 +24,10 @@
from boto.regioninfo import RegionInfo
+
class RDSRegionInfo(RegionInfo):
def __init__(self, connection=None, name=None, endpoint=None):
- from boto.rds import RDSConnection
+ from boto.rds.connection import RDSConnection
RegionInfo.__init__(self, connection, name, endpoint,
RDSConnection)
diff --git a/boto/roboto/__init__.py b/boto/roboto/__init__.py
deleted file mode 100644
index 792d6005..00000000
--- a/boto/roboto/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-#
diff --git a/boto/roboto/awsqueryrequest.py b/boto/roboto/awsqueryrequest.py
deleted file mode 100644
index 3fdaf07b..00000000
--- a/boto/roboto/awsqueryrequest.py
+++ /dev/null
@@ -1,504 +0,0 @@
-# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
-# Copyright (c) 2010, Eucalyptus Systems, Inc.
-#
-# Permission is hereby granted, free of charge, to any person obtaining a
-# copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish, dis-
-# tribute, sublicense, and/or sell copies of the Software, and to permit
-# persons to whom the Software is furnished to do so, subject to the fol-
-# lowing conditions:
-#
-# The above copyright notice and this permission notice shall be included
-# in all copies or substantial portions of the Software.
-#
-# 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,
-# 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.
-
-import sys
-import os
-import boto
-import optparse
-import copy
-import boto.exception
-import boto.roboto.awsqueryservice
-
-import bdb
-import traceback
-try:
- import epdb as debugger
-except ImportError:
- import pdb as debugger
-
-def boto_except_hook(debugger_flag, debug_flag):
- def excepthook(typ, value, tb):
- if typ is bdb.BdbQuit:
- sys.exit(1)
- sys.excepthook = sys.__excepthook__
-
- if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
- if debugger.__name__ == 'epdb':
- debugger.post_mortem(tb, typ, value)
- else:
- debugger.post_mortem(tb)
- elif debug_flag:
- print(traceback.print_tb(tb))
- sys.exit(1)
- else:
- print(value)
- sys.exit(1)
-
- return excepthook
-
-class Line(object):
-
- def __init__(self, fmt, data, label):
- self.fmt = fmt
- self.data = data
- self.label = label
- self.line = '%s\t' % label
- self.printed = False
-
- def append(self, datum):
- self.line += '%s\t' % datum
-
- def print_it(self):
- if not self.printed:
- print(self.line)
- self.printed = True
-
-class RequiredParamError(boto.exception.BotoClientError):
-
- def __init__(self, required):
- self.required = required
- s = 'Required parameters are missing: %s' % self.required
- boto.exception.BotoClientError.__init__(self, s)
-
-class EncoderError(boto.exception.BotoClientError):
-
- def __init__(self, error_msg):
- s = 'Error encoding value (%s)' % error_msg
- boto.exception.BotoClientError.__init__(self, s)
-
-class FilterError(boto.exception.BotoClientError):
-
- def __init__(self, filters):
- self.filters = filters
- s = 'Unknown filters: %s' % self.filters
- boto.exception.BotoClientError.__init__(self, s)
-
-class Encoder:
-
- @classmethod
- def encode(cls, p, rp, v, label=None):
- if p.name.startswith('_'):
- return
- try:
- mthd = getattr(cls, 'encode_'+p.ptype)
- mthd(p, rp, v, label)
- except AttributeError:
- raise EncoderError('Unknown type: %s' % p.ptype)
-
- @classmethod
- def encode_string(cls, p, rp, v, l):
- if l:
- label = l
- else:
- label = p.name
- rp[label] = v
-
- encode_file = encode_string
- encode_enum = encode_string
-
- @classmethod
- def encode_integer(cls, p, rp, v, l):
- if l:
- label = l
- else:
- label = p.name
- rp[label] = '%d' % v
-
- @classmethod
- def encode_boolean(cls, p, rp, v, l):
- if l:
- label = l
- else:
- label = p.name
- if v:
- v = 'true'
- else:
- v = 'false'
- rp[label] = v
-
- @classmethod
- def encode_datetime(cls, p, rp, v, l):
- if l:
- label = l
- else:
- label = p.name
- rp[label] = v
-
- @classmethod
- def encode_array(cls, p, rp, v, l):
- v = boto.utils.mklist(v)
- if l:
- label = l
- else:
- label = p.name
- label = label + '.%d'
- for i, value in enumerate(v):
- rp[label%(i+1)] = value
-
-class AWSQueryRequest(object):
-
- ServiceClass = None
-
- Description = ''
- Params = []
- Args = []
- Filters = []
- Response = {}
-
- CLITypeMap = {'string' : 'string',
- 'integer' : 'int',
- 'int' : 'int',
- 'enum' : 'choice',
- 'datetime' : 'string',
- 'dateTime' : 'string',
- 'file' : 'string',
- 'boolean' : None}
-
- @classmethod
- def name(cls):
- return cls.__name__
-
- def __init__(self, **args):
- self.args = args
- self.parser = None
- self.cli_options = None
- self.cli_args = None
- self.cli_output_format = None
- self.connection = None
- self.list_markers = []
- self.item_markers = []
- self.request_params = {}
- self.connection_args = None
-
- def __repr__(self):
- return self.name()
-
- def get_connection(self, **args):
- if self.connection is None:
- self.connection = self.ServiceClass(**args)
- return self.connection
-
- @property
- def status(self):
- retval = None
- if self.http_response is not None:
- retval = self.http_response.status
- return retval
-
- @property
- def reason(self):
- retval = None
- if self.http_response is not None:
- retval = self.http_response.reason
- return retval
-
- @property
- def request_id(self):
- retval = None
- if self.aws_response is not None:
- retval = getattr(self.aws_response, 'requestId')
- return retval
-
- def process_filters(self):
- filters = self.args.get('filters', [])
- filter_names = [f['name'] for f in self.Filters]
- unknown_filters = [f for f in filters if f not in filter_names]
- if unknown_filters:
- raise FilterError('Unknown filters: %s' % unknown_filters)
- for i, filter in enumerate(self.Filters):
- name = filter['name']
- if name in filters:
- self.request_params['Filter.%d.Name' % (i+1)] = name
- for j, value in enumerate(boto.utils.mklist(filters[name])):
- Encoder.encode(filter, self.request_params, value,
- 'Filter.%d.Value.%d' % (i+1,j+1))
-
- def process_args(self, **args):
- """
- Responsible for walking through Params defined for the request and:
-
- * Matching them with keyword parameters passed to the request
- constructor or via the command line.
- * Checking to see if all required parameters have been specified
- and raising an exception, if not.
- * Encoding each value into the set of request parameters that will
- be sent in the request to the AWS service.
- """
- self.args.update(args)
- self.connection_args = copy.copy(self.args)
- if 'debug' in self.args and self.args['debug'] >= 2:
- boto.set_stream_logger(self.name())
- required = [p.name for p in self.Params+self.Args if not p.optional]
- for param in self.Params+self.Args:
- if param.long_name:
- python_name = param.long_name.replace('-', '_')
- else:
- python_name = boto.utils.pythonize_name(param.name, '_')
- value = None
- if python_name in self.args:
- value = self.args[python_name]
- if value is None:
- value = param.default
- if value is not None:
- if param.name in required:
- required.remove(param.name)
- if param.request_param:
- if param.encoder:
- param.encoder(param, self.request_params, value)
- else:
- Encoder.encode(param, self.request_params, value)
- if python_name in self.args:
- del self.connection_args[python_name]
- if required:
- l = []
- for p in self.Params+self.Args:
- if p.name in required:
- if p.short_name and p.long_name:
- l.append('(%s, %s)' % (p.optparse_short_name,
- p.optparse_long_name))
- elif p.short_name:
- l.append('(%s)' % p.optparse_short_name)
- else:
- l.append('(%s)' % p.optparse_long_name)
- raise RequiredParamError(','.join(l))
- boto.log.debug('request_params: %s' % self.request_params)
- self.process_markers(self.Response)
-
- def process_markers(self, fmt, prev_name=None):
- if fmt and fmt['type'] == 'object':
- for prop in fmt['properties']:
- self.process_markers(prop, fmt['name'])
- elif fmt and fmt['type'] == 'array':
- self.list_markers.append(prev_name)
- self.item_markers.append(fmt['name'])
-
- def send(self, verb='GET', **args):
- self.process_args(**args)
- self.process_filters()
- conn = self.get_connection(**self.connection_args)
- self.http_response = conn.make_request(self.name(),
- self.request_params,
- verb=verb)
- self.body = self.http_response.read()
- boto.log.debug(self.body)
- if self.http_response.status == 200:
- self.aws_response = boto.jsonresponse.Element(list_marker=self.list_markers,
- item_marker=self.item_markers)
- h = boto.jsonresponse.XmlHandler(self.aws_response, self)
- h.parse(self.body)
- return self.aws_response
- else:
- boto.log.error('%s %s' % (self.http_response.status,
- self.http_response.reason))
- boto.log.error('%s' % self.body)
- raise conn.ResponseError(self.http_response.status,
- self.http_response.reason,
- self.body)
-
- def add_standard_options(self):
- group = optparse.OptionGroup(self.parser, 'Standard Options')
- # add standard options that all commands get
- group.add_option('-D', '--debug', action='store_true',
- help='Turn on all debugging output')
- group.add_option('--debugger', action='store_true',
- default=False,
- help='Enable interactive debugger on error')
- group.add_option('-U', '--url', action='store',
- help='Override service URL with value provided')
- group.add_option('--region', action='store',
- help='Name of the region to connect to')
- group.add_option('-I', '--access-key-id', action='store',
- help='Override access key value')
- group.add_option('-S', '--secret-key', action='store',
- help='Override secret key value')
- group.add_option('--version', action='store_true',
- help='Display version string')
- if self.Filters:
- self.group.add_option('--help-filters', action='store_true',
- help='Display list of available filters')
- self.group.add_option('--filter', action='append',
- metavar=' name=value',
- help='A filter for limiting the results')
- self.parser.add_option_group(group)
-
- def process_standard_options(self, options, args, d):
- if hasattr(options, 'help_filters') and options.help_filters:
- print('Available filters:')
- for filter in self.Filters:
- print('%s\t%s' % (filter.name, filter.doc))
- sys.exit(0)
- if options.debug:
- self.args['debug'] = 2
- if options.url:
- self.args['url'] = options.url
- if options.region:
- self.args['region'] = options.region
- if options.access_key_id:
- self.args['aws_access_key_id'] = options.access_key_id
- if options.secret_key:
- self.args['aws_secret_access_key'] = options.secret_key
- if options.version:
- # TODO - Where should the version # come from?
- print('version x.xx')
- exit(0)
- sys.excepthook = boto_except_hook(options.debugger,
- options.debug)
-
- def get_usage(self):
- s = 'usage: %prog [options] '
- l = [ a.long_name for a in self.Args ]
- s += ' '.join(l)
- for a in self.Args:
- if a.doc:
- s += '\n\n\t%s - %s' % (a.long_name, a.doc)
- return s
-
- def build_cli_parser(self):
- self.parser = optparse.OptionParser(description=self.Description,
- usage=self.get_usage())
- self.add_standard_options()
- for param in self.Params:
- ptype = action = choices = None
- if param.ptype in self.CLITypeMap:
- ptype = self.CLITypeMap[param.ptype]
- action = 'store'
- if param.ptype == 'boolean':
- action = 'store_true'
- elif param.ptype == 'array':
- if len(param.items) == 1:
- ptype = param.items[0]['type']
- action = 'append'
- elif param.cardinality != 1:
- action = 'append'
- if ptype or action == 'store_true':
- if param.short_name:
- self.parser.add_option(param.optparse_short_name,
- param.optparse_long_name,
- action=action, type=ptype,
- choices=param.choices,
- help=param.doc)
- elif param.long_name:
- self.parser.add_option(param.optparse_long_name,
- action=action, type=ptype,
- choices=param.choices,
- help=param.doc)
-
- def do_cli(self):
- if not self.parser:
- self.build_cli_parser()
- self.cli_options, self.cli_args = self.parser.parse_args()
- d = {}
- self.process_standard_options(self.cli_options, self.cli_args, d)
- for param in self.Params:
- if param.long_name:
- p_name = param.long_name.replace('-', '_')
- else:
- p_name = boto.utils.pythonize_name(param.name)
- value = getattr(self.cli_options, p_name)
- if param.ptype == 'file' and value:
- if value == '-':
- value = sys.stdin.read()
- else:
- path = os.path.expanduser(value)
- path = os.path.expandvars(path)
- if os.path.isfile(path):
- fp = open(path)
- value = fp.read()
- fp.close()
- else:
- self.parser.error('Unable to read file: %s' % path)
- d[p_name] = value
- for arg in self.Args:
- if arg.long_name:
- p_name = arg.long_name.replace('-', '_')
- else:
- p_name = boto.utils.pythonize_name(arg.name)
- value = None
- if arg.cardinality == 1:
- if len(self.cli_args) >= 1:
- value = self.cli_args[0]
- else:
- value = self.cli_args
- d[p_name] = value
- self.args.update(d)
- if hasattr(self.cli_options, 'filter') and self.cli_options.filter:
- d = {}
- for filter in self.cli_options.filter:
- name, value = filter.split('=')
- d[name] = value
- if 'filters' in self.args:
- self.args['filters'].update(d)
- else:
- self.args['filters'] = d
- try:
- response = self.main()
- self.cli_formatter(response)
- except RequiredParamError as e:
- print(e)
- sys.exit(1)
- except self.ServiceClass.ResponseError as err:
- print('Error(%s): %s' % (err.error_code, err.error_message))
- sys.exit(1)
- except boto.roboto.awsqueryservice.NoCredentialsError as err:
- print('Unable to find credentials.')
- sys.exit(1)
- except Exception as e:
- print(e)
- sys.exit(1)
-
- def _generic_cli_formatter(self, fmt, data, label=''):
- if fmt['type'] == 'object':
- for prop in fmt['properties']:
- if 'name' in fmt:
- if fmt['name'] in data:
- data = data[fmt['name']]
- if fmt['name'] in self.list_markers:
- label = fmt['name']
- if label[-1] == 's':
- label = label[0:-1]
- label = label.upper()
- self._generic_cli_formatter(prop, data, label)
- elif fmt['type'] == 'array':
- for item in data:
- line = Line(fmt, item, label)
- if isinstance(item, dict):
- for field_name in item:
- line.append(item[field_name])
- elif isinstance(item, basestring):
- line.append(item)
- line.print_it()
-
- def cli_formatter(self, data):
- """
- This method is responsible for formatting the output for the
- command line interface. The default behavior is to call the
- generic CLI formatter which attempts to print something
- reasonable. If you want specific formatting, you should
- override this method and do your own thing.
-
- :type data: dict
- :param data: The data returned by AWS.
- """
- if data:
- self._generic_cli_formatter(self.Response, data)
-
-
diff --git a/boto/roboto/awsqueryservice.py b/boto/roboto/awsqueryservice.py
deleted file mode 100644
index 0b3db140..00000000
--- a/boto/roboto/awsqueryservice.py
+++ /dev/null
@@ -1,122 +0,0 @@
-import os
-import boto
-import boto.connection
-import boto.jsonresponse
-import boto.exception
-import boto.compat as compat
-from . import awsqueryrequest
-
-
-class NoCredentialsError(boto.exception.BotoClientError):
-
- def __init__(self):
- s = 'Unable to find credentials'
- boto.exception.BotoClientError.__init__(self, s)
-
-class AWSQueryService(boto.connection.AWSQueryConnection):
-
- Name = ''
- Description = ''
- APIVersion = ''
- Authentication = 'sign-v2'
- Path = '/'
- Port = 443
- Provider = 'aws'
- EnvURL = 'AWS_URL'
-
- Regions = []
-
- def __init__(self, **args):
- self.args = args
- self.check_for_credential_file()
- self.check_for_env_url()
- if 'host' not in self.args:
- if self.Regions:
- region_name = self.args.get('region_name',
- self.Regions[0]['name'])
- for region in self.Regions:
- if region['name'] == region_name:
- self.args['host'] = region['endpoint']
- if 'path' not in self.args:
- self.args['path'] = self.Path
- if 'port' not in self.args:
- self.args['port'] = self.Port
- try:
- boto.connection.AWSQueryConnection.__init__(self, **self.args)
- self.aws_response = None
- except boto.exception.NoAuthHandlerFound:
- raise NoCredentialsError()
-
- def check_for_credential_file(self):
- """
- Checks for the existance of an AWS credential file.
- If the environment variable AWS_CREDENTIAL_FILE is
- set and points to a file, that file will be read and
- will be searched credentials.
- Note that if credentials have been explicitelypassed
- into the class constructor, those values always take
- precedence.
- """
- if 'AWS_CREDENTIAL_FILE' in os.environ:
- path = os.environ['AWS_CREDENTIAL_FILE']
- path = os.path.expanduser(path)
- path = os.path.expandvars(path)
- if os.path.isfile(path):
- fp = open(path)
- lines = fp.readlines()
- fp.close()
- for line in lines:
- if line[0] != '#':
- if '=' in line:
- name, value = line.split('=', 1)
- if name.strip() == 'AWSAccessKeyId':
- if 'aws_access_key_id' not in self.args:
- value = value.strip()
- self.args['aws_access_key_id'] = value
- elif name.strip() == 'AWSSecretKey':
- if 'aws_secret_access_key' not in self.args:
- value = value.strip()
- self.args['aws_secret_access_key'] = value
- else:
- print('Warning: unable to read AWS_CREDENTIAL_FILE')
-
- def check_for_env_url(self):
- """
- First checks to see if a url argument was explicitly passed
- in. If so, that will be used. If not, it checks for the
- existence of the environment variable specified in ENV_URL.
- If this is set, it should contain a fully qualified URL to the
- service you want to use.
- Note that any values passed explicitly to the class constructor
- will take precedence.
- """
- url = self.args.get('url', None)
- if url:
- del self.args['url']
- if not url and self.EnvURL in os.environ:
- url = os.environ[self.EnvURL]
- if url:
- rslt = compat.urlparse.urlparse(url)
- if 'is_secure' not in self.args:
- if rslt.scheme == 'https':
- self.args['is_secure'] = True
- else:
- self.args['is_secure'] = False
-
- host = rslt.netloc
- port = None
- l = host.split(':')
- if len(l) > 1:
- host = l[0]
- port = int(l[1])
- if 'host' not in self.args:
- self.args['host'] = host
- if port and 'port' not in self.args:
- self.args['port'] = port
-
- if rslt.path and 'path' not in self.args:
- self.args['path'] = rslt.path
-
- def _required_auth_capability(self):
- return [self.Authentication]
-
diff --git a/boto/roboto/param.py b/boto/roboto/param.py
deleted file mode 100644
index 61364003..00000000
--- a/boto/roboto/param.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
-# Copyright (c) 2010, Eucalyptus Systems, Inc.
-#
-# Permission is hereby granted, free of charge, to any person obtaining a
-# copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish, dis-
-# tribute, sublicense, and/or sell copies of the Software, and to permit
-# persons to whom the Software is furnished to do so, subject to the fol-
-# lowing conditions:
-#
-# The above copyright notice and this permission notice shall be included
-# in all copies or substantial portions of the Software.
-#
-# 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,
-# 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.
-
-import os
-
-class Converter(object):
-
- @classmethod
- def convert_string(cls, param, value):
- # TODO: could do length validation, etc. here
- if not isinstance(value, basestring):
- raise ValueError
- return value
-
- @classmethod
- def convert_integer(cls, param, value):
- # TODO: could do range checking here
- return int(value)
-
- @classmethod
- def convert_boolean(cls, param, value):
- """
- For command line arguments, just the presence
- of the option means True so just return True
- """
- return True
-
- @classmethod
- def convert_file(cls, param, value):
- if os.path.isfile(value):
- return value
- raise ValueError
-
- @classmethod
- def convert_dir(cls, param, value):
- if os.path.isdir(value):
- return value
- raise ValueError
-
- @classmethod
- def convert(cls, param, value):
- try:
- if hasattr(cls, 'convert_'+param.ptype):
- mthd = getattr(cls, 'convert_'+param.ptype)
- else:
- mthd = cls.convert_string
- return mthd(param, value)
- except:
- raise ValidationException(param, '')
-
-class Param(object):
-
- def __init__(self, name=None, ptype='string', optional=True,
- short_name=None, long_name=None, doc='',
- metavar=None, cardinality=1, default=None,
- choices=None, encoder=None, request_param=True):
- self.name = name
- self.ptype = ptype
- self.optional = optional
- self.short_name = short_name
- self.long_name = long_name
- self.doc = doc
- self.metavar = metavar
- self.cardinality = cardinality
- self.default = default
- self.choices = choices
- self.encoder = encoder
- self.request_param = request_param
-
- @property
- def optparse_long_name(self):
- ln = None
- if self.long_name:
- ln = '--%s' % self.long_name
- return ln
-
- @property
- def synopsis_long_name(self):
- ln = None
- if self.long_name:
- ln = '--%s' % self.long_name
- return ln
-
- @property
- def getopt_long_name(self):
- ln = None
- if self.long_name:
- ln = '%s' % self.long_name
- if self.ptype != 'boolean':
- ln += '='
- return ln
-
- @property
- def optparse_short_name(self):
- sn = None
- if self.short_name:
- sn = '-%s' % self.short_name
- return sn
-
- @property
- def synopsis_short_name(self):
- sn = None
- if self.short_name:
- sn = '-%s' % self.short_name
- return sn
-
- @property
- def getopt_short_name(self):
- sn = None
- if self.short_name:
- sn = '%s' % self.short_name
- if self.ptype != 'boolean':
- sn += ':'
- return sn
-
- def convert(self, value):
- """
- Convert a string value as received in the command line
- tools and convert to the appropriate type of value.
- Raise a ValidationError if the value can't be converted.
-
- :type value: str
- :param value: The value to convert. This should always
- be a string.
- """
- return Converter.convert(self, value)
-
-