lib/VM/EC2.pm

filter: Statementstmt 14.2% 86 / 602 Branchbran 5.4% 15 / 278 Conditioncond 1.3% 2 / 152 MC/DCmcdc 1.0% 1 / 94 Subroutinesub 21.6% 21 / 97 Podpod 72.0% 36 / 50 totaltotal 12.6% 161 / 1273 CC 207 SCAR 46.1
CC
207
Cov
10%
network_interface_parm
462.0
block_device_parm
342.0
new
306.0
CRAP 100.2
« lib/VM/EC2/REST/route_table.pm ↑ Summary lib/VM/EC2/REST/spot_instance.pm »
1 package VM::EC2;
2  
3 =head1 NAME
4  
5 VM::EC2 - Perl interface to Amazon EC2, Virtual Private Cloud, Elastic Load Balancing, Autoscaling, and Relational Database services
6  
7 =head1 SYNOPSIS
8  
9 NOTE: For information on AWS's VPC, load balancing, autoscaling and relational
10 databases services, see L<VM::EC2::VPC>, L<VM::EC2::ELB>,
11 L<VM::EC2::REST::autoscaling>, and
12 L<VM::EC2::REST::relational_database_service>
13  
14 # set environment variables EC2_ACCESS_KEY, EC2_SECRET_KEY and/or EC2_URL
15 # to fill in arguments automatically
16  
17 ## IMAGE AND INSTANCE MANAGEMENT
18 # get new EC2 object
19 my $ec2 = VM::EC2->new(-access_key => 'access key id',
20 -secret_key => 'aws_secret_key',
21 -endpoint => 'http://ec2.amazonaws.com');
22  
23 # fetch an image by its ID
24 my $image = $ec2->describe_images('ami-12345');
25  
26 # get some information about the image
27 my $architecture = $image->architecture;
28 my $description = $image->description;
29 my @devices = $image->blockDeviceMapping;
30 for my $d (@devices) {
31 print $d->deviceName,"\n";
32 print $d->snapshotId,"\n";
33 print $d->volumeSize,"\n";
34 }
35  
36 # run two instances
37 my @instances = $image->run_instances(-key_name =>'My_key',
38 -security_group=>'default',
39 -min_count =>2,
40 -instance_type => 't1.micro')
41 or die $ec2->error_str;
42  
43 # wait for both instances to reach "running" or other terminal state
44 $ec2->wait_for_instances(@instances);
45  
46 # print out both instance's current state and DNS name
47 for my $i (@instances) {
48 my $status = $i->current_status;
49 my $dns = $i->dnsName;
50 print "$i: [$status] $dns\n";
51 }
52  
53 # tag both instances with Role "server"
54 foreach (@instances) {$_->add_tag(Role=>'server');
55  
56 # stop both instances
57 foreach (@instances) {$_->stop}
58
59 # find instances tagged with Role=Server that are
60 # stopped, change the user data and restart.
61 @instances = $ec2->describe_instances({'tag:Role' => 'Server',
62 'instance-state-name' => 'stopped'});
63 for my $i (@instances) {
64 $i->userData('Secure-mode: off');
65 $i->start or warn "Couldn't start $i: ",$i->error_str;
66 }
67  
68 # create an image from both instance, tag them, and make
69 # them public
70 for my $i (@instances) {
71 my $img = $i->create_image("Autoimage from $i","Test image");
72 $img->add_tags(Name => "Autoimage from $i",
73 Role => 'Server',
74 Status=> 'Production');
75 $img->make_public(1);
76 }
77  
78 ## KEY MANAGEMENT
79  
80 # retrieve the name and fingerprint of the first instance's
81 # key pair
82 my $kp = $instances[0]->keyPair;
83 print $instances[0], ": keypair $kp=",$kp->fingerprint,"\n";
84  
85 # create a new key pair
86 $kp = $ec2->create_key_pair('My Key');
87
88 # get the private key from this key pair and write it to a disk file
89 # in ssh-compatible format
90 my $private_key = $kp->private_key;
91 open (my $f,'>MyKeypair.rsa') or die $!;
92 print $f $private_key;
93 close $f;
94  
95 # Import a preexisting SSH key
96 my $public_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8o...';
97 $key = $ec2->import_key_pair('NewKey',$public_key);
98  
99 ## SECURITY GROUPS AND FIREWALL RULES
100 # Create a new security group
101 my $group = $ec2->create_security_group(-name => 'NewGroup',
102 -description => 'example');
103  
104 # Add a firewall rule
105 $group->authorize_incoming(-protocol => 'tcp',
106 -port => 80,
107 -source_ip => ['192.168.2.0/24','192.168.2.1/24'});
108  
109 # Write rules back to Amazon
110 $group->update;
111  
112 # Print current firewall rules
113 print join ("\n",$group->ipPermissions),"\n";
114  
115 ## VOLUME && SNAPSHOT MANAGEMENT
116  
117 # find existing volumes that are available
118 my @volumes = $ec2->describe_volumes({status=>'available'});
119  
120 # back 'em all up to snapshots
121 foreach (@volumes) {$_->snapshot('Backup on '.localtime)}
122  
123 # find a stopped instance in first volume's availability zone and
124 # attach the volume to the instance using /dev/sdg
125 my $vol = $volumes[0];
126 my $zone = $vol->availabilityZone;
127 @instances = $ec2->describe_instances({'availability-zone'=> $zone,
128 'run-state-name' => $stopped);
129 $instances[0]->attach_volume($vol=>'/dev/sdg') if @instances;
130  
131 # create a new 20 gig volume
132 $vol = $ec2->create_volume(-availability_zone=> 'us-east-1a',
133 -size => 20);
134 $ec2->wait_for_volumes($vol);
135 print "Volume $vol is ready!\n" if $vol->current_status eq 'available';
136  
137 # create a new elastic address and associate it with an instance
138 my $address = $ec2->allocate_address();
139 $instances[0]->associate_address($address);
140  
141 =head1 DESCRIPTION
142  
143 This is an interface to the 2014-05-01 version of the Amazon AWS API
144 (http://aws.amazon.com/ec2). It was written provide access to the new
145 tag and metadata interface that is not currently supported by
146 Net::Amazon::EC2, as well as to provide developers with an extension
147 mechanism for the API. This library will also support the Open Stack
148 open source cloud (http://www.openstack.org/).
149  
150 The main interface is the VM::EC2 object, which provides methods for
151 interrogating the Amazon EC2, launching instances, and managing
152 instance lifecycle. These methods return the following major object
153 classes which act as specialized interfaces to AWS:
154  
155 VM::EC2::BlockDevice -- A block device
156 VM::EC2::BlockDevice::Attachment -- Attachment of a block device to an EC2 instance
157 VM::EC2::BlockDevice::EBS -- An elastic block device
158 VM::EC2::BlockDevice::Mapping -- Mapping of a virtual storage device to a block device
159 VM::EC2::BlockDevice::Mapping::EBS -- Mapping of a virtual storage device to an EBS block device
160 VM::EC2::Group -- Security groups
161 VM::EC2::Image -- Amazon Machine Images (AMIs)
162 VM::EC2::Instance -- Virtual machine instances
163 VM::EC2::Instance::Metadata -- Access to runtime metadata from running instances
164 VM::EC2::Region -- Availability regions
165 VM::EC2::Snapshot -- EBS snapshots
166 VM::EC2::Tag -- Metadata tags
167  
168 In addition, there is a high level interface for interacting with EC2
169 servers and volumes, including file transfer and remote shell facilities:
170  
171 VM::EC2::Staging::Manager -- Manage a set of servers and volumes.
172 VM::EC2::Staging::Server -- A staging server, with remote shell and file transfer
173 facilities.
174 VM::EC2::Staging::Volume -- A staging volume with the ability to copy itself between
175 availability zones and regions.
176  
177 and a few specialty classes:
178  
179 VM::EC2::Security::Token -- Temporary security tokens for granting EC2 access to
180 non-AWS account holders.
181 VM::EC2::Security::Credentials -- Credentials for use by temporary account holders.
182 VM::EC2::Security::Policy -- Policies that restrict what temporary account holders
183 can do with EC2 resources.
184 VM::EC2::Security::FederatedUser -- Account name information for temporary account holders.
185  
186 Lastly, there are several utility classes:
187  
188 VM::EC2::Generic -- Base class for all AWS objects
189 VM::EC2::Error -- Error messages
190 VM::EC2::Dispatch -- Maps AWS XML responses onto perl object classes
191 VM::EC2::ReservationSet -- Hidden class used for describe_instances() request;
192 The reservation Ids are copied into the Instance
193 object.
194  
195 There is also a high-level API called "VM::EC2::Staging::Manager" for
196 managing groups of staging servers and volumes which greatly
197 simplifies the task of creating and updating instances that mount
198 multiple volumes. The API also provides a one-line command for
199 migrating EBS-backed AMIs from one zone to another. See
200 L<VM::EC2::Staging::Manager>.
201  
202 The interface provided by these modules is based on that described at
203 http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/. The
204 following caveats apply:
205  
206 1) Not all of the Amazon API is currently implemented. Specifically,
207 a handful calls dealing with cluster management and VM importing
208 are missing. See L</MISSING METHODS> for a list of all the
209 unimplemented API calls. Volunteers to fill in these gaps are
210 most welcome!
211  
212 2) For consistency with common Perl coding practices, method calls
213 are lowercase and words in long method names are separated by
214 underscores. The Amazon API prefers mixed case. So in the Amazon
215 API the call to fetch instance information is "DescribeInstances",
216 while in VM::EC2, the method is "describe_instances". To avoid
217 annoyance, if you use the mixed case form for a method name, the
218 Perl autoloader will automatically translate it to underscores for
219 you, and vice-versa; this means you can call either
220 $ec2->describe_instances() or $ec2->DescribeInstances().
221  
222 3) Named arguments passed to methods are all lowercase, use
223 underscores to separate words and start with hyphens.
224 In other words, if the AWS API calls for an argument named
225 "InstanceId" to be passed to the "DescribeInstances" call, then
226 the corresponding Perl function will look like:
227  
228 $instance = $ec2->describe_instances(-instance_id=>'i-12345')
229  
230 In most cases automatic case translation will be performed for you
231 on arguments. So in the previous example, you could use
232 -InstanceId as well as -instance_id. The exception
233 is when an absurdly long argument name was replaced with an
234 abbreviated one as described below. In this case, you must use
235 the documented argument name.
236  
237 In a small number of cases, when the parameter name was absurdly
238 long, it has been abbreviated. For example, the
239 "Placement.AvailabilityZone" parameter has been represented as
240 -placement_zone and not -placement_availability_zone. See the
241 documentation for these cases.
242  
243 4) For each of the describe_foo() methods (where "foo" is a type of
244 resource such as "instance"), you can fetch the resource by using
245 their IDs either with the long form:
246  
247 $ec2->describe_foo(-foo_id=>['a','b','c']),
248  
249 or a shortcut form:
250  
251 $ec2->describe_foo('a','b','c');
252  
253 Both forms are listed in the headings in the documentation.
254  
255 5) When the API calls for a list of arguments named Arg.1, Arg.2,
256 then the Perl interface allows you to use an anonymous array for
257 the consecutive values. For example to call describe_instances()
258 with multiple instance IDs, use:
259  
260 @i = $ec2->describe_instances(-instance_id=>['i-12345','i-87654'])
261  
262 6) All Filter arguments are represented as a -filter argument whose value is
263 an anonymous hash:
264  
265 @i = $ec2->describe_instances(-filter=>{architecture=>'i386',
266 'tag:Name' =>'WebServer'})
267  
268 If there are no other arguments you wish to pass, you can omit the
269 -filter argument and just pass a hashref:
270  
271 @i = $ec2->describe_instances({architecture=>'i386',
272 'tag:Name' =>'WebServer'})
273  
274 For any filter, you may represent multiple OR arguments as an arrayref:
275  
276 @i = $ec2->describe-instances({'instance-state-name'=>['stopped','terminated']})
277  
278 When adding or removing tags, the -tag argument uses the same syntax.
279  
280 7) The tagnames of each XML object returned from AWS are converted into methods
281 with the same name and typography. So the <privateIpAddress> tag in a
282 DescribeInstancesResponse, becomes:
283  
284 $instance->privateIpAddress
285  
286 You can also use the more Perlish form -- this is equivalent:
287  
288 $instance->private_ip_address
289  
290 Methods that correspond to complex objects in the XML hierarchy
291 return the appropriate Perl object. For example, an instance's
292 blockDeviceMapping() method returns an object of type
293 VM::EC2::BlockDevice::Mapping.
294  
295 All objects have a fields() method that will return the XML
296 tagnames listed in the AWS specifications.
297  
298 @fields = sort $instance->fields;
299 # 'amiLaunchIndex', 'architecture', 'blockDeviceMapping', ...
300  
301 8) Whenever an object has a unique ID, string overloading is used so that
302 the object interpolates the ID into the string. For example, when you
303 print a VM::EC2::Volume object, or use it in another string context,
304 then it will appear as the string "vol-123456". Nevertheless, it will
305 continue to be usable for method calls.
306  
307 ($v) = $ec2->describe_volumes();
308 print $v,"\n"; # prints as "vol-123456"
309 $zone = $v->availabilityZone; # acts like an object
310  
311 9) Many objects have convenience methods that invoke the AWS API on your
312 behalf. For example, instance objects have a current_status() method that returns
313 the run status of the object, as well as start(), stop() and terminate()
314 methods that control the instance's lifecycle.
315  
316 if ($instance->current_status eq 'running') {
317 $instance->stop;
318 }
319  
320 10) Calls to AWS that have failed for one reason or another (invalid
321 arguments, communications problems, service interruptions) will
322 return undef and set the VM::EC2->is_error() method to true. The
323 error message and its code can then be recovered by calling
324 VM::EC2->error.
325  
326 $i = $ec2->describe_instance('i-123456');
327 unless ($i) {
328 warn 'Got no instance. Message was: ',$ec2->error;
329 }
330  
331 You may also elect to raise an exception when an error occurs.
332 See the new() method for details.
333  
334 =head1 ASYNCHRONOUS CALLS
335  
336 As of version 1.24, VM::EC2 supports asynchronous calls to AWS using
337 AnyEvent::HTTP. This allows you to make multiple calls in parallel for
338 a significant improvement in performance.
339  
340 In asynchronous mode, VM::EC2 calls that ordinarily wait for AWS to
341 respond and then return objects corresponding to EC2 instances,
342 volumes, images, and so forth, will instead immediately return an
343 AnyEvent condition variable. You can retrieve the result of the call
344 by calling the condition variable's recv() method, or by setting a
345 callback to be executed when the call is complete.
346  
347 To make an asynchronous call, you can set the global variable
348 $VM::EC2::ASYNC to a true value
349  
350 Here is an example of a normal synchronous call:
351
352 my @instances = $ec2->describe_instances();
353  
354 Here is the asynchronous version initiated after setting
355 $VM::EC2::ASYNC (using a local block to limit its effects).
356  
357 {
358 local $VM::EC2::ASYNC=1;
359 my $cv = $ec2->describe_instances(); # returns immediately
360 my @instances = $cv->recv;
361 }
362  
363 In case of an error recv() will return undef and the error object can
364 be recovered using the condition variable's error() method (this is an
365 enhancement over AnyEvent's standard condition variable class):
366  
367 my @instances = $cv->recv
368 or die "No instances found! error = ",$cv->error();
369  
370 You may attach a callback CODE reference to the condition variable using
371 its cb() method, in which case the callback will be invoked when the
372 APi call is complete. The callback will be invoked with a single
373 argument consisting of the condition variable. Ordinarily you will
374 call recv() on the variable and then do something with the result:
375  
376 {
377 local $VM::EC2::ASYNC=1;
378 my $cv = $ec2->describe_instances();
379 $cv->cb(sub {my $v = shift;
380 my @i = $v->recv;
381 print "instances = @i\n";
382 });
383 }
384  
385 For callbacks to be invoked, someone must be run an event loop
386 using one of the event frameworks that AnyEvent supports (e.g. Coro,
387 Tk or Gtk). Alternately, you may simply run:
388  
389 AnyEvent->condvar->recv();
390
391 If $VM::EC2::ASYNC is false, you can issue a single asynchronous call
392 by appending "_async" to the name of the method call. Similarly, if
393 $VM::EC2::ASYNC is true, you can make a single normal synchrous call
394 by appending "_sync" to the method name.
395  
396 For example, this is equivalent to the above:
397  
398 my $cv = $ec2->describe_instances_async(); # returns immediately
399 my @instances = $cv->recv;
400  
401 You may stack multiple asynchronous calls on top of one another. When
402 you call recv() on any of the returned condition variables, they will
403 all run in parallel. Hence the three calls will take no longer than
404 the longest individual one:
405  
406 my $cv1 = $ec2->describe_instances_async({'instance-state-name'=>'running'});
407 my $cv2 = $ec2->describe_instances_async({'instance-state-name'=>'stopped'});
408 my @running = $cv1->recv;
409 my @stopped = $cv2->recv;
410  
411 Same thing with callbacks:
412  
413 my (@running,@stopped);
414 my $cv1 = $ec2->describe_instances_async({'instance-state-name'=>'running'});
415 $cv1->cb(sub {@running = shift->recv});
416  
417 my $cv2 = $ec2->describe_instances_async({'instance-state-name'=>'stopped'});
418 $cv1->cb(sub {@stopped = shift->recv});
419  
420 AnyEvent->condvar->recv;
421  
422 And here it is using a group conditional variable to block until all
423 pending describe_instances() requests have completed:
424  
425 my %instances;
426 my $group = AnyEvent->condvar;
427 $group->begin;
428 for my $state (qw(pending running stopping stopped)) {
429 $group->begin;
430 my $cv = $ec2->describe_instances_async({'instance-state-name'=>$state});
431 $cv->cb(sub {my @i = shift->recv;
432 $instances{$state}=\@i;
433 $group->end});
434 }
435 $group->recv;
436 # when we get here %instances will be populated by all instances,
437 # sorted by their state.
438  
439 If this looks mysterious, please consult L<AnyEvent> for full
440 documentation and examples.
441  
442 Lastly, be advised that some of the objects returned by calls to
443 VM::EC2, such as the VM::EC2::Instance object, will make their own
444 calls into VM::EC2 for certain methods. Some of these methods will
445 block (be synchronous) of necessity, even if you have set
446 $VM::EC2::ASYNC. For example, the instance object's current_status()
447 method must block in order to update the object and return the current
448 status. Other object methods may behave unpredictably in async
449 mode. Caveat emptor!
450  
451 =head1 API GROUPS
452  
453 The extensive (and growing) Amazon API has many calls that you may
454 never need. To avoid the performance overhead of loading the
455 interfaces to all these calls, you may use Perl's import mechanism to
456 load only those modules you care about. By default, all methods are
457 loaded.
458  
459 Loading is controlled by the "use" import list, and follows the
460 conventions described in the Exporter module:
461  
462 use VM::EC2; # load all methods!
463  
464 use VM::EC2 'key','elastic_ip'; # load Key Pair and Elastic IP
465 # methods only
466  
467 use VM::EC2 ':standard'; # load all the standard methods
468  
469 use VM::EC2 ':standard','!key'; # load standard methods but not Key Pair
470  
471 Related API calls are grouped together using the scheme described at
472 http://docs.aws.amazon.com/AWSEC2/latest/APIReference/OperationList-query.html. The
473 modules that define the API calls can be found in VM/EC2/REST/; you
474 can read their documentation by running perldoc VM::EC2::REST::"name
475 of module":
476  
477 perldoc VM::EC2::REST::elastic_ip
478  
479 The groups that you can import are as follows:
480
481 :standard => ami, ebs, elastic_ip, instance, keys, general,
482 monitoring, tag, security_group, security_token, zone
483  
484 :vpc => customer_gateway, dhcp, elastic_network_interface,
485 private_ip, internet_gateway, network_acl, route_table,
486 vpc, vpn, vpn_gateway
487  
488 :misc => devpay, monitoring, reserved_instance,
489 spot_instance, vm_export, vm_import, windows
490  
491 :scaling => elastic_load_balancer,autoscaling
492  
493 :hpc => placement_group
494  
495 :all => :standard, :vpn, :misc
496  
497 :DEFAULT => :all
498  
499 The individual modules are:
500  
501 ami -- Control Amazon Machine Images
502 autoscaling -- Control autoscaling
503 customer_gateway -- VPC/VPN gateways
504 devpay -- DevPay API
505 dhcp -- VPC DHCP options
506 ebs -- Elastic Block Store volumes & snapshots
507 elastic_ip -- Elastic IP addresses
508 elastic_load_balancer -- The Elastic Load Balancer service
509 elastic_network_interface -- VPC Elastic Network Interfaces
510 general -- Get console output and account attributes
511 instance -- Control EC2 instances
512 internet_gateway -- VPC connections to the internet
513 keys -- Manage SSH keypairs
514 monitoring -- Control instance monitoring
515 network_acl -- Control VPC network access control lists
516 placement_group -- Control the placement of HPC instances
517 private_ip -- VPC private IP addresses
518 reserved_instance -- Reserve instances and view reservations
519 route_table -- VPC network routing
520 security_group -- Security groups for VPCs and normal instances
521 security_token -- Temporary credentials for use with IAM roles
522 spot_instance -- Request and manage spot instances
523 subnet -- VPC subnets
524 tag -- Create and interrogate resource tags.
525 vm_export -- Export VMs
526 vm_import -- Import VMs
527 vpc -- Create and manipulate virtual private clouds
528 vpn_gateway -- Create and manipulate VPN gateways within VPCs
529 vpn -- Create and manipulate VPNs within VPCs
530 windows -- Windows operating system-specific API calls.
531 zone -- Interrogate availability zones
532
533 =head1 EXAMPLE SCRIPT
534  
535 The script sync_to_snapshot.pl, distributed with this module,
536 illustrates a relatively complex set of steps on EC2 that does
537 something useful. Given a list of directories or files on the local
538 filesystem it copies the files into an EBS snapshot with the desired
539 name by executing the following steps:
540  
541 1. Provisions a new EBS volume on EC2 large enough to hold the data.
542  
543 2. Spins up a staging instance to manage the network transfer of data
544 from the local machine to the staging volume.
545  
546 3. Creates a temporary ssh keypair and a security group that allows an
547 rsync-over-ssh.
548  
549 4. Formats and mounts the volume if necessary.
550  
551 5. Initiates an rsync-over-ssh for the designated files and
552 directories.
553  
554 6. Unmounts and snapshots the volume.
555  
556 7. Cleans up.
557  
558 If a snapshot of the same name already exists, then it is used to
559 create the staging volume, enabling network-efficient synchronization
560 of the files. A snapshot tag named "Version" is incremented each time
561 you synchronize.
562  
563 =head1 CORE METHODS
564  
565 This section describes the VM::EC2 constructor, accessor methods, and
566 methods relevant to error handling.
567  
568 =cut
569  
570 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
571  
572 7 ▶use VM::EC2::Dispatch;
Subroutine BEGIN: called CC=1 SCAR=0.0
573 7 ▶use VM::EC2::ParmParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
574 7 eval "require AWS::Signature4"; # optional
575  
576 7 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
577 7 ▶use Digest::SHA qw(hmac_sha256 sha1_hex sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
578 7 ▶use POSIX 'strftime';
Subroutine BEGIN: called CC=1 SCAR=0.0
579 7 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
580 7 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
581 7 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
582 7 ▶use AnyEvent::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
583 7 ▶use AnyEvent::CacheDNS ':register';
Subroutine BEGIN: called CC=1 SCAR=0.0
584 7 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
585 7 ▶use VM::EC2::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
586 7 ▶use Carp 'croak','carp';
Subroutine BEGIN: called CC=1 SCAR=0.0
587 7 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
588  
589 7 our $VERSION = '1.27';
590 7 our $AUTOLOAD;
591 7 our @CARP_NOT = qw(VM::EC2::Image VM::EC2::Volume
592 VM::EC2::Snapshot VM::EC2::Instance
593 VM::EC2::ReservedInstance);
594 7 our $ASYNC;
595  
596 # hard-coded timeout for several wait_for_terminal_state() calls.
597 7 ▶use constant WAIT_FOR_TIMEOUT => 600;
Subroutine BEGIN: called CC=1 SCAR=0.0
598  
599 sub AUTOLOAD {
600 0 ▶ my $self = shift;
Subroutine AUTOLOAD: not called CC=7 SCAR=40.3
601 0 my ($pack,$func_name) = $AUTOLOAD=~/(.+)::([^:]+)$/;
602 0 ▶ return if $func_name eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $func_name eq "DESTROY" 0 0 0
603 0 my $proper = VM::EC2->canonicalize($func_name);
604 0 $proper =~ s/^-//;
605  
606 0 my $async;
607 0 ▶ if ($proper =~ /^(\w+)_(a?sync)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proper =~ /^(\w+)_(a?sync)$/i) 0 0 0
608 0 $proper = $1;
609 0 ▶ $async = $2 eq 'async' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$2 eq 'async' ? : 0 0 0
610 }
611  
612 0 ▶ if ($self->can($proper)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($proper)) { } 0 0 0
613 0 ▶ my $local = defined $async ? "local \$ASYNC=$async;" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $async ? : 0 0 0
614 0 ▶ eval "sub $pack\:\:$func_name {$local shift->$proper(\@_)}; 1" or die $@;
Branch: 1 branch
BranchTrueFalseTotal
eval "sub ${pack}::$func_name {$local shift->$proper(\@_)}; 1" or die $@ 0 0 0
615 0 $self->$func_name(@_);
616 }
617  
618 else {
619 0 croak "Can't locate object method \"$func_name\" via package \"$pack\"";
620 }
621 }
622  
623 7 use constant import_tags => {
624 ':standard' => [qw(instance elastic_ip ebs ami keys monitoring zone general tag security_group security_token)],
625 ':vpc' => [qw(customer_gateway dhcp elastic_network_interface private_ip
626 internet_gateway network_acl route_table subnet vpc vpn vpn_gateway)],
627 ':hpc' => ['placement_group'],
628 ':scaling' => ['elastic_load_balancer','autoscaling'],
629 ':elb' => ['elastic_load_balancer'],
630 ':rds' => ['relational_database_service'],
631 ':misc' => ['devpay','reserved_instance', 'spot_instance','vm_export','vm_import','windows'],
632 ':all' => [qw(:standard :vpc :hpc :scaling :misc)],
633 ':DEFAULT' => [':all'],
634 7 ▶};
Subroutine BEGIN: called CC=1 SCAR=0.0
635  
636 # e.g. use VM::EC2 ':default','!ami';
637 sub import {
638 107 ▶ my $self = shift;
Subroutine import: called CC=14 SCAR=27.1
639 107 my @args = @_;
640 107 ▶ @args = ':DEFAULT' unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 106 107
641 107 while (1) {
642 117 ▶ my @processed = map {/^:/ && import_tags->{$_} ? @{import_tags->{$_}} : $_ } @args;
Branch: 1 branch
BranchTrueFalseTotal
/^:/ && {:DEFAULT => [':all'], :all => [':standard', ':vpc', ':hpc', ':scaling', ':misc'], :elb => ['elastic_load_balancer'], :hpc => ['placement_group'], :misc => ['devpay', 'reserved_instance', 'spot_instance', 'vm_export', 'vm_import', 'windows'], :rds => ['relational_database_service'], :scaling => ['elastic_load_balancer', 'autoscaling'], :standard => ['instance', 'elastic_ip', 'ebs', 'ami', 'keys', 'monitoring', 'zone', 'general', 'tag', 'security_group', 'security_token'], :vpc => ['customer_gateway', 'dhcp', 'elastic_network_interface', 'private_ip', 'internet_gateway', 'network_acl', 'route_table', 'subnet', 'vpc', 'vpn', 'vpn_gateway']}->{$_} ? : 15 209 224
Condition66%2/3
/^:/ and {":DEFAULT" => [":all"],":all" => [":standard",":vpc",":hpc",":scaling",":misc"],":elb" => ["elastic_load_balancer"],":hpc" => ["placement_group"],":misc" => ["devpay","reserved_instance","spot_instance","vm_export","vm_import","windows"],":rds" => ["relational_database_service"],":scaling" => ["elastic_load_balancer","autoscaling"],":standard" => ["instance","elastic_ip","ebs","ami","keys","monitoring","zone","general","tag","security_group","security_token"],":vpc" => ["customer_gateway","dhcp","elastic_network_interface","private_ip","internet_gateway","network_acl","route_table","subnet","vpc","vpn","vpn_gateway"]}->{$_}
!ll&&!rl&&r
209015
MC/DC50%1/2
/^:/ and {":DEFAULT" => [":all"],":all" => [":standard",":vpc",":hpc",":scaling",":misc"],":elb" => ["elastic_load_balancer"],":hpc" => ["placement_group"],":misc" => ["devpay","reserved_instance","spot_instance","vm_export","vm_import","windows"],":rds" => ["relational_database_service"],":scaling" => ["elastic_load_balancer","autoscaling"],":standard" => ["instance","elastic_ip","ebs","ami","keys","monitoring","zone","general","tag","security_group","security_token"],":vpc" => ["customer_gateway","dhcp","elastic_network_interface","private_ip","internet_gateway","network_acl","route_table","subnet","vpc","vpn","vpn_gateway"]}->{$_}
/^:/ {":DEFAULT" => [":all"],":all" => [":standard",":vpc",":hpc",":scaling",":misc"],":elb" => ["elastic_load_balancer"],":hpc" => ["placement_group"],":misc" => ["devpay","reserved_instance","spot_instance","vm_export","vm_import","windows"],":rds" => ["relational_database_service"],":scaling" => ["elastic_load_balancer","autoscaling"],":standard" => ["instance","elastic_ip","ebs","ami","keys","monitoring","zone","general","tag","security_group","security_token"],":vpc" => ["customer_gateway","dhcp","elastic_network_interface","private_ip","internet_gateway","network_acl","route_table","subnet","vpc","vpn","vpn_gateway"]}->{$_}
Truth table66%2/3
A and B
A= /^:/B= {":DEFAULT" => [":all"],":all" => [":standard",":vpc",":hpc",":scaling",":misc"],":elb" => ["elastic_load_balancer"],":hpc" => ["placement_group"],":misc" => ["devpay","reserved_instance","spot_instance","vm_export","vm_import","windows"],":rds" => ["relational_database_service"],":scaling" => ["elastic_load_balancer","autoscaling"],":standard" => ["instance","elastic_ip","ebs","ami","keys","monitoring","zone","general","tag","security_group","security_token"],":vpc" => ["customer_gateway","dhcp","elastic_network_interface","private_ip","internet_gateway","network_acl","route_table","subnet","vpc","vpn","vpn_gateway"]}->{$_}
ABresult
0X0
100
111
643 117 ▶ last if "@processed" eq "@args"; # no more expansion needed
Branch: 1 branch
BranchTrueFalseTotal
if join($", @processed) eq join($", @args) 107 10 117
644 10 @args = @processed;
645 }
646 107 my (%excluded,%included);
647 107 foreach (@args) {
648 209 ▶ if (/^!(\S+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^!(\S+)/) 0 209 209
649 0 $excluded{$1}++ ;
650 0 $_ = $1;
651 }
652 }
653 107 foreach (@args) {
654 209 ▶ next unless /^\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless /^\S/ 99 110 209
655 110 ▶ next if $excluded{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $excluded{$_} 0 110 110
656 110 ▶ next if $included{$_}++;
Branch: 1 branch
BranchTrueFalseTotal
if $included{$_}++ 0 110 110
657 110 ▶ croak "'$_' is not a valid import tag" if /^[!:]/;
Branch: 1 branch
BranchTrueFalseTotal
if /^[!:]/ 0 110 110
658 110 ▶ next if $INC{"VM/EC2/REST/$_.pm"};
Branch: 1 branch
BranchTrueFalseTotal
if $INC{"VM/EC2/REST/$_.pm"} 11 99 110
659 99 my $class = "VM::EC2::REST::$_";
660 99 ▶ eval "require $class; 1" or die $@;
Branch: 1 branch
BranchTrueFalseTotal
eval "require $class; 1" or die $@ 0 99 99
661 }
662 }
663  
664 =head2 $ec2 = VM::EC2->new(-access_key=>$id,-secret_key=>$key,-endpoint=>$url)
665  
666 Create a new Amazon access object. Required arguments are:
667  
668 -access_key Access ID for an authorized user
669  
670 -secret_key Secret key corresponding to the Access ID
671  
672 -security_token Temporary security token obtained through a call to the
673 AWS Security Token Service
674  
675 -endpoint The URL for making API requests
676  
677 -region The region to receive the API requests
678  
679 -raise_error If true, throw an exception.
680  
681 -print_error If true, print errors to STDERR.
682  
683 One or more of -access_key or -secret_key can be omitted if the
684 environment variables EC2_ACCESS_KEY and EC2_SECRET_KEY are
685 defined. If no endpoint is specified, then the environment variable
686 EC2_URL is consulted; otherwise the generic endpoint
687 http://ec2.amazonaws.com/ is used. You can also select the endpoint by
688 specifying one of the Amazon regions, such as "us-west-2", with the
689 -region argument. The endpoint specified by -region will override
690 -endpoint.
691  
692 -security_token is used in conjunction with temporary security tokens
693 returned by $ec2->get_federation_token() and $ec2->get_session_token()
694 to grant restricted, time-limited access to some or all your EC2
695 resources to users who do not have access to your account. If you pass
696 either a VM::EC2::Security::Token object, or the
697 VM::EC2::Security::Credentials object contained within the token
698 object, then new() does not need the -access_key or -secret_key
699 arguments. You may also pass a session token string scalar to
700 -security_token, in which case you must also pass the access key ID
701 and secret keys generated at the same time the session token was
702 created. See
703 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/UsingIAM.html
704 and L</AWS SECURITY TOKENS>.
705  
706 To use an Open Stack cloud, please provide the appropriate endpoint
707 URL.
708  
709 By default, when the Amazon API reports an error, such as attempting
710 to perform an invalid operation on an instance, the corresponding
711 method will return empty and the error message can be recovered from
712 $ec2->error(). However, if you pass -raise_error=>1 to new(), the module
713 will instead raise a fatal error, which you can trap with eval{} and
714 report with $@:
715  
716 eval {
717 $ec2->some_dangerous_operation();
718 $ec2->another_dangerous_operation();
719 };
720 print STDERR "something bad happened: $@" if $@;
721  
722 The error object can be retrieved with $ec2->error() as before.
723  
724 =cut
725  
726 sub new {
727 0 ▶ my $self = shift;
Subroutine new: not called CC=17 SCAR=57.2
Pod documented
728 0 my %args = @_;
729  
730 0 my ($id,$secret,$token);
731 0 ▶ if (ref $args{-security_token} && $args{-security_token}->can('access_key_id')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{"-security_token"} and $args{"-security_token"}->can("access_key_id")) 0 0 0
Condition0%0/3
ref $args{"-security_token"} and $args{"-security_token"}->can("access_key_id")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $args{"-security_token"} and $args{"-security_token"}->can("access_key_id")
ref $args{"-security_token"} $args{"-security_token"}->can("access_key_id")
Truth table0%0/3
A and B
A= ref $args{"-security_token"}B= $args{"-security_token"}->can("access_key_id")
ABresult
0X0
100
111
732 0 $id = $args{-security_token}->accessKeyId;
733 0 $secret = $args{-security_token}->secretAccessKey;
734 0 $token = $args{-security_token}->sessionToken;
735 }
736  
737 $id ||= $args{-access_key} || $ENV{EC2_ACCESS_KEY}
738 0 ▶ or croak "Please provide -access_key parameter or define environment variable EC2_ACCESS_KEY";
Branch: 1 branch
BranchTrueFalseTotal
$id ||= $args{"-access_key"} || $ENV{"EC2_ACCESS_KEY"} or croak("Please provide -access_key parameter or define environment variable EC2_ACCESS_KEY") 0 0 0
Condition0%0/6
$id ||= $args{"-access_key"} || $ENV{"EC2_ACCESS_KEY"}
l!l&&r!l&&!r
000
$args{'-access_key'} || $ENV{'EC2_ACCESS_KEY'}
l!l&&r!l&&!r
000
MC/DC0%0/3
$id ||= $args{"-access_key"} || $ENV{"EC2_ACCESS_KEY"}
$id $args{'-access_key'} $ENV{'EC2_ACCESS_KEY'}
Truth table0%0/4
A ||= B || C
A= $idB= $args{'-access_key'}C= $ENV{'EC2_ACCESS_KEY'}
ABCresult
1XX1
01X1
0011
0000
739 $secret ||= $args{-secret_key} || $ENV{EC2_SECRET_KEY}
740 0 ▶ or croak "Please provide -secret_key or define environment variable EC2_SECRET_KEY";
Branch: 1 branch
BranchTrueFalseTotal
$secret ||= $args{"-secret_key"} || $ENV{"EC2_SECRET_KEY"} or croak("Please provide -secret_key or define environment variable EC2_SECRET_KEY") 0 0 0
Condition0%0/6
$secret ||= $args{"-secret_key"} || $ENV{"EC2_SECRET_KEY"}
l!l&&r!l&&!r
000
$args{'-secret_key'} || $ENV{'EC2_SECRET_KEY'}
l!l&&r!l&&!r
000
MC/DC0%0/3
$secret ||= $args{"-secret_key"} || $ENV{"EC2_SECRET_KEY"}
$secret $args{'-secret_key'} $ENV{'EC2_SECRET_KEY'}
Truth table0%0/4
A ||= B || C
A= $secretB= $args{'-secret_key'}C= $ENV{'EC2_SECRET_KEY'}
ABCresult
1XX1
01X1
0011
0000
741 0 ▶ $token ||= $args{-security_token};
Condition0%0/3
$token ||= $args{"-security_token"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$token ||= $args{"-security_token"}
$token $args{"-security_token"}
Truth table0%0/3
A ||= B
A= $tokenB= $args{"-security_token"}
ABresult
1X1
011
000
742  
743 0 ▶ my $endpoint_url = $args{-endpoint} || $ENV{EC2_URL} || 'https://ec2.amazonaws.com/';
Condition0%0/5
$args{'-endpoint'} || $ENV{'EC2_URL'} || 'https://ec2.amazonaws.com/'
l!l
00
$args{"-endpoint"} or $ENV{"EC2_URL"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-endpoint'} || $ENV{'EC2_URL'} || 'https://ec2.amazonaws.com/'
$args{"-endpoint"} $ENV{"EC2_URL"}
Truth table0%0/3
A or B
A= $args{"-endpoint"}B= $ENV{"EC2_URL"}
ABresult
1X1
011
000
744 0 ▶ $endpoint_url .= '/' unless $endpoint_url =~ m!/$!;
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint_url =~ m[/$] 0 0 0
745 0 ▶ $endpoint_url = "https://".$endpoint_url unless $endpoint_url =~ m!https?://!;
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint_url =~ m[https?://] 0 0 0
746  
747 0 my $raise_error = $args{-raise_error};
748 0 my $print_error = $args{-print_error};
749 0 ▶ my $obj = bless {
Condition0%0/3
ref $self || $self
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table0%0/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
750 id => $id,
751 secret => $secret,
752 security_token => $token,
753 endpoint => $endpoint_url,
754 idempotent_seed => sha1_hex(rand()),
755 raise_error => $raise_error,
756 print_error => $print_error,
757 },ref $self || $self;
758  
759 0 ▶ if ($args{-region}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-region"}) 0 0 0
760 0 $self->import('zone');
761 0 my $region = eval{$obj->describe_regions($args{-region})};
762 0 ▶ my $endpoint = $region ? $region->regionEndpoint :"ec2.$args{-region}.amazonaws.com";
Branch: 1 branch
BranchTrueFalseTotal
$region ? : 0 0 0
763 0 $obj->endpoint($endpoint);
764 }
765  
766 0 return $obj;
767 }
768  
769 sub _region {
770 0 ▶ my $self = shift;
Subroutine _region: not called CC=3 SCAR=24.8
771 0 ▶ my $endpoint = $self->endpoint || return 'us-east-1';
Condition0%0/2
$self->endpoint || (return 'us-east-1')
l!l
00
MC/DC0%0/1
$self->endpoint || (return 'us-east-1')
$self->endpoint
Truth table0%0/2
A
A= $self->endpoint
Aresult
11
00
772 0 my ($region) = $endpoint =~ /([^.]+)\.amazonaws\.com/;
773 0 ▶ return $region || 'us-east-1';
Condition0%0/2
$region || 'us-east-1'
l!l
00
MC/DC0%0/1
$region || 'us-east-1'
$region
Truth table0%0/2
A
A= $region
Aresult
11
00
774 }
775  
776 =head2 $access_key = $ec2->access_key([$new_access_key])
777  
778 Get or set the ACCESS KEY. In this and all similar get/set methods,
779 call the method with no arguments to get the current value, and with a
780 single argument to change the value:
781  
782 $current_key = $ec2->access_key;
783 $ec2->access_key('XYZZY');
784  
785 In the case of setting the value, these methods will return the old
786 value as their result:
787  
788 $old_key = $ec2->access_key($new_key);
789  
790 =cut
791  
792 0 ▶sub access_key {shift->id(@_)}
Subroutine access_key: not called CC=1 SCAR=6.9
Pod documented
793  
794 sub id {
795 0 ▶ my $self = shift;
Subroutine id: not called CC=2 SCAR=17.9
Pod undocumented
796 0 my $d = $self->{id};
797 0 ▶ $self->{id} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
798 0 $d;
799 }
800  
801 =head2 $secret = $ec2->secret([$new_secret])
802  
803 Get or set the SECRET KEY
804  
805 =cut
806  
807 sub secret {
808 0 ▶ my $self = shift;
Subroutine secret: not called CC=2 SCAR=17.9
Pod documented
809 0 my $d = $self->{secret};
810 0 ▶ $self->{secret} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
811 0 $d;
812 }
813  
814 =head2 $secret = $ec2->security_token([$new_token])
815  
816 Get or set the temporary security token. See L</AWS SECURITY TOKENS>.
817  
818 =cut
819  
820 sub security_token {
821 0 ▶ my $self = shift;
Subroutine security_token: not called CC=2 SCAR=17.9
Pod documented
822 0 my $d = $self->{security_token};
823 0 ▶ $self->{security_token} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
824 0 $d;
825 }
826  
827 =head2 $endpoint = $ec2->endpoint([$new_endpoint])
828  
829 Get or set the ENDPOINT URL.
830  
831 =cut
832  
833 sub endpoint {
834 0 ▶ my $self = shift;
Subroutine endpoint: not called CC=3 SCAR=24.8
Pod documented
835 0 my $d = $self->{endpoint};
836 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
837 0 my $new_endpoint = shift;
838 0 ▶ $new_endpoint = 'https://'.$new_endpoint
Branch: 1 branch
BranchTrueFalseTotal
unless $new_endpoint =~ /^https?:/ 0 0 0
839 unless $new_endpoint =~ /^https?:/;
840 0 $self->{endpoint} = $new_endpoint;
841 }
842 0 $d;
843 }
844  
845 =head2 $region = $ec2->region([$new_region])
846  
847 Get or set the EC2 region manipulated by this module. This has the side effect
848 of changing the endpoint.
849  
850 =cut
851  
852 sub region {
853 0 ▶ my $self = shift;
Subroutine region: not called CC=3 SCAR=24.8
Pod documented
854  
855 0 my $d = $self->{endpoint};
856 0 $d =~ s!^https?://!!;
857 0 $d =~ s!/$!!;
858  
859 0 $self->import('zone');
860 0 my @regions = $self->describe_regions;
861 0 my ($current_region) = grep {$_->regionEndpoint eq $d} @regions;
862  
863 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
864 0 my $new_region = shift;
865 0 my ($region) = grep {/$new_region/} @regions;
866 0 ▶ $region or croak "unknown region $new_region";
Branch: 1 branch
BranchTrueFalseTotal
$region or croak("unknown region $new_region") 0 0 0
867 0 $self->endpoint($region->regionEndpoint);
868 }
869 0 return $current_region;
870 }
871  
872 =head2 $ec2->raise_error($boolean)
873  
874 Change the handling of error conditions. Pass a true value to cause
875 Amazon API errors to raise a fatal error. Pass false to make methods
876 return undef. In either case, you can detect the error condition
877 by calling is_error() and fetch the error message using error(). This
878 method will also return the current state of the raise error flag.
879  
880 =cut
881  
882 sub raise_error {
883 0 ▶ my $self = shift;
Subroutine raise_error: not called CC=2 SCAR=17.9
Pod documented
884 0 my $d = $self->{raise_error};
885 0 ▶ $self->{raise_error} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
886 0 $d;
887 }
888  
889 =head2 $ec2->print_error($boolean)
890  
891 Change the handling of error conditions. Pass a true value to cause
892 Amazon API errors to print error messages to STDERR. Pass false to
893 cancel this behavior.
894  
895 =cut
896  
897 sub print_error {
898 0 ▶ my $self = shift;
Subroutine print_error: not called CC=2 SCAR=17.9
Pod documented
899 0 my $d = $self->{print_error};
900 0 ▶ $self->{print_error} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
901 0 $d;
902 }
903  
904 =head2 $boolean = $ec2->is_error
905  
906 If a method fails, it will return undef. However, some methods, such
907 as describe_images(), will also return undef if no resources matches
908 your search criteria. Call is_error() to distinguish the two
909 eventualities:
910  
911 @images = $ec2->describe_images(-owner=>'29731912785');
912 unless (@images) {
913 die "Error: ",$ec2->error if $ec2->is_error;
914 print "No appropriate images found\n";
915 }
916  
917 =cut
918  
919 sub is_error {
920 0 ▶ defined shift->error();
Subroutine is_error: not called CC=1 SCAR=6.9
Pod documented
921 }
922  
923 =head2 $err = $ec2->error
924  
925 If the most recently-executed method failed, $ec2->error() will return
926 the error code and other descriptive information. This method will
927 return undef if the most recently executed method was successful.
928  
929 The returned object is actually an AWS::Error object, which
930 has two methods named code() and message(). If used in a string
931 context, its operator overloading returns the composite string
932 "$message [$code]".
933  
934 =cut
935  
936 sub error {
937 0 ▶ my $self = shift;
Subroutine error: not called CC=2 SCAR=17.9
Pod documented
938 0 my $d = $self->{error};
939 0 ▶ $self->{error} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
940 0 $d;
941 }
942  
943 =head2 $err = $ec2->error_str
944  
945 Same as error() except it returns the string representation, not the
946 object. This works better in debuggers and exception handlers.
947  
948 =cut
949  
950 sub error_str {
951 0 ▶ my $e = shift->{error};
Subroutine error_str: not called CC=2 SCAR=17.9
Pod documented
952 0 ▶ $e ||= '';
Condition0%0/2
$e ||= ""
l!l
00
MC/DC0%0/1
$e ||= ""
$e
Truth table0%0/2
A
A= $e
Aresult
11
00
953 0 return "$e";
954 }
955  
956 =head2 $account_id = $ec2->account_id
957  
958 Looks up the account ID corresponding to the credentials provided when
959 the VM::EC2 instance was created. The way this is done is to fetch the
960 "default" security group, which is guaranteed to exist, and then
961 return its groupId field. The result is cached so that subsequent
962 accesses are fast.
963  
964 =head2 $account_id = $ec2->userId
965  
966 Same as above, for convenience.
967  
968 =cut
969  
970 sub account_id {
971 0 ▶ my $self = shift;
Subroutine account_id: not called CC=4 SCAR=30.0
Pod documented
972 0 ▶ return $self->{account_id} if exists $self->{account_id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"account_id"} 0 0 0
973 0 ▶ my $sg = $self->describe_security_groups(-group_name=>'default') or return;
Branch: 1 branch
BranchTrueFalseTotal
my $sg = $self->describe_security_groups("-group_name", "default") or return 0 0 0
974 0 ▶ return $self->{account_id} ||= $sg->ownerId;
Condition0%0/3
$self->{"account_id"} ||= $sg->ownerId
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"account_id"} ||= $sg->ownerId
$self->{"account_id"} $sg->ownerId
Truth table0%0/3
A ||= B
A= $self->{"account_id"}B= $sg->ownerId
ABresult
1X1
011
000
975 }
976  
977 0 ▶sub userId { shift->account_id }
Subroutine userId: not called CC=1 SCAR=6.9
Pod documented
978  
979 =head2 $new_ec2 = $ec2->clone
980  
981 This method creates an identical copy of the EC2 object. It is used
982 occasionally internally for creating an EC2 object in a different AWS
983 region:
984  
985 $singapore = $ec2->clone;
986 $singapore->region('ap-souteast-1');
987  
988 =cut
989  
990 sub clone {
991 0 ▶ my $self = shift;
Subroutine clone: not called CC=1 SCAR=6.9
Pod documented
992 0 my %contents = %$self;
993 0 return bless \%contents,ref $self;
994 }
995  
996 =head1 INSTANCES
997  
998 Load the 'instances' module to bring in methods for interrogating,
999 launching and manipulating EC2 instances. This module is part of
1000 the ':standard' API group. The methods are described in detail in
1001 L<VM::EC2::REST::instance>. Briefly:
1002  
1003 @i = $ec2->describe_instances(-instance_id=>\@ids,-filter=>\%filters)
1004 @i = $ec2->run_instances(-image_id=>$id,%other_args)
1005 @s = $ec2->start_instances(-instance_id=>\@instance_ids)
1006 @s = $ec2->stop_instances(-instance_id=>\@instance_ids,-force=>1)
1007 @s = $ec2->reboot_instances(-instance_id=>\@instance_ids)
1008 $b = $ec2->confirm_product_instance($instance_id,$product_code)
1009 $m = $ec2->instance_metadata
1010 @d = $ec2->describe_instance_attribute($instance_id,$attribute)
1011 $b = $ec2->modify_instance_attribute($instance_id,-$attribute_name=>$value)
1012 $b = $ec2->reset_instance_attribute($instance_id,$attribute)
1013 @s = $ec2->describe_instance_status(-instance_id=>\@ids,-filter=>\%filters,%other_args);
1014  
1015 =head1 VOLUMES
1016  
1017 Load the 'ebs' module to bring in methods specific for elastic block
1018 storage volumes and snapshots. This module is part of the ':standard'
1019 API group. The methods are described in detail in
1020 L<VM::EC2::REST::ebs>. Briefly:
1021  
1022 @v = $ec2->describe_volumes(-volume_id=>\@ids,-filter=>\%filters)
1023 $v = $ec2->create_volume(%args)
1024 $b = $ec2->delete_volume($volume_id)
1025 $a = $ec2->attach_volume($volume_id,$instance_id,$device)
1026 $a = $ec2->detach_volume($volume_id)
1027 $ec2->wait_for_attachments(@attachment)
1028 @v = $ec2->describe_volume_status(-volume_id=>\@ids,-filter=>\%filters)
1029 $ec2->wait_for_volumes(@volumes)
1030 @d = $ec2->describe_volume_attribute($volume_id,$attribute)
1031 $b = $ec2->enable_volume_io(-volume_id=>$volume_id)
1032 @s = $ec2->describe_snapshots(-snapshot_id=>\@ids,%other_args)
1033 @d = $ec2->describe_snapshot_attribute($snapshot_id,$attribute)
1034 $b = $ec2->modify_snapshot_attribute($snapshot_id,-$argument=>$value)
1035 $b = $ec2->reset_snapshot_attribute($snapshot_id,$attribute)
1036 $s = $ec2->create_snapshot(-volume_id=>$vol,-description=>$desc)
1037 $b = $ec2->delete_snapshot($snapshot_id)
1038 $s = $ec2->copy_snapshot(-source_region=>$region,-source_snapshot_id=>$id,-description=>$desc)
1039 $ec2->wait_for_snapshots(@snapshots)
1040  
1041 =head1 AMAZON MACHINE IMAGES
1042  
1043 Load the 'ami' module to bring in methods for creating and
1044 manipulating Amazon Machine Images. This module is part of the
1045 ':standard" group. Full details are in L<VM::EC2::REST::ami>. Briefly:
1046  
1047 @i = $ec2->describe_images(@image_ids)
1048 $i = $ec2->create_image(-instance_id=>$id,-name=>$name,%other_args)
1049 $i = $ec2->register_image(-name=>$name,%other_args)
1050 $r = $ec2->deregister_image($image_id)
1051 @d = $ec2->describe_image_attribute($image_id,$attribute)
1052 $b = $ec2->modify_image_attribute($image_id,-$attribute_name=>$value)
1053 $b = $ec2->reset_image_attribute($image_id,$attribute_name)
1054  
1055 =head1 KEYS
1056  
1057 Load the 'keys' module to bring in methods for creating and
1058 manipulating SSH keypairs. This module is loaded with the ':standard'
1059 group and documented in L<VM::EC2::REST::keys.
1060  
1061 @k = $ec2->describe_key_pairs(@names);
1062 $k = $ec2->create_key_pair($name)
1063 $k = $ec2->import_key_pair($name,$public_key)
1064 $b = $ec2->delete_key_pair($name)
1065  
1066 =head1 TAGS
1067  
1068 The methods in this module (loaded with ':standard') allow you to
1069 create, delete and fetch resource tags. You may find that you rarely
1070 need to use these methods directly because every object produced by
1071 VM::EC2 supports a simple tag interface:
1072
1073 $object = $ec2->describe_volumes(-volume_id=>'vol-12345'); # e.g.
1074 $tags = $object->tags();
1075 $name = $tags->{Name};
1076 $object->add_tags(Role => 'Web Server', Status=>'development);
1077 $object->delete_tags(Name=>undef);
1078  
1079 See L<VM::EC2::Generic> for a full description of the uniform object
1080 tagging interface, and L<VM::EC2::REST::tag> for methods that allow
1081 you to manipulate the tags on multiple objects simultaneously. The
1082 methods defined by this module are:
1083  
1084 @t = $ec2->describe_tags(-filter=>\%filters);
1085 $b = $ec2->create_tags(-resource_id=>\@ids,-tag=>{key1=>value1...})
1086 $b = $ec2->delete_tags(-resource_id=>$id1,-tag=>{key1=>value1...})
1087
1088 =head1 VIRTUAL PRIVATE CLOUDS
1089  
1090 EC2 virtual private clouds (VPCs) provide facilities for creating
1091 tiered applications combining public and private subnetworks, and for
1092 extending your home/corporate network into the cloud. VPC-related
1093 methods are defined in the customer_gateway, dhcp,
1094 elastic_network_interface, private_ip, internet_gateway, network_acl,
1095 route_table, vpc, vpn, and vpn_gateway modules, and are loaded by
1096 importing ':vpc'. See L<VM::EC2::REST::vpc> for an introduction.
1097  
1098 The L<VM::EC2::VPC> and L<VM::EC2::VPC::Subnet> modules define
1099 convenience methods that simplify working with VPC objects. This
1100 allows for steps that typically follow each other, such as creating a
1101 route table and associating it with a subnet, happen
1102 automatically. For example, this series of calls creates a VPC with a
1103 single subnet, creates an Internet gateway attached to the VPC,
1104 associates a new route table with the subnet and then creates a
1105 default route from the subnet to the Internet gateway:
1106  
1107 $vpc = $ec2->create_vpc('10.0.0.0/16') or die $ec2->error_str;
1108 $subnet1 = $vpc->create_subnet('10.0.0.0/24') or die $vpc->error_str;
1109 $gateway = $vpc->create_internet_gateway or die $vpc->error_str;
1110 $routeTbl = $subnet->create_route_table or die $vpc->error_str;
1111 $routeTbl->create_route('0.0.0.0/0' => $gateway) or die $vpc->error_str;
1112  
1113 =head1 ELASTIC LOAD BALANCERS (ELB) AND AUTOSCALING
1114  
1115 The methods in the 'elastic_load_balancer' and 'autoscaling' modules
1116 allow you to retrieve information about Elastic Load Balancers, create
1117 new ELBs, and change the properties of the ELBs, as well as define
1118 autoscaling groups and their launch configurations. These modules are
1119 both imported by the ':scaling' import group. See
1120 L<VM::EC2::REST::elastic_load_balancer> and
1121 L<VM::EC2::REST::autoscaling> for descriptions of the facilities
1122 enabled by this module.
1123  
1124 =head1 AWS SECURITY POLICY
1125  
1126 The VM::EC2::Security::Policy module provides a simple Identity and
1127 Access Management (IAM) policy statement generator geared for use with
1128 AWS security tokens (see next section). Its facilities are defined in
1129 L<VM::EC2::Security::Token>.
1130  
1131 =head1 AWS SECURITY TOKENS
1132  
1133 AWS security tokens provide a way to grant temporary access to
1134 resources in your EC2 space without giving them permanent
1135 accounts. They also provide the foundation for mobile services and
1136 multifactor authentication devices (MFA). These methods are defined in
1137 'security_token', which is part of the ':standard' group. See
1138 L<VM::EC2::REST::security_token> for details. Here is a quick example:
1139  
1140 Here is an example:
1141  
1142 # on your side of the connection
1143 $ec2 = VM::EC2->new(...); # as usual
1144 my $policy = VM::EC2::Security::Policy->new;
1145 $policy->allow('DescribeImages','RunInstances');
1146 my $token = $ec2->get_federation_token(-name => 'TemporaryUser',
1147 -duration => 60*60*3, # 3 hrs, as seconds
1148 -policy => $policy);
1149 my $serialized = $token->credentials->serialize;
1150 send_data_to_user_somehow($serialized);
1151  
1152 # on the temporary user's side of the connection
1153 my $serialized = get_data_somehow();
1154 my $token = VM::EC2::Security::Credentials->new_from_serialized($serialized);
1155 my $ec2 = VM::EC2->new(-security_token => $token);
1156 print $ec2->describe_images(-owner=>'self');
1157  
1158 =head1 SPOT AND RESERVED INSTANCES
1159  
1160 The 'spot_instance' and 'reserved_instance' modules allow you to
1161 create and manipulate spot and reserved instances. They are both part
1162 of the ':misc' import group. See L<VM::EC2::REST::spot_instance> and
1163 L<VM::EC2::REST::reserved_instance>. For example:
1164  
1165 @offerings = $ec2->describe_reserved_instances_offerings(
1166 {'availability-zone' => 'us-east-1a',
1167 'instance-type' => 'c1.medium',
1168 'product-description' =>'Linux/UNIX',
1169 'duration' => 31536000, # this is 1 year
1170 });
1171 $offerings[0]->purchase(5) and print "Five reserved instances purchased\n";
1172  
1173  
1174  
1175 =head1 WAITING FOR STATE CHANGES
1176  
1177 VM::EC2 provides a series of methods that allow your script to wait in
1178 an efficient manner for desired state changes in instances, volumes
1179 and other objects. They are described in detail the individual modules
1180 to which they apply, but in each case the method will block until each
1181 member of a list of objects transitions to a terminal state
1182 (e.g. "completed" in the case of a snapshot). Briefly:
1183  
1184 $ec2->wait_for_instances(@instances)
1185 $ec2->wait_for_snapshots(@snapshots)
1186 $ec2->wait_for_volumes(@volumes)
1187 $ec2->wait_for_attachments(@attachment)
1188  
1189 There is also a generic version of this defined in the VM::EC2 core:
1190  
1191 =head2 $ec2->wait_for_terminal_state(\@objects,['list','of','states'] [,$timeout])
1192  
1193 Generic version of the last four methods. Wait for all members of the
1194 provided list of Amazon objects instances to reach some terminal state
1195 listed in the second argument, and then return a hash reference that
1196 maps each object ID to its final state.
1197  
1198 If a timeout is provided, in seconds, then the method will abort after
1199 waiting the indicated time and return undef.
1200  
1201 =cut
1202  
1203 sub wait_for_terminal_state {
1204 0 ▶ my $self = shift;
Subroutine wait_for_terminal_state: not called CC=4 SCAR=30.0
Pod documented
1205 0 my ($objects,$terminal_states,$timeout) = @_;
1206 0 my %terminal_state = map {$_=>1} @$terminal_states;
1207 0 my %status = ();
1208 0 my @pending = grep {defined $_} @$objects; # in case we're passed an undef
1209  
1210 0 my %timers;
1211 0 my $done = $self->condvar();
1212 $done->begin(sub {
1213 0 ▶ my $cv = shift;
Subroutine __ANON__: not called CC=2 SCAR=17.9
1214 0 ▶ if ($cv->error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cv->error) { } 0 0 0
1215 0 $self->error($cv->error);
1216 0 $cv->send();
1217 } else {
1218 0 $cv->send(\%status);
1219 }
1220 }
1221 0 );
1222
1223 0 for my $obj (@pending) {
1224 0 $done->begin;
1225 my $timer = AnyEvent->timer(interval => 3,
1226 cb => sub {
1227 $obj->current_status_async->cb(
1228 sub {
1229 0 ▶ my $state = shift->recv;
Subroutine __ANON__: not called CC=3 SCAR=24.8
1230 0 ▶ if (!$state || $terminal_state{$state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $state or $terminal_state{$state}) 0 0 0
Condition0%0/3
not $state or $terminal_state{$state}
l!l&&r!l&&!r
000
MC/DC0%0/2
not $state or $terminal_state{$state}
not $state $terminal_state{$state}
Truth table0%0/3
not(A) or B
A= not $stateB= $terminal_state{$state}
ABresult
1X1
011
000
1231 0 $status{$obj} = $state;
1232 0 $done->end;
1233 0 undef $timers{$obj};
1234 0 ▶ }})});
Subroutine __ANON__: not called CC=1 SCAR=6.9
1235 0 $timers{$obj} = $timer;
1236 }
1237  
1238 # timeout
1239 0 my $timeout_event;
1240 $timeout_event = AnyEvent->timer(after=> $timeout,
1241 cb => sub {
1242 0 ▶ undef %timers; # cancel all timers
Subroutine __ANON__: not called CC=2 SCAR=17.9
1243 0 undef $timeout_event;
1244 0 $done->error('timeout waiting for terminal state');
1245 0 $done->end foreach @pending;
1246 0 ▶ }) if $timeout;
Branch: 1 branch
BranchTrueFalseTotal
if $timeout 0 0 0
1247 0 $done->end;
1248  
1249 0 ▶ return $ASYNC ? $done : $done->recv;
Branch: 1 branch
BranchTrueFalseTotal
$VM::EC2::ASYNC ? : 0 0 0
1250 }
1251  
1252 =head2 $timeout = $ec2->wait_for_timeout([$new_timeout]);
1253  
1254 Get or change the timeout for wait_for_instances(), wait_for_attachments(),
1255 and wait_for_volumes(). The timeout is given in seconds, and defaults to
1256 600 (10 minutes). You can set this to 0 to wait forever.
1257  
1258 =cut
1259  
1260 sub wait_for_timeout {
1261 0 ▶ my $self = shift;
Subroutine wait_for_timeout: not called CC=3 SCAR=24.8
Pod documented
1262 $self->{wait_for_timeout} = WAIT_FOR_TIMEOUT
1263 0 ▶ unless defined $self->{wait_for_timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"wait_for_timeout"} 0 0 0
1264 0 my $d = $self->{wait_for_timeout};
1265 0 ▶ $self->{wait_for_timeout} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
1266 0 return $d;
1267 }
1268  
1269 # ------------------------------------------------------------------------------------------
1270  
1271 =head1 INTERNAL METHODS
1272  
1273 These methods are used internally and are listed here without
1274 documentation (yet).
1275  
1276 =head2 $underscore_name = $ec2->canonicalize($mixedCaseName)
1277  
1278 =cut
1279  
1280 sub canonicalize {
1281 0 ▶ my $self = shift;
Subroutine canonicalize: not called CC=3 SCAR=24.8
Pod documented
1282 0 my $name = shift;
1283  
1284 0 $name =~ s/^-//;
1285 0 $name =~ s/DB/Db/g;
1286 0 $name =~ s/AZ/Az/g;
1287  
1288 0 ▶ while ($name =~ /[A-Z][^A-Z]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /[A-Z][^A-Z]/) 0 0 0
1289 0 ▶ $name =~ s/(?<!^)([A-Z]*[\d]*)\.?([A-Z])/\L$1_$2/g or last;
Branch: 1 branch
BranchTrueFalseTotal
$name =~ s/(?<!^)([A-Z]*[\d]*)\.?([A-Z])/\L$1_$2\E/g or last 0 0 0
1290 }
1291 0 return '-'.lc $name;
1292 }
1293  
1294 sub uncanonicalize {
1295 0 ▶ my $self = shift;
Subroutine uncanonicalize: not called CC=1 SCAR=6.9
Pod undocumented
1296 0 my $name = shift;
1297 0 $name =~ s/_([a-z])/\U$1/g;
1298 0 return $name;
1299 }
1300  
1301 =head2 $instance_id = $ec2->instance_parm(@args)
1302  
1303 =cut
1304  
1305 sub instance_parm {
1306 0 ▶ my $self = shift;
Subroutine instance_parm: not called CC=5 SCAR=34.0
Pod documented
1307 0 my %args;
1308 0 ▶ if ($_[0] =~ /^-/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($_[0] =~ /^-/) { } 0 0 0
elsif (@_ > 1) { } 0 0 0
1309 0 %args = @_;
1310 } elsif (@_ > 1) {
1311 0 %args = (-instance_id => [@_]);
1312 } else {
1313 0 %args = (-instance_id => shift);
1314 }
1315 0 my $id = $args{-instance_id};
1316 0 ▶ return ref $id && ref $id eq 'ARRAY' ? @$id : $id;
Branch: 1 branch
BranchTrueFalseTotal
ref $id && ref $id eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $id and ref $id eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $id and ref $id eq "ARRAY"
ref $id ref $id eq "ARRAY"
Truth table0%0/3
A and B
A= ref $idB= ref $id eq "ARRAY"
ABresult
0X0
100
111
1317 }
1318  
1319 =head2 @arguments = $ec2->value_parm(ParameterName => \%args)
1320  
1321 =cut
1322  
1323 sub value_parm {
1324 0 ▶ my $self = shift;
Subroutine value_parm: not called CC=4 SCAR=30.0
Pod documented
1325 0 my ($argname,$args) = @_;
1326 0 my $name = $self->canonicalize($argname);
1327 0 ▶ return unless exists $args->{$name} || exists $args->{"-$argname"};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{$name} or exists $$args{"-$argname"} 0 0 0
Condition0%0/3
exists $args->{$name} or exists $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $args->{$name} or exists $$args{"-$argname"}
exists $args->{$name} exists $$args{"-$argname"}
Truth table0%0/3
A or B
A= exists $args->{$name}B= exists $$args{"-$argname"}
ABresult
1X1
011
000
1328 0 ▶ my $val = $args->{$name} || $args->{"-$argname"};
Condition0%0/3
$args->{$name} || $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $$args{"-$argname"}
$args->{$name} $$args{"-$argname"}
Truth table0%0/3
A || B
A= $args->{$name}B= $$args{"-$argname"}
ABresult
1X1
011
000
1329 0 return ("$argname.Value"=>$val);
1330 }
1331  
1332 =head2 @arguments = $ec2->single_parm(ParameterName => \%args)
1333  
1334 =cut
1335  
1336 sub single_parm {
1337 0 ▶ my $self = shift;
Subroutine single_parm: not called CC=5 SCAR=34.0
Pod documented
1338 0 my ($argname,$args) = @_;
1339 0 my $name = $self->canonicalize($argname);
1340 0 ▶ my $val = $args->{$name} || $args->{"-$argname"};
Condition0%0/3
$args->{$name} || $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $$args{"-$argname"}
$args->{$name} $$args{"-$argname"}
Truth table0%0/3
A || B
A= $args->{$name}B= $$args{"-$argname"}
ABresult
1X1
011
000
1341 0 ▶ defined $val or return;
Branch: 1 branch
BranchTrueFalseTotal
defined $val or return 0 0 0
1342 0 ▶ my $v = ref $val && ref $val eq 'ARRAY' ? $val->[0] : $val;
Branch: 1 branch
BranchTrueFalseTotal
ref $val && ref $val eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $val and ref $val eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $val and ref $val eq "ARRAY"
ref $val ref $val eq "ARRAY"
Truth table0%0/3
A and B
A= ref $valB= ref $val eq "ARRAY"
ABresult
0X0
100
111
1343 0 return ($argname=>$v);
1344 }
1345  
1346 =head2 @parameters = $ec2->prefix_parm($prefix, ParameterName => \%args)
1347  
1348 =cut
1349  
1350 sub prefix_parm {
1351 0 ▶ my $self = shift;
Subroutine prefix_parm: not called CC=5 SCAR=34.0
Pod documented
1352 0 my ($prefix,$argname,$args) = @_;
1353 0 my $name = $self->canonicalize($argname);
1354 0 ▶ my $val = $args->{$name} || $args->{"-$argname"};
Condition0%0/3
$args->{$name} || $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $$args{"-$argname"}
$args->{$name} $$args{"-$argname"}
Truth table0%0/3
A || B
A= $args->{$name}B= $$args{"-$argname"}
ABresult
1X1
011
000
1355 0 ▶ defined $val or return;
Branch: 1 branch
BranchTrueFalseTotal
defined $val or return 0 0 0
1356 0 ▶ my $v = ref $val && ref $val eq 'ARRAY' ? $val->[0] : $val;
Branch: 1 branch
BranchTrueFalseTotal
ref $val && ref $val eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $val and ref $val eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $val and ref $val eq "ARRAY"
ref $val ref $val eq "ARRAY"
Truth table0%0/3
A and B
A= ref $valB= ref $val eq "ARRAY"
ABresult
0X0
100
111
1357 0 return ("$prefix.$argname"=>$v);
1358 }
1359  
1360 =head2 @arguments = $ec2->member_hash_parms(ParameterName => \%args)
1361  
1362 Create a parameter list from a hashref or arrayref of hashes
1363  
1364 Created specifically for the RDS ModifyDBParameterGroup parameter
1365 'Parameters', but may be useful for other calls in the future.
1366  
1367 ie:
1368  
1369 The argument would be in the form:
1370  
1371 [
1372 {
1373 ParameterName=>'max_user_connections',
1374 ParameterValue=>24,
1375 ApplyMethod=>'pending-reboot'
1376 },
1377 {
1378 ParameterName=>'max_allowed_packet',
1379 ParameterValue=>1024,
1380 ApplyMethod=>'immediate'
1381 },
1382 ];
1383  
1384 The resulting output would be if the argname is '-parameters':
1385  
1386 Parameters.member.1.ParameterName => max_user_connections
1387 Parameters.member.1.ParameterValue => 24
1388 Parameters.member.1.ApplyMethod => pending-reboot
1389 Parameters.member.2.ParameterName => max_allowed_packet
1390 Parameters.member.2.ParameterValue => 1024
1391 Parameters.member.2.ApplyMethod => immediate
1392  
1393 =cut
1394  
1395 sub member_hash_parms {
1396 0 ▶ my $self = shift;
Subroutine member_hash_parms: not called CC=8 SCAR=42.8
Pod documented
1397 0 my ($argname,$args) = @_;
1398 0 my $name = $self->canonicalize($argname);
1399  
1400 0 my @params;
1401 0 ▶ if (my $arg = $args->{$name}||$args->{"-$argname"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $arg = $args->{$name} || $$args{"-$argname"}) 0 0 0
Condition0%0/3
$args->{$name} || $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $$args{"-$argname"}
$args->{$name} $$args{"-$argname"}
Truth table0%0/3
A || B
A= $args->{$name}B= $$args{"-$argname"}
ABresult
1X1
011
000
1402 0 ▶ $arg = [ $arg ] if ref $arg eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg eq "HASH" 0 0 0
1403 0 ▶ return unless ref $arg eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg eq "ARRAY" 0 0 0
1404 0 my $c = 1;
1405 0 foreach my $a (@$arg) {
1406 0 ▶ next unless ref $a eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $a eq "HASH" 0 0 0
1407 0 foreach my $key (keys %$a) {
1408 0 push @params, ("$argname.member.$c.$key" => $a->{$key});
1409 }
1410 0 $c++;
1411 }
1412 }
1413 0 return @params;
1414 }
1415  
1416 =head2 @arguments = $ec2->list_parm(ParameterName => \%args)
1417  
1418 =cut
1419  
1420 sub list_parm {
1421 0 ▶ my $self = shift;
Subroutine list_parm: not called CC=1 SCAR=6.9
Pod documented
1422 0 my ($argname,$args) = @_;
1423 0 return $self->_list_parm($argname,$args);
1424 }
1425  
1426 =head2 @parameters = $ec2->member_list_parm(ParameterName => \%args)
1427  
1428 =cut
1429  
1430 sub member_list_parm {
1431 0 ▶ my $self = shift;
Subroutine member_list_parm: not called CC=1 SCAR=6.9
Pod documented
1432 0 my ($argname,$args) = @_;
1433 0 return $self->_list_parm($argname,$args,'member');
1434 }
1435  
1436 sub _list_parm {
1437 0 ▶ my $self = shift;
Subroutine _list_parm: not called CC=7 SCAR=40.3
1438 0 my ($argname,$args,$append) = @_;
1439 0 my $name = $self->canonicalize($argname);
1440  
1441 0 my @params;
1442 0 ▶ if (my $a = $args->{$name}||$args->{"-$argname"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $a = $args->{$name} || $$args{"-$argname"}) 0 0 0
Condition0%0/3
$args->{$name} || $$args{"-$argname"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $$args{"-$argname"}
$args->{$name} $$args{"-$argname"}
Truth table0%0/3
A || B
A= $args->{$name}B= $$args{"-$argname"}
ABresult
1X1
011
000
1443 0 ▶ $argname .= ".$append" if $append;
Branch: 1 branch
BranchTrueFalseTotal
if $append 0 0 0
1444 0 my $c = 1;
1445 0 ▶ for (ref $a && ref $a eq 'ARRAY' ? @$a : $a) {
Branch: 1 branch
BranchTrueFalseTotal
ref $a && ref $a eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $a and ref $a eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $a and ref $a eq "ARRAY"
ref $a ref $a eq "ARRAY"
Truth table0%0/3
A and B
A= ref $aB= ref $a eq "ARRAY"
ABresult
0X0
100
111
1446 0 push @params,("$argname.".$c++ => $_);
1447 }
1448 }
1449  
1450 0 return @params;
1451 }
1452  
1453 =head2 @arguments = $ec2->filter_parm(\%args)
1454  
1455 =cut
1456  
1457 sub filter_parm {
1458 0 ▶ my $self = shift;
Subroutine filter_parm: not called CC=1 SCAR=6.9
Pod documented
1459 0 my $args = shift;
1460 0 return $self->key_value_parameters('Filter','Name','Value',$args);
1461 }
1462  
1463 =head2 @arguments = $ec2->key_value_parameters($param_name,$keyname,$valuename,\%args,$skip_undef_values)
1464  
1465 =cut
1466  
1467 sub key_value_parameters {
1468 0 ▶ my $self = shift;
Subroutine key_value_parameters: not called CC=1 SCAR=6.9
Pod documented
1469 # e.g. 'Filter', 'Name','Value',{-filter=>{a=>b}}
1470 0 return $self->_key_value_parameters(@_);
1471 }
1472  
1473 =head2 @arguments = $ec2->member_key_value_parameters($param_name,$keyname,$valuename,\%args,$skip_undef_values)
1474  
1475 =cut
1476  
1477 sub member_key_value_parameters {
1478 0 ▶ my $self = shift;
Subroutine member_key_value_parameters: not called CC=1 SCAR=6.9
Pod documented
1479 0 my ($parameter_name,$keyname,$valuename,$args,$skip_undef_values) = @_;
1480 0 return $self->_key_value_parameters($parameter_name,$keyname,$valuename,$args,$skip_undef_values,'member');
1481 }
1482  
1483 sub _key_value_parameters {
1484 0 ▶ my $self = shift;
Subroutine _key_value_parameters: not called CC=16 SCAR=56.1
1485 # e.g. 'Filter', 'Name','Value',{-filter=>{a=>b}}
1486 0 my ($parameter_name,$keyname,$valuename,$args,$skip_undef_values,$append) = @_;
1487 0 my $arg_name = $self->canonicalize($parameter_name);
1488
1489 0 my @params;
1490 0 ▶ if (my $a = $args->{$arg_name}||$args->{"-$parameter_name"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $a = $args->{$arg_name} || $$args{"-$parameter_name"}) 0 0 0
Condition0%0/3
$args->{$arg_name} || $$args{"-$parameter_name"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$arg_name} || $$args{"-$parameter_name"}
$args->{$arg_name} $$args{"-$parameter_name"}
Truth table0%0/3
A || B
A= $args->{$arg_name}B= $$args{"-$parameter_name"}
ABresult
1X1
011
000
1491 0 ▶ $parameter_name .= ".$append" if $append;
Branch: 1 branch
BranchTrueFalseTotal
if $append 0 0 0
1492 0 my $c = 1;
1493 0 ▶ if (ref $a && ref $a eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $a and ref $a eq 'HASH') { } 0 0 0
Condition0%0/3
ref $a and ref $a eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $a and ref $a eq "HASH"
ref $a ref $a eq "HASH"
Truth table0%0/3
A and B
A= ref $aB= ref $a eq "HASH"
ABresult
0X0
100
111
1494 0 ▶ while (my ($name,$value) = each %$a) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$a) 0 0 0
1495 0 push @params,("$parameter_name.$c.$keyname" => $name);
1496 0 ▶ if (ref $value && ref $value eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and ref $value eq 'ARRAY') { } 0 0 0
Condition0%0/3
ref $value and ref $value eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $value and ref $value eq "ARRAY"
ref $value ref $value eq "ARRAY"
Truth table0%0/3
A and B
A= ref $valueB= ref $value eq "ARRAY"
ABresult
0X0
100
111
1497 0 ▶ for (my $m=1;$m<=@$value;$m++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m <= @$value) 0 0 0
1498 0 push @params,("$parameter_name.$c.$valuename.$m" => $value->[$m-1])
1499 }
1500 } else {
1501 0 ▶ push @params,("$parameter_name.$c.$valuename" => $value)
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $value and $skip_undef_values 0 0 0
Condition0%0/3
not defined $value and $skip_undef_values
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $value and $skip_undef_values
not defined $value $skip_undef_values
Truth table0%0/3
not(A) and B
A= not defined $valueB= $skip_undef_values
ABresult
0X0
100
111
1502 unless !defined $value && $skip_undef_values;
1503 }
1504 0 $c++;
1505 }
1506 } else {
1507 0 ▶ for (ref $a ? @$a : $a) {
Branch: 1 branch
BranchTrueFalseTotal
ref $a ? : 0 0 0
1508 0 my ($name,$value) = /([^=]+)\s*=\s*(.+)/;
1509 0 push @params,("$parameter_name.$c.$keyname" => $name);
1510 0 ▶ push @params,("$parameter_name.$c.$valuename" => $value)
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $value and $skip_undef_values 0 0 0
Condition0%0/3
not defined $value and $skip_undef_values
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $value and $skip_undef_values
not defined $value $skip_undef_values
Truth table0%0/3
not(A) and B
A= not defined $valueB= $skip_undef_values
ABresult
0X0
100
111
1511 unless !defined $value && $skip_undef_values;
1512 0 $c++;
1513 }
1514 }
1515 }
1516  
1517 0 return @params;
1518 }
1519  
1520 =head2 @arguments = $ec2->launch_perm_parm($prefix,$suffix,$value)
1521  
1522 =cut
1523  
1524 sub launch_perm_parm {
1525 0 ▶ my $self = shift;
Subroutine launch_perm_parm: not called CC=2 SCAR=17.9
Pod documented
1526 0 my ($prefix,$suffix,$value) = @_;
1527 0 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
1528 0 $self->_perm_parm('LaunchPermission',$prefix,$suffix,$value);
1529 }
1530  
1531 sub create_volume_perm_parm {
1532 0 ▶ my $self = shift;
Subroutine create_volume_perm_parm: not called CC=2 SCAR=17.9
Pod undocumented
1533 0 my ($prefix,$suffix,$value) = @_;
1534 0 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
1535 0 $self->_perm_parm('CreateVolumePermission',$prefix,$suffix,$value);
1536 }
1537  
1538 sub _perm_parm {
1539 0 ▶ my $self = shift;
Subroutine _perm_parm: not called CC=5 SCAR=34.0
1540 0 my ($base,$prefix,$suffix,$value) = @_;
1541 0 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
1542 0 ▶ my @list = ref $value && ref $value eq 'ARRAY' ? @$value : $value;
Branch: 1 branch
BranchTrueFalseTotal
ref $value && ref $value eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $value and ref $value eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $value and ref $value eq "ARRAY"
ref $value ref $value eq "ARRAY"
Truth table0%0/3
A and B
A= ref $valueB= ref $value eq "ARRAY"
ABresult
0X0
100
111
1543 0 my $c = 1;
1544 0 my @param;
1545 0 for my $v (@list) {
1546 0 push @param,("$base.$prefix.$c.$suffix" => $v);
1547 0 $c++;
1548 }
1549 0 return @param;
1550 }
1551  
1552 =head2 @arguments = $ec2->iam_parm($args)
1553  
1554 =cut
1555  
1556 sub iam_parm {
1557 0 ▶ my $self = shift;
Subroutine iam_parm: not called CC=3 SCAR=24.8
Pod documented
1558 0 my $args = shift;
1559 0 my @p;
1560 0 ▶ push @p,('IamInstanceProfile.Arn' => $args->{-iam_arn}) if $args->{-iam_arn};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"-iam_arn"} 0 0 0
1561 0 ▶ push @p,('IamInstanceProfile.Name' => $args->{-iam_name}) if $args->{-iam_name};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"-iam_name"} 0 0 0
1562 0 return @p;
1563 }
1564  
1565 =head2 @arguments = $ec2->block_device_parm($block_device_mapping_string)
1566  
1567 =cut
1568  
1569 sub block_device_parm {
1570 0 ▶ my $self = shift;
Subroutine block_device_parm: not called CC=18 SCAR=58.3
Pod documented
1571 0 ▶ my $devlist = shift or return;
Branch: 1 branch
BranchTrueFalseTotal
my $devlist = shift() or return 0 0 0
1572  
1573 0 ▶ my @dev = ref $devlist && ref $devlist eq 'ARRAY' ? @$devlist : $devlist;
Branch: 1 branch
BranchTrueFalseTotal
ref $devlist && ref $devlist eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $devlist and ref $devlist eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $devlist and ref $devlist eq "ARRAY"
ref $devlist ref $devlist eq "ARRAY"
Truth table0%0/3
A and B
A= ref $devlistB= ref $devlist eq "ARRAY"
ABresult
0X0
100
111
1574  
1575 0 my @p;
1576 0 my $c = 1;
1577 0 for my $d (@dev) {
1578 0 ▶ $d =~ /^([^=]+)=([^=]+)$/ or croak "block device mapping must be in format /dev/sdXX=device-name";
Branch: 1 branch
BranchTrueFalseTotal
$d =~ /^([^=]+)=([^=]+)$/ or croak("block device mapping must be in format /dev/sdXX=device-name") 0 0 0
1579  
1580 0 my ($devicename,$blockdevice) = ($1,$2);
1581 0 push @p,("BlockDeviceMapping.$c.DeviceName"=>$devicename);
1582  
1583 0 ▶ if ($blockdevice =~ /^vol-/) { # this is a volume, and not a snapshot
Branch: 3 branches
BranchTrueFalseTotal
if ($blockdevice =~ /^vol-/) { } 0 0 0
elsif ($blockdevice eq 'none') { } 0 0 0
elsif ($blockdevice =~ /^ephemeral\d$/) { } 0 0 0
1584 0 my ($volume,$delete_on_term) = split ':',$blockdevice;
1585 0 push @p,("BlockDeviceMapping.$c.Ebs.VolumeId" => $volume);
1586 0 ▶ push @p,("BlockDeviceMapping.$c.Ebs.DeleteOnTermination"=>$delete_on_term)
Branch: 1 branch
BranchTrueFalseTotal
if defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/ 0 0 0
Condition0%0/3
defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/
defined $delete_on_term $delete_on_term =~ /^(true|false|1|0)$/
Truth table0%0/3
A and B
A= defined $delete_on_termB= $delete_on_term =~ /^(true|false|1|0)$/
ABresult
0X0
100
111
1587 if defined $delete_on_term && $delete_on_term=~/^(true|false|1|0)$/
1588 }
1589 elsif ($blockdevice eq 'none') {
1590 0 push @p,("BlockDeviceMapping.$c.NoDevice" => '');
1591 } elsif ($blockdevice =~ /^ephemeral\d$/) {
1592 0 push @p,("BlockDeviceMapping.$c.VirtualName"=>$blockdevice);
1593 } else {
1594 0 my ($snapshot,$size,$delete_on_term,$vtype,$iops) = split ':',$blockdevice;
1595  
1596 # Workaround for apparent bug in 2012-12-01 API; instances will crash without volume size
1597 # even if a snapshot ID is provided
1598 0 ▶ if ($snapshot) {
Branch: 1 branch
BranchTrueFalseTotal
if ($snapshot) 0 0 0
1599 0 ▶ $size ||= eval{$self->describe_snapshots($snapshot)->volumeSize};
Condition0%0/3
$size ||= eval { do { $self->describe_snapshots($snapshot)->volumeSize } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$size ||= eval { do { $self->describe_snapshots($snapshot)->volumeSize } }
$size eval { do { $self->describe_snapshots($snapshot)->volumeSize } }
Truth table0%0/3
A ||= B
A= $sizeB= eval { do { $self->describe_snapshots($snapshot)->volumeSize } }
ABresult
1X1
011
000
1600 0 push @p,("BlockDeviceMapping.$c.Ebs.SnapshotId" =>$snapshot);
1601 }
1602  
1603 0 ▶ push @p,("BlockDeviceMapping.$c.Ebs.VolumeSize" =>$size) if $size;
Branch: 1 branch
BranchTrueFalseTotal
if $size 0 0 0
1604 0 ▶ push @p,("BlockDeviceMapping.$c.Ebs.DeleteOnTermination"=>$delete_on_term)
Branch: 1 branch
BranchTrueFalseTotal
if defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/ 0 0 0
Condition0%0/3
defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $delete_on_term and $delete_on_term =~ /^(true|false|1|0)$/
defined $delete_on_term $delete_on_term =~ /^(true|false|1|0)$/
Truth table0%0/3
A and B
A= defined $delete_on_termB= $delete_on_term =~ /^(true|false|1|0)$/
ABresult
0X0
100
111
1605 if defined $delete_on_term && $delete_on_term=~/^(true|false|1|0)$/;
1606 0 ▶ push @p,("BlockDeviceMapping.$c.Ebs.VolumeType"=>$vtype) if $vtype;
Branch: 1 branch
BranchTrueFalseTotal
if $vtype 0 0 0
1607 0 ▶ push @p,("BlockDeviceMapping.$c.Ebs.Iops"=>$iops) if $iops;
Branch: 1 branch
BranchTrueFalseTotal
if $iops 0 0 0
1608 }
1609 0 $c++;
1610 }
1611 0 return @p;
1612 }
1613  
1614 # ['eth0=eni-123456','eth1=192.168.2.1,192.168.3.1,192.168.4.1:subnet-12345:sg-12345:true:My Weird Network']
1615 # form 1: ethX=network device id
1616 # form 2: ethX=primary_address,secondary_address1,secondary_address2...:subnetId:securityGroupId:deleteOnTermination:description:AssociatePublicIpAddress
1617 # form 3: ethX=primary_address,secondary_address_count:subnetId:securityGroupId:deleteOnTermination:description:AssociatePublicIpAddress
1618 sub network_interface_parm {
1619 0 ▶ my $self = shift;
Subroutine network_interface_parm: not called CC=21 SCAR=61.4
Pod undocumented
1620 0 my $args = shift;
1621 0 ▶ my $devlist = $args->{-network_interfaces} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $devlist = $args->{"-network_interfaces"} or return 0 0 0
1622 0 ▶ my @dev = ref $devlist && ref $devlist eq 'ARRAY' ? @$devlist : $devlist;
Branch: 1 branch
BranchTrueFalseTotal
ref $devlist && ref $devlist eq 'ARRAY' ? : 0 0 0
Condition0%0/3
ref $devlist and ref $devlist eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $devlist and ref $devlist eq "ARRAY"
ref $devlist ref $devlist eq "ARRAY"
Truth table0%0/3
A and B
A= ref $devlistB= ref $devlist eq "ARRAY"
ABresult
0X0
100
111
1623  
1624 0 my @p;
1625 0 my $c = 0;
1626 0 for my $d (@dev) {
1627 0 ▶ $d =~ /^eth(\d+)\s*=\s*([^=]+)$/ or croak "network device mapping must be in format ethX=option-string";
Branch: 1 branch
BranchTrueFalseTotal
$d =~ /^eth(\d+)\s*=\s*([^=]+)$/ or croak("network device mapping must be in format ethX=option-string") 0 0 0
1628  
1629 0 my ($device_index,$device_options) = ($1,$2);
1630 0 push @p,("NetworkInterface.$c.DeviceIndex" => $device_index);
1631 0 my @options = split ':',$device_options;
1632 0 ▶ if (@options == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@options == 1) { } 0 0 0
1633 0 push @p,("NetworkInterface.$c.NetworkInterfaceId" => $options[0]);
1634 }
1635 else {
1636 0 my ($ip_addresses,$subnet_id,$security_group_id,$delete_on_termination,$description,$assoc_public_ip_addr) = @options;
1637 # if assoc_public_ip_addr is true, the following conditions must be met:
1638 # * can only associate a public address with a single network interface with a device index of 0
1639 # * cannot associate a public ip with a second network interface
1640 # * cannot assoicate a public ip when launching more than one network interface
1641 # NOTE: This option defaults to true in a default VPC
1642 0 ▶ if ($assoc_public_ip_addr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($assoc_public_ip_addr) 0 0 0
1643 0 ▶ $assoc_public_ip_addr = (($assoc_public_ip_addr eq 'true') &&
Branch: 1 branch
BranchTrueFalseTotal
$assoc_public_ip_addr eq 'true' && $device_index == 0 && @dev == 1 ? : 0 0 0
Condition0%0/6
$assoc_public_ip_addr eq "true" and $device_index == 0 and @dev == 1
!ll&&!rl&&r
000
$assoc_public_ip_addr eq "true" and $device_index == 0
!ll&&!rl&&r
000
MC/DC0%0/3
$assoc_public_ip_addr eq "true" and $device_index == 0 and @dev == 1
$assoc_public_ip_addr eq "true" $device_index == 0 @dev == 1
Truth table0%0/4
A and B and C
A= $assoc_public_ip_addr eq "true"B= $device_index == 0C= @dev == 1
ABCresult
0XX0
10X0
1100
1111
1644 ($device_index == 0) &&
1645 (@dev == 1)) ? 'true' : 'false';
1646 }
1647 0 my @addresses = split /\s*,\s*/,$ip_addresses;
1648 0 ▶ for (my $a = 0; $a < @addresses; $a++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a < @addresses) 0 0 0
1649 0 ▶ if ($addresses[$a] =~ /^\d+\.\d+\.\d+\.\d+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($addresses[$a] =~ /^\d+\.\d+\.\d+\.\d+$/) { } 0 0 0
elsif ($addresses[$a] =~ /^\d+$/ and $a > 0) { } 0 0 0
1650 0 push @p,("NetworkInterface.$c.PrivateIpAddresses.$a.PrivateIpAddress" => $addresses[$a]);
1651 0 ▶ push @p,("NetworkInterface.$c.PrivateIpAddresses.$a.Primary" => $a == 0 ? 'true' : 'false');
Branch: 1 branch
BranchTrueFalseTotal
$a == 0 ? : 0 0 0
1652 }
1653 ▶ elsif ($addresses[$a] =~ /^\d+$/ && $a > 0) {
Condition0%0/3
$addresses[$a] =~ /^\d+$/ and $a > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$addresses[$a] =~ /^\d+$/ and $a > 0
$addresses[$a] =~ /^\d+$/ $a > 0
Truth table0%0/3
A and B
A= $addresses[$a] =~ /^\d+$/B= $a > 0
ABresult
0X0
100
111
1654 0 push @p,("NetworkInterface.$c.SecondaryPrivateIpAddressCount" => $addresses[$a]);
1655 }
1656 }
1657 0 my @sgs = split ',',$security_group_id;
1658 0 ▶ for (my $i=0;$i<@sgs;$i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @sgs) 0 0 0
1659 0 push @p,("NetworkInterface.$c.SecurityGroupId.$i" => $sgs[$i]);
1660 }
1661  
1662 0 ▶ push @p,("NetworkInterface.$c.SubnetId" => $subnet_id) if length $subnet_id;
Branch: 1 branch
BranchTrueFalseTotal
if length $subnet_id 0 0 0
1663 0 ▶ push @p,("NetworkInterface.$c.DeleteOnTermination" => $delete_on_termination) if length $delete_on_termination;
Branch: 1 branch
BranchTrueFalseTotal
if length $delete_on_termination 0 0 0
1664 0 ▶ push @p,("NetworkInterface.$c.Description" => $description) if length $description;
Branch: 1 branch
BranchTrueFalseTotal
if length $description 0 0 0
1665 0 ▶ push @p,("NetworkInterface.$c.AssociatePublicIpAddress" => $assoc_public_ip_addr) if $assoc_public_ip_addr;
Branch: 1 branch
BranchTrueFalseTotal
if $assoc_public_ip_addr 0 0 0
1666 }
1667 0 $c++;
1668 }
1669 0 return @p;
1670 }
1671  
1672 sub boolean_parm {
1673 0 ▶ my $self = shift;
Subroutine boolean_parm: not called CC=5 SCAR=34.0
Pod undocumented
1674 0 my ($argname,$args) = @_;
1675 0 my $name = $self->canonicalize($argname);
1676 0 ▶ return unless exists $args->{$name} || exists $args->{$argname};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{$name} or exists $args->{$argname} 0 0 0
Condition0%0/3
exists $args->{$name} or exists $args->{$argname}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $args->{$name} or exists $args->{$argname}
exists $args->{$name} exists $args->{$argname}
Truth table0%0/3
A or B
A= exists $args->{$name}B= exists $args->{$argname}
ABresult
1X1
011
000
1677 0 ▶ my $val = $args->{$name} || $args->{$argname};
Condition0%0/3
$args->{$name} || $args->{$argname}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $args->{$argname}
$args->{$name} $args->{$argname}
Truth table0%0/3
A || B
A= $args->{$name}B= $args->{$argname}
ABresult
1X1
011
000
1678 0 ▶ return ($argname => $val ? 'true' : 'false');
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
1679 }
1680  
1681 sub boolean_value_parm {
1682 0 ▶ my $self = shift;
Subroutine boolean_value_parm: not called CC=5 SCAR=34.0
Pod undocumented
1683 0 my ($argname,$args) = @_;
1684 0 my $name = $self->canonicalize($argname);
1685 0 ▶ return unless exists $args->{$name} || exists $args->{$argname};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{$name} or exists $args->{$argname} 0 0 0
Condition0%0/3
exists $args->{$name} or exists $args->{$argname}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $args->{$name} or exists $args->{$argname}
exists $args->{$name} exists $args->{$argname}
Truth table0%0/3
A or B
A= exists $args->{$name}B= exists $args->{$argname}
ABresult
1X1
011
000
1686 0 ▶ my $val = $args->{$name} || $args->{$argname};
Condition0%0/3
$args->{$name} || $args->{$argname}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{$name} || $args->{$argname}
$args->{$name} $args->{$argname}
Truth table0%0/3
A || B
A= $args->{$name}B= $args->{$argname}
ABresult
1X1
011
000
1687 0 ▶ return ("$argname.Value" => $val ? 'true' : 'false');
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
1688 }
1689  
1690 =head2 $version = $ec2->version()
1691  
1692 Returns the API version to be sent to the endpoint. Calls
1693 guess_version_from_endpoint() to determine this.
1694  
1695 =cut
1696  
1697 sub version {
1698 0 ▶ my $self = shift;
Subroutine version: not called CC=2 SCAR=17.9
Pod documented
1699 0 ▶ return $self->{version} ||= $self->guess_version_from_endpoint();
Condition0%0/3
$self->{"version"} ||= $self->guess_version_from_endpoint
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"version"} ||= $self->guess_version_from_endpoint
$self->{"version"} $self->guess_version_from_endpoint
Truth table0%0/3
A ||= B
A= $self->{"version"}B= $self->guess_version_from_endpoint
ABresult
1X1
011
000
1700 }
1701  
1702 =head2 $version = $ec2->guess_version_from_endpoint()
1703  
1704 This method attempts to guess what version string to use when
1705 communicating with various endpoints. When talking to endpoints that
1706 contain the string "Eucalyptus" uses the old EC2 API
1707 "2009-04-04". When talking to other endpoints, uses the latest EC2
1708 version string.
1709  
1710 =cut
1711  
1712 sub guess_version_from_endpoint {
1713 0 ▶ my $self = shift;
Subroutine guess_version_from_endpoint: not called CC=2 SCAR=17.9
Pod documented
1714 0 my $endpoint = $self->endpoint;
1715 0 ▶ return '2009-04-04' if $endpoint =~ /Eucalyptus/; # eucalyptus version according to http://www.eucalyptus.com/participate/code
Branch: 1 branch
BranchTrueFalseTotal
if $endpoint =~ /Eucalyptus/ 0 0 0
1716 0 return '2014-05-01'; # most recent AWS version that we support
1717 }
1718  
1719 =head2 $ts = $ec2->timestamp
1720  
1721 =cut
1722  
1723 sub timestamp {
1724 0 ▶ return strftime("%Y-%m-%dT%H:%M:%SZ",gmtime);
Subroutine timestamp: not called CC=1 SCAR=6.9
Pod documented
1725 }
1726  
1727  
1728 =head2 @obj = $ec2->call($action,@param);
1729  
1730 Make a call to Amazon using $action and the passed arguments, and
1731 return a list of objects.
1732  
1733 if $VM::EC2::ASYNC is set to true, then will return a
1734 AnyEvent::CondVar object instead of a list of objects. You may
1735 retrieve the objects by calling recv() or setting a callback:
1736  
1737 $VM::EC2::ASYNC = 1;
1738 my $cv = $ec2->call('DescribeInstances');
1739 my @obj = $cv->recv;
1740  
1741 or
1742  
1743 $VM::EC2::ASYNC = 1;
1744 my $cv = $ec2->call('DescribeInstances');
1745 $cv->cb(sub { my @objs = shift->recv;
1746 do_something(@objs);
1747 });
1748  
1749 =cut
1750  
1751 sub call {
1752 0 ▶ my $self = shift;
Subroutine call: not called CC=2 SCAR=17.9
Pod documented
1753 0 ▶ return $ASYNC ? $self->_call_async(@_) : $self->_call_sync(@_);
Branch: 1 branch
BranchTrueFalseTotal
$VM::EC2::ASYNC ? : 0 0 0
1754 }
1755 sub _call_sync {
1756 0 ▶ my $self = shift;
Subroutine _call_sync: not called CC=5 SCAR=34.0
1757 0 my $cv = $self->_call_async(@_);
1758 0 my @obj = $cv->recv;
1759 0 ▶ $self->error($cv->error) if $cv->error;
Branch: 1 branch
BranchTrueFalseTotal
if $cv->error 0 0 0
1760 0 ▶ if (!wantarray) { # scalar context
Branch: 1 branch
BranchTrueFalseTotal
if (not wantarray) { } 0 0 0
1761 0 ▶ return $obj[0] if @obj == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @obj == 1 0 0 0
1762 0 ▶ return if @obj == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @obj == 0 0 0 0
1763 0 return @obj;
1764 } else {
1765 0 return @obj;
1766 }
1767 }
1768  
1769 sub _call_async {
1770 0 ▶ my $self = shift;
Subroutine _call_async: not called CC=3 SCAR=24.8
1771 0 my ($action,@param) = @_;
1772  
1773 # called if AWS::Signature4 NOT present; use built-in method
1774 0 ▶ unless (AWS::Signature4->can('new')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("AWS::Signature4"->can("new")) 0 0 0
1775 0 my ($action,@param) = @_;
1776 0 my $post = $self->_signature(Action=>$action,@param);
1777 0 my $u = URI->new($self->endpoint);
1778 0 $u->query_form(@$post);
1779 0 return $self->async_post($action,POST($self->endpoint,Content=>$u->query));
1780 }
1781  
1782  
1783 # called if AWS::Signature4 IS present; use external module
1784 0 my $request = POST($self->endpoint,
1785 'content-type'=>'application/x-www-form-urlencoded',
1786 Content => [
1787 Action => $action,
1788 Version => $self->version,
1789 @param
1790 ]);
1791 0 my $access_key = $self->access_key;
1792 0 my $secret_key = $self->secret;
1793 0 my $host = URI->new($self->endpoint)->host;
1794 0 ▶ $request->header('x-amz-security-token'=>$self->security_token) if $self->security_token;
Branch: 1 branch
BranchTrueFalseTotal
if $self->security_token 0 0 0
1795 0 $request->header('user-agent' => 'VM::EC2-perl');
1796 0 $request->header('action' => $action); # maybe not necessary, but docs say it is!
1797 0 $request->header('host' => $host);
1798
1799 0 AWS::Signature4->new(-access_key=>$access_key,
1800 -secret_key=>$secret_key)->sign($request);
1801 0 $self->async_post($action,$request);
1802 }
1803  
1804 sub async_post {
1805 0 ▶ my $self = shift;
Subroutine async_post: not called CC=1 SCAR=6.9
Pod undocumented
1806 0 $self->async_request('POST',@_);
1807 }
1808  
1809 sub async_get {
1810 0 ▶ my $self = shift;
Subroutine async_get: not called CC=1 SCAR=6.9
Pod undocumented
1811 0 $self->async_request('GET',@_);
1812 }
1813  
1814 sub async_put {
1815 0 ▶ my $self = shift;
Subroutine async_put: not called CC=1 SCAR=6.9
Pod undocumented
1816 0 $self->async_request('PUT',@_);
1817 }
1818  
1819 sub async_delete {
1820 0 ▶ my $self = shift;
Subroutine async_delete: not called CC=1 SCAR=6.9
Pod undocumented
1821 0 $self->async_request('DELETE',@_);
1822 }
1823  
1824 sub async_request {
1825 0 ▶ my $self = shift;
Subroutine async_request: not called CC=1 SCAR=6.9
Pod undocumented
1826 0 my ($method,$action,$request) = @_;
1827  
1828 0 my @headers;
1829 0 ▶ $request->headers->scan(sub {push @headers,@_});
Subroutine __ANON__: not called CC=1 SCAR=6.9
1830  
1831 0 my $cv = $self->condvar;
1832 my $callback = sub {
1833 0 ▶ my $timer = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1834 http_request(
1835 $method => $request->uri,
1836 body => $request->content,
1837 headers => {
1838 TE => undef,
1839 Referer => undef,
1840 @headers,
1841 },
1842 sub {
1843 0 ▶ my ($body,$hdr) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
1844 0 ▶ if ($hdr->{Status} !~ /^2/) { # an error
Branch: 1 branch
BranchTrueFalseTotal
if (not $hdr->{'Status'} =~ /^2/) { } 0 0 0
1845 0 ▶ if ($body =~ /RequestLimitExceeded/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /RequestLimitExceeded/) { } 0 0 0
1846 0 warn "RequestLimitExceeded. Retry in ",$timer->next_interval()," seconds\n";
1847 0 $timer->retry();
1848 0 return;
1849 } else {
1850 0 $self->async_send_error($action,$hdr,$body,$cv);
1851 0 $timer->success();
1852 0 return;
1853 }
1854 } else { # success
1855 0 $self->error(undef);
1856 0 my @obj = VM::EC2::Dispatch->content2objects($action,$body,$self);
1857 0 $cv->send(@obj);
1858 0 $timer->success();
1859 }
1860 })
1861 0 };
1862 RetryTimer->new(on_retry => $callback,
1863 interval => 1,
1864 max_retries => 12,
1865 0 ▶ on_max_retries => sub { $cv->error(VM::EC2::Error->new({Code=>500,Message=>'RequestLimitExceeded'},$self)) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1866  
1867 0 return $cv;
1868 }
1869  
1870 sub async_send_error {
1871 0 ▶ my $self = shift;
Subroutine async_send_error: not called CC=6 SCAR=37.4
Pod undocumented
1872 0 my ($action,$hdr,$body,$cv) = @_;
1873 0 my $error;
1874  
1875 0 ▶ if ($body =~ /<Response>/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /<Response>/) { } 0 0 0
elsif ($body =~ m[<ErrorResponse xmlns="http://]) { } 0 0 0
1876 0 $error = VM::EC2::Dispatch->create_error_object($body,$self,$action);
1877 } elsif ($body =~ /<ErrorResponse xmlns="http:\/\//) {
1878 0 $error = VM::EC2::Dispatch->create_alt_error_object($body,$self,$action);
1879 } else {
1880 0 my $code = $hdr->{Status};
1881 0 ▶ my $msg = $code =~ /^59[0-9]/ ? $hdr->{Reason} : $body;
Branch: 1 branch
BranchTrueFalseTotal
$code =~ /^59[0-9]/ ? : 0 0 0
1882 0 $error = VM::EC2::Error->new({Code=>$code,Message=>"$msg, at API call '$action')"},$self);
1883 }
1884  
1885 0 $cv->error($error);
1886  
1887 # this is probably not want we want to do, because it will cause error messages to
1888 # appear in random places nested into some deep callback.
1889 0 ▶ carp "$error" if $self->print_error;
Branch: 1 branch
BranchTrueFalseTotal
if $self->print_error 0 0 0
1890  
1891 0 ▶ if ($self->raise_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->raise_error) { } 0 0 0
1892 0 $cv->croak($error);
1893 } else {
1894 0 $cv->send;
1895 }
1896 }
1897  
1898 sub signin_call {
1899 0 ▶ my $self = shift;
Subroutine signin_call: not called CC=2 SCAR=17.9
Pod undocumented
1900 0 my ($action,%args) = @_;
1901 0 my $endpoint = 'https://signin.aws.amazon.com/federation';
1902  
1903 0 $args{'Action'} = $action;
1904  
1905 0 my @param;
1906 0 for my $p (sort keys %args) {
1907 0 push @param , join '=' , map { uri_escape($_,"^A-Za-z0-9\-_.~") } ($p,$args{$p});
1908 }
1909
1910 0 my $request = GET "$endpoint?" . join '&', @param;
1911  
1912 0 my $response = $self->ua->request($request);
1913  
1914 0 return JSON::decode_json($response->content);
1915 }
1916  
1917 =head2 $url = $ec2->login_url(-credentials => $credentials, -issuer => $issuer_url, -destination => $console_url);
1918  
1919 Returns an HTTP::Request object that points to the URL to login a user with STS credentials
1920  
1921 -credentials => $fed_token->credentials - Credentials from an $ec2->get_federation_token call
1922 -token => $token - a SigninToken from $ec2->get_signin_token call
1923 -issuer => $issuer_url
1924 -destination => $console_url - URL of the AWS console. Defaults to https://console.aws.amazon.com/console/home
1925 -auto_scaling_group_names List of auto scaling groups to describe
1926 -names Alias of -auto_scaling_group_names
1927  
1928 -credentials or -token are required for this method to work
1929  
1930 Usage can be:
1931  
1932 my $fed_token = $ec2->get_federation_token(...);
1933 my $token = $ec2->get_signin_token(-credentials => $fed_token->credentials);
1934 my $url = $ec2->login_url(-token => $token->{SigninToken}, -issuer => $issuer_url, -destination => $console_url);
1935  
1936 Or:
1937  
1938 my $fed_token = $ec2->get_federation_token(...);
1939 my $url = $ec2->login_url(-credentials => $fed_token->credentials, -issuer => $issuer_url, -destination => $console_url);
1940  
1941 =cut
1942  
1943 sub login_url {
1944 0 ▶ my $self = shift;
Subroutine login_url: not called CC=7 SCAR=40.3
Pod documented
1945 0 my %args = @_;
1946 0 my $endpoint = 'https://signin.aws.amazon.com/federation';
1947  
1948 0 my %parms;
1949 0 $parms{Action} = 'login';
1950 0 ▶ $parms{Destination} = $args{-destination} if ($args{-destination});
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-destination"} 0 0 0
1951 0 ▶ $parms{Issuer} = $args{-issuer} if ($args{-issuer});
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-issuer"} 0 0 0
1952 0 ▶ $parms{SigninToken} = $args{-token} if ($args{-token});
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-token"} 0 0 0
1953  
1954 0 ▶ if (defined $args{-credentials} and not defined $parms{SigninToken}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"-credentials"} and not defined $parms{"SigninToken"}) 0 0 0
Condition0%0/3
defined $args{"-credentials"} and not defined $parms{"SigninToken"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args{"-credentials"} and not defined $parms{"SigninToken"}
defined $args{"-credentials"} not defined $parms{"SigninToken"}
Truth table0%0/3
A and not(B)
A= defined $args{"-credentials"}B= not defined $parms{"SigninToken"}
ABresult
0X0
100
111
1955 0 $parms{SigninToken} = $self->get_signin_token(-credentials => $args{-credentials})->{SigninToken};
1956 }
1957  
1958  
1959 0 my @param;
1960 0 for my $p (sort keys %parms) {
1961 0 push @param , join '=' , map { uri_escape($_,"^A-Za-z0-9\-_.~") } ($p,$parms{$p});
1962 }
1963  
1964 0 GET "$endpoint?" . join '&', @param;
1965 }
1966  
1967 =head2 $request = $ec2->_sign(@args)
1968  
1969 Create and sign an HTTP::Request.
1970  
1971 =cut
1972  
1973 # adapted from Jeff Kim's Net::Amazon::EC2 module
1974 sub _sign {
1975 0 ▶ my $self = shift;
Subroutine _sign: not called CC=1 SCAR=6.9
1976 0 my $signature = $self->_signature(@_);
1977 0 return POST $self->endpoint,$signature;
1978 }
1979  
1980 sub _signature {
1981 0 ▶ my $self = shift;
Subroutine _signature: not called CC=4 SCAR=30.0
1982 0 my @args = @_;
1983  
1984 0 my $action = 'POST';
1985 0 my $uri = URI->new($self->endpoint);
1986 0 my $host = $uri->host_port;
1987 0 $host =~ s/:(80|443)$//; # default ports will break
1988 0 ▶ my $path = $uri->path||'/';
Condition0%0/2
$uri->path || '/'
l!l
00
MC/DC0%0/1
$uri->path || '/'
$uri->path
Truth table0%0/2
A
A= $uri->path
Aresult
11
00
1989  
1990 0 my %sign_hash = @args;
1991 0 $sign_hash{AWSAccessKeyId} = $self->id;
1992 0 $sign_hash{Timestamp} = $self->timestamp;
1993 0 $sign_hash{Version} = $self->version;
1994 0 $sign_hash{SignatureVersion} = 2;
1995 0 $sign_hash{SignatureMethod} = 'HmacSHA256';
1996 0 ▶ $sign_hash{SecurityToken} = $self->security_token if $self->security_token;
Branch: 1 branch
BranchTrueFalseTotal
if $self->security_token 0 0 0
1997  
1998 0 my @param;
1999 0 my @parameter_keys = sort keys %sign_hash;
2000 0 for my $p (@parameter_keys) {
2001 0 push @param,join '=',map {uri_escape($_,"^A-Za-z0-9\-_.~")} ($p,$sign_hash{$p});
2002 }
2003 0 my $to_sign = join("\n",
2004 $action,$host,$path,join('&',@param));
2005 0 my $signature = encode_base64(hmac_sha256($to_sign,$self->secret),'');
2006 0 $sign_hash{Signature} = $signature;
2007 0 return [%sign_hash];
2008 }
2009  
2010 =head2 @param = $ec2->args(ParamName=>@_)
2011  
2012 Set up calls that take either method(-resource_id=>'foo') or method('foo').
2013  
2014 =cut
2015  
2016 sub args {
2017 0 ▶ my $self = shift;
Subroutine args: not called CC=6 SCAR=37.4
Pod documented
2018 0 my $default_param_name = shift;
2019 0 ▶ return unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
2020 0 ▶ return @_ if $_[0] =~ /^-/;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] =~ /^-/ 0 0 0
2021 0 ▶ return (-filter=>shift) if @_==1 && ref $_[0] && ref $_[0] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 and ref $_[0] and ref $_[0] eq "HASH" 0 0 0
Condition0%0/6
@_ == 1 and ref $_[0] and ref $_[0] eq "HASH"
!ll&&!rl&&r
000
@_ == 1 and ref $_[0]
!ll&&!rl&&r
000
MC/DC0%0/3
@_ == 1 and ref $_[0] and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] ref $_[0] eq "HASH"
Truth table0%0/4
A and B and C
A= @_ == 1B= ref $_[0]C= ref $_[0] eq "HASH"
ABCresult
0XX0
10X0
1100
1111
2022 0 return ($default_param_name => \@_);
2023 }
2024  
2025 sub condvar {
2026 0 ▶ bless AnyEvent->condvar,'VM::EC2::CondVar';
Subroutine condvar: not called CC=1 SCAR=6.9
Pod undocumented
2027 }
2028  
2029 # utility - retry a call with exponential backoff until it succeeds
2030 package RetryTimer;
2031 7 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
2032 7 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
2033  
2034 # try a subroutine multiple times with exponential backoff
2035 # until it succeeds. Subroutine must call timer's success() method
2036 # if it succeds, retry() otherwise.
2037  
2038 # Arguments
2039 # on_retry=>CODEREF,
2040 # on_max_retries=>CODEREF,
2041 # interval => $seconds, # defaults to 1
2042 # multiplier=>$fraction, # defaults to 1.5
2043 # max_retries=>$integer, # defaults to 10
2044 sub new {
2045 0 ▶ my $class = shift;
Subroutine new: not called CC=6 SCAR=37.4
2046 0 my @args = @_;
2047  
2048 0 my $self;
2049 $self = bless {
2050 timer => AE::timer(0,0, sub {
2051 0 ▶ delete $self->{timer};
Subroutine __ANON__: not called CC=2 SCAR=17.9
2052 0 ▶ $self->{on_retry}->($self) if $self->{on_retry};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_retry"} 0 0 0
2053 0 ▶ }),
Condition0%0/3
ref $class || $class
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table0%0/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
2054 tries => 0,
2055 current_interval => 0,
2056 @args,
2057 },ref $class || $class;
2058  
2059 0 ▶ croak "need a on_retry argument" unless $self->{on_retry};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"on_retry"} 0 0 0
2060 0 ▶ $self->{interval} ||= 1;
Condition0%0/2
$self->{"interval"} ||= 1
l!l
00
MC/DC0%0/1
$self->{"interval"} ||= 1
$self->{"interval"}
Truth table0%0/2
A
A= $self->{"interval"}
Aresult
11
00
2061 0 ▶ $self->{multiplier} ||= 1.5;
Condition0%0/2
$self->{"multiplier"} ||= "1.5"
l!l
00
MC/DC0%0/1
$self->{"multiplier"} ||= "1.5"
$self->{"multiplier"}
Truth table0%0/2
A
A= $self->{"multiplier"}
Aresult
11
00
2062 0 ▶ $self->{max_retries} = 10 unless defined $self->{max_retries};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"max_retries"} 0 0 0
2063 0 return $self;
2064 }
2065  
2066 sub retry {
2067 0 ▶ my $self = shift;
Subroutine retry: not called CC=5 SCAR=34.0
2068 0 ▶ return if $self->{timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"timer"} 0 0 0
2069 0 $self->{current_interval} = $self->next_interval;
2070 0 $self->{tries}++;
2071  
2072 0 ▶ if ($self->{max_retries} && $self->{max_retries} <= $self->{tries}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_retries"} and $self->{"max_retries"} <= $self->{"tries"}) 0 0 0
Condition0%0/3
$self->{"max_retries"} and $self->{"max_retries"} <= $self->{"tries"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"max_retries"} and $self->{"max_retries"} <= $self->{"tries"}
$self->{"max_retries"} $self->{"max_retries"} <= $self->{"tries"}
Truth table0%0/3
A and B
A= $self->{"max_retries"}B= $self->{"max_retries"} <= $self->{"tries"}
ABresult
0X0
100
111
2073 0 delete $self->{timer};
2074 0 delete $self->{current_interval};
2075 0 ▶ $self->{on_max_retries}->($self) if $self->{on_max_retries};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_max_retries"} 0 0 0
2076 0 return;
2077 }
2078 $self->{timer} = AE::timer ($self->{current_interval},0,
2079 sub {
2080 0 ▶ delete $self->{timer};
Subroutine __ANON__: not called CC=3 SCAR=24.8
2081 $self->{on_retry}->($self)
2082 0 ▶ if $self && $self->{on_retry};
Branch: 1 branch
BranchTrueFalseTotal
if $self and $self->{"on_retry"} 0 0 0
Condition0%0/3
$self and $self->{"on_retry"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self and $self->{"on_retry"}
$self $self->{"on_retry"}
Truth table0%0/3
A and B
A= $selfB= $self->{"on_retry"}
ABresult
0X0
100
111
2083 0 });
2084 }
2085  
2086 sub next_interval {
2087 0 ▶ my $self = shift;
Subroutine next_interval: not called CC=2 SCAR=17.9
2088 0 ▶ if ($self->{current_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'current_interval'}) { } 0 0 0
2089 0 return $self->{current_interval} * $self->{multiplier};
2090 } else {
2091 0 return $self->{interval};
2092 }
2093 }
2094  
2095 0 ▶sub current_interval { shift->{current_interval} };
Subroutine current_interval: not called CC=1 SCAR=6.9
2096  
2097 sub success {
2098 0 ▶ my $self = shift;
Subroutine success: not called CC=1 SCAR=6.9
2099 0 delete $self->{current_interval};
2100 0 delete $self->{timer};
2101 }
2102  
2103 package VM::EC2::CondVar;
2104 7 ▶use base 'AnyEvent::CondVar';
Subroutine BEGIN: called CC=1 SCAR=0.0
2105  
2106 sub error {
2107 0 ▶ my $self = shift;
Subroutine error: not called CC=2 SCAR=17.9
2108 0 my $d = $self->{error};
2109 0 ▶ $self->{error} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
2110 0 return $d;
2111 }
2112  
2113 sub recv {
2114 0 ▶ my $self = shift;
Subroutine recv: not called CC=4 SCAR=30.0
2115 0 my @obj = $self->SUPER::recv;
2116 0 ▶ if (!wantarray) { # scalar context
Branch: 1 branch
BranchTrueFalseTotal
if (not wantarray) { } 0 0 0
2117 0 ▶ return $obj[0] if @obj == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @obj == 1 0 0 0
2118 0 ▶ return if @obj == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @obj == 0 0 0 0
2119 0 return @obj;
2120 } else {
2121 0 return @obj;
2122 }
2123 }
2124  
2125 =head1 OTHER INFORMATION
2126  
2127 This section contains technical information that may be of interest to developers.
2128  
2129 =head2 Signing and authentication protocol
2130  
2131 This module uses Amazon AWS signing protocol version 2, as described at
2132 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using-query-api.html.
2133 It uses the HmacSHA256 signature method, which is the most secure
2134 method currently available. For additional security, use "https" for
2135 the communications endpoint:
2136  
2137 $ec2 = VM::EC2->new(-endpoint=>'https://ec2.amazonaws.com');
2138  
2139 =head2 Subclassing VM::EC2 objects
2140  
2141 To subclass VM::EC2 objects (or implement your own from scratch) you
2142 will need to override the object dispatch mechanism. Fortunately this
2143 is very easy. After "use VM::EC2" call
2144 VM::EC2::Dispatch->register() one or more times:
2145  
2146 VM::EC2::Dispatch->register($call_name => $dispatch).
2147  
2148 The first argument, $call_name, is name of the Amazon API call, such as "DescribeImages".
2149  
2150 The second argument, $dispatch, instructs VM::EC2::Dispatch how to
2151 create objects from the parsed XML. There are three possible syntaxes:
2152  
2153 1) A CODE references, such as an anonymous subroutine.
2154  
2155 In this case the code reference will be invoked to handle the
2156 parsed XML returned from the request. The code will receive
2157 two arguments consisting of the parsed
2158 content of the response, and the VM::EC2 object used to generate the
2159 request.
2160  
2161 2) A VM::EC2::Dispatch method name, optionally followed by its arguments
2162 delimited by commas. Example:
2163  
2164 "fetch_items,securityGroupInfo,VM::EC2::SecurityGroup"
2165  
2166 This tells Dispatch to invoke its fetch_items() method with
2167 the following arguments:
2168  
2169 $dispatch->fetch_items($parsed_xml,$ec2,'securityGroupInfo','VM::EC2::SecurityGroup')
2170  
2171 The fetch_items() method is used for responses in which a
2172 list of objects is embedded within a series of <item> tags.
2173 See L<VM::EC2::Dispatch> for more information.
2174  
2175 Other commonly-used methods are "fetch_one", and "boolean".
2176  
2177 3) A class name, such as 'MyVolume'
2178  
2179 In this case, class MyVolume is loaded and then its new() method
2180 is called with the four arguments ($parsed_xml,$ec2,$xmlns,$requestid),
2181 where $parsed_xml is the parsed XML response, $ec2 is the VM::EC2
2182 object that generated the request, $xmlns is the XML namespace
2183 of the XML response, and $requestid is the AWS-generated ID for the
2184 request. Only the first two arguments are really useful.
2185  
2186 I suggest you inherit from VM::EC2::Generic and use the inherited new()
2187 method to store the parsed XML object and other arguments.
2188  
2189 Dispatch tries each of (1), (2) and (3), in order. This means that
2190 class names cannot collide with method names.
2191  
2192 The parsed content is the result of passing the raw XML through a
2193 XML::Simple object created with:
2194  
2195 XML::Simple->new(ForceArray => ['item'],
2196 KeyAttr => ['key'],
2197 SuppressEmpty => undef);
2198  
2199 In general, this will give you a hash of hashes. Any tag named 'item'
2200 will be forced to point to an array reference, and any tag named "key"
2201 will be flattened as described in the XML::Simple documentation.
2202  
2203 A simple way to examine the raw parsed XML is to invoke any
2204 VM::EC2::Generic's as_string() method:
2205  
2206 my ($i) = $ec2->describe_instances;
2207 print $i->as_string;
2208  
2209 This will give you a Data::Dumper representation of the XML after it
2210 has been parsed.
2211  
2212 The suggested way to override the dispatch table is from within a
2213 subclass of VM::EC2:
2214
2215 package 'VM::EC2New';
2216 use base 'VM::EC2';
2217 sub new {
2218 my $self=shift;
2219 VM::EC2::Dispatch->register('call_name_1'=>\&subroutine1).
2220 VM::EC2::Dispatch->register('call_name_2'=>\&subroutine2).
2221 $self->SUPER::new(@_);
2222 }
2223  
2224 See L<VM::EC2::Dispatch> for a working example of subclassing VM::EC2
2225 and one of its object classes.
2226  
2227 =head1 DEVELOPING
2228  
2229 The git source for this library can be found at https://github.com/lstein/LibVM-EC2-Perl,
2230 To contribute to development, please obtain a github account and then either:
2231
2232 1) Fork a copy of the repository, make your changes against this repository,
2233 and send a pull request to me to incorporate your changes.
2234  
2235 2) Contact me by email and ask for push privileges on the repository.
2236  
2237 See http://help.github.com/ for help getting started.
2238  
2239 =head1 SEE ALSO
2240  
2241 L<Net::Amazon::EC2>
2242 L<VM::EC2::Dispatch>
2243 L<VM::EC2::Generic>
2244 L<VM::EC2::BlockDevice>
2245 L<VM::EC2::BlockDevice::Attachment>
2246 L<VM::EC2::BlockDevice::EBS>
2247 L<VM::EC2::BlockDevice::Mapping>
2248 L<VM::EC2::BlockDevice::Mapping::EBS>
2249 L<VM::EC2::Error>
2250 L<VM::EC2::Generic>
2251 L<VM::EC2::Group>
2252 L<VM::EC2::Image>
2253 L<VM::EC2::Instance>
2254 L<VM::EC2::Instance::ConsoleOutput>
2255 L<VM::EC2::Instance::Metadata>
2256 L<VM::EC2::Instance::MonitoringState>
2257 L<VM::EC2::Instance::PasswordData>
2258 L<VM::EC2::Instance::Set>
2259 L<VM::EC2::Instance::State>
2260 L<VM::EC2::Instance::State::Change>
2261 L<VM::EC2::Instance::State::Reason>
2262 L<VM::EC2::KeyPair>
2263 L<VM::EC2::Region>
2264 L<VM::EC2::ReservationSet>
2265 L<VM::EC2::ReservedInstance>
2266 L<VM::EC2::ReservedInstance::Offering>
2267 L<VM::EC2::SecurityGroup>
2268 L<VM::EC2::Snapshot>
2269 L<VM::EC2::Staging::Manager>
2270 L<VM::EC2::Tag>
2271 L<VM::EC2::Volume>
2272  
2273 =head1 AUTHOR
2274  
2275 Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.
2276  
2277 Copyright (c) 2011 Ontario Institute for Cancer Research
2278  
2279 This package and its accompanying libraries is free software; you can
2280 redistribute it and/or modify it under the terms of the GPL (either
2281 version 1, or at your option, any later version) or the Artistic
2282 License 2.0. Refer to LICENSE for the full license text. In addition,
2283 please see DISCLAIMER.txt for disclaimers of warranty.
2284  
2285 =cut
2286  
2287  
2288 7 1;
« lib/VM/EC2/REST/route_table.pm ↑ Summary lib/VM/EC2/REST/spot_instance.pm »