Merge lp:~ubuntu-branches/ubuntu/oneiric/txaws/oneiric-201109300905 into lp:ubuntu/oneiric/txaws

Proposed by Ubuntu Package Importer
Status: Needs review
Proposed branch: lp:~ubuntu-branches/ubuntu/oneiric/txaws/oneiric-201109300905
Merge into: lp:ubuntu/oneiric/txaws
Diff against target: 3121 lines (+3099/-0) (has conflicts)
3 files modified
.pc/fix-openstack-terminate-instances.patch/txaws/ec2/client.py (+1023/-0)
.pc/fix-openstack-terminate-instances.patch/txaws/ec2/tests/test_client.py (+1996/-0)
debian/patches/fix-openstack-terminate-instances.patch (+80/-0)
Conflict adding file .pc/fix-openstack-terminate-instances.patch.  Moved existing file to .pc/fix-openstack-terminate-instances.patch.moved.
Conflict adding file debian/patches/fix-openstack-terminate-instances.patch.  Moved existing file to debian/patches/fix-openstack-terminate-instances.patch.moved.
To merge this branch: bzr merge lp:~ubuntu-branches/ubuntu/oneiric/txaws/oneiric-201109300905
Reviewer Review Type Date Requested Status
Ubuntu branches Pending
Review via email: mp+77671@code.launchpad.net

Description of the change

The package importer has detected a possible inconsistency between the package history in the archive and the history in bzr. As the archive is authoritative the importer has made lp:ubuntu/oneiric/txaws reflect what is in the archive and the old bzr branch has been pushed to lp:~ubuntu-branches/ubuntu/oneiric/txaws/oneiric-201109300905. This merge proposal was created so that an Ubuntu developer can review the situations and perform a merge/upload if necessary. There are three typical cases where this can happen.
  1. Where someone pushes a change to bzr and someone else uploads the package without that change. This is the reason that this check is done by the importer. If this appears to be the case then a merge/upload should be done if the changes that were in bzr are still desirable.
  2. The importer incorrectly detected the above situation when someone made a change in bzr and then uploaded it.
  3. The importer incorrectly detected the above situation when someone just uploaded a package and didn't touch bzr.

If this case doesn't appear to be the first situation then set the status of the merge proposal to "Rejected" and help avoid the problem in future by filing a bug at https://bugs.launchpad.net/udd linking to this merge proposal.

(this is an automatically generated message)

To post a comment you must log in.

Unmerged revisions

8. By Clint Byrum

releasing version 0.2-0ubuntu5

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added directory '.pc/fix-openstack-terminate-instances.patch'
2=== renamed directory '.pc/fix-openstack-terminate-instances.patch' => '.pc/fix-openstack-terminate-instances.patch.moved'
3=== added file '.pc/fix-openstack-terminate-instances.patch/.timestamp'
4=== added directory '.pc/fix-openstack-terminate-instances.patch/txaws'
5=== added directory '.pc/fix-openstack-terminate-instances.patch/txaws/ec2'
6=== added file '.pc/fix-openstack-terminate-instances.patch/txaws/ec2/client.py'
7--- .pc/fix-openstack-terminate-instances.patch/txaws/ec2/client.py 1970-01-01 00:00:00 +0000
8+++ .pc/fix-openstack-terminate-instances.patch/txaws/ec2/client.py 2011-09-30 09:11:28 +0000
9@@ -0,0 +1,1023 @@
10+# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
11+# Copyright (C) 2009 Canonical Ltd
12+# Copyright (C) 2009 Duncan McGreggor <oubiwann@adytum.us>
13+# Licenced under the txaws licence available at /LICENSE in the txaws source.
14+
15+"""EC2 client support."""
16+
17+from datetime import datetime
18+from urllib import quote
19+from base64 import b64encode
20+
21+from txaws import version
22+from txaws.client.base import BaseClient, BaseQuery, error_wrapper
23+from txaws.ec2 import model
24+from txaws.ec2.exception import EC2Error
25+from txaws.util import iso8601time, XML
26+
27+
28+__all__ = ["EC2Client", "Query", "Parser"]
29+
30+
31+def ec2_error_wrapper(error):
32+ error_wrapper(error, EC2Error)
33+
34+
35+class EC2Client(BaseClient):
36+ """A client for EC2."""
37+
38+ def __init__(self, creds=None, endpoint=None, query_factory=None,
39+ parser=None):
40+ if query_factory is None:
41+ query_factory = Query
42+ if parser is None:
43+ parser = Parser()
44+ super(EC2Client, self).__init__(creds, endpoint, query_factory, parser)
45+
46+ def describe_instances(self, *instance_ids):
47+ """Describe current instances."""
48+ instances = {}
49+ for pos, instance_id in enumerate(instance_ids):
50+ instances["InstanceId.%d" % (pos + 1)] = instance_id
51+ query = self.query_factory(
52+ action="DescribeInstances", creds=self.creds,
53+ endpoint=self.endpoint, other_params=instances)
54+ d = query.submit()
55+ return d.addCallback(self.parser.describe_instances)
56+
57+ def run_instances(self, image_id, min_count, max_count,
58+ security_groups=None, key_name=None, instance_type=None,
59+ user_data=None, availability_zone=None, kernel_id=None,
60+ ramdisk_id=None):
61+ """Run new instances."""
62+ params = {"ImageId": image_id, "MinCount": str(min_count),
63+ "MaxCount": str(max_count)}
64+ if security_groups is not None:
65+ for i, name in enumerate(security_groups):
66+ params["SecurityGroup.%d" % (i + 1)] = name
67+ if key_name is not None:
68+ params["KeyName"] = key_name
69+ if user_data is not None:
70+ params["UserData"] = b64encode(user_data)
71+ if instance_type is not None:
72+ params["InstanceType"] = instance_type
73+ if availability_zone is not None:
74+ params["Placement.AvailabilityZone"] = availability_zone
75+ if kernel_id is not None:
76+ params["KernelId"] = kernel_id
77+ if ramdisk_id is not None:
78+ params["RamdiskId"] = ramdisk_id
79+ query = self.query_factory(
80+ action="RunInstances", creds=self.creds, endpoint=self.endpoint,
81+ other_params=params)
82+ d = query.submit()
83+ return d.addCallback(self.parser.run_instances)
84+
85+ def terminate_instances(self, *instance_ids):
86+ """Terminate some instances.
87+
88+ @param instance_ids: The ids of the instances to terminate.
89+ @return: A deferred which on success gives an iterable of
90+ (id, old-state, new-state) tuples.
91+ """
92+ instances = {}
93+ for pos, instance_id in enumerate(instance_ids):
94+ instances["InstanceId.%d" % (pos + 1)] = instance_id
95+ query = self.query_factory(
96+ action="TerminateInstances", creds=self.creds,
97+ endpoint=self.endpoint, other_params=instances)
98+ d = query.submit()
99+ return d.addCallback(self.parser.terminate_instances)
100+
101+ def describe_security_groups(self, *names):
102+ """Describe security groups.
103+
104+ @param names: Optionally, a list of security group names to describe.
105+ Defaults to all security groups in the account.
106+ @return: A C{Deferred} that will fire with a list of L{SecurityGroup}s
107+ retrieved from the cloud.
108+ """
109+ group_names = {}
110+ if names:
111+ group_names = dict([("GroupName.%d" % (i + 1), name)
112+ for i, name in enumerate(names)])
113+ query = self.query_factory(
114+ action="DescribeSecurityGroups", creds=self.creds,
115+ endpoint=self.endpoint, other_params=group_names)
116+ d = query.submit()
117+ return d.addCallback(self.parser.describe_security_groups)
118+
119+ def create_security_group(self, name, description):
120+ """Create security group.
121+
122+ @param name: Name of the new security group.
123+ @param description: Description of the new security group.
124+ @return: A C{Deferred} that will fire with a truth value for the
125+ success of the operation.
126+ """
127+ parameters = {"GroupName": name, "GroupDescription": description}
128+ query = self.query_factory(
129+ action="CreateSecurityGroup", creds=self.creds,
130+ endpoint=self.endpoint, other_params=parameters)
131+ d = query.submit()
132+ return d.addCallback(self.parser.truth_return)
133+
134+ def delete_security_group(self, name):
135+ """
136+ @param name: Name of the new security group.
137+ @return: A C{Deferred} that will fire with a truth value for the
138+ success of the operation.
139+ """
140+ parameter = {"GroupName": name}
141+ query = self.query_factory(
142+ action="DeleteSecurityGroup", creds=self.creds,
143+ endpoint=self.endpoint, other_params=parameter)
144+ d = query.submit()
145+ return d.addCallback(self.parser.truth_return)
146+
147+ def authorize_security_group(
148+ self, group_name, source_group_name="", source_group_owner_id="",
149+ ip_protocol="", from_port="", to_port="", cidr_ip=""):
150+ """
151+ There are two ways to use C{authorize_security_group}:
152+ 1) associate an existing group (source group) with the one that you
153+ are targeting (group_name) with an authorization update; or
154+ 2) associate a set of IP permissions with the group you are
155+ targeting with an authorization update.
156+
157+ @param group_name: The group you will be modifying with a new
158+ authorization.
159+
160+ Optionally, the following parameters:
161+ @param source_group_name: Name of security group to authorize access to
162+ when operating on a user/group pair.
163+ @param source_group_owner_id: Owner of security group to authorize
164+ access to when operating on a user/group pair.
165+
166+ If those parameters are not specified, then the following must be:
167+ @param ip_protocol: IP protocol to authorize access to when operating
168+ on a CIDR IP.
169+ @param from_port: Bottom of port range to authorize access to when
170+ operating on a CIDR IP. This contains the ICMP type if ICMP is
171+ being authorized.
172+ @param to_port: Top of port range to authorize access to when operating
173+ on a CIDR IP. This contains the ICMP code if ICMP is being
174+ authorized.
175+ @param cidr_ip: CIDR IP range to authorize access to when operating on
176+ a CIDR IP.
177+
178+ @return: A C{Deferred} that will fire with a truth value for the
179+ success of the operation.
180+ """
181+ if source_group_name and source_group_owner_id:
182+ parameters = {
183+ "SourceSecurityGroupName": source_group_name,
184+ "SourceSecurityGroupOwnerId": source_group_owner_id,
185+ }
186+ elif ip_protocol and from_port and to_port and cidr_ip:
187+ parameters = {
188+ "IpProtocol": ip_protocol,
189+ "FromPort": from_port,
190+ "ToPort": to_port,
191+ "CidrIp": cidr_ip,
192+ }
193+ else:
194+ msg = ("You must specify either both group parameters or "
195+ "all the ip parameters.")
196+ raise ValueError(msg)
197+ parameters["GroupName"] = group_name
198+ query = self.query_factory(
199+ action="AuthorizeSecurityGroupIngress", creds=self.creds,
200+ endpoint=self.endpoint, other_params=parameters)
201+ d = query.submit()
202+ return d.addCallback(self.parser.truth_return)
203+
204+ def authorize_group_permission(
205+ self, group_name, source_group_name, source_group_owner_id):
206+ """
207+ This is a convenience function that wraps the "authorize group"
208+ functionality of the C{authorize_security_group} method.
209+
210+ For an explanation of the parameters, see C{authorize_security_group}.
211+ """
212+ d = self.authorize_security_group(
213+ group_name,
214+ source_group_name=source_group_name,
215+ source_group_owner_id=source_group_owner_id)
216+ return d
217+
218+ def authorize_ip_permission(
219+ self, group_name, ip_protocol, from_port, to_port, cidr_ip):
220+ """
221+ This is a convenience function that wraps the "authorize ip
222+ permission" functionality of the C{authorize_security_group} method.
223+
224+ For an explanation of the parameters, see C{authorize_security_group}.
225+ """
226+ d = self.authorize_security_group(
227+ group_name,
228+ ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
229+ cidr_ip=cidr_ip)
230+ return d
231+
232+ def revoke_security_group(
233+ self, group_name, source_group_name="", source_group_owner_id="",
234+ ip_protocol="", from_port="", to_port="", cidr_ip=""):
235+ """
236+ There are two ways to use C{revoke_security_group}:
237+ 1) associate an existing group (source group) with the one that you
238+ are targeting (group_name) with the revoke update; or
239+ 2) associate a set of IP permissions with the group you are
240+ targeting with a revoke update.
241+
242+ @param group_name: The group you will be modifying with an
243+ authorization removal.
244+
245+ Optionally, the following parameters:
246+ @param source_group_name: Name of security group to revoke access from
247+ when operating on a user/group pair.
248+ @param source_group_owner_id: Owner of security group to revoke
249+ access from when operating on a user/group pair.
250+
251+ If those parameters are not specified, then the following must be:
252+ @param ip_protocol: IP protocol to revoke access from when operating
253+ on a CIDR IP.
254+ @param from_port: Bottom of port range to revoke access from when
255+ operating on a CIDR IP. This contains the ICMP type if ICMP is
256+ being revoked.
257+ @param to_port: Top of port range to revoke access from when operating
258+ on a CIDR IP. This contains the ICMP code if ICMP is being
259+ revoked.
260+ @param cidr_ip: CIDR IP range to revoke access from when operating on
261+ a CIDR IP.
262+
263+ @return: A C{Deferred} that will fire with a truth value for the
264+ success of the operation.
265+ """
266+ if source_group_name and source_group_owner_id:
267+ parameters = {
268+ "SourceSecurityGroupName": source_group_name,
269+ "SourceSecurityGroupOwnerId": source_group_owner_id,
270+ }
271+ elif ip_protocol and from_port and to_port and cidr_ip:
272+ parameters = {
273+ "IpProtocol": ip_protocol,
274+ "FromPort": from_port,
275+ "ToPort": to_port,
276+ "CidrIp": cidr_ip,
277+ }
278+ else:
279+ msg = ("You must specify either both group parameters or "
280+ "all the ip parameters.")
281+ raise ValueError(msg)
282+ parameters["GroupName"] = group_name
283+ query = self.query_factory(
284+ action="RevokeSecurityGroupIngress", creds=self.creds,
285+ endpoint=self.endpoint, other_params=parameters)
286+ d = query.submit()
287+ return d.addCallback(self.parser.truth_return)
288+
289+ def revoke_group_permission(
290+ self, group_name, source_group_name, source_group_owner_id):
291+ """
292+ This is a convenience function that wraps the "authorize group"
293+ functionality of the C{authorize_security_group} method.
294+
295+ For an explanation of the parameters, see C{revoke_security_group}.
296+ """
297+ d = self.revoke_security_group(
298+ group_name,
299+ source_group_name=source_group_name,
300+ source_group_owner_id=source_group_owner_id)
301+ return d
302+
303+ def revoke_ip_permission(
304+ self, group_name, ip_protocol, from_port, to_port, cidr_ip):
305+ """
306+ This is a convenience function that wraps the "authorize ip
307+ permission" functionality of the C{authorize_security_group} method.
308+
309+ For an explanation of the parameters, see C{revoke_security_group}.
310+ """
311+ d = self.revoke_security_group(
312+ group_name,
313+ ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
314+ cidr_ip=cidr_ip)
315+ return d
316+
317+ def describe_volumes(self, *volume_ids):
318+ """Describe available volumes."""
319+ volumeset = {}
320+ for pos, volume_id in enumerate(volume_ids):
321+ volumeset["VolumeId.%d" % (pos + 1)] = volume_id
322+ query = self.query_factory(
323+ action="DescribeVolumes", creds=self.creds, endpoint=self.endpoint,
324+ other_params=volumeset)
325+ d = query.submit()
326+ return d.addCallback(self.parser.describe_volumes)
327+
328+ def create_volume(self, availability_zone, size=None, snapshot_id=None):
329+ """Create a new volume."""
330+ params = {"AvailabilityZone": availability_zone}
331+ if ((snapshot_id is None and size is None) or
332+ (snapshot_id is not None and size is not None)):
333+ raise ValueError("Please provide either size or snapshot_id")
334+ if size is not None:
335+ params["Size"] = str(size)
336+ if snapshot_id is not None:
337+ params["SnapshotId"] = snapshot_id
338+ query = self.query_factory(
339+ action="CreateVolume", creds=self.creds, endpoint=self.endpoint,
340+ other_params=params)
341+ d = query.submit()
342+ return d.addCallback(self.parser.create_volume)
343+
344+ def delete_volume(self, volume_id):
345+ query = self.query_factory(
346+ action="DeleteVolume", creds=self.creds, endpoint=self.endpoint,
347+ other_params={"VolumeId": volume_id})
348+ d = query.submit()
349+ return d.addCallback(self.parser.truth_return)
350+
351+ def describe_snapshots(self, *snapshot_ids):
352+ """Describe available snapshots."""
353+ snapshot_set = {}
354+ for pos, snapshot_id in enumerate(snapshot_ids):
355+ snapshot_set["SnapshotId.%d" % (pos + 1)] = snapshot_id
356+ query = self.query_factory(
357+ action="DescribeSnapshots", creds=self.creds,
358+ endpoint=self.endpoint, other_params=snapshot_set)
359+ d = query.submit()
360+ return d.addCallback(self.parser.snapshots)
361+
362+ def create_snapshot(self, volume_id):
363+ """Create a new snapshot of an existing volume."""
364+ query = self.query_factory(
365+ action="CreateSnapshot", creds=self.creds, endpoint=self.endpoint,
366+ other_params={"VolumeId": volume_id})
367+ d = query.submit()
368+ return d.addCallback(self.parser.create_snapshot)
369+
370+ def delete_snapshot(self, snapshot_id):
371+ """Remove a previously created snapshot."""
372+ query = self.query_factory(
373+ action="DeleteSnapshot", creds=self.creds, endpoint=self.endpoint,
374+ other_params={"SnapshotId": snapshot_id})
375+ d = query.submit()
376+ return d.addCallback(self.parser.truth_return)
377+
378+ def attach_volume(self, volume_id, instance_id, device):
379+ """Attach the given volume to the specified instance at C{device}."""
380+ query = self.query_factory(
381+ action="AttachVolume", creds=self.creds, endpoint=self.endpoint,
382+ other_params={"VolumeId": volume_id, "InstanceId": instance_id,
383+ "Device": device})
384+ d = query.submit()
385+ return d.addCallback(self.parser.attach_volume)
386+
387+ def describe_keypairs(self, *keypair_names):
388+ """Returns information about key pairs available."""
389+ keypairs = {}
390+ for index, keypair_name in enumerate(keypair_names):
391+ keypairs["KeyPair.%d" % (index + 1)] = keypair_name
392+ query = self.query_factory(
393+ action="DescribeKeyPairs", creds=self.creds,
394+ endpoint=self.endpoint, other_params=keypairs)
395+ d = query.submit()
396+ return d.addCallback(self.parser.describe_keypairs)
397+
398+ def create_keypair(self, keypair_name):
399+ """
400+ Create a new 2048 bit RSA key pair and return a unique ID that can be
401+ used to reference the created key pair when launching new instances.
402+ """
403+ query = self.query_factory(
404+ action="CreateKeyPair", creds=self.creds, endpoint=self.endpoint,
405+ other_params={"KeyName": keypair_name})
406+ d = query.submit()
407+ return d.addCallback(self.parser.create_keypair)
408+
409+ def delete_keypair(self, keypair_name):
410+ """Delete a given keypair."""
411+ query = self.query_factory(
412+ action="DeleteKeyPair", creds=self.creds, endpoint=self.endpoint,
413+ other_params={"KeyName": keypair_name})
414+ d = query.submit()
415+ return d.addCallback(self.parser.truth_return)
416+
417+ def import_keypair(self, keypair_name, key_material):
418+ """
419+ Import an existing SSH key into EC2. It supports:
420+ * OpenSSH public key format (e.g., the format in
421+ ~/.ssh/authorized_keys)
422+ * Base64 encoded DER format
423+ * SSH public key file format as specified in RFC4716
424+
425+ @param keypair_name: The name of the key to create.
426+ @param key_material: The material in one of the supported format.
427+
428+ @return: A L{Deferred} firing with a L{model.Keypair} instance if
429+ successful.
430+ """
431+ query = self.query_factory(
432+ action="ImportKeyPair", creds=self.creds, endpoint=self.endpoint,
433+ other_params={"KeyName": keypair_name,
434+ "PublicKeyMaterial": b64encode(key_material)})
435+ d = query.submit()
436+ return d.addCallback(self.parser.import_keypair, key_material)
437+
438+ def allocate_address(self):
439+ """
440+ Acquire an elastic IP address to be attached subsequently to EC2
441+ instances.
442+
443+ @return: the IP address allocated.
444+ """
445+ # XXX remove empty other_params
446+ query = self.query_factory(
447+ action="AllocateAddress", creds=self.creds, endpoint=self.endpoint,
448+ other_params={})
449+ d = query.submit()
450+ return d.addCallback(self.parser.allocate_address)
451+
452+ def release_address(self, address):
453+ """
454+ Release a previously allocated address returned by C{allocate_address}.
455+
456+ @return: C{True} if the operation succeeded.
457+ """
458+ query = self.query_factory(
459+ action="ReleaseAddress", creds=self.creds, endpoint=self.endpoint,
460+ other_params={"PublicIp": address})
461+ d = query.submit()
462+ return d.addCallback(self.parser.truth_return)
463+
464+ def associate_address(self, instance_id, address):
465+ """
466+ Associate an allocated C{address} with the instance identified by
467+ C{instance_id}.
468+
469+ @return: C{True} if the operation succeeded.
470+ """
471+ query = self.query_factory(
472+ action="AssociateAddress", creds=self.creds,
473+ endpoint=self.endpoint,
474+ other_params={"InstanceId": instance_id, "PublicIp": address})
475+ d = query.submit()
476+ return d.addCallback(self.parser.truth_return)
477+
478+ def disassociate_address(self, address):
479+ """
480+ Disassociate an address previously associated with
481+ C{associate_address}. This is an idempotent operation, so it can be
482+ called several times without error.
483+ """
484+ query = self.query_factory(
485+ action="DisassociateAddress", creds=self.creds,
486+ endpoint=self.endpoint, other_params={"PublicIp": address})
487+ d = query.submit()
488+ return d.addCallback(self.parser.truth_return)
489+
490+ def describe_addresses(self, *addresses):
491+ """
492+ List the elastic IPs allocated in this account.
493+
494+ @param addresses: if specified, the addresses to get information about.
495+
496+ @return: a C{list} of (address, instance_id). If the elastic IP is not
497+ associated currently, C{instance_id} will be C{None}.
498+ """
499+ address_set = {}
500+ for pos, address in enumerate(addresses):
501+ address_set["PublicIp.%d" % (pos + 1)] = address
502+ query = self.query_factory(
503+ action="DescribeAddresses", creds=self.creds,
504+ endpoint=self.endpoint, other_params=address_set)
505+ d = query.submit()
506+ return d.addCallback(self.parser.describe_addresses)
507+
508+ def describe_availability_zones(self, names=None):
509+ zone_names = None
510+ if names:
511+ zone_names = dict([("ZoneName.%d" % (i + 1), name)
512+ for i, name in enumerate(names)])
513+ query = self.query_factory(
514+ action="DescribeAvailabilityZones", creds=self.creds,
515+ endpoint=self.endpoint, other_params=zone_names)
516+ d = query.submit()
517+ return d.addCallback(self.parser.describe_availability_zones)
518+
519+
520+class Parser(object):
521+ """A parser for EC2 responses"""
522+
523+ def instances_set(self, root, reservation):
524+ """Parse instance data out of an XML payload.
525+
526+ @param root: The root node of the XML payload.
527+ @param reservation: The L{Reservation} associated with the instances
528+ from the response.
529+ @return: A C{list} of L{Instance}s.
530+ """
531+ instances = []
532+ for instance_data in root.find("instancesSet"):
533+ instances.append(self.instance(instance_data, reservation))
534+ return instances
535+
536+ def instance(self, instance_data, reservation):
537+ """Parse instance data out of an XML payload.
538+
539+ @param instance_data: An XML node containing instance data.
540+ @param reservation: The L{Reservation} associated with the instance.
541+ @return: An L{Instance}.
542+ """
543+ instance_id = instance_data.findtext("instanceId")
544+ instance_state = instance_data.find(
545+ "instanceState").findtext("name")
546+ instance_type = instance_data.findtext("instanceType")
547+ image_id = instance_data.findtext("imageId")
548+ private_dns_name = instance_data.findtext("privateDnsName")
549+ dns_name = instance_data.findtext("dnsName")
550+ key_name = instance_data.findtext("keyName")
551+ ami_launch_index = instance_data.findtext("amiLaunchIndex")
552+ launch_time = instance_data.findtext("launchTime")
553+ placement = instance_data.find("placement").findtext(
554+ "availabilityZone")
555+ products = []
556+ product_codes = instance_data.find("productCodes")
557+ if product_codes is not None:
558+ for product_data in instance_data.find("productCodes"):
559+ products.append(product_data.text)
560+ kernel_id = instance_data.findtext("kernelId")
561+ ramdisk_id = instance_data.findtext("ramdiskId")
562+ instance = model.Instance(
563+ instance_id, instance_state, instance_type, image_id,
564+ private_dns_name, dns_name, key_name, ami_launch_index,
565+ launch_time, placement, products, kernel_id, ramdisk_id,
566+ reservation=reservation)
567+ return instance
568+
569+ def describe_instances(self, xml_bytes):
570+ """
571+ Parse the reservations XML payload that is returned from an AWS
572+ describeInstances API call.
573+
574+ Instead of returning the reservations as the "top-most" object, we
575+ return the object that most developers and their code will be
576+ interested in: the instances. In instances reservation is available on
577+ the instance object.
578+
579+ The following instance attributes are optional:
580+ * ami_launch_index
581+ * key_name
582+ * kernel_id
583+ * product_codes
584+ * ramdisk_id
585+ * reason
586+
587+ @param xml_bytes: raw XML payload from AWS.
588+ """
589+ root = XML(xml_bytes)
590+ results = []
591+ # May be a more elegant way to do this:
592+ for reservation_data in root.find("reservationSet"):
593+ # Get the security group information.
594+ groups = []
595+ for group_data in reservation_data.find("groupSet"):
596+ group_id = group_data.findtext("groupId")
597+ groups.append(group_id)
598+ # Create a reservation object with the parsed data.
599+ reservation = model.Reservation(
600+ reservation_id=reservation_data.findtext("reservationId"),
601+ owner_id=reservation_data.findtext("ownerId"),
602+ groups=groups)
603+ # Get the list of instances.
604+ instances = self.instances_set(
605+ reservation_data, reservation)
606+ results.extend(instances)
607+ return results
608+
609+ def run_instances(self, xml_bytes):
610+ """
611+ Parse the reservations XML payload that is returned from an AWS
612+ RunInstances API call.
613+
614+ @param xml_bytes: raw XML payload from AWS.
615+ """
616+ root = XML(xml_bytes)
617+ # Get the security group information.
618+ groups = []
619+ for group_data in root.find("groupSet"):
620+ group_id = group_data.findtext("groupId")
621+ groups.append(group_id)
622+ # Create a reservation object with the parsed data.
623+ reservation = model.Reservation(
624+ reservation_id=root.findtext("reservationId"),
625+ owner_id=root.findtext("ownerId"),
626+ groups=groups)
627+ # Get the list of instances.
628+ instances = self.instances_set(root, reservation)
629+ return instances
630+
631+ def terminate_instances(self, xml_bytes):
632+ """Parse the XML returned by the C{TerminateInstances} function.
633+
634+ @param xml_bytes: XML bytes with a C{TerminateInstancesResponse} root
635+ element.
636+ @return: An iterable of C{tuple} of (instanceId, previousState,
637+ shutdownState) for the ec2 instances that where terminated.
638+ """
639+ root = XML(xml_bytes)
640+ result = []
641+ # May be a more elegant way to do this:
642+ for instance in root.find("instancesSet"):
643+ instanceId = instance.findtext("instanceId")
644+ previousState = instance.find("previousState").findtext(
645+ "name")
646+ shutdownState = instance.find("shutdownState").findtext(
647+ "name")
648+ result.append((instanceId, previousState, shutdownState))
649+ return result
650+
651+ def describe_security_groups(self, xml_bytes):
652+ """Parse the XML returned by the C{DescribeSecurityGroups} function.
653+
654+ @param xml_bytes: XML bytes with a C{DescribeSecurityGroupsResponse}
655+ root element.
656+ @return: A list of L{SecurityGroup} instances.
657+ """
658+ root = XML(xml_bytes)
659+ result = []
660+ for group_info in root.findall("securityGroupInfo/item"):
661+ name = group_info.findtext("groupName")
662+ description = group_info.findtext("groupDescription")
663+ owner_id = group_info.findtext("ownerId")
664+ allowed_groups = []
665+ allowed_ips = []
666+ ip_permissions = group_info.find("ipPermissions")
667+ if ip_permissions is None:
668+ ip_permissions = ()
669+ for ip_permission in ip_permissions:
670+
671+ # openstack doesn't handle self authorized groups properly
672+ # XXX this is an upstream problem and should be addressed there
673+ # lp bug #829609
674+ ip_protocol = ip_permission.findtext("ipProtocol")
675+ from_port = ip_permission.findtext("fromPort")
676+ to_port = ip_permission.findtext("toPort")
677+
678+ if from_port:
679+ from_port = int(from_port)
680+
681+ if to_port:
682+ to_port = int(to_port)
683+
684+ for groups in ip_permission.findall("groups/item") or ():
685+ user_id = groups.findtext("userId")
686+ group_name = groups.findtext("groupName")
687+ if user_id and group_name:
688+ if (user_id, group_name) not in allowed_groups:
689+ allowed_groups.append((user_id, group_name))
690+ for ip_ranges in ip_permission.findall("ipRanges/item") or ():
691+ cidr_ip = ip_ranges.findtext("cidrIp")
692+ allowed_ips.append(
693+ model.IPPermission(
694+ ip_protocol, from_port, to_port, cidr_ip))
695+
696+ allowed_groups = [model.UserIDGroupPair(user_id, group_name)
697+ for user_id, group_name in allowed_groups]
698+
699+ security_group = model.SecurityGroup(
700+ name, description, owner_id=owner_id,
701+ groups=allowed_groups, ips=allowed_ips)
702+ result.append(security_group)
703+ return result
704+
705+ def truth_return(self, xml_bytes):
706+ """Parse the XML for a truth value.
707+
708+ @param xml_bytes: XML bytes.
709+ @return: True if the node contains "return" otherwise False.
710+ """
711+ root = XML(xml_bytes)
712+ return root.findtext("return") == "true"
713+
714+ def describe_volumes(self, xml_bytes):
715+ """Parse the XML returned by the C{DescribeVolumes} function.
716+
717+ @param xml_bytes: XML bytes with a C{DescribeVolumesResponse} root
718+ element.
719+ @return: A list of L{Volume} instances.
720+ """
721+ root = XML(xml_bytes)
722+ result = []
723+ for volume_data in root.find("volumeSet"):
724+ volume_id = volume_data.findtext("volumeId")
725+ size = int(volume_data.findtext("size"))
726+ status = volume_data.findtext("status")
727+ availability_zone = volume_data.findtext("availabilityZone")
728+ snapshot_id = volume_data.findtext("snapshotId")
729+ create_time = volume_data.findtext("createTime")
730+ create_time = datetime.strptime(
731+ create_time[:19], "%Y-%m-%dT%H:%M:%S")
732+ volume = model.Volume(
733+ volume_id, size, status, create_time, availability_zone,
734+ snapshot_id)
735+ result.append(volume)
736+ for attachment_data in volume_data.find("attachmentSet"):
737+ instance_id = attachment_data.findtext("instanceId")
738+ status = attachment_data.findtext("status")
739+ device = attachment_data.findtext("device")
740+ attach_time = attachment_data.findtext("attachTime")
741+ attach_time = datetime.strptime(
742+ attach_time[:19], "%Y-%m-%dT%H:%M:%S")
743+ attachment = model.Attachment(
744+ instance_id, device, status, attach_time)
745+ volume.attachments.append(attachment)
746+ return result
747+
748+ def create_volume(self, xml_bytes):
749+ """Parse the XML returned by the C{CreateVolume} function.
750+
751+ @param xml_bytes: XML bytes with a C{CreateVolumeResponse} root
752+ element.
753+ @return: The L{Volume} instance created.
754+ """
755+ root = XML(xml_bytes)
756+ volume_id = root.findtext("volumeId")
757+ size = int(root.findtext("size"))
758+ status = root.findtext("status")
759+ create_time = root.findtext("createTime")
760+ availability_zone = root.findtext("availabilityZone")
761+ snapshot_id = root.findtext("snapshotId")
762+ create_time = datetime.strptime(
763+ create_time[:19], "%Y-%m-%dT%H:%M:%S")
764+ volume = model.Volume(
765+ volume_id, size, status, create_time, availability_zone,
766+ snapshot_id)
767+ return volume
768+
769+ def snapshots(self, xml_bytes):
770+ """Parse the XML returned by the C{DescribeSnapshots} function.
771+
772+ @param xml_bytes: XML bytes with a C{DescribeSnapshotsResponse} root
773+ element.
774+ @return: A list of L{Snapshot} instances.
775+ """
776+ root = XML(xml_bytes)
777+ result = []
778+ for snapshot_data in root.find("snapshotSet"):
779+ snapshot_id = snapshot_data.findtext("snapshotId")
780+ volume_id = snapshot_data.findtext("volumeId")
781+ status = snapshot_data.findtext("status")
782+ start_time = snapshot_data.findtext("startTime")
783+ start_time = datetime.strptime(
784+ start_time[:19], "%Y-%m-%dT%H:%M:%S")
785+ progress = snapshot_data.findtext("progress")[:-1]
786+ progress = float(progress or "0") / 100.
787+ snapshot = model.Snapshot(
788+ snapshot_id, volume_id, status, start_time, progress)
789+ result.append(snapshot)
790+ return result
791+
792+ def create_snapshot(self, xml_bytes):
793+ """Parse the XML returned by the C{CreateSnapshot} function.
794+
795+ @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root
796+ element.
797+ @return: The L{Snapshot} instance created.
798+ """
799+ root = XML(xml_bytes)
800+ snapshot_id = root.findtext("snapshotId")
801+ volume_id = root.findtext("volumeId")
802+ status = root.findtext("status")
803+ start_time = root.findtext("startTime")
804+ start_time = datetime.strptime(
805+ start_time[:19], "%Y-%m-%dT%H:%M:%S")
806+ progress = root.findtext("progress")[:-1]
807+ progress = float(progress or "0") / 100.
808+ return model.Snapshot(
809+ snapshot_id, volume_id, status, start_time, progress)
810+
811+ def attach_volume(self, xml_bytes):
812+ """Parse the XML returned by the C{AttachVolume} function.
813+
814+ @param xml_bytes: XML bytes with a C{AttachVolumeResponse} root
815+ element.
816+ @return: a C{dict} with status and attach_time keys.
817+ """
818+ root = XML(xml_bytes)
819+ status = root.findtext("status")
820+ attach_time = root.findtext("attachTime")
821+ attach_time = datetime.strptime(
822+ attach_time[:19], "%Y-%m-%dT%H:%M:%S")
823+ return {"status": status, "attach_time": attach_time}
824+
825+ def describe_keypairs(self, xml_bytes):
826+ """Parse the XML returned by the C{DescribeKeyPairs} function.
827+
828+ @param xml_bytes: XML bytes with a C{DescribeKeyPairsResponse} root
829+ element.
830+ @return: a C{list} of L{Keypair}.
831+ """
832+ results = []
833+ root = XML(xml_bytes)
834+ keypairs = root.find("keySet")
835+ if keypairs is None:
836+ return results
837+ for keypair_data in keypairs:
838+ key_name = keypair_data.findtext("keyName")
839+ key_fingerprint = keypair_data.findtext("keyFingerprint")
840+ results.append(model.Keypair(key_name, key_fingerprint))
841+ return results
842+
843+ def create_keypair(self, xml_bytes):
844+ """Parse the XML returned by the C{CreateKeyPair} function.
845+
846+ @param xml_bytes: XML bytes with a C{CreateKeyPairResponse} root
847+ element.
848+ @return: The L{Keypair} instance created.
849+ """
850+ keypair_data = XML(xml_bytes)
851+ key_name = keypair_data.findtext("keyName")
852+ key_fingerprint = keypair_data.findtext("keyFingerprint")
853+ key_material = keypair_data.findtext("keyMaterial")
854+ return model.Keypair(key_name, key_fingerprint, key_material)
855+
856+ def import_keypair(self, xml_bytes, key_material):
857+ """Extract the key name and the fingerprint from the result."""
858+ keypair_data = XML(xml_bytes)
859+ key_name = keypair_data.findtext("keyName")
860+ key_fingerprint = keypair_data.findtext("keyFingerprint")
861+ return model.Keypair(key_name, key_fingerprint, key_material)
862+
863+ def allocate_address(self, xml_bytes):
864+ """Parse the XML returned by the C{AllocateAddress} function.
865+
866+ @param xml_bytes: XML bytes with a C{AllocateAddress} root element.
867+ @return: The public ip address as a string.
868+ """
869+ address_data = XML(xml_bytes)
870+ return address_data.findtext("publicIp")
871+
872+ def describe_addresses(self, xml_bytes):
873+ """Parse the XML returned by the C{DescribeAddresses} function.
874+
875+ @param xml_bytes: XML bytes with a C{DescribeAddressesResponse} root
876+ element.
877+ @return: a C{list} of L{tuple} of (publicIp, instancId).
878+ """
879+ results = []
880+ root = XML(xml_bytes)
881+ for address_data in root.find("addressesSet"):
882+ address = address_data.findtext("publicIp")
883+ instance_id = address_data.findtext("instanceId")
884+ results.append((address, instance_id))
885+ return results
886+
887+ def describe_availability_zones(self, xml_bytes):
888+ """Parse the XML returned by the C{DescribeAvailibilityZones} function.
889+
890+ @param xml_bytes: XML bytes with a C{DescribeAvailibilityZonesResponse}
891+ root element.
892+ @return: a C{list} of L{AvailabilityZone}.
893+ """
894+ results = []
895+ root = XML(xml_bytes)
896+ for zone_data in root.find("availabilityZoneInfo"):
897+ zone_name = zone_data.findtext("zoneName")
898+ zone_state = zone_data.findtext("zoneState")
899+ results.append(model.AvailabilityZone(zone_name, zone_state))
900+ return results
901+
902+
903+class Query(BaseQuery):
904+ """A query that may be submitted to EC2."""
905+
906+ timeout = 30
907+
908+ def __init__(self, other_params=None, time_tuple=None, api_version=None,
909+ *args, **kwargs):
910+ """Create a Query to submit to EC2."""
911+ super(Query, self).__init__(*args, **kwargs)
912+ # Currently, txAWS only supports version 2008-12-01
913+ if api_version is None:
914+ api_version = version.ec2_api
915+ self.params = {
916+ "Version": api_version,
917+ "SignatureVersion": "2",
918+ "Action": self.action,
919+ "AWSAccessKeyId": self.creds.access_key,
920+ }
921+ if other_params is None or "Expires" not in other_params:
922+ # Only add a Timestamp parameter, if Expires isn't used,
923+ # since both can't be used in the same request.
924+ self.params["Timestamp"] = iso8601time(time_tuple)
925+ if other_params:
926+ self.params.update(other_params)
927+ self.signature = Signature(self.creds, self.endpoint, self.params)
928+
929+ def sign(self, hash_type="sha256"):
930+ """Sign this query using its built in credentials.
931+
932+ @param hash_type: if the SignatureVersion is 2, specify the type of
933+ hash to use, either "sha1" or "sha256". It defaults to the latter.
934+
935+ This prepares it to be sent, and should be done as the last step before
936+ submitting the query. Signing is done automatically - this is a public
937+ method to facilitate testing.
938+ """
939+ version = self.params["SignatureVersion"]
940+ if version == "2":
941+ self.params["SignatureMethod"] = "Hmac%s" % hash_type.upper()
942+ self.params["Signature"] = self.signature.compute()
943+
944+ def submit(self):
945+ """Submit this query.
946+
947+ @return: A deferred from get_page
948+ """
949+ self.sign()
950+ url = self.endpoint.get_uri()
951+ method = self.endpoint.method
952+ params = self.signature.get_canonical_query_params()
953+ headers = {}
954+ kwargs = {"method": method}
955+ if method == "POST":
956+ headers["Content-Type"] = "application/x-www-form-urlencoded"
957+ kwargs["postdata"] = params
958+ else:
959+ url += "?%s" % params
960+ if self.endpoint.get_host() != self.endpoint.get_canonical_host():
961+ headers["Host"] = self.endpoint.get_canonical_host()
962+ if headers:
963+ kwargs["headers"] = headers
964+ if self.timeout:
965+ kwargs["timeout"] = self.timeout
966+ d = self.get_page(url, **kwargs)
967+ return d.addErrback(ec2_error_wrapper)
968+
969+
970+class Signature(object):
971+ """Compute EC2-compliant signatures for requests.
972+
973+ @ivar creds: The L{AWSCredentials} to use to compute the signature.
974+ @ivar endpoint: The {AWSServiceEndpoint} to consider.
975+ @ivar params: A C{dict} of parameters to consider.
976+ """
977+
978+ def __init__(self, creds, endpoint, params):
979+ """Create a Query to submit to EC2."""
980+ self.creds = creds
981+ self.endpoint = endpoint
982+ self.params = params
983+
984+ def compute(self):
985+ """Compute and return the signature according to the given data."""
986+ if "Signature" in self.params:
987+ raise RuntimeError("Existing signature in parameters")
988+ version = self.params["SignatureVersion"]
989+ if version == "1":
990+ bytes = self.old_signing_text()
991+ hash_type = "sha1"
992+ elif version == "2":
993+ bytes = self.signing_text()
994+ hash_type = self.params["SignatureMethod"][len("Hmac"):].lower()
995+ else:
996+ raise RuntimeError("Unsupported SignatureVersion: '%s'" % version)
997+ return self.creds.sign(bytes, hash_type)
998+
999+ def old_signing_text(self):
1000+ """Return the text needed for signing using SignatureVersion 1."""
1001+ result = []
1002+ lower_cmp = lambda x, y: cmp(x[0].lower(), y[0].lower())
1003+ for key, value in sorted(self.params.items(), cmp=lower_cmp):
1004+ result.append("%s%s" % (key, value))
1005+ return "".join(result)
1006+
1007+ def signing_text(self):
1008+ """Return the text to be signed when signing the query."""
1009+ result = "%s\n%s\n%s\n%s" % (self.endpoint.method,
1010+ self.endpoint.get_canonical_host(),
1011+ self.endpoint.path,
1012+ self.get_canonical_query_params())
1013+ return result
1014+
1015+ def get_canonical_query_params(self):
1016+ """Return the canonical query params (used in signing)."""
1017+ result = []
1018+ for key, value in self.sorted_params():
1019+ result.append("%s=%s" % (self.encode(key), self.encode(value)))
1020+ return "&".join(result)
1021+
1022+ def encode(self, string):
1023+ """Encode a_string as per the canonicalisation encoding rules.
1024+
1025+ See the AWS dev reference page 90 (2008-12-01 version).
1026+ @return: a_string encoded.
1027+ """
1028+ return quote(string, safe="~")
1029+
1030+ def sorted_params(self):
1031+ """Return the query parameters sorted appropriately for signing."""
1032+ return sorted(self.params.items())
1033
1034=== added directory '.pc/fix-openstack-terminate-instances.patch/txaws/ec2/tests'
1035=== added file '.pc/fix-openstack-terminate-instances.patch/txaws/ec2/tests/test_client.py'
1036--- .pc/fix-openstack-terminate-instances.patch/txaws/ec2/tests/test_client.py 1970-01-01 00:00:00 +0000
1037+++ .pc/fix-openstack-terminate-instances.patch/txaws/ec2/tests/test_client.py 2011-09-30 09:11:28 +0000
1038@@ -0,0 +1,1996 @@
1039+# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
1040+# Copyright (C) 2009 Canonical Ltd
1041+# Copyright (C) 2009 Duncan McGreggor <oubiwann@adytum.us>
1042+# Licenced under the txaws licence available at /LICENSE in the txaws source.
1043+
1044+from datetime import datetime
1045+import os
1046+
1047+from twisted.internet import reactor
1048+from twisted.internet.defer import succeed, fail
1049+from twisted.internet.error import ConnectionRefusedError
1050+from twisted.python.failure import Failure
1051+from twisted.python.filepath import FilePath
1052+from twisted.web import server, static, util
1053+from twisted.web.error import Error as TwistedWebError
1054+from twisted.protocols.policies import WrappingFactory
1055+
1056+from txaws.util import iso8601time
1057+from txaws.credentials import AWSCredentials
1058+from txaws.ec2 import client
1059+from txaws.ec2 import model
1060+from txaws.ec2.exception import EC2Error
1061+from txaws.service import AWSServiceEndpoint, EC2_ENDPOINT_US
1062+from txaws.testing import payload
1063+from txaws.testing.base import TXAWSTestCase
1064+from txaws.testing.ec2 import FakePageGetter
1065+
1066+
1067+class ReservationTestCase(TXAWSTestCase):
1068+
1069+ def test_reservation_creation(self):
1070+ reservation = model.Reservation(
1071+ "id1", "owner", groups=["one", "two"])
1072+ self.assertEquals(reservation.reservation_id, "id1")
1073+ self.assertEquals(reservation.owner_id, "owner")
1074+ self.assertEquals(reservation.groups, ["one", "two"])
1075+
1076+
1077+class InstanceTestCase(TXAWSTestCase):
1078+
1079+ def test_instance_creation(self):
1080+ instance = model.Instance(
1081+ "id1", "running", "type", "id2", "dns1", "dns2", "key", "ami",
1082+ "time", "placement", ["prod1", "prod2"], "id3", "id4")
1083+ self.assertEquals(instance.instance_id, "id1")
1084+ self.assertEquals(instance.instance_state, "running")
1085+ self.assertEquals(instance.instance_type, "type")
1086+ self.assertEquals(instance.image_id, "id2")
1087+ self.assertEquals(instance.private_dns_name, "dns1")
1088+ self.assertEquals(instance.dns_name, "dns2")
1089+ self.assertEquals(instance.key_name, "key")
1090+ self.assertEquals(instance.ami_launch_index, "ami")
1091+ self.assertEquals(instance.launch_time, "time")
1092+ self.assertEquals(instance.placement, "placement")
1093+ self.assertEquals(instance.product_codes, ["prod1", "prod2"])
1094+ self.assertEquals(instance.kernel_id, "id3")
1095+ self.assertEquals(instance.ramdisk_id, "id4")
1096+
1097+
1098+class EC2ClientTestCase(TXAWSTestCase):
1099+
1100+ def test_init_no_creds(self):
1101+ os.environ["AWS_SECRET_ACCESS_KEY"] = "foo"
1102+ os.environ["AWS_ACCESS_KEY_ID"] = "bar"
1103+ ec2 = client.EC2Client()
1104+ self.assertNotEqual(None, ec2.creds)
1105+
1106+ def test_post_method(self):
1107+ """
1108+ If the method of the endpoint is POST, the parameters are passed in the
1109+ body.
1110+ """
1111+ self.addCleanup(setattr, client.Query, "get_page",
1112+ client.Query.get_page)
1113+
1114+ def get_page(query, url, *args, **kwargs):
1115+ self.assertEquals(args, ())
1116+ self.assertEquals(
1117+ kwargs["headers"],
1118+ {"Content-Type": "application/x-www-form-urlencoded"})
1119+ self.assertIn("postdata", kwargs)
1120+ self.assertEquals(kwargs["method"], "POST")
1121+ self.assertEquals(kwargs["timeout"], 30)
1122+ return succeed(payload.sample_describe_instances_result)
1123+
1124+ client.Query.get_page = get_page
1125+
1126+ creds = AWSCredentials("foo", "bar")
1127+ endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US, method="POST")
1128+ ec2 = client.EC2Client(creds=creds, endpoint=endpoint)
1129+ return ec2.describe_instances()
1130+
1131+ def test_init_no_creds_non_available_errors(self):
1132+ self.assertRaises(ValueError, client.EC2Client)
1133+
1134+ def test_init_explicit_creds(self):
1135+ creds = AWSCredentials("foo", "bar")
1136+ ec2 = client.EC2Client(creds=creds)
1137+ self.assertEqual(creds, ec2.creds)
1138+
1139+ def test_describe_availability_zones_single(self):
1140+
1141+ class StubQuery(object):
1142+
1143+ def __init__(stub, action="", creds=None, endpoint=None,
1144+ other_params={}):
1145+ self.assertEqual(action, "DescribeAvailabilityZones")
1146+ self.assertEqual(creds.access_key, "foo")
1147+ self.assertEqual(creds.secret_key, "bar")
1148+ self.assertEqual(
1149+ other_params,
1150+ {"ZoneName.1": "us-east-1a"})
1151+
1152+ def submit(self):
1153+ return succeed(
1154+ payload.sample_describe_availability_zones_single_result)
1155+
1156+ def check_parsed_availability_zone(results):
1157+ self.assertEquals(len(results), 1)
1158+ [zone] = results
1159+ self.assertEquals(zone.name, "us-east-1a")
1160+ self.assertEquals(zone.state, "available")
1161+
1162+ creds = AWSCredentials("foo", "bar")
1163+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1164+ d = ec2.describe_availability_zones(["us-east-1a"])
1165+ d.addCallback(check_parsed_availability_zone)
1166+ return d
1167+
1168+ def test_describe_availability_zones_multiple(self):
1169+
1170+ class StubQuery(object):
1171+
1172+ def __init__(stub, action="", creds=None, endpoint=None,
1173+ other_params={}):
1174+ self.assertEqual(action, "DescribeAvailabilityZones")
1175+ self.assertEqual(creds.access_key, "foo")
1176+ self.assertEqual(creds.secret_key, "bar")
1177+
1178+ def submit(self):
1179+ return succeed(
1180+ payload.sample_describe_availability_zones_multiple_results)
1181+
1182+ def check_parsed_availability_zones(results):
1183+ self.assertEquals(len(results), 3)
1184+ self.assertEquals(results[0].name, "us-east-1a")
1185+ self.assertEquals(results[0].state, "available")
1186+ self.assertEquals(results[1].name, "us-east-1b")
1187+ self.assertEquals(results[1].state, "available")
1188+ self.assertEquals(results[2].name, "us-east-1c")
1189+ self.assertEquals(results[2].state, "available")
1190+
1191+ creds = AWSCredentials("foo", "bar")
1192+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1193+ d = ec2.describe_availability_zones()
1194+ d.addCallback(check_parsed_availability_zones)
1195+ return d
1196+
1197+
1198+class EC2ClientInstancesTestCase(TXAWSTestCase):
1199+
1200+ def check_parsed_instances(self, results):
1201+ instance = results[0]
1202+ # check reservations
1203+ reservation = instance.reservation
1204+ self.assertEquals(reservation.reservation_id, "r-cf24b1a6")
1205+ self.assertEquals(reservation.owner_id, "123456789012")
1206+ # check groups
1207+ group = reservation.groups[0]
1208+ self.assertEquals(group, "default")
1209+ # check instance
1210+ self.assertEquals(instance.instance_id, "i-abcdef01")
1211+ self.assertEquals(instance.instance_state, "running")
1212+ self.assertEquals(instance.instance_type, "c1.xlarge")
1213+ self.assertEquals(instance.image_id, "ami-12345678")
1214+ self.assertEquals(
1215+ instance.private_dns_name,
1216+ "domU-12-31-39-03-15-11.compute-1.internal")
1217+ self.assertEquals(
1218+ instance.dns_name,
1219+ "ec2-75-101-245-65.compute-1.amazonaws.com")
1220+ self.assertEquals(instance.key_name, "keyname")
1221+ self.assertEquals(instance.ami_launch_index, "0")
1222+ self.assertEquals(instance.launch_time, "2009-04-27T02:23:18.000Z")
1223+ self.assertEquals(instance.placement, "us-east-1c")
1224+ self.assertEquals(instance.product_codes, ["774F4FF8"])
1225+ self.assertEquals(instance.kernel_id, "aki-b51cf9dc")
1226+ self.assertEquals(instance.ramdisk_id, "ari-b31cf9da")
1227+
1228+ def check_parsed_instances_required(self, results):
1229+ instance = results[0]
1230+ # check reservations
1231+ reservation = instance.reservation
1232+ self.assertEquals(reservation.reservation_id, "r-cf24b1a6")
1233+ self.assertEquals(reservation.owner_id, "123456789012")
1234+ # check groups
1235+ group = reservation.groups[0]
1236+ self.assertEquals(group, "default")
1237+ # check instance
1238+ self.assertEquals(instance.instance_id, "i-abcdef01")
1239+ self.assertEquals(instance.instance_state, "running")
1240+ self.assertEquals(instance.instance_type, "c1.xlarge")
1241+ self.assertEquals(instance.image_id, "ami-12345678")
1242+ self.assertEquals(
1243+ instance.private_dns_name,
1244+ "domU-12-31-39-03-15-11.compute-1.internal")
1245+ self.assertEquals(
1246+ instance.dns_name,
1247+ "ec2-75-101-245-65.compute-1.amazonaws.com")
1248+ self.assertEquals(instance.key_name, None)
1249+ self.assertEquals(instance.ami_launch_index, None)
1250+ self.assertEquals(instance.launch_time, "2009-04-27T02:23:18.000Z")
1251+ self.assertEquals(instance.placement, "us-east-1c")
1252+ self.assertEquals(instance.product_codes, [])
1253+ self.assertEquals(instance.kernel_id, None)
1254+ self.assertEquals(instance.ramdisk_id, None)
1255+
1256+ def test_parse_reservation(self):
1257+ creds = AWSCredentials("foo", "bar")
1258+ ec2 = client.EC2Client(creds=creds)
1259+ results = ec2.parser.describe_instances(
1260+ payload.sample_describe_instances_result)
1261+ self.check_parsed_instances(results)
1262+
1263+ def test_describe_instances(self):
1264+
1265+ class StubQuery(object):
1266+
1267+ def __init__(stub, action="", creds=None, endpoint=None,
1268+ other_params={}):
1269+ self.assertEqual(action, "DescribeInstances")
1270+ self.assertEqual(creds.access_key, "foo")
1271+ self.assertEqual(creds.secret_key, "bar")
1272+ self.assertEquals(other_params, {})
1273+
1274+ def submit(self):
1275+ return succeed(payload.sample_describe_instances_result)
1276+
1277+ creds = AWSCredentials("foo", "bar")
1278+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1279+ d = ec2.describe_instances()
1280+ d.addCallback(self.check_parsed_instances)
1281+ return d
1282+
1283+ def test_describe_instances_required(self):
1284+
1285+ class StubQuery(object):
1286+
1287+ def __init__(stub, action="", creds=None, endpoint=None,
1288+ other_params={}):
1289+ self.assertEqual(action, "DescribeInstances")
1290+ self.assertEqual(creds.access_key, "foo")
1291+ self.assertEqual(creds.secret_key, "bar")
1292+ self.assertEquals(other_params, {})
1293+
1294+ def submit(self):
1295+ return succeed(
1296+ payload.sample_required_describe_instances_result)
1297+
1298+ creds = AWSCredentials("foo", "bar")
1299+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1300+ d = ec2.describe_instances()
1301+ d.addCallback(self.check_parsed_instances_required)
1302+ return d
1303+
1304+ def test_describe_instances_specific_instances(self):
1305+
1306+ class StubQuery(object):
1307+
1308+ def __init__(stub, action="", creds=None, endpoint=None,
1309+ other_params={}):
1310+ self.assertEqual(action, "DescribeInstances")
1311+ self.assertEqual(creds.access_key, "foo")
1312+ self.assertEqual(creds.secret_key, "bar")
1313+ self.assertEquals(
1314+ other_params,
1315+ {"InstanceId.1": "i-16546401",
1316+ "InstanceId.2": "i-49873415"})
1317+
1318+ def submit(self):
1319+ return succeed(
1320+ payload.sample_required_describe_instances_result)
1321+
1322+ creds = AWSCredentials("foo", "bar")
1323+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1324+ d = ec2.describe_instances("i-16546401", "i-49873415")
1325+ d.addCallback(self.check_parsed_instances_required)
1326+ return d
1327+
1328+ def test_terminate_instances(self):
1329+
1330+ class StubQuery(object):
1331+
1332+ def __init__(stub, action="", creds=None, endpoint=None,
1333+ other_params={}):
1334+ self.assertEqual(action, "TerminateInstances")
1335+ self.assertEqual(creds.access_key, "foo")
1336+ self.assertEqual(creds.secret_key, "bar")
1337+ self.assertEqual(
1338+ other_params,
1339+ {"InstanceId.1": "i-1234", "InstanceId.2": "i-5678"})
1340+
1341+ def submit(self):
1342+ return succeed(payload.sample_terminate_instances_result)
1343+
1344+ def check_transition(changes):
1345+ self.assertEqual([("i-1234", "running", "shutting-down"),
1346+ ("i-5678", "shutting-down", "shutting-down")], sorted(changes))
1347+
1348+ creds = AWSCredentials("foo", "bar")
1349+ endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
1350+ ec2 = client.EC2Client(creds=creds, endpoint=endpoint,
1351+ query_factory=StubQuery)
1352+ d = ec2.terminate_instances("i-1234", "i-5678")
1353+ d.addCallback(check_transition)
1354+ return d
1355+
1356+ def check_parsed_run_instances(self, results):
1357+ instance = results[0]
1358+ # check reservations
1359+ reservation = instance.reservation
1360+ self.assertEquals(reservation.reservation_id, "r-47a5402e")
1361+ self.assertEquals(reservation.owner_id, "495219933132")
1362+ # check groups
1363+ group = reservation.groups[0]
1364+ self.assertEquals(group, "default")
1365+ # check instance
1366+ self.assertEquals(instance.instance_id, "i-2ba64342")
1367+ self.assertEquals(instance.instance_state, "pending")
1368+ self.assertEquals(instance.instance_type, "m1.small")
1369+ self.assertEquals(instance.placement, "us-east-1b")
1370+ instance = results[1]
1371+ self.assertEquals(instance.instance_id, "i-2bc64242")
1372+ self.assertEquals(instance.instance_state, "pending")
1373+ self.assertEquals(instance.instance_type, "m1.small")
1374+ self.assertEquals(instance.placement, "us-east-1b")
1375+ instance = results[2]
1376+ self.assertEquals(instance.instance_id, "i-2be64332")
1377+ self.assertEquals(instance.instance_state, "pending")
1378+ self.assertEquals(instance.instance_type, "m1.small")
1379+ self.assertEquals(instance.placement, "us-east-1b")
1380+
1381+ def test_run_instances(self):
1382+
1383+ class StubQuery(object):
1384+
1385+ def __init__(stub, action="", creds=None, endpoint=None,
1386+ other_params={}):
1387+ self.assertEqual(action, "RunInstances")
1388+ self.assertEqual(creds.access_key, "foo")
1389+ self.assertEqual(creds.secret_key, "bar")
1390+ self.assertEquals(
1391+ other_params,
1392+ {"ImageId": "ami-1234", "MaxCount": "2", "MinCount": "1",
1393+ "SecurityGroup.1": u"group1", "KeyName": u"default",
1394+ "UserData": "Zm9v", "InstanceType": u"m1.small",
1395+ "Placement.AvailabilityZone": u"us-east-1b",
1396+ "KernelId": u"k-1234", "RamdiskId": u"r-1234"})
1397+
1398+ def submit(self):
1399+ return succeed(
1400+ payload.sample_run_instances_result)
1401+
1402+ creds = AWSCredentials("foo", "bar")
1403+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1404+ d = ec2.run_instances("ami-1234", 1, 2, security_groups=[u"group1"],
1405+ key_name=u"default", user_data=u"foo", instance_type=u"m1.small",
1406+ availability_zone=u"us-east-1b", kernel_id=u"k-1234",
1407+ ramdisk_id=u"r-1234")
1408+ d.addCallback(self.check_parsed_run_instances)
1409+
1410+
1411+class EC2ClientSecurityGroupsTestCase(TXAWSTestCase):
1412+
1413+ def test_describe_security_groups(self):
1414+ """
1415+ L{EC2Client.describe_security_groups} returns a C{Deferred} that
1416+ eventually fires with a list of L{SecurityGroup} instances created
1417+ using XML data received from the cloud.
1418+ """
1419+ class StubQuery(object):
1420+
1421+ def __init__(stub, action="", creds=None, endpoint=None,
1422+ other_params={}):
1423+ self.assertEqual(action, "DescribeSecurityGroups")
1424+ self.assertEqual(creds.access_key, "foo")
1425+ self.assertEqual(creds.secret_key, "bar")
1426+ self.assertEqual(other_params, {})
1427+
1428+ def submit(self):
1429+ return succeed(payload.sample_describe_security_groups_result)
1430+
1431+ def check_results(security_groups):
1432+ [security_group] = security_groups
1433+ self.assertEquals(security_group.owner_id,
1434+ "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM")
1435+ self.assertEquals(security_group.name, "WebServers")
1436+ self.assertEquals(security_group.description, "Web Servers")
1437+ self.assertEquals(security_group.allowed_groups, [])
1438+ self.assertEquals(
1439+ [(ip.ip_protocol, ip.from_port, ip.to_port, ip.cidr_ip)
1440+ for ip in security_group.allowed_ips],
1441+ [("tcp", 80, 80, "0.0.0.0/0")])
1442+
1443+ creds = AWSCredentials("foo", "bar")
1444+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1445+ d = ec2.describe_security_groups()
1446+ return d.addCallback(check_results)
1447+
1448+ def test_describe_security_groups_with_multiple_results(self):
1449+ """
1450+ The C{DescribeSecurityGroupsResponse} XML payload retrieved when
1451+ L{EC2Client.describe_security_groups} is called can contain
1452+ information about more than one L{SecurityGroup}.
1453+ """
1454+ class StubQuery(object):
1455+
1456+ def __init__(stub, action="", creds=None, endpoint=None,
1457+ other_params={}):
1458+ self.assertEqual(action, "DescribeSecurityGroups")
1459+ self.assertEqual(creds.access_key, "foo")
1460+ self.assertEqual(creds.secret_key, "bar")
1461+ self.assertEqual(other_params, {})
1462+
1463+ def submit(self):
1464+ return succeed(
1465+ payload.sample_describe_security_groups_multiple_result)
1466+
1467+ def check_results(security_groups):
1468+ self.assertEquals(len(security_groups), 2)
1469+
1470+ security_group = security_groups[0]
1471+ self.assertEquals(security_group.owner_id,
1472+ "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM")
1473+ self.assertEquals(security_group.name, "MessageServers")
1474+ self.assertEquals(security_group.description, "Message Servers")
1475+ self.assertEquals(security_group.allowed_groups, [])
1476+ self.assertEquals(
1477+ [(ip.ip_protocol, ip.from_port, ip.to_port, ip.cidr_ip)
1478+ for ip in security_group.allowed_ips],
1479+ [("tcp", 80, 80, "0.0.0.0/0")])
1480+
1481+ security_group = security_groups[1]
1482+ self.assertEquals(security_group.owner_id,
1483+ "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM")
1484+ self.assertEquals(security_group.name, "WebServers")
1485+ self.assertEquals(security_group.description, "Web Servers")
1486+ self.assertEquals([(pair.user_id, pair.group_name)
1487+ for pair in security_group.allowed_groups],
1488+ [("group-user-id", "group-name1"),
1489+ ("group-user-id", "group-name2")])
1490+ self.assertEquals(
1491+ [(ip.ip_protocol, ip.from_port, ip.to_port, ip.cidr_ip)
1492+ for ip in security_group.allowed_ips],
1493+ [("tcp", 80, 80, "0.0.0.0/0")])
1494+
1495+ creds = AWSCredentials("foo", "bar")
1496+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1497+ d = ec2.describe_security_groups()
1498+ return d.addCallback(check_results)
1499+
1500+ def test_describe_security_groups_with_multiple_groups(self):
1501+ """
1502+ Several groups can be contained in a single ip permissions content, and
1503+ there are recognized by the group parser.
1504+ """
1505+ class StubQuery(object):
1506+
1507+ def __init__(stub, action="", creds=None, endpoint=None,
1508+ other_params={}):
1509+ self.assertEqual(action, "DescribeSecurityGroups")
1510+ self.assertEqual(creds.access_key, "foo")
1511+ self.assertEqual(creds.secret_key, "bar")
1512+ self.assertEqual(other_params, {})
1513+
1514+ def submit(self):
1515+ return succeed(
1516+ payload.sample_describe_security_groups_multiple_groups)
1517+
1518+ def check_results(security_groups):
1519+ self.assertEquals(len(security_groups), 1)
1520+
1521+ security_group = security_groups[0]
1522+ self.assertEquals(security_group.name, "web/ssh")
1523+ self.assertEquals([(pair.user_id, pair.group_name)
1524+ for pair in security_group.allowed_groups],
1525+ [("170723411662", "default"),
1526+ ("175723011368", "test1")])
1527+ self.assertEquals(
1528+ [(ip.ip_protocol, ip.from_port, ip.to_port, ip.cidr_ip)
1529+ for ip in security_group.allowed_ips],
1530+ [('tcp', 22, 22, '0.0.0.0/0'), ("tcp", 80, 80, "0.0.0.0/0")])
1531+
1532+ creds = AWSCredentials("foo", "bar")
1533+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1534+ d = ec2.describe_security_groups()
1535+ return d.addCallback(check_results)
1536+
1537+ def test_describe_security_groups_with_name(self):
1538+ """
1539+ L{EC2Client.describe_security_groups} optionally takes a list of
1540+ security group names to limit results to.
1541+ """
1542+ class StubQuery(object):
1543+
1544+ def __init__(stub, action="", creds=None, endpoint=None,
1545+ other_params={}):
1546+ self.assertEqual(action, "DescribeSecurityGroups")
1547+ self.assertEqual(creds.access_key, "foo")
1548+ self.assertEqual(creds.secret_key, "bar")
1549+ self.assertEqual(other_params, {"GroupName.1": "WebServers"})
1550+
1551+ def submit(self):
1552+ return succeed(payload.sample_describe_security_groups_result)
1553+
1554+ def check_result(security_groups):
1555+ [security_group] = security_groups
1556+ self.assertEquals(security_group.name, "WebServers")
1557+
1558+ creds = AWSCredentials("foo", "bar")
1559+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1560+ d = ec2.describe_security_groups("WebServers")
1561+ return d.addCallback(check_result)
1562+
1563+ def test_describe_security_groups_with_openstack(self):
1564+ """
1565+ L{EC2Client.describe_security_groups} can work with openstack
1566+ responses, which may lack proper port information for
1567+ self-referencing group. Verifying that the response doesn't
1568+ cause an internal error, workaround for nova launchpad bug
1569+ #829609.
1570+ """
1571+ class StubQuery(object):
1572+
1573+ def __init__(stub, action="", creds=None, endpoint=None,
1574+ other_params={}):
1575+ self.assertEqual(action, "DescribeSecurityGroups")
1576+ self.assertEqual(creds.access_key, "foo")
1577+ self.assertEqual(creds.secret_key, "bar")
1578+ self.assertEqual(other_params, {"GroupName.1": "WebServers"})
1579+
1580+ def submit(self):
1581+ return succeed(
1582+ payload.sample_describe_security_groups_with_openstack)
1583+
1584+ def check_result(security_groups):
1585+ [security_group] = security_groups
1586+ self.assertEquals(security_group.name, "WebServers")
1587+ self.assertEqual(
1588+ security_group.allowed_groups[0].group_name, "WebServers")
1589+
1590+ creds = AWSCredentials("foo", "bar")
1591+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1592+ d = ec2.describe_security_groups("WebServers")
1593+ return d.addCallback(check_result)
1594+
1595+ def test_create_security_group(self):
1596+ """
1597+ L{EC2Client.create_security_group} returns a C{Deferred} that
1598+ eventually fires with a true value, indicating the success of the
1599+ operation.
1600+ """
1601+ class StubQuery(object):
1602+
1603+ def __init__(stub, action="", creds=None, endpoint=None,
1604+ other_params={}):
1605+ self.assertEqual(action, "CreateSecurityGroup")
1606+ self.assertEqual(creds.access_key, "foo")
1607+ self.assertEqual(creds.secret_key, "bar")
1608+ self.assertEqual(other_params, {
1609+ "GroupName": "WebServers",
1610+ "GroupDescription": "The group for the web server farm.",
1611+ })
1612+
1613+ def submit(self):
1614+ return succeed(payload.sample_create_security_group)
1615+
1616+ creds = AWSCredentials("foo", "bar")
1617+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1618+ d = ec2.create_security_group(
1619+ "WebServers",
1620+ "The group for the web server farm.")
1621+ return self.assertTrue(d)
1622+
1623+ def test_delete_security_group(self):
1624+ """
1625+ L{EC2Client.delete_security_group} returns a C{Deferred} that
1626+ eventually fires with a true value, indicating the success of the
1627+ operation.
1628+ """
1629+ class StubQuery(object):
1630+
1631+ def __init__(stub, action="", creds=None, endpoint=None,
1632+ other_params={}):
1633+ self.assertEqual(action, "DeleteSecurityGroup")
1634+ self.assertEqual(creds.access_key, "foo")
1635+ self.assertEqual(creds.secret_key, "bar")
1636+ self.assertEqual(other_params, {
1637+ "GroupName": "WebServers",
1638+ })
1639+
1640+ def submit(self):
1641+ return succeed(payload.sample_delete_security_group)
1642+
1643+ creds = AWSCredentials("foo", "bar")
1644+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1645+ d = ec2.delete_security_group("WebServers")
1646+ return self.assertTrue(d)
1647+
1648+ def test_delete_security_group_failure(self):
1649+ """
1650+ L{EC2Client.delete_security_group} returns a C{Deferred} that
1651+ eventually fires with a failure when EC2 is asked to delete a group
1652+ that another group uses in that other group's policy.
1653+ """
1654+ class StubQuery(object):
1655+
1656+ def __init__(stub, action="", creds=None, endpoint=None,
1657+ other_params={}):
1658+ self.assertEqual(action, "DeleteSecurityGroup")
1659+ self.assertEqual(creds.access_key, "foo")
1660+ self.assertEqual(creds.secret_key, "bar")
1661+ self.assertEqual(other_params, {
1662+ "GroupName": "GroupReferredTo",
1663+ })
1664+
1665+ def submit(self):
1666+ error = EC2Error(
1667+ payload.sample_delete_security_group_failure, 400)
1668+ return fail(error)
1669+
1670+ def check_error(error):
1671+ self.assertEquals(
1672+ str(error),
1673+ ("Error Message: Group groupID1:GroupReferredTo is used by "
1674+ "groups: groupID2:UsingGroup"))
1675+
1676+ creds = AWSCredentials("foo", "bar")
1677+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1678+ failure = ec2.delete_security_group("GroupReferredTo")
1679+ d = self.assertFailure(failure, EC2Error)
1680+ return d.addCallback(check_error)
1681+
1682+ def test_authorize_security_group_with_user_group_pair(self):
1683+ """
1684+ L{EC2Client.authorize_security_group} returns a C{Deferred} that
1685+ eventually fires with a true value, indicating the success of the
1686+ operation. There are two ways to use the method: set another group's
1687+ IP permissions or set new IP permissions; this test checks the first
1688+ way.
1689+ """
1690+ class StubQuery(object):
1691+
1692+ def __init__(stub, action="", creds=None, endpoint=None,
1693+ other_params={}):
1694+ self.assertEqual(action, "AuthorizeSecurityGroupIngress")
1695+ self.assertEqual(creds.access_key, "foo")
1696+ self.assertEqual(creds.secret_key, "bar")
1697+ self.assertEqual(other_params, {
1698+ "GroupName": "WebServers",
1699+ "SourceSecurityGroupName": "AppServers",
1700+ "SourceSecurityGroupOwnerId": "123456789123",
1701+ })
1702+
1703+ def submit(self):
1704+ return succeed(payload.sample_authorize_security_group)
1705+
1706+ creds = AWSCredentials("foo", "bar")
1707+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1708+ d = ec2.authorize_security_group(
1709+ "WebServers", source_group_name="AppServers",
1710+ source_group_owner_id="123456789123")
1711+ return self.assertTrue(d)
1712+
1713+ def test_authorize_security_group_with_ip_permissions(self):
1714+ """
1715+ L{EC2Client.authorize_security_group} returns a C{Deferred} that
1716+ eventually fires with a true value, indicating the success of the
1717+ operation. There are two ways to use the method: set another group's
1718+ IP permissions or set new IP permissions; this test checks the second
1719+ way.
1720+ """
1721+ class StubQuery(object):
1722+
1723+ def __init__(stub, action="", creds=None, endpoint=None,
1724+ other_params={}):
1725+ self.assertEqual(action, "AuthorizeSecurityGroupIngress")
1726+ self.assertEqual(creds.access_key, "foo")
1727+ self.assertEqual(creds.secret_key, "bar")
1728+ self.assertEqual(other_params, {
1729+ "GroupName": "WebServers",
1730+ "FromPort": "22", "ToPort": "80",
1731+ "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0",
1732+ })
1733+
1734+ def submit(self):
1735+ return succeed(payload.sample_authorize_security_group)
1736+
1737+ creds = AWSCredentials("foo", "bar")
1738+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1739+ d = ec2.authorize_security_group(
1740+ "WebServers", ip_protocol="tcp", from_port="22", to_port="80",
1741+ cidr_ip="0.0.0.0/0")
1742+ return self.assertTrue(d)
1743+
1744+ def test_authorize_security_group_with_missing_parameters(self):
1745+ """
1746+ L{EC2Client.authorize_security_group} returns a C{Deferred} that
1747+ eventually fires with a true value, indicating the success of the
1748+ operation. There are two ways to use the method: set another group's
1749+ IP permissions or set new IP permissions. If not all group-setting
1750+ parameters are set and not all IP permission parameters are set, an
1751+ error is raised.
1752+ """
1753+ creds = AWSCredentials("foo", "bar")
1754+ ec2 = client.EC2Client(creds)
1755+ self.assertRaises(ValueError, ec2.authorize_security_group,
1756+ "WebServers", ip_protocol="tcp", from_port="22")
1757+ try:
1758+ ec2.authorize_security_group(
1759+ "WebServers", ip_protocol="tcp", from_port="22")
1760+ except Exception, error:
1761+ self.assertEquals(
1762+ str(error),
1763+ ("You must specify either both group parameters or all the "
1764+ "ip parameters."))
1765+
1766+ def test_authorize_group_permission(self):
1767+ """
1768+ L{EC2Client.authorize_group_permission} returns a C{Deferred}
1769+ that eventually fires with a true value, indicating the success of the
1770+ operation.
1771+ """
1772+ class StubQuery(object):
1773+
1774+ def __init__(stub, action="", creds=None, endpoint=None,
1775+ other_params={}):
1776+ self.assertEqual(action, "AuthorizeSecurityGroupIngress")
1777+ self.assertEqual(creds.access_key, "foo")
1778+ self.assertEqual(creds.secret_key, "bar")
1779+ self.assertEqual(other_params, {
1780+ "GroupName": "WebServers",
1781+ "SourceSecurityGroupName": "AppServers",
1782+ "SourceSecurityGroupOwnerId": "123456789123",
1783+ })
1784+
1785+ def submit(self):
1786+ return succeed(payload.sample_authorize_security_group)
1787+
1788+ creds = AWSCredentials("foo", "bar")
1789+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1790+ d = ec2.authorize_group_permission(
1791+ "WebServers", source_group_name="AppServers",
1792+ source_group_owner_id="123456789123")
1793+ return self.assertTrue(d)
1794+
1795+ def test_authorize_ip_permission(self):
1796+ """
1797+ L{EC2Client.authorize_ip_permission} returns a C{Deferred} that
1798+ eventually fires with a true value, indicating the success of the
1799+ operation.
1800+ """
1801+ class StubQuery(object):
1802+
1803+ def __init__(stub, action="", creds=None, endpoint=None,
1804+ other_params={}):
1805+ self.assertEqual(action, "AuthorizeSecurityGroupIngress")
1806+ self.assertEqual(creds.access_key, "foo")
1807+ self.assertEqual(creds.secret_key, "bar")
1808+ self.assertEqual(other_params, {
1809+ "GroupName": "WebServers",
1810+ "FromPort": "22", "ToPort": "80",
1811+ "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0",
1812+ })
1813+
1814+ def submit(self):
1815+ return succeed(payload.sample_authorize_security_group)
1816+
1817+ creds = AWSCredentials("foo", "bar")
1818+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1819+ d = ec2.authorize_ip_permission(
1820+ "WebServers", ip_protocol="tcp", from_port="22", to_port="80",
1821+ cidr_ip="0.0.0.0/0")
1822+ return self.assertTrue(d)
1823+
1824+ def test_revoke_security_group_with_user_group_pair(self):
1825+ """
1826+ L{EC2Client.revoke_security_group} returns a C{Deferred} that
1827+ eventually fires with a true value, indicating the success of the
1828+ operation. There are two ways to use the method: set another group's
1829+ IP permissions or set new IP permissions; this test checks the first
1830+ way.
1831+ """
1832+ class StubQuery(object):
1833+
1834+ def __init__(stub, action="", creds=None, endpoint=None,
1835+ other_params={}):
1836+ self.assertEqual(action, "RevokeSecurityGroupIngress")
1837+ self.assertEqual(creds.access_key, "foo")
1838+ self.assertEqual(creds.secret_key, "bar")
1839+ self.assertEqual(other_params, {
1840+ "GroupName": "WebServers",
1841+ "SourceSecurityGroupName": "AppServers",
1842+ "SourceSecurityGroupOwnerId": "123456789123",
1843+ })
1844+
1845+ def submit(self):
1846+ return succeed(payload.sample_revoke_security_group)
1847+
1848+ creds = AWSCredentials("foo", "bar")
1849+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1850+ d = ec2.revoke_security_group(
1851+ "WebServers", source_group_name="AppServers",
1852+ source_group_owner_id="123456789123")
1853+ return self.assertTrue(d)
1854+
1855+ def test_revoke_security_group_with_ip_permissions(self):
1856+ """
1857+ L{EC2Client.revoke_security_group} returns a C{Deferred} that
1858+ eventually fires with a true value, indicating the success of the
1859+ operation. There are two ways to use the method: set another group's
1860+ IP permissions or set new IP permissions; this test checks the second
1861+ way.
1862+ """
1863+ class StubQuery(object):
1864+
1865+ def __init__(stub, action="", creds=None, endpoint=None,
1866+ other_params={}):
1867+ self.assertEqual(action, "RevokeSecurityGroupIngress")
1868+ self.assertEqual(creds.access_key, "foo")
1869+ self.assertEqual(creds.secret_key, "bar")
1870+ self.assertEqual(other_params, {
1871+ "GroupName": "WebServers",
1872+ "FromPort": "22", "ToPort": "80",
1873+ "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0",
1874+ })
1875+
1876+ def submit(self):
1877+ return succeed(payload.sample_revoke_security_group)
1878+
1879+ creds = AWSCredentials("foo", "bar")
1880+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1881+ d = ec2.revoke_security_group(
1882+ "WebServers", ip_protocol="tcp", from_port="22", to_port="80",
1883+ cidr_ip="0.0.0.0/0")
1884+ return self.assertTrue(d)
1885+
1886+ def test_revoke_security_group_with_missing_parameters(self):
1887+ """
1888+ L{EC2Client.revoke_security_group} returns a C{Deferred} that
1889+ eventually fires with a true value, indicating the success of the
1890+ operation. There are two ways to use the method: set another group's
1891+ IP permissions or set new IP permissions. If not all group-setting
1892+ parameters are set and not all IP permission parameters are set, an
1893+ error is raised.
1894+ """
1895+ creds = AWSCredentials("foo", "bar")
1896+ ec2 = client.EC2Client(creds)
1897+ self.assertRaises(ValueError, ec2.authorize_security_group,
1898+ "WebServers", ip_protocol="tcp", from_port="22")
1899+ try:
1900+ ec2.authorize_security_group(
1901+ "WebServers", ip_protocol="tcp", from_port="22")
1902+ except Exception, error:
1903+ self.assertEquals(
1904+ str(error),
1905+ ("You must specify either both group parameters or all the "
1906+ "ip parameters."))
1907+
1908+ def test_revoke_group_permission(self):
1909+ """
1910+ L{EC2Client.revoke_group_permission} returns a C{Deferred} that
1911+ eventually fires with a true value, indicating the success of the
1912+ operation.
1913+ """
1914+ class StubQuery(object):
1915+
1916+ def __init__(stub, action="", creds=None, endpoint=None,
1917+ other_params={}):
1918+ self.assertEqual(action, "RevokeSecurityGroupIngress")
1919+ self.assertEqual(creds.access_key, "foo")
1920+ self.assertEqual(creds.secret_key, "bar")
1921+ self.assertEqual(other_params, {
1922+ "GroupName": "WebServers",
1923+ "SourceSecurityGroupName": "AppServers",
1924+ "SourceSecurityGroupOwnerId": "123456789123",
1925+ })
1926+
1927+ def submit(self):
1928+ return succeed(payload.sample_revoke_security_group)
1929+
1930+ creds = AWSCredentials("foo", "bar")
1931+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1932+ d = ec2.revoke_group_permission(
1933+ "WebServers", source_group_name="AppServers",
1934+ source_group_owner_id="123456789123")
1935+ return self.assertTrue(d)
1936+
1937+ def test_revoke_ip_permission(self):
1938+ """
1939+ L{EC2Client.revoke_ip_permission} returns a C{Deferred} that
1940+ eventually fires with a true value, indicating the success of the
1941+ operation.
1942+ """
1943+ class StubQuery(object):
1944+
1945+ def __init__(stub, action="", creds=None, endpoint=None,
1946+ other_params={}):
1947+ self.assertEqual(action, "RevokeSecurityGroupIngress")
1948+ self.assertEqual(creds.access_key, "foo")
1949+ self.assertEqual(creds.secret_key, "bar")
1950+ self.assertEqual(other_params, {
1951+ "GroupName": "WebServers",
1952+ "FromPort": "22", "ToPort": "80",
1953+ "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0",
1954+ })
1955+
1956+ def submit(self):
1957+ return succeed(payload.sample_revoke_security_group)
1958+
1959+ creds = AWSCredentials("foo", "bar")
1960+ ec2 = client.EC2Client(creds, query_factory=StubQuery)
1961+ d = ec2.revoke_ip_permission(
1962+ "WebServers", ip_protocol="tcp", from_port="22", to_port="80",
1963+ cidr_ip="0.0.0.0/0")
1964+ return self.assertTrue(d)
1965+
1966+
1967+class EC2ClientEBSTestCase(TXAWSTestCase):
1968+
1969+ def setUp(self):
1970+ TXAWSTestCase.setUp(self)
1971+ self.creds = AWSCredentials("foo", "bar")
1972+ self.endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
1973+
1974+ def check_parsed_volumes(self, volumes):
1975+ self.assertEquals(len(volumes), 1)
1976+ volume = volumes[0]
1977+ self.assertEquals(volume.id, "vol-4282672b")
1978+ self.assertEquals(volume.size, 800)
1979+ self.assertEquals(volume.status, "in-use")
1980+ self.assertEquals(volume.availability_zone, "us-east-1a")
1981+ self.assertEquals(volume.snapshot_id, "snap-12345678")
1982+ create_time = datetime(2008, 05, 07, 11, 51, 50)
1983+ self.assertEquals(volume.create_time, create_time)
1984+ self.assertEquals(len(volume.attachments), 1)
1985+ attachment = volume.attachments[0]
1986+ self.assertEquals(attachment.instance_id, "i-6058a509")
1987+ self.assertEquals(attachment.status, "attached")
1988+ self.assertEquals(attachment.device, u"/dev/sdh")
1989+ attach_time = datetime(2008, 05, 07, 12, 51, 50)
1990+ self.assertEquals(attachment.attach_time, attach_time)
1991+
1992+ def test_describe_volumes(self):
1993+
1994+ class StubQuery(object):
1995+
1996+ def __init__(stub, action="", creds=None, endpoint=None,
1997+ other_params={}):
1998+ self.assertEqual(action, "DescribeVolumes")
1999+ self.assertEqual(self.creds, creds)
2000+ self.assertEqual(self.endpoint, endpoint)
2001+ self.assertEquals(other_params, {})
2002+
2003+ def submit(self):
2004+ return succeed(payload.sample_describe_volumes_result)
2005+
2006+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2007+ query_factory=StubQuery)
2008+ d = ec2.describe_volumes()
2009+ d.addCallback(self.check_parsed_volumes)
2010+ return d
2011+
2012+ def test_describe_specified_volumes(self):
2013+
2014+ class StubQuery(object):
2015+
2016+ def __init__(stub, action="", creds=None, endpoint=None,
2017+ other_params={}):
2018+ self.assertEqual(action, "DescribeVolumes")
2019+ self.assertEqual(self.creds, creds)
2020+ self.assertEqual(self.endpoint, endpoint)
2021+ self.assertEquals(
2022+ other_params,
2023+ {"VolumeId.1": "vol-4282672b"})
2024+
2025+ def submit(self):
2026+ return succeed(payload.sample_describe_volumes_result)
2027+
2028+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2029+ query_factory=StubQuery)
2030+ d = ec2.describe_volumes("vol-4282672b")
2031+ d.addCallback(self.check_parsed_volumes)
2032+ return d
2033+
2034+ def check_parsed_snapshots(self, snapshots):
2035+ self.assertEquals(len(snapshots), 1)
2036+ snapshot = snapshots[0]
2037+ self.assertEquals(snapshot.id, "snap-78a54011")
2038+ self.assertEquals(snapshot.volume_id, "vol-4d826724")
2039+ self.assertEquals(snapshot.status, "pending")
2040+ start_time = datetime(2008, 05, 07, 12, 51, 50)
2041+ self.assertEquals(snapshot.start_time, start_time)
2042+ self.assertEquals(snapshot.progress, 0.8)
2043+
2044+ def test_describe_snapshots(self):
2045+
2046+ class StubQuery(object):
2047+
2048+ def __init__(stub, action="", creds=None, endpoint=None,
2049+ other_params={}):
2050+ self.assertEqual(action, "DescribeSnapshots")
2051+ self.assertEqual(self.creds, creds)
2052+ self.assertEqual(self.endpoint, endpoint)
2053+ self.assertEquals(other_params, {})
2054+
2055+ def submit(self):
2056+ return succeed(payload.sample_describe_snapshots_result)
2057+
2058+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2059+ query_factory=StubQuery)
2060+ d = ec2.describe_snapshots()
2061+ d.addCallback(self.check_parsed_snapshots)
2062+ return d
2063+
2064+ def test_describe_specified_snapshots(self):
2065+
2066+ class StubQuery(object):
2067+
2068+ def __init__(stub, action="", creds=None, endpoint=None,
2069+ other_params={}):
2070+ self.assertEqual(action, "DescribeSnapshots")
2071+ self.assertEqual(self.creds, creds)
2072+ self.assertEqual(self.endpoint, endpoint)
2073+ self.assertEquals(
2074+ other_params,
2075+ {"SnapshotId.1": "snap-78a54011"})
2076+
2077+ def submit(self):
2078+ return succeed(payload.sample_describe_snapshots_result)
2079+
2080+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2081+ query_factory=StubQuery)
2082+ d = ec2.describe_snapshots("snap-78a54011")
2083+ d.addCallback(self.check_parsed_snapshots)
2084+ return d
2085+
2086+ def test_create_volume(self):
2087+
2088+ class StubQuery(object):
2089+
2090+ def __init__(stub, action="", creds=None, endpoint=None,
2091+ other_params={}):
2092+ self.assertEqual(action, "CreateVolume")
2093+ self.assertEqual(self.creds, creds)
2094+ self.assertEqual(self.endpoint, endpoint)
2095+ self.assertEqual(
2096+ other_params,
2097+ {"AvailabilityZone": "us-east-1", "Size": "800"})
2098+
2099+ def submit(self):
2100+ return succeed(payload.sample_create_volume_result)
2101+
2102+ def check_parsed_volume(volume):
2103+ self.assertEquals(volume.id, "vol-4d826724")
2104+ self.assertEquals(volume.size, 800)
2105+ self.assertEquals(volume.snapshot_id, "")
2106+ create_time = datetime(2008, 05, 07, 11, 51, 50)
2107+ self.assertEquals(volume.create_time, create_time)
2108+
2109+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2110+ query_factory=StubQuery)
2111+ d = ec2.create_volume("us-east-1", size=800)
2112+ d.addCallback(check_parsed_volume)
2113+ return d
2114+
2115+ def test_create_volume_with_snapshot(self):
2116+
2117+ class StubQuery(object):
2118+
2119+ def __init__(stub, action="", creds=None, endpoint=None,
2120+ other_params={}):
2121+ self.assertEqual(action, "CreateVolume")
2122+ self.assertEqual(self.creds, creds)
2123+ self.assertEqual(self.endpoint, endpoint)
2124+ self.assertEqual(
2125+ other_params,
2126+ {"AvailabilityZone": "us-east-1",
2127+ "SnapshotId": "snap-12345678"})
2128+
2129+ def submit(self):
2130+ return succeed(payload.sample_create_volume_result)
2131+
2132+ def check_parsed_volume(volume):
2133+ self.assertEquals(volume.id, "vol-4d826724")
2134+ self.assertEquals(volume.size, 800)
2135+ create_time = datetime(2008, 05, 07, 11, 51, 50)
2136+ self.assertEquals(volume.create_time, create_time)
2137+
2138+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2139+ query_factory=StubQuery)
2140+ d = ec2.create_volume("us-east-1", snapshot_id="snap-12345678")
2141+ d.addCallback(check_parsed_volume)
2142+ return d
2143+
2144+ def test_create_volume_no_params(self):
2145+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint)
2146+ error = self.assertRaises(ValueError, ec2.create_volume, "us-east-1")
2147+ self.assertEquals(
2148+ str(error),
2149+ "Please provide either size or snapshot_id")
2150+
2151+ def test_create_volume_both_params(self):
2152+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint)
2153+ error = self.assertRaises(ValueError, ec2.create_volume, "us-east-1",
2154+ size=800, snapshot_id="snap-12345678")
2155+ self.assertEquals(
2156+ str(error),
2157+ "Please provide either size or snapshot_id")
2158+
2159+ def test_delete_volume(self):
2160+
2161+ class StubQuery(object):
2162+
2163+ def __init__(stub, action="", creds=None, endpoint=None,
2164+ other_params={}):
2165+ self.assertEqual(action, "DeleteVolume")
2166+ self.assertEqual(self.creds, creds)
2167+ self.assertEqual(self.endpoint, endpoint)
2168+ self.assertEqual(
2169+ other_params,
2170+ {"VolumeId": "vol-4282672b"})
2171+
2172+ def submit(self):
2173+ return succeed(payload.sample_delete_volume_result)
2174+
2175+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2176+ query_factory=StubQuery)
2177+ d = ec2.delete_volume("vol-4282672b")
2178+ d.addCallback(self.assertEquals, True)
2179+ return d
2180+
2181+ def test_create_snapshot(self):
2182+
2183+ class StubQuery(object):
2184+
2185+ def __init__(stub, action="", creds=None, endpoint=None,
2186+ other_params={}):
2187+ self.assertEqual(action, "CreateSnapshot")
2188+ self.assertEqual(self.creds, creds)
2189+ self.assertEqual(self.endpoint, endpoint)
2190+ self.assertEqual(
2191+ other_params,
2192+ {"VolumeId": "vol-4d826724"})
2193+
2194+ def submit(self):
2195+ return succeed(payload.sample_create_snapshot_result)
2196+
2197+ def check_parsed_snapshot(snapshot):
2198+ self.assertEquals(snapshot.id, "snap-78a54011")
2199+ self.assertEquals(snapshot.volume_id, "vol-4d826724")
2200+ self.assertEquals(snapshot.status, "pending")
2201+ start_time = datetime(2008, 05, 07, 12, 51, 50)
2202+ self.assertEquals(snapshot.start_time, start_time)
2203+ self.assertEquals(snapshot.progress, 0)
2204+
2205+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2206+ query_factory=StubQuery)
2207+ d = ec2.create_snapshot("vol-4d826724")
2208+ d.addCallback(check_parsed_snapshot)
2209+ return d
2210+
2211+ def test_delete_snapshot(self):
2212+
2213+ class StubQuery(object):
2214+
2215+ def __init__(stub, action="", creds=None, endpoint=None,
2216+ other_params={}):
2217+ self.assertEqual(action, "DeleteSnapshot")
2218+ self.assertEqual(self.creds, creds)
2219+ self.assertEqual(self.endpoint, endpoint)
2220+ self.assertEqual(
2221+ other_params,
2222+ {"SnapshotId": "snap-78a54011"})
2223+
2224+ def submit(self):
2225+ return succeed(payload.sample_delete_snapshot_result)
2226+
2227+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2228+ query_factory=StubQuery)
2229+ d = ec2.delete_snapshot("snap-78a54011")
2230+ d.addCallback(self.assertEquals, True)
2231+ return d
2232+
2233+ def test_attach_volume(self):
2234+
2235+ class StubQuery(object):
2236+
2237+ def __init__(stub, action="", creds=None, endpoint=None,
2238+ other_params={}):
2239+ self.assertEqual(action, "AttachVolume")
2240+ self.assertEqual(self.creds, creds)
2241+ self.assertEqual(self.endpoint, endpoint)
2242+ self.assertEqual(
2243+ other_params,
2244+ {"VolumeId": "vol-4d826724", "InstanceId": "i-6058a509",
2245+ "Device": "/dev/sdh"})
2246+
2247+ def submit(self):
2248+ return succeed(payload.sample_attach_volume_result)
2249+
2250+ def check_parsed_response(response):
2251+ self.assertEquals(
2252+ response,
2253+ {"status": "attaching",
2254+ "attach_time": datetime(2008, 05, 07, 11, 51, 50)})
2255+
2256+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2257+ query_factory=StubQuery)
2258+ d = ec2.attach_volume("vol-4d826724", "i-6058a509", "/dev/sdh")
2259+ d.addCallback(check_parsed_response)
2260+ return d
2261+
2262+ def check_parsed_keypairs(self, results):
2263+ self.assertEquals(len(results), 1)
2264+ keypair = results[0]
2265+ self.assertEquals(keypair.name, "gsg-keypair")
2266+ self.assertEquals(
2267+ keypair.fingerprint,
2268+ "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f")
2269+
2270+ def test_single_describe_keypairs(self):
2271+
2272+ class StubQuery(object):
2273+
2274+ def __init__(stub, action="", creds=None, endpoint=None,
2275+ other_params={}):
2276+ self.assertEqual(action, "DescribeKeyPairs")
2277+ self.assertEqual("foo", creds)
2278+ self.assertEquals(other_params, {})
2279+
2280+ def submit(self):
2281+ return succeed(payload.sample_single_describe_keypairs_result)
2282+
2283+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2284+ d = ec2.describe_keypairs()
2285+ d.addCallback(self.check_parsed_keypairs)
2286+ return d
2287+
2288+ def test_multiple_describe_keypairs(self):
2289+
2290+ def check_parsed_keypairs(results):
2291+ self.assertEquals(len(results), 2)
2292+ keypair1, keypair2 = results
2293+ self.assertEquals(keypair1.name, "gsg-keypair-1")
2294+ self.assertEquals(
2295+ keypair1.fingerprint,
2296+ "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f")
2297+ self.assertEquals(keypair2.name, "gsg-keypair-2")
2298+ self.assertEquals(
2299+ keypair2.fingerprint,
2300+ "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:70")
2301+
2302+ class StubQuery(object):
2303+
2304+ def __init__(stub, action="", creds=None, endpoint=None,
2305+ other_params={}):
2306+ self.assertEqual(action, "DescribeKeyPairs")
2307+ self.assertEqual("foo", creds)
2308+ self.assertEquals(other_params, {})
2309+
2310+ def submit(self):
2311+ return succeed(
2312+ payload.sample_multiple_describe_keypairs_result)
2313+
2314+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2315+ d = ec2.describe_keypairs()
2316+ d.addCallback(check_parsed_keypairs)
2317+ return d
2318+
2319+ def test_describe_specified_keypairs(self):
2320+
2321+ class StubQuery(object):
2322+
2323+ def __init__(stub, action="", creds=None, endpoint=None,
2324+ other_params={}):
2325+ self.assertEqual(action, "DescribeKeyPairs")
2326+ self.assertEqual("foo", creds)
2327+ self.assertEquals(
2328+ other_params,
2329+ {"KeyPair.1": "gsg-keypair"})
2330+
2331+ def submit(self):
2332+ return succeed(payload.sample_single_describe_keypairs_result)
2333+
2334+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2335+ d = ec2.describe_keypairs("gsg-keypair")
2336+ d.addCallback(self.check_parsed_keypairs)
2337+ return d
2338+
2339+ def test_create_keypair(self):
2340+
2341+ def check_parsed_create_keypair(keypair):
2342+ self.assertEquals(keypair.name, "example-key-name")
2343+ self.assertEquals(
2344+ keypair.fingerprint,
2345+ "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f")
2346+ self.assertTrue(keypair.material.startswith(
2347+ "-----BEGIN RSA PRIVATE KEY-----"))
2348+ self.assertTrue(keypair.material.endswith(
2349+ "-----END RSA PRIVATE KEY-----"))
2350+ self.assertEquals(len(keypair.material), 1670)
2351+
2352+ class StubQuery(object):
2353+
2354+ def __init__(stub, action="", creds=None, endpoint=None,
2355+ other_params={}):
2356+ self.assertEqual(action, "CreateKeyPair")
2357+ self.assertEqual("foo", creds)
2358+ self.assertEquals(
2359+ other_params,
2360+ {"KeyName": "example-key-name"})
2361+
2362+ def submit(self):
2363+ return succeed(payload.sample_create_keypair_result)
2364+
2365+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2366+ d = ec2.create_keypair("example-key-name")
2367+ d.addCallback(check_parsed_create_keypair)
2368+ return d
2369+
2370+ def test_delete_keypair_true_result(self):
2371+
2372+ class StubQuery(object):
2373+
2374+ def __init__(stub, action="", creds=None, endpoint=None,
2375+ other_params={}):
2376+ self.assertEqual(action, "DeleteKeyPair")
2377+ self.assertEqual("foo", creds)
2378+ self.assertEqual("http:///", endpoint.get_uri())
2379+ self.assertEquals(
2380+ other_params,
2381+ {"KeyName": "example-key-name"})
2382+
2383+ def submit(self):
2384+ return succeed(payload.sample_delete_keypair_true_result)
2385+
2386+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2387+ d = ec2.delete_keypair("example-key-name")
2388+ d.addCallback(self.assertTrue)
2389+ return d
2390+
2391+ def test_delete_keypair_false_result(self):
2392+
2393+ class StubQuery(object):
2394+
2395+ def __init__(stub, action="", creds=None, endpoint=None,
2396+ other_params={}):
2397+ self.assertEqual(action, "DeleteKeyPair")
2398+ self.assertEqual("foo", creds)
2399+ self.assertEqual("http:///", endpoint.get_uri())
2400+ self.assertEquals(
2401+ other_params,
2402+ {"KeyName": "example-key-name"})
2403+
2404+ def submit(self):
2405+ return succeed(payload.sample_delete_keypair_false_result)
2406+
2407+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2408+ d = ec2.delete_keypair("example-key-name")
2409+ d.addCallback(self.assertFalse)
2410+ return d
2411+
2412+ def test_delete_keypair_no_result(self):
2413+
2414+ class StubQuery(object):
2415+
2416+ def __init__(stub, action="", creds=None, endpoint=None,
2417+ other_params={}):
2418+ self.assertEqual(action, "DeleteKeyPair")
2419+ self.assertEqual("foo", creds)
2420+ self.assertEqual("http:///", endpoint.get_uri())
2421+ self.assertEquals(
2422+ other_params,
2423+ {"KeyName": "example-key-name"})
2424+
2425+ def submit(self):
2426+ return succeed(payload.sample_delete_keypair_no_result)
2427+
2428+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2429+ d = ec2.delete_keypair("example-key-name")
2430+ d.addCallback(self.assertFalse)
2431+ return d
2432+
2433+ def test_import_keypair(self):
2434+ """
2435+ L{client.EC2Client.import_keypair} calls the C{ImportKeyPair} method
2436+ with the given arguments, encoding the key material in base64, and
2437+ returns a C{Keypair} instance.
2438+ """
2439+
2440+ def check_parsed_import_keypair(keypair):
2441+ self.assertEquals(keypair.name, "example-key-name")
2442+ self.assertEquals(
2443+ keypair.fingerprint,
2444+ "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f")
2445+ self.assertEquals(keypair.material, material)
2446+
2447+ class StubQuery(object):
2448+
2449+ def __init__(stub, action="", creds=None, endpoint=None,
2450+ other_params={}):
2451+ self.assertEqual(action, "ImportKeyPair")
2452+ self.assertEqual("foo", creds)
2453+ self.assertEquals(
2454+ other_params,
2455+ {"KeyName": "example-key-name",
2456+ "PublicKeyMaterial":
2457+ "c3NoLWRzcyBBQUFBQjNOemFDMWtjM01BQUFDQkFQNmFjakFQeitUR"
2458+ "jJkREtmZGlhcnp2cXBBcjhlbUl6UElBWUp6QXNoTFgvUTJCZ2tWc0"
2459+ "42eGI2QUlIUGE1MUFtWXVieU5PYjMxeVhWS2FRQTF6L213SHZtRld"
2460+ "LQ1ZFQ0wwPSkgdXNlckBob3N0"})
2461+
2462+ def submit(self):
2463+ return succeed(payload.sample_import_keypair_result)
2464+
2465+ ec2 = client.EC2Client(creds="foo", query_factory=StubQuery)
2466+ material = (
2467+ "ssh-dss AAAAB3NzaC1kc3MAAACBAP6acjAPz+TF2dDKfdiarzvqpAr8emIzPIAY"
2468+ "JzAshLX/Q2BgkVsN6xb6AIHPa51AmYubyNOb31yXVKaQA1z/mwHvmFWKCVECL0=)"
2469+ " user@host")
2470+ d = ec2.import_keypair("example-key-name", material)
2471+ d.addCallback(check_parsed_import_keypair)
2472+ return d
2473+
2474+
2475+class EC2ErrorWrapperTestCase(TXAWSTestCase):
2476+
2477+ def setUp(self):
2478+ TXAWSTestCase.setUp(self)
2479+
2480+ def make_failure(self, status=None, type=None, message="", response=""):
2481+ if type == TwistedWebError:
2482+ error = type(status)
2483+ elif message:
2484+ error = type(message)
2485+ else:
2486+ error = type()
2487+ failure = Failure(error)
2488+ if not response:
2489+ response = payload.sample_ec2_error_message
2490+ failure.value.response = response
2491+ failure.value.status = status
2492+ return failure
2493+
2494+ def test_302_error(self):
2495+ failure = self.make_failure(302, Exception, "found")
2496+ error = self.assertRaises(Exception, client.ec2_error_wrapper, failure)
2497+ self.assertEquals(failure.type, type(error))
2498+ self.assertFalse(isinstance(error, EC2Error))
2499+ self.assertTrue(isinstance(error, Exception))
2500+ self.assertEquals(str(error), "found")
2501+
2502+ def test_400_error(self):
2503+ failure = self.make_failure(400, TwistedWebError)
2504+ error = self.assertRaises(EC2Error, client.ec2_error_wrapper, failure)
2505+ self.assertNotEquals(failure.type, type(error))
2506+ self.assertTrue(isinstance(error, EC2Error))
2507+ self.assertEquals(error.get_error_codes(), "Error.Code")
2508+ self.assertEquals(error.get_error_messages(), "Message for Error.Code")
2509+
2510+ def test_404_error(self):
2511+ failure = self.make_failure(404, TwistedWebError)
2512+ error = self.assertRaises(EC2Error, client.ec2_error_wrapper, failure)
2513+ self.assertNotEquals(failure.type, type(error))
2514+ self.assertTrue(isinstance(error, EC2Error))
2515+ self.assertEquals(error.get_error_codes(), "Error.Code")
2516+ self.assertEquals(error.get_error_messages(), "Message for Error.Code")
2517+
2518+ def test_non_EC2_404_error(self):
2519+ """
2520+ The error wrapper should handle cases where an endpoint returns a
2521+ non-EC2 404.
2522+ """
2523+ some_html = "<html><body>404</body></html>"
2524+ failure = self.make_failure(404, TwistedWebError, "not found",
2525+ some_html)
2526+ error = self.assertRaises(
2527+ TwistedWebError, client.ec2_error_wrapper, failure)
2528+ self.assertTrue(isinstance(error, TwistedWebError))
2529+ self.assertEquals(error.status, 404)
2530+ self.assertEquals(str(error), "404 Not Found")
2531+
2532+ def test_500_error(self):
2533+ failure = self.make_failure(
2534+ 500, type=TwistedWebError,
2535+ response=payload.sample_server_internal_error_result)
2536+ error = self.assertRaises(EC2Error, client.ec2_error_wrapper, failure)
2537+ self.assertTrue(isinstance(error, EC2Error))
2538+ self.assertEquals(error.get_error_codes(), "InternalError")
2539+ self.assertEquals(
2540+ error.get_error_messages(),
2541+ "We encountered an internal error. Please try again.")
2542+ self.assertEquals(error.request_id, "A2A7E5395E27DFBB")
2543+ self.assertEquals(
2544+ error.host_id,
2545+ "f691zulHNsUqonsZkjhILnvWwD3ZnmOM4ObM1wXTc6xuS3GzPmjArp8QC/sGsn6K")
2546+
2547+ def test_non_EC2_500_error(self):
2548+ failure = self.make_failure(500, Exception, "A server error occurred")
2549+ error = self.assertRaises(Exception, client.ec2_error_wrapper, failure)
2550+ self.assertFalse(isinstance(error, EC2Error))
2551+ self.assertTrue(isinstance(error, Exception))
2552+ self.assertEquals(str(error), "A server error occurred")
2553+
2554+ def test_timeout_error(self):
2555+ failure = self.make_failure(type=Exception, message="timeout")
2556+ error = self.assertRaises(Exception, client.ec2_error_wrapper, failure)
2557+ self.assertFalse(isinstance(error, EC2Error))
2558+ self.assertTrue(isinstance(error, Exception))
2559+ self.assertEquals(str(error), "timeout")
2560+
2561+ def test_connection_error(self):
2562+ failure = self.make_failure(type=ConnectionRefusedError)
2563+ error = self.assertRaises(ConnectionRefusedError,
2564+ client.ec2_error_wrapper, failure)
2565+ self.assertFalse(isinstance(error, EC2Error))
2566+ self.assertTrue(isinstance(error, ConnectionRefusedError))
2567+
2568+ def test_response_parse_error(self):
2569+ bad_payload = "<bad></xml>"
2570+ failure = self.make_failure(400, type=TwistedWebError,
2571+ response=bad_payload)
2572+ error = self.assertRaises(Exception, client.ec2_error_wrapper, failure)
2573+ self.assertEquals(str(error), "400 Bad Request")
2574+
2575+
2576+class QueryTestCase(TXAWSTestCase):
2577+
2578+ def setUp(self):
2579+ TXAWSTestCase.setUp(self)
2580+ self.creds = AWSCredentials("foo", "bar")
2581+ self.endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
2582+
2583+ def test_init_minimum(self):
2584+ query = client.Query(
2585+ action="DescribeInstances", creds=self.creds,
2586+ endpoint=self.endpoint)
2587+ self.assertTrue("Timestamp" in query.params)
2588+ del query.params["Timestamp"]
2589+ self.assertEqual(
2590+ query.params,
2591+ {"AWSAccessKeyId": "foo",
2592+ "Action": "DescribeInstances",
2593+ "SignatureVersion": "2",
2594+ "Version": "2008-12-01"})
2595+
2596+ def test_init_other_args_are_params(self):
2597+ query = client.Query(
2598+ action="DescribeInstances", creds=self.creds,
2599+ endpoint=self.endpoint, other_params={"InstanceId.0": "12345"},
2600+ time_tuple=(2007, 11, 12, 13, 14, 15, 0, 0, 0))
2601+ self.assertEqual(
2602+ query.params,
2603+ {"AWSAccessKeyId": "foo",
2604+ "Action": "DescribeInstances",
2605+ "InstanceId.0": "12345",
2606+ "SignatureVersion": "2",
2607+ "Timestamp": "2007-11-12T13:14:15Z",
2608+ "Version": "2008-12-01"})
2609+
2610+ def test_no_timestamp_if_expires_in_other_params(self):
2611+ """
2612+ If Expires is present in other_params, Timestamp won't be added,
2613+ since a request should contain either Expires or Timestamp, but
2614+ not both.
2615+ """
2616+ query = client.Query(
2617+ action="DescribeInstances", creds=self.creds,
2618+ endpoint=self.endpoint,
2619+ other_params={"Expires": "2007-11-12T13:14:15Z"})
2620+ self.assertEqual(
2621+ query.params,
2622+ {"AWSAccessKeyId": "foo",
2623+ "Action": "DescribeInstances",
2624+ "SignatureVersion": "2",
2625+ "Expires": "2007-11-12T13:14:15Z",
2626+ "Version": "2008-12-01"})
2627+
2628+ def test_sign(self):
2629+ query = client.Query(
2630+ action="DescribeInstances", creds=self.creds,
2631+ endpoint=self.endpoint,
2632+ time_tuple=(2007, 11, 12, 13, 14, 15, 0, 0, 0))
2633+ query.sign()
2634+ self.assertEqual("aDmLr0Ktjsmt17UJD/EZf6DrfKWT1JW0fq2FDUCOPic=",
2635+ query.params["Signature"])
2636+
2637+ def test_old_sign(self):
2638+ query = client.Query(
2639+ action="DescribeInstances", creds=self.creds,
2640+ endpoint=self.endpoint,
2641+ time_tuple=(2007, 11, 12, 13, 14, 15, 0, 0, 0),
2642+ other_params={"SignatureVersion": "1"})
2643+ query.sign()
2644+ self.assertEqual(
2645+ "MBKyHoxqCd/lBQLVkCZYpwAtNJg=", query.params["Signature"])
2646+
2647+ def test_unsupported_sign(self):
2648+ query = client.Query(
2649+ action="DescribeInstances", creds=self.creds,
2650+ endpoint=self.endpoint,
2651+ time_tuple=(2007, 11, 12, 13, 14, 15, 0, 0, 0),
2652+ other_params={"SignatureVersion": "0"})
2653+ self.assertRaises(RuntimeError, query.sign)
2654+
2655+ def test_submit_with_port(self):
2656+ """
2657+ If the endpoint port differs from the default one, the Host header
2658+ of the request will include it.
2659+ """
2660+ self.addCleanup(setattr, client.Query, "get_page",
2661+ client.Query.get_page)
2662+
2663+ def get_page(query, url, **kwargs):
2664+ self.assertEqual("example.com:99", kwargs["headers"]["Host"])
2665+ return succeed(None)
2666+
2667+ client.Query.get_page = get_page
2668+ endpoint = AWSServiceEndpoint(uri="http://example.com:99/foo")
2669+ query = client.Query(action="SomeQuery", creds=self.creds,
2670+ endpoint=endpoint)
2671+
2672+ d = query.submit()
2673+ return d
2674+
2675+ def test_submit_400(self):
2676+ """A 4xx response status from EC2 should raise a txAWS EC2Error."""
2677+ status = 400
2678+ self.addCleanup(setattr, client.Query, "get_page",
2679+ client.Query.get_page)
2680+ fake_page_getter = FakePageGetter(
2681+ status, payload.sample_ec2_error_message)
2682+ client.Query.get_page = fake_page_getter.get_page_with_exception
2683+
2684+ def check_error(error):
2685+ self.assertTrue(isinstance(error, EC2Error))
2686+ self.assertEquals(error.get_error_codes(), "Error.Code")
2687+ self.assertEquals(
2688+ error.get_error_messages(),
2689+ "Message for Error.Code")
2690+ self.assertEquals(error.status, status)
2691+ self.assertEquals(error.response, payload.sample_ec2_error_message)
2692+
2693+ query = client.Query(
2694+ action='BadQuery', creds=self.creds, endpoint=self.endpoint,
2695+ time_tuple=(2009, 8, 15, 13, 14, 15, 0, 0, 0))
2696+
2697+ failure = query.submit()
2698+ d = self.assertFailure(failure, TwistedWebError)
2699+ d.addCallback(check_error)
2700+ return d
2701+
2702+ def test_submit_non_EC2_400(self):
2703+ """
2704+ A 4xx response status from a non-EC2 compatible service should raise a
2705+ Twisted web error.
2706+ """
2707+ status = 400
2708+ self.addCleanup(setattr, client.Query, "get_page",
2709+ client.Query.get_page)
2710+ fake_page_getter = FakePageGetter(
2711+ status, payload.sample_ec2_error_message)
2712+ client.Query.get_page = fake_page_getter.get_page_with_exception
2713+
2714+ def check_error(error):
2715+ self.assertTrue(isinstance(error, TwistedWebError))
2716+ self.assertEquals(error.status, status)
2717+
2718+ query = client.Query(
2719+ action='BadQuery', creds=self.creds, endpoint=self.endpoint,
2720+ time_tuple=(2009, 8, 15, 13, 14, 15, 0, 0, 0))
2721+
2722+ failure = query.submit()
2723+ d = self.assertFailure(failure, TwistedWebError)
2724+ d.addCallback(check_error)
2725+ return d
2726+
2727+ def test_submit_500(self):
2728+ """
2729+ A 5xx response status from EC2 should raise the original Twisted
2730+ exception.
2731+ """
2732+ status = 500
2733+ self.addCleanup(setattr, client.Query, "get_page",
2734+ client.Query.get_page)
2735+ fake_page_getter = FakePageGetter(
2736+ status, payload.sample_server_internal_error_result)
2737+ client.Query.get_page = fake_page_getter.get_page_with_exception
2738+
2739+ def check_error(error):
2740+ self.assertTrue(isinstance(error, EC2Error))
2741+ self.assertEquals(error.status, status)
2742+ self.assertEquals(error.get_error_codes(), "InternalError")
2743+ self.assertEquals(
2744+ error.get_error_messages(),
2745+ "We encountered an internal error. Please try again.")
2746+
2747+ query = client.Query(
2748+ action='BadQuery', creds=self.creds, endpoint=self.endpoint,
2749+ time_tuple=(2009, 8, 15, 13, 14, 15, 0, 0, 0))
2750+
2751+ failure = query.submit()
2752+ d = self.assertFailure(failure, TwistedWebError)
2753+ d.addCallback(check_error)
2754+ return d
2755+
2756+
2757+class SignatureTestCase(TXAWSTestCase):
2758+
2759+ def setUp(self):
2760+ TXAWSTestCase.setUp(self)
2761+ self.creds = AWSCredentials("foo", "bar")
2762+ self.endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
2763+ self.params = {}
2764+
2765+ def test_encode_unreserved(self):
2766+ all_unreserved = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2767+ "abcdefghijklmnopqrstuvwxyz0123456789-_.~")
2768+ signature = client.Signature(self.creds, self.endpoint, self.params)
2769+ self.assertEqual(all_unreserved, signature.encode(all_unreserved))
2770+
2771+ def test_encode_space(self):
2772+ """This may be just 'url encode', but the AWS manual isn't clear."""
2773+ signature = client.Signature(self.creds, self.endpoint, self.params)
2774+ self.assertEqual("a%20space", signature.encode("a space"))
2775+
2776+ def test_canonical_query(self):
2777+ signature = client.Signature(self.creds, self.endpoint, self.params)
2778+ time_tuple = (2007, 11, 12, 13, 14, 15, 0, 0, 0)
2779+ self.params.update({"AWSAccessKeyId": "foo",
2780+ "fu n": "g/ames",
2781+ "argwithnovalue": "",
2782+ "SignatureVersion": "2",
2783+ "Timestamp": iso8601time(time_tuple),
2784+ "Version": "2008-12-01",
2785+ "Action": "DescribeInstances",
2786+ "InstanceId.1": "i-1234"})
2787+ expected_params = ("AWSAccessKeyId=foo&Action=DescribeInstances"
2788+ "&InstanceId.1=i-1234"
2789+ "&SignatureVersion=2&"
2790+ "Timestamp=2007-11-12T13%3A14%3A15Z&Version=2008-12-01&"
2791+ "argwithnovalue=&fu%20n=g%2Fames")
2792+ self.assertEqual(expected_params, signature.get_canonical_query_params())
2793+
2794+ def test_signing_text(self):
2795+ signature = client.Signature(self.creds, self.endpoint, self.params)
2796+ self.params.update({"AWSAccessKeyId": "foo",
2797+ "SignatureVersion": "2",
2798+ "Action": "DescribeInstances"})
2799+ signing_text = ("GET\n%s\n/\n" % self.endpoint.host +
2800+ "AWSAccessKeyId=foo&Action=DescribeInstances&" +
2801+ "SignatureVersion=2")
2802+ self.assertEqual(signing_text, signature.signing_text())
2803+
2804+ def test_signing_text_with_non_default_port(self):
2805+ """
2806+ The signing text uses the canonical host name, which includes
2807+ the port number, if it differs from the default one.
2808+ """
2809+ endpoint = AWSServiceEndpoint(uri="http://example.com:99/path")
2810+ signature = client.Signature(self.creds, endpoint, self.params)
2811+ self.params.update({"AWSAccessKeyId": "foo",
2812+ "SignatureVersion": "2",
2813+ "Action": "DescribeInstances"})
2814+ signing_text = ("GET\n"
2815+ "example.com:99\n"
2816+ "/path\n"
2817+ "AWSAccessKeyId=foo&"
2818+ "Action=DescribeInstances&"
2819+ "SignatureVersion=2")
2820+ self.assertEqual(signing_text, signature.signing_text())
2821+
2822+ def test_old_signing_text(self):
2823+ signature = client.Signature(self.creds, self.endpoint, self.params)
2824+ self.params.update({"AWSAccessKeyId": "foo",
2825+ "SignatureVersion": "1",
2826+ "Action": "DescribeInstances"})
2827+ signing_text = (
2828+ "ActionDescribeInstancesAWSAccessKeyIdfooSignatureVersion1")
2829+ self.assertEqual(signing_text, signature.old_signing_text())
2830+
2831+ def test_sorted_params(self):
2832+ signature = client.Signature(self.creds, self.endpoint, self.params)
2833+ self.params.update({"AWSAccessKeyId": "foo",
2834+ "fun": "games",
2835+ "SignatureVersion": "2",
2836+ "Version": "2008-12-01",
2837+ "Action": "DescribeInstances"})
2838+
2839+ self.assertEqual([
2840+ ("AWSAccessKeyId", "foo"),
2841+ ("Action", "DescribeInstances"),
2842+ ("SignatureVersion", "2"),
2843+ ("Version", "2008-12-01"),
2844+ ("fun", "games"),
2845+ ], signature.sorted_params())
2846+
2847+
2848+class QueryPageGetterTestCase(TXAWSTestCase):
2849+
2850+ def setUp(self):
2851+ TXAWSTestCase.setUp(self)
2852+ self.creds = AWSCredentials("foo", "bar")
2853+ self.endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
2854+ self.twisted_client_test_setup()
2855+ self.cleanupServerConnections = 0
2856+
2857+ def tearDown(self):
2858+ """Copied from twisted.web.test.test_webclient."""
2859+ # If the test indicated it might leave some server-side connections
2860+ # around, clean them up.
2861+ connections = self.wrapper.protocols.keys()
2862+ # If there are fewer server-side connections than requested,
2863+ # that's okay. Some might have noticed that the client closed
2864+ # the connection and cleaned up after themselves.
2865+ for n in range(min(len(connections), self.cleanupServerConnections)):
2866+ proto = connections.pop()
2867+ #msg("Closing %r" % (proto,))
2868+ proto.transport.loseConnection()
2869+ if connections:
2870+ #msg("Some left-over connections; this test is probably buggy.")
2871+ pass
2872+ return self.port.stopListening()
2873+
2874+ def _listen(self, site):
2875+ return reactor.listenTCP(0, site, interface="127.0.0.1")
2876+
2877+ def twisted_client_test_setup(self):
2878+ name = self.mktemp()
2879+ os.mkdir(name)
2880+ FilePath(name).child("file").setContent("0123456789")
2881+ resource = static.File(name)
2882+ resource.putChild("redirect", util.Redirect("/file"))
2883+ self.site = server.Site(resource, timeout=None)
2884+ self.wrapper = WrappingFactory(self.site)
2885+ self.port = self._listen(self.wrapper)
2886+ self.portno = self.port.getHost().port
2887+
2888+ def get_url(self, path):
2889+ return "http://127.0.0.1:%d/%s" % (self.portno, path)
2890+
2891+ def test_get_page(self):
2892+ """Copied from twisted.web.test.test_webclient."""
2893+ query = client.Query(
2894+ action="DummyQuery", creds=self.creds, endpoint=self.endpoint,
2895+ time_tuple=(2009, 8, 15, 13, 14, 15, 0, 0, 0))
2896+ deferred = query.get_page(self.get_url("file"))
2897+ deferred.addCallback(self.assertEquals, "0123456789")
2898+ return deferred
2899+
2900+
2901+class EC2ClientAddressTestCase(TXAWSTestCase):
2902+
2903+ def setUp(self):
2904+ TXAWSTestCase.setUp(self)
2905+ self.creds = AWSCredentials("foo", "bar")
2906+ self.endpoint = AWSServiceEndpoint(uri=EC2_ENDPOINT_US)
2907+
2908+ def test_describe_addresses(self):
2909+
2910+ class StubQuery(object):
2911+
2912+ def __init__(stub, action="", creds=None, endpoint=None,
2913+ other_params={}):
2914+ self.assertEqual(action, "DescribeAddresses")
2915+ self.assertEqual(self.creds, creds)
2916+ self.assertEqual(self.endpoint, endpoint)
2917+ self.assertEquals(other_params, {})
2918+
2919+ def submit(self):
2920+ return succeed(payload.sample_describe_addresses_result)
2921+
2922+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2923+ query_factory=StubQuery)
2924+ d = ec2.describe_addresses()
2925+ d.addCallback(
2926+ self.assertEquals, [("67.202.55.255", "i-28a64341"),
2927+ ("67.202.55.233", None)])
2928+ return d
2929+
2930+ def test_describe_specified_addresses(self):
2931+
2932+ class StubQuery(object):
2933+
2934+ def __init__(stub, action="", creds=None, endpoint=None,
2935+ other_params={}):
2936+ self.assertEqual(action, "DescribeAddresses")
2937+ self.assertEqual(self.creds, creds)
2938+ self.assertEqual(self.endpoint, endpoint)
2939+ self.assertEquals(
2940+ other_params,
2941+ {"PublicIp.1": "67.202.55.255"})
2942+
2943+ def submit(self):
2944+ return succeed(payload.sample_describe_addresses_result)
2945+
2946+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2947+ query_factory=StubQuery)
2948+ d = ec2.describe_addresses("67.202.55.255")
2949+ d.addCallback(
2950+ self.assertEquals, [("67.202.55.255", "i-28a64341"),
2951+ ("67.202.55.233", None)])
2952+ return d
2953+
2954+ def test_associate_address(self):
2955+
2956+ class StubQuery(object):
2957+
2958+ def __init__(stub, action="", creds=None, endpoint=None,
2959+ other_params={}):
2960+ self.assertEqual(action, "AssociateAddress")
2961+ self.assertEqual(self.creds, creds)
2962+ self.assertEqual(self.endpoint, endpoint)
2963+ self.assertEquals(
2964+ other_params,
2965+ {"InstanceId": "i-28a64341", "PublicIp": "67.202.55.255"})
2966+
2967+ def submit(self):
2968+ return succeed(payload.sample_associate_address_result)
2969+
2970+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2971+ query_factory=StubQuery)
2972+ d = ec2.associate_address("i-28a64341", "67.202.55.255")
2973+ d.addCallback(self.assertTrue)
2974+ return d
2975+
2976+ def test_allocate_address(self):
2977+
2978+ class StubQuery(object):
2979+
2980+ def __init__(stub, action="", creds=None, endpoint=None,
2981+ other_params={}):
2982+ self.assertEqual(action, "AllocateAddress")
2983+ self.assertEqual(self.creds, creds)
2984+ self.assertEqual(self.endpoint, endpoint)
2985+ self.assertEquals(other_params, {})
2986+
2987+ def submit(self):
2988+ return succeed(payload.sample_allocate_address_result)
2989+
2990+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
2991+ query_factory=StubQuery)
2992+ d = ec2.allocate_address()
2993+ d.addCallback(self.assertEquals, "67.202.55.255")
2994+ return d
2995+
2996+ def test_release_address(self):
2997+
2998+ class StubQuery(object):
2999+
3000+ def __init__(stub, action="", creds=None, endpoint=None,
3001+ other_params={}):
3002+ self.assertEqual(action, "ReleaseAddress")
3003+ self.assertEqual(self.creds, creds)
3004+ self.assertEqual(self.endpoint, endpoint)
3005+ self.assertEquals(other_params, {"PublicIp": "67.202.55.255"})
3006+
3007+ def submit(self):
3008+ return succeed(payload.sample_release_address_result)
3009+
3010+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
3011+ query_factory=StubQuery)
3012+ d = ec2.release_address("67.202.55.255")
3013+ d.addCallback(self.assertTrue)
3014+ return d
3015+
3016+ def test_disassociate_address(self):
3017+
3018+ class StubQuery(object):
3019+
3020+ def __init__(stub, action="", creds=None, endpoint=None,
3021+ other_params={}):
3022+ self.assertEqual(action, "DisassociateAddress")
3023+ self.assertEqual(self.creds, creds)
3024+ self.assertEqual(self.endpoint, endpoint)
3025+ self.assertEquals(other_params, {"PublicIp": "67.202.55.255"})
3026+
3027+ def submit(self):
3028+ return succeed(payload.sample_disassociate_address_result)
3029+
3030+ ec2 = client.EC2Client(creds=self.creds, endpoint=self.endpoint,
3031+ query_factory=StubQuery)
3032+ d = ec2.disassociate_address("67.202.55.255")
3033+ d.addCallback(self.assertTrue)
3034+ return d
3035
3036=== added file 'debian/patches/fix-openstack-terminate-instances.patch'
3037--- debian/patches/fix-openstack-terminate-instances.patch 1970-01-01 00:00:00 +0000
3038+++ debian/patches/fix-openstack-terminate-instances.patch 2011-09-30 09:11:28 +0000
3039@@ -0,0 +1,80 @@
3040+Author: Clint Byrum <clint@ubuntu.com>
3041+Bug: http://pad.lv/862595
3042+Description: Fixes txaws's terminate_instances call to allow for Nova's
3043+ less than standard response.
3044+Origin: https://code.launchpad.net/~clint-fewbar/txaws/openstack-terminate-instances/+merge/77593
3045+Forwarded: yes
3046+
3047+=== modified file 'txaws/ec2/client.py'
3048+Index: txaws/txaws/ec2/client.py
3049+===================================================================
3050+--- txaws.orig/txaws/ec2/client.py 2011-09-29 18:24:31.633198000 -0700
3051++++ txaws/txaws/ec2/client.py 2011-09-29 18:25:54.554602018 -0700
3052+@@ -630,13 +630,15 @@
3053+ root = XML(xml_bytes)
3054+ result = []
3055+ # May be a more elegant way to do this:
3056+- for instance in root.find("instancesSet"):
3057+- instanceId = instance.findtext("instanceId")
3058+- previousState = instance.find("previousState").findtext(
3059+- "name")
3060+- shutdownState = instance.find("shutdownState").findtext(
3061+- "name")
3062+- result.append((instanceId, previousState, shutdownState))
3063++ instances = root.find("instancesSet")
3064++ if instances is not None:
3065++ for instance in instances:
3066++ instanceId = instance.findtext("instanceId")
3067++ previousState = instance.find("previousState").findtext(
3068++ "name")
3069++ shutdownState = instance.find("shutdownState").findtext(
3070++ "name")
3071++ result.append((instanceId, previousState, shutdownState))
3072+ return result
3073+
3074+ def describe_security_groups(self, xml_bytes):
3075+Index: txaws/txaws/ec2/tests/test_client.py
3076+===================================================================
3077+--- txaws.orig/txaws/ec2/tests/test_client.py 2011-09-29 18:24:31.633198000 -0700
3078++++ txaws/txaws/ec2/tests/test_client.py 2011-09-29 18:25:54.554602018 -0700
3079+@@ -1994,3 +1994,40 @@
3080+ d = ec2.disassociate_address("67.202.55.255")
3081+ d.addCallback(self.assertTrue)
3082+ return d
3083++
3084++class EC2ParserTestCase(TXAWSTestCase):
3085++
3086++ def setUp(self):
3087++ self.parser = client.Parser()
3088++
3089++ def test_ec2_terminate_instances(self):
3090++ """ Given a well formed response from EC2, will we parse the correct thing. """
3091++
3092++ ec2_xml = """<?xml version="1.0" encoding="UTF-8"?>
3093++<TerminateInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/">
3094++ <requestId>d0adc305-7f97-4652-b7c2-6993b2bb8260</requestId>
3095++ <instancesSet>
3096++ <item>
3097++ <instanceId>i-cab0c1aa</instanceId>
3098++ <shutdownState>
3099++ <code>32</code>
3100++ <name>shutting-down</name>
3101++ </shutdownState>
3102++ <previousState>
3103++ <code>16</code>
3104++ <name>running</name>
3105++ </previousState>
3106++ </item>
3107++ </instancesSet>
3108++</TerminateInstancesResponse>"""
3109++ ec2_response = self.parser.terminate_instances(ec2_xml)
3110++ self.assertEquals([('i-cab0c1aa','running','shutting-down')], ec2_response)
3111++
3112++ def test_nova_terminate_instances(self):
3113++ """ Ensure parser can handle the somewhat non-standard response from nova
3114++ Note that the bug has been reported in nova here:
3115++ https://launchpad.net/bugs/862680 """
3116++
3117++ nova_xml = """<?xml version="1.0" ?><TerminateInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2008-12-01/"><requestId>4fe6643d-2346-4add-adb7-a1f61f37c043</requestId><return>true</return></TerminateInstancesResponse>"""
3118++ nova_response = self.parser.terminate_instances(nova_xml)
3119++ self.assertEquals([], nova_response)
3120
3121=== renamed file 'debian/patches/fix-openstack-terminate-instances.patch' => 'debian/patches/fix-openstack-terminate-instances.patch.moved'

Subscribers

People subscribed via source and target branches

to all changes: