blib/lib/VM/EC2/Instance/Metadata.pm untested

filter: Statementstmt 0.0% 0 / 91 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 20 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 37 totaltotal 0.0% 0 / 202 CC 7 SCAR 13.9
CC
7
Cov
0%
fetch
20.0
interfaces
6.0
iam_credentials
6.0
CRAP 4.0
1 package VM::EC2::Instance::Metadata;
2  
3 =head1 NAME
4  
5 VM::EC2::Instance::Metadata - Object describing the metadata of a running instance
6  
7 =head1 SYNOPSIS
8  
9 # For use within a running EC2 instance only!
10  
11 use VM::EC2::Instance::Metadata;
12 my $meta = VM::EC2::Instance::Metadata->new;
13  
14 # alternatively...
15 my $meta = VM::EC2->instance_metadata;
16 my $meta = $instance->metadata;
17  
18 # image information
19 $image_id = $meta->imageId;
20 $index = $meta->imageLaunchIndex;
21 $path = $meta->amiManifestPath;
22 $location = $meta->imageLocation; # same as previous
23 @ancestors = $meta->ancestorAmiIds;
24 @ancestors = $meta->imageAncestorIds; # same as previous
25 @codes = $meta->productCodes;
26  
27 # launch and runtime information
28 $inst_id = $meta->instanceId;
29 $kern_id = $meta->kernelId;
30 $rd_id = $meta->ramdiskId;
31 $res_id = $meta->reservationId;
32 $type = $meta->instanceType;
33 $zone = $meta->availabilityZone;
34 $userdata = $meta->userData;
35 @groups = $meta->securityGroups;
36 @keys = $meta->publicKeys;
37 $block_dev = $meta->blockDeviceMapping; # a hashref
38  
39 # Network information
40 $priv_name = $meta->localHostname;
41 $priv_name = $meta->privateDnsName; # same as previous
42 $priv_ip = $meta->localIpv4;
43 $priv_ip = $meta->privateIpAddress;
44 $mac = $meta->mac;
45 $pub_name = $meta->publicHostname;
46 $pub_name = $meta->dnsName; # same as previous
47 $pub_ip = $meta->publicIpv4;
48 $pub_ip = $meta->ipAddress;
49 $interfaces= $meta->interfaces; # a hashref
50  
51 # IAM information
52 $iam_info = $metadata->iam_info; # a hashref
53 $iam_role = $metadata->iam_role; # name of the role
54 $credentials= $metadata->iam_credentials; # VM::EC2::Security::Credentials object
55  
56 # Undocumented fields
57 $action = $meta->instanceAction;
58 $profile = $meta->profile;
59  
60 =head1 DESCRIPTION
61  
62 This is an interface to the metadata that is provided to a running
63 instance via the http://169.254.169.254/latest URL, as described in
64 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instancedata-data-categories.html.
65  
66 Each metadata object caches its values, so there is no overhead in
67 calling a method repeatedly. Methods return scalar values, lists and
68 hashrefs as appropriate.
69  
70 The methods from this class should only be called within the context
71 of a running EC2 instance. Attempts to call outside of this
72 context will result in long delays as the module attempts to
73 connect to an invalid hostname.
74  
75 =head1 METHODS
76  
77 =head2 $meta = VM::EC2::Instance::Metadata->new()
78  
79 =head2 $meta = $ec2->instance_metadata()
80  
81 =head2 $meta = $instance->metadata()
82  
83 You can create a new metadata object either using this class's new()
84 constructor, or by calling an VM::EC2 object's instance_metadata()
85 method, or by calling a VM::EC2::Instance object's metadata () method.
86  
87 =head2 Methods that return scalar values
88  
89 The following methods all return single-valued results:
90  
91 =over 4
92  
93 =item Image information:
94  
95 imageId -- ID of AMI used to launch this instance
96 imageLaunchIndex -- This index's launch index. If four instances
97 were launched by one $image->run_instances()
98 call, they will be numbered from 0 to 3.
99 amiManifestPath -- S3 path to the image
100 imageLocation -- Same as amiManifestPath(), for consistency with
101 VM::EC2::Image
102  
103 =item Launch and runtime information:
104  
105 instanceId -- ID of this instance
106 kernelId -- ID of this instance's kernel.
107 ramdiskId -- This instance's ramdisk ID
108 reservationId -- This instance's reservation ID
109 instanceType -- Machine type, e.g. "m1.small"
110 availabilityZone -- This instance's availability zone.
111 region -- This instance's region.
112 endpoint -- This instance's endpoint.
113 userData -- User data passed at launch time.
114  
115 =item Network information:
116  
117 localHostname -- The instance hostname corresponding to its
118 internal EC2 IP address.
119 privateDnsName -- Same as localHostname(), for consistency with
120 VM::EC2::Instance
121 localIpv4 -- The instance IP address on the internal EC2 network.
122 privateIpAddress -- Same as localIpv4(), for consistency with
123 VM::EC2::Instance.
124 mac -- This instance's MAC (ethernet) address.
125 publicHostname -- This instance's public hostname.
126 dnsName -- Same as publicHostname() for consistency with
127 VM::EC2::Instance.
128 publicIpv4 -- This instance's public IP address.
129 ipAddress -- Same as publicIpv4() for consistency with
130 VM::EC2::Instance.
131  
132 =item IAM information
133  
134 These routines return information about the instance's IAM role, if
135 any. These calls also provide a temporary security credentials for
136 making EC2 calls, as described here:
137 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/UsingIAM.html.
138  
139 Note that these routines require installation of the perl JSON module, and will
140 cause a fatal error if this module cannot be loaded.
141  
142 iam_info -- Returns a hash containing the fields 'LastUpdated',
143 'InstanceProfileArn', and 'InstanceProfileId'. These
144 provide information about the instance's IAM role.
145 iam_role -- Returns the IAM role name for the currently running
146 instance.
147 iam_credentials -- Returns a VM::EC2::Security::Credentials object that can
148 be passed to VM::EC2->new(-security_token=>$credentials).
149  
150 =item Unknown information:
151  
152 profile -- An undocumented field that contains the virtualization
153 type in the form "default-paravirtual".
154 instanceAction -- Undocumented metadata field named "instance-action"
155  
156 =back
157  
158 =head2 Methods that return lists
159  
160 The following methods all return lists.
161  
162 =over 4
163  
164 =item Image information
165  
166 ancestorAmiIds -- List of AMIs from which the current one was derived
167 imageAncestorIds -- Same as ancestorAmiIds() but easier to read.
168 productCodes -- List of product codes applying to the image from which
169 this instance was launched.
170  
171 =item Launch and runtime information
172  
173 securityGroups -- List of security groups to which this instance is assigned.
174 For non-VPC instances, this will be the security group
175 name. For VPC instances, this will be the security group ID.
176 publicKeys -- List of public key pair names attached to this instance.
177  
178 =back
179  
180 =head2 Methods that return a hashref
181  
182 The following methods return a hashref for representing complex data structures:
183  
184 =over 4
185  
186 =item $devices = $meta->blockDeviceMapping
187  
188 This returns a hashref in which the keys are the names of instance
189 block devices, such as "/dev/sda1", and the values are the EC2 virtual
190 machine names. For example:
191  
192 x $meta->blockDeviceMapping
193 0 HASH(0x9b4f2f8)
194 '/dev/sda1' => 'root'
195 '/dev/sda2' => 'ephemeral0'
196 '/dev/sdg' => 'ebs1'
197 '/dev/sdh' => 'ebs9'
198 '/dev/sdi' => 'ebs10'
199 'sda3' => 'swap'
200  
201 For reasons that are not entirely clear, the swap device is reported
202 as "sda3" rather than as "/dev/sda3".
203  
204 =item $interfaces = $meta->interfaces
205  
206 Returns a mapping of all virtual ethernet devices owned by this
207 instance. This is primarily useful for VPC instances, which can have
208 more than one device. The hash keys are the MAC addresses of each
209 ethernet device, and the values are hashes that have the following
210 keys:
211  
212 mac
213 localHostname
214 localIpv4s (an array ref)
215 publicIpv4s (an array ref)
216 securityGroupIds (an array ref)
217 subnetId
218 subnetIpv4CidrBlock
219 vpcId
220 vpcIpv4CidrBlock
221  
222 For example:
223  
224 D
225 x $meta->interfaces
226 0 HASH(0x9b4f518)
227 '12:31:38:01:b8:97' => HASH(0x9eaa090)
228 'localHostname' => 'domU-12-31-38-01-B8-97.compute-1.internal'
229 'localIpv4s' => ARRAY(0x9b4f8a8)
230 0 '10.253.191.101'
231 'mac' => '12:31:38:01:b8:97'
232 'publicIpv4s' => ARRAY(0x9ea9e40)
233 0 '184.73.241.210'
234 'securityGroupIds' => ARRAY(0x9eaa490)
235 empty array
236 'subnetId' => undef
237 'subnetIpv4CidrBlock' => undef
238 'vpcId' => undef
239 'vpcIpv4CidrBlock' => undef
240  
241 =back
242  
243 =head1 SEE ALSO
244  
245 L<VM::EC2>
246 L<VM::EC2::Generic>
247 L<VM::EC2::BlockDevice>
248 L<VM::EC2::State::Reason>
249 L<VM::EC2::State>
250 L<VM::EC2::Instance>
251 L<VM::EC2::Tag>
252  
253 =head1 AUTHOR
254  
255 Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.
256  
257 Copyright (c) 2011 Ontario Institute for Cancer Research
258  
259 This package and its accompanying libraries is free software; you can
260 redistribute it and/or modify it under the terms of the GPL (either
261 version 1, or at your option, any later version) or the Artistic
262 License 2.0. Refer to LICENSE for the full license text. In addition,
263 please see DISCLAIMER.txt for disclaimers of warranty.
264  
265 =cut
266  
267 use strict;
268 use LWP::UserAgent;
269 use URI::Escape 'uri_unescape';
270 use Carp 'croak';
271  
272 use constant TIMEOUT => 5; # seconds
273 my $global_cache = {};
274  
275 sub new {
276 my $pack = shift;
277 return bless { cache => {} },ref $pack || $pack;
278 }
279  
280 sub imageId { shift->fetch('ami-id') }
281 sub imageLaunchIndex { shift->fetch('ami-launch-index') }
282 sub amiManifestPath { shift->fetch('ami-manifest-path')}
283 sub imageLocation { shift->amiManifestPath }
284 sub ancestorAmiIds { split /\s+/,shift->fetch('ancestor-ami-ids') }
285 sub imageAncestorIds { shift->ancestorAmiIds }
286 sub instanceAction { shift->fetch('instance-action') }
287 sub instanceId { shift->fetch('instance-id') }
288 sub instanceType { shift->fetch('instance-type') }
289 sub localHostname { shift->fetch('local-hostname') }
290 sub privateDnsName { shift->localHostname }
291 sub localIpv4 { shift->fetch('local-ipv4') }
292 sub privateIpAddress { shift->localIpv4 }
293 sub kernelId { shift->fetch('kernel-id') }
294 sub mac { shift->fetch('mac') }
295 sub availabilityZone { shift->fetch('placement/availability-zone') }
296 sub region { my $r = shift->availabilityZone;
297 $r =~ s/[a-z]$//;
298 return $r; }
299 sub endpoint { 'http://ec2.'.shift->region.'.amazonaws.com'}
300 sub productCodes { split /\s+/,shift->fetch('product-codes') }
301 sub publicHostname { shift->fetch('public-hostname') }
302 sub dnsName { shift->publicHostname }
303 sub publicIpv4 { shift->fetch('public-ipv4') }
304 sub ipAddress { shift->publicIpv4 }
305 sub ramdiskId { shift->fetch('ramdisk-id') }
306 sub reservationId { shift->fetch('reservation-id') }
307 sub securityGroups { split /\s+/,shift->fetch('security-groups') }
308 sub profile { shift->fetch('profile') }
309 sub userData { shift->fetch('../user-data') }
310  
311 sub blockDeviceMapping {
312 my $self = shift;
313 my @devices = split /\s+/,$self->fetch('block-device-mapping');
314 my %map = map {$self->fetch("block-device-mapping/$_") => $_} @devices;
315 return \%map;
316 }
317 sub interfaces {
318 my $self = shift;
319 my @macs = split /\s+/,$self->fetch('network/interfaces/macs');
320 my %result;
321 for my $m (@macs) {
322 $m =~ s/\/$//; # get rid of hanging slash
323 for my $pair ([localHostname => 'local-hostname'],
324 [localIpv4s => 'local-ipv4s'],
325 [mac => 'mac'],
326 [publicIpv4s => 'public-ipv4s'],
327 [securityGroupIds => 'security-groupids'],
328 [subnetId => 'subnet-id'],
329 [subnetIpv4CidrBlock => 'subnet-ipv4-cidr-block'],
330 [vpcId => 'vpc-id'],
331 [vpcIpv4CidrBlock => 'vpc-ipv4-cidr-block']) {
332 my ($tag,$attribute) = @$pair;
333 my $value = $self->fetch("network/interfaces/macs/$m/$attribute");
334 my @value = split /\s+/,$value;
335 $result{$m}{$tag} = $attribute =~ /s$/ ? \@value : $value;
336 }
337 }
338 return \%result;
339 }
340  
341 sub publicKeys {
342 my $self = shift;
343 my @keys = split /\s+/,$self->fetch('public-keys');
344 return map {/^\d+=(.+)/ && $1} @keys;
345 }
346  
347 sub iam_info {
348 my $self = shift;
349 $self->_load_json;
350 return JSON::from_json($self->fetch('iam/info'));
351 }
352  
353 sub iam_role {
354 my $self = shift;
355 return $self->fetch('iam/security-credentials');
356 }
357  
358 sub iam_credentials {
359 my $self = shift;
360 my $role = $self->iam_role or return;
361 my $data = $self->fetch("iam/security-credentials/$role") or return;
362 eval "require VM::EC2::Security::Credentials"
363 unless VM::EC2::Security::Credentials->can('new_from_json');
364 return VM::EC2::Security::Credentials->new_from_json($data,$self->endpoint);
365 }
366  
367 sub _load_json {
368 return if JSON->can('decode');
369 eval "require JSON; 1" or croak "no JSON module installed: $@";
370 }
371  
372 sub fetch {
373 my $self = shift;
374 my $attribute = shift or croak "Usage: VM::EC2::Instance::Metadata->get('attribute')";
375 my $cache = $self->{cache} || $global_cache; # protect against class invocation
376 return $cache->{$attribute} if exists $cache->{$attribute};
377 my $ua = $self->{ua} ||= LWP::UserAgent->new();
378 $ua->timeout(TIMEOUT);
379 my $response = $ua->get("http://169.254.169.254/latest/meta-data/$attribute");
380 if ($response->is_success) {
381 return $cache->{$attribute} = uri_unescape($response->decoded_content); # don't know why, but URI escapes used here.
382 } else {
383 print STDERR $response->status_line,"\n" unless $response->code == 404;
384 return;
385 }
386 }
387  
388 1;
389