blib/lib/VM/EC2/Staging/Volume.pm untested

filter: Statementstmt 0.0% 0 / 191 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 39 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 361 CC 26 SCAR 21.3
CC
26
Cov
0%
_spin_up
20.0
mount
20.0
delete
20.0
CRAP 8.4
1 package VM::EC2::Staging::Volume;
2  
3 =head1 NAME
4  
5 VM::EC2::Staging::Volume - High level functions for provisioning and populating EC2 volumes
6  
7 =head1 SYNOPSIS
8  
9 use VM::EC2::Staging::manager;
10  
11 # get a new staging manager
12 my $ec2 = VM::EC2->new;
13 my $staging = $ec2->staging_manager(); );
14  
15 my $vol1 = $staging->get_volume(-name => 'Backup',
16 -fstype => 'ext4',
17 -size => 11,
18 -zone => 'us-east-1a');
19  
20 # make a couple of directories in new volume
21 $vol1->mkdir('pictures');
22 $vol1->mkdir('videos');
23  
24 # use rsync to copy local files onto a subdirectory of this volume
25 $vol1->put('/usr/local/my_pictures/' =>'pictures');
26 $vol1->put('/usr/local/my_videos/' =>'videos');
27  
28 # use rsync to to copy a set of files on the volume to a local directory
29 mkdir('/tmp/jpegs');
30 $vol1->get('pictures/*.jpg','/tmp/jpegs');
31  
32 # note that these commands are executed on the remote server as root!
33 @listing = $vol1->ls('-r','pictures');
34 $vol1->chown('fred','pictures');
35 $vol1->chgrp('nobody','pictures');
36 $vol1->chmod('0700','pictures');
37 $vol1->rm('-rf','pictures/*');
38 $vol1->rmdir('pictures');
39  
40 # get some information about the volume
41 my $mtpt = $vol->mtpt;
42 my $mtdev = $vol->mtdev;
43 my $mounted = $vol->mounted;
44 my $server = $vol->server;
45  
46 # detach the volume
47 $vol->detach;
48  
49 # delete the volume entirely
50 $vol->delete;
51  
52 =head1 DESCRIPTION
53  
54 This is a high-level interface to EBS volumes which is used in
55 conjunction with VM::EC2::Staging::Manager and
56 VM::EC2::Staging::Server. It is intended to ease the process of
57 allocating and managing EBS volumes, and provides for completely
58 automated filesystem creation, directory management, and data transfer
59 to and from the volume.
60  
61 You can use staging volumes without having to manually create and
62 manage the instances needed to manipulate the volumes. As needed, the
63 staging manager will create the server(s) needed to execute the
64 desired actions on the volumes.
65  
66 Staging volumes are wrappers around VM::EC2::Volume, and have all the
67 methods associated with those objects. In addition to the standard EC2
68 volume characteristics, each staging volume in an EC2 region has a
69 symbolic name, which can be used to retrieve previously-created
70 volumes without remembering their volume ID. This symbolic name is
71 stored in the tag StagingName. Volumes also have a filesystem type
72 (stored in the tag StagingFsType). When a volume is mounted on a
73 staging server, it will also have a mount point on the file system,
74 and a mounting device (e.g. /dev/sdf1).
75  
76 =cut
77  
78 use strict;
79 use VM::EC2;
80 use Carp 'croak';
81 use File::Spec;
82  
83 use overload
84 '""' => sub {my $self = shift;
85 return $self->short_name; # "inherited" from VM::EC2::Volume
86 },
87 fallback => 1;
88  
89 my $Volume = 1; # for anonymously-named volumes
90 our $AUTOLOAD;
91  
92 sub AUTOLOAD {
93 my $self = shift;
94 my ($pack,$func_name) = $AUTOLOAD=~/(.+)::([^:]+)$/;
95 return if $func_name eq 'DESTROY';
96 my $vol = eval {$self->ebs} or croak overload::StrVal($self)," no longer connected to an Amazon EBS object, so can't execute $func_name()";
97 return $vol->$func_name(@_);
98 }
99  
100 sub can {
101 my $self = shift;
102 my $method = shift;
103  
104 my $can = $self->SUPER::can($method);
105 return $can if $can;
106  
107 my $ebs = $self->ebs or return;
108 return $ebs->can($method);
109 }
110  
111 =head1 Staging Volume Creation
112  
113 Staging volumes are created via a staging manager's get_volume() or
114 provision_volume() methods. See L<VM::EC2::Staging::Manager>. One
115 typical invocation is:
116  
117 my $ec2 = VM::EC2->new;
118 my $manager = $ec2->staging_manager(); );
119 my $vol = $manager->get_volume(-name => 'Backup',
120 -fstype => 'ext4',
121 -size => 5,
122 -zone => 'us-east-1a');
123  
124 This will either retrieve an existing volume named "Backup", or, if
125 none exists, create a new one using the provided specification. Behind
126 the scenes, a staging server will be allocated to mount the
127 volume. The manager tries to conserve resources, and so will reuse a
128 suitable running staging server if one is available.
129  
130 The other typical invocation is:
131  
132 my $vol = $manager->provision_volume(-name => 'Backup',
133 -fstype => 'ext4',
134 -size => 5,
135 -zone => 'us-east-1a');
136  
137 This forces creation of a new volume with the indicated
138 characteristics. If a volume of the same name already exists, this
139 method will die with a fatal error (to avoid this, either wrap in an
140 eval, or leave off the -name argument and let the manager pick a
141 unique name for you).
142  
143 =cut
144  
145 =head1 Volume Information
146  
147 The methods in this section return status information about the staging volume.
148  
149 =head2 $name = $vol->name([$newname])
150  
151 Get/set the symbolic name associated with this volume.
152  
153 =head2 $mounted = $vol->mounted
154  
155 Returns true if the volume is currently mounted on a server.
156  
157 =cut
158  
159 sub mounted {
160 my $self = shift;
161 my $m = $self->{mounted};
162 $self->{mounted} = shift if @_;
163 return $m;
164 }
165  
166 =head2 $type = $vol->fstype
167  
168 Return the filesystem type requested at volume creation time.
169  
170 =head2 $server = $vol->server
171  
172 Get the server associated with this volume, if any.
173  
174 =head2 $device = $vol->mtdev
175  
176 Get the device that the volume is attached to, e.g. /dev/sdf1. If the
177 volume is not attached to a server, returns undef.
178  
179 =head2 $device = $vol->mtpt
180  
181 Get the mount point for this volume on the attached server. If the
182 volume is not mounted, returns undef.
183  
184 =head2 $ebs_vol = $vol->ebs
185  
186 Get the underlying EBS volume associated with the staging volume object.
187  
188 =head2 $manager = $vol->manager
189  
190 Return the VM::EC2::Staging::Manager which manages this volume.
191  
192 =cut
193  
194 =head2 $string = $vol->fstab_line();
195  
196 This method returns the line in /etc/fstab that would be necessary to
197 mount this volume on the server to which it is currently attached at
198 boot time. For example:
199  
200 /dev/sdf1 /mnt/staging/Backups ext4 defaults,nobootwait 0 2
201  
202 You can add this to the current server's fstab using the following
203 code fragment:
204  
205 my $server = $vol->server;
206 my $fh = $server->scmd_write('sudo -s "cat >>/etc/fstab"');
207 print $fh $vol->fstab,"\n";
208 close $fh;
209  
210 =cut
211  
212 sub fstab_line {
213 my $self = shift;
214 return join "\t",$self->mtdev,$self->mtpt,$self->fstype,'defaults,nobootwait',0,2;
215 }
216  
217  
218 # $stagingvolume->new({-server => $server, -volume => $volume,
219 # -mtdev => $device, -mtpt => $mtpt,
220 # -name => $name, -fstype => $fstype})
221 #
222 sub new {
223 my $self = shift;
224 my $args;
225 if (ref $_[0]) {
226 $args = shift;
227 } else {
228 my %args = @_;
229 $args = \%args;
230 }
231 return bless $args,ref $self || $self;
232 }
233  
234 # accessors:
235 # sub volume
236 # sub mtpt
237 # sub name
238 # sub manager
239 foreach (qw(-server -volume -name -endpoint -mtpt -mtdev -fstype)) {
240 (my $function = $_) =~ s/^-//;
241 eval <<END;
242 sub $function {
243 my \$self = shift;
244 my \$d = \$self->{$_};
245 \$self->{$_} = shift if \@_;
246 return \$d;
247 }
248 END
249 }
250  
251 sub ebs {shift->volume(@_)}
252 sub manager {
253 my $self = shift;
254 my $ep = $self->endpoint;
255 return VM::EC2::Staging::Manager->find_manager($ep);
256 }
257  
258 =head2 $type = $vol->get_fstype
259  
260 Return the volume's actual filesystem type. This can be different from
261 the requested type if it was later altered by running mkfs on the
262 volume, or the contents of the disk were overwritten by a block-level
263 dd command. As a side effect, this method sets fstype() to the current
264 correct value.
265  
266 =cut
267  
268 # look up our filesystem type
269 sub get_fstype {
270 my $self = shift;
271 return $self->fstype if $self->fstype;
272 return 'raw' if $self->mtpt eq 'none';
273  
274 $self->_spin_up;
275 my $dev = $self->mtdev;
276 my $blkid = $self->server->scmd("sudo blkid -p $dev");
277 my ($type) = $blkid =~ /TYPE="([^"]+)"/;
278 $self->fstype($type);
279 return $type || 'raw';
280 }
281  
282 sub _spin_up {
283 my $self = shift;
284 my $nomount = shift;
285 unless ($self->server) {
286 $self->manager->info("provisioning server to mount $self\n");
287 my $server = $self->manager->get_server_in_zone($self->availabilityZone);
288 $self->server($server);
289 }
290 unless ($self->server->status eq 'running') {
291 $self->manager->info("Starting server to mount $self\n");
292 $self->server->start;
293 }
294 $self->server->mount_volume($self) unless $nomount || $self->mounted();
295 }
296  
297 #sub as_string {
298 # my $self = shift;
299 # return $self->server.':'.$self->mtpt;
300 #}
301  
302 =head1 Lifecycle Methods
303  
304 The methods in this section control the state of the volume.
305  
306 =head2 $snapshot = $vol->create_snapshot('description')
307  
308 Create a VM::EC2::Snapshot of the volume with an optional
309 description. This differs from the VM::EC2::Volume method of the same
310 name in that it is aware of the mount state of the volume and will
311 first try to unmount it so that the snapshot is clean. After the
312 snapshot is started, the volume is remounted.
313  
314 =cut
315  
316 sub create_snapshot {
317 my $self = shift;
318 my $description = shift;
319 if (my $server = $self->server) {
320 my ($snap) = $server->create_snapshot($self => $description);
321 return $snap;
322 } else {
323 $self->ebs->create_snapshot($description);
324 }
325 }
326  
327 =head2 $snapshot = $vol->snapshot('description')
328  
329 Identical to create_snapshot(), but the method name is shorter.
330  
331 =cut
332  
333 sub snapshot {shift->create_snapshot(@_)}
334  
335 =head2 $vol->mount($server [,$mtpt])
336  
337 =head2 $vol->mount()
338  
339 Mount the volume on the indicated VM::EC2::Staging::Server, optionally
340 at a named mount point on the file system. If the volume is already
341 attached to a different server, it will be detached first. If any of
342 these step fails, the method will die with a fatal error.
343  
344 When called with no arguments, the volume is automounted on a staging
345 server, creating or starting the server if necessary.
346  
347 =cut
348  
349 # mount the volume on a server
350 sub mount {
351 my $self = shift;
352 unless (@_) {
353 return $self->_spin_up;
354 }
355 my ($server,$mtpt) = @_;
356 if (my $existing_server = $self->server) {
357 if ($existing_server eq $server) {
358 $self->unmount;
359 } else {
360 $self->detach;
361 }
362 }
363 $server->mount_volume($self,$mtpt);
364 }
365  
366 =head2 $vol->unmount()
367  
368 Unmount the volume from wherever it is, but leave it attached to the
369 staging server. If the volume is not already mounted, nothing happens.
370  
371 Note that it is possible for a volume to be mounted on a I<stopped>
372 server, in which case the server will be started and the volume only
373 unmounted when it is up and running.
374  
375 =cut
376  
377 # unmount volume from wherever it is
378 sub unmount {
379 my $self = shift;
380 my $server = $self->server or return;
381 # guarantees that server is running, but avoids mounting the disk
382 # prior to unmounting it again.
383 $self->_spin_up('nomount');
384 $server->unmount_volume($self);
385 $self->mtpt(undef);
386 }
387  
388 sub umount { shift->unmount(@_) } # because I forget
389  
390 =head2 $vol->detach()
391  
392 Unmount and detach the volume from its current server, if any.
393  
394 Note that it is possible for a volume to be mounted on a I<stopped>
395 server, in which case the server will be started and the volume only
396 unmounted when it is up and running.
397  
398 =cut
399  
400 sub detach {
401 my $self = shift;
402 my $server = $self->server or return;
403 $self->current_status eq 'in-use' or return;
404 $self->unmount; # make sure we are not mounted; this might involve starting a server
405 $server->info("detaching $self\n");
406 my $status = $self->volume->detach;
407 $self->mtpt(undef);
408 $self->mtdev(undef);
409 $self->server(undef);
410 return $status;
411 }
412  
413 =head2 $vol->delete()
414  
415 Delete the volume entirely. If it is mounted and/or attached to a
416 server, it will be unmounted/detached first. If any steps fail, the
417 method will die with a fatal error.
418  
419 =cut
420  
421 # remove volume entirely
422 sub delete {
423 my $self = shift;
424 my $status = $self->current_status;
425 if ($status eq 'in-use') {
426 my $server = $self->server
427 || $self->manager->find_server_by_instance($self->attachment->instanceId);
428 $server->delete_volume($self) if $server;
429 } elsif ($status eq 'available') {
430 $self->ec2->delete_volume($self);
431 } else {
432 croak "Cannot delete volume, status is $status";
433 }
434 $self->mounted(0);
435 $self->mtpt(undef);
436 $self->mtdev(undef);
437 $self->fstype(undef);
438 }
439  
440 =head1 Data Operations
441  
442 The methods in this section operate on the contents of the volume. By
443 and large, they operate with root privileges on the server machine via
444 judicious use of sudo. Elevated permissions on the local machine (on
445 which the script is running) are not needed.
446  
447 =cut
448  
449 =head2 $vol->get($source_on_vol_1,$source_on_vol_2,...,$dest)
450  
451 Invoke rsync() on the server to copy files & directories from the
452 indicated source locations on the staging volume to the
453 destination. Source paths can be relative paths, such as
454 "media/photos/vacation", in which case they are relative to the top
455 level of the mounted volume, or absolute paths, such as
456 "/usr/local/media/photos/vacation", in which case they are treated as
457 absolute paths on the server on which the volume is mounted.
458  
459 The destination can be a path on the local machine, a host:/path on a
460 remote machine, a staging server and path in the form $server:/path,
461 or a staging volume and path in the form "$volume/path". See
462 L<VM::EC2::Staging::Manager/Instance Methods for Managing Staging Volumes>
463 for more formats you can use.
464  
465 As a special case, if you invoke get() with a
466 single argument:
467  
468 $vol->get('/tmp/foo')
469  
470 Then the entire volume will be rsynced into the destination directory
471 /tmp/foo.
472  
473 =cut
474  
475 # $vol->get($source1,$source2,$source3....,$dest)
476 # If $source not in format hostname:/path then
477 # volume will be appended to it.
478 sub get {
479 my $self = shift;
480 croak 'usage: ',ref($self),'->get($source1,$source2,$source3....,$dest_path)'
481 unless @_;
482 unshift @_,'./' if @_ < 2;
483
484 my $dest = pop;
485 my $server = $self->server or croak "no staging server available";
486  
487 $self->mounted or croak "Volume is not currently mounted";
488 my @source = $self->_rel2abs(@_);
489 $server->rsync(@source,$dest);
490 }
491  
492 =head2 $vol->copy($source_on_vol_1,$source_on_vol_2,...,$dest)
493  
494 This is an alias for get(). It is intended to make it easier to read the
495 intent of this command:
496  
497 $source_volume->copy($destination_volume);
498  
499 Which basically makes a copy of $source_volume onto
500 $destination_volume.
501  
502 =cut
503  
504 sub copy { shift->get(@_) }
505  
506 =head2 $vol->put($source1,$source2,$source3,...,$dest_on_volume)
507  
508 Invoke rsync() on the server to copy files & directories from the
509 indicated source locations a destination located on the staging
510 volume. The rules for paths are the same as for the get() method and as described in
511 L<VM::EC2::Staging::Manager/Instance Methods for Managing Staging Volumes> .
512  
513 As a special case, if you invoke put() with a single argument:
514  
515 $vol->put('/tmp/foo')
516  
517 Then the local directory /tmp/foo will be copied onto the top level of
518 the staging volume. To do something similar with multiple source
519 directories, use '/' or '.' as the destination:
520  
521 $vol->put('/tmp/pictures','/tmp/audio' => '/');
522  
523 =cut
524  
525 # $vol->put($source1,$source2,$source3....,$dest)
526 # If $dest not in format hostname:/path then
527 # volume will be appended to it.
528 sub put {
529 my $self = shift;
530 croak 'usage: ',ref($self),'->put($source1,$source2,$source3....,$dest_path)'
531 unless @_;
532 push @_,'.' if @_ < 2;
533  
534 my $dest = pop;
535 my @source = @_;
536  
537 $self->_spin_up;
538 my $server = $self->server or croak "no staging server available";
539 ($dest) = $self->_rel2abs($dest);
540 $server->rsync(@source,$dest);
541 }
542  
543 =head2 $vol->dd($destination_volume)
544  
545 The dd() method performs a block level copy of the volume's disk onto
546 the destination. The destination must be another staging volume.
547  
548 =cut
549  
550 sub dd {
551 my $self = shift;
552 unshift @_,$self if @_ < 2;
553 $self->_spin_up;
554 $self->server->dd(@_);
555 }
556  
557 =head2 $output = $vol->cmd($cmd,@args)
558  
559 This method runs command $cmd on the server that is mounting the
560 volume using ssh. Before the command is run, the working directory is
561 changed to the top level of the volume's mount point. Any arguments,
562 switches, etc you wish to pass to the command can be provided as
563 @args. The output of the command is returned as a string in a scalar
564 context, or an array of lines in a list context.
565  
566 Example:
567  
568 @log = $volume->cmd('tar cvf /tmp/archive.tar .');
569  
570 =head2 $result = $vol->ssh($cmd,@args)
571  
572 This is similar to cmd(), except that the output of the command is
573 sent to STDOUT and the method returns true if the command executed
574 succcessfully on the remote machine. The cmd() and ssh() methods are
575 equivalent to backticks are system() respectively.
576  
577 Example:
578  
579 $volume->ssh('gzip /tmp/archive.tar') or die "couldn't compress archive";
580  
581 =head2 $output = $vol->df(@args)
582  
583 =head2 $output = $vol->ls(@args)
584  
585 =head2 $success = $vol->mkdir(@args)
586  
587 =head2 $success = $vol->chown(@args)
588  
589 =head2 $success = $vol->chgrp(@args)
590  
591 =head2 $success = $vol->chmod(@args)
592  
593 =head2 $success = $vol->cp(@args)
594  
595 =head2 $success = $vol->mv(@args)
596  
597 =head2 $success = $vol->rm(@args)
598  
599 =head2 $success = $vol->rmdir(@args)
600  
601 Each of these methods performs the same function as the like-named
602 command-line function, after first changing the working directory to
603 the top level of the volume. They behave as shown in the pseudocode
604 below:
605  
606 chdir $vol->mtpt;
607 sudo $method @args
608  
609 The df() and ls() methods return the output of their corresponding
610 commands. In a scalar context each method returns a string
611 corresponding to the output of running the command on the server to
612 which the volume is attached. In a list context, the methods return
613 one element per line of output.
614  
615 For example:
616  
617 my $free = $volume->df('.'); # free on current directory
618 my ($percent) = $free =~ /(\d+)%/;
619 warn "almost out of space" if $percent > 90;
620  
621 The other methods return a boolean value indicating successful
622 execution of the command on the remote machine.
623  
624 Command line switches can be passed along with other arguments:
625  
626 $volume->mkdir('-p','media/photos/vacation');
627 $volume->chown('-R','fred','media');
628  
629 With the exception of df, each of these commands runs as the
630 superuser, so be careful how you call them.
631  
632 You may run your own commands using the cmd() and ssh() methods. The
633 former returns the output of the command. The latter returns a success
634 code:
635  
636 @log = $volume->cmd('tar cvf /tmp/archive.tar .');
637 $volume->ssh('gzip /tmp/archive.tar') or die "couldn't compress archive";
638  
639 Before calling any of these methods, the volume must be mounted and
640 its server running. A fatal error will occur otherwise.
641  
642 =cut
643  
644 sub df { shift->_cmd('df',@_) }
645 sub ls { shift->_cmd('sudo ls',@_) }
646 sub mkdir { shift->_ssh('sudo mkdir',@_) }
647 sub chown { shift->_ssh('sudo chown',@_) }
648 sub chgrp { shift->_ssh('sudo chgrp',@_) }
649 sub chmod { shift->_ssh('sudo chmod',@_) }
650 sub rm { shift->_ssh('sudo rm',@_) }
651 sub rmdir { shift->_ssh('sudo rmdir',@_) }
652 sub cp { shift->_ssh('sudo cp',@_) }
653 sub mv { shift->_ssh('sudo mv',@_) }
654  
655 sub _cmd {
656 my $self = shift;
657 my $cmd = shift;
658 my @args = map {quotemeta} @_;
659 $self->mounted or croak "Volume is not currently mounted";
660 my $mtpt = $self->mtpt;
661 $self->server->scmd("cd '$mtpt'; $cmd @args");
662 }
663  
664 sub _ssh {
665 my $self = shift;
666 my $cmd = shift;
667 my @args = map {quotemeta} @_;
668 $self->mounted or croak "Volume is not currently mounted";
669 my $mtpt = $self->mtpt;
670 $self->server->ssh("cd '$mtpt'; $cmd @args");
671 }
672  
673 sub cmd { shift->_cmd(@_) }
674 sub ssh { shift->_ssh(@_) }
675  
676 sub _rel2abs {
677 my $self = shift;
678 my @paths = @_;
679  
680 my $server = $self->server or croak "no server";
681  
682 my @result;
683 foreach (@paths) {
684 if (/^([^:]+):(.+)$/) {
685 push @result,$_;
686 }
687 elsif (m!^/!) { # absolute path
688 push @result,"$server:".$_;
689 }
690 else {
691 my $p = "$server:".File::Spec->rel2abs($_,$self->mtpt);
692 $p .= '/' if m!/$!;
693 push @result,$p;
694 }
695 }
696 return @result;
697 }
698  
699 sub _select_zone {
700 my $self = shift;
701 my $ec2 = shift;
702 if (my @servers = VM::EC2::Staging::Server->_servers($ec2->endpoint)) {
703 return $servers[0]->instance->placement;
704 } else {
705 my @zones = $ec2->describe_availability_zones;
706 return $zones[rand @zones];
707 }
708 }
709  
710 sub _get_vol_zone {
711 my $self = shift;
712 my ($ec2,$volid) = @_;
713 my $volume = $ec2->describe_volumes($volid) or croak "unknown volumeid $volid";
714 return $volume->availabilityZone;
715 }
716  
717 sub DESTROY {
718 my $self = shift;
719 my $manager = $self->manager or return;
720 my $ebs = $self->ebs or return;
721 $manager->unregister_volume($self);
722 }
723  
724 =head1 SEE ALSO
725  
726 L<VM::EC2>
727 L<VM::EC2::Staging::Manager>
728 L<VM::EC2::Staging::Server>
729 L<VM::EC2::Instance>
730 L<VM::EC2::Volume>
731 L<VM::EC2::Snapshot>
732  
733 =head1 AUTHOR
734  
735 Lincoln Stein E<lt>lincoln.stein@gmail.comE<gt>.
736  
737 Copyright (c) 2012 Ontario Institute for Cancer Research
738  
739 This package and its accompanying libraries is free software; you can
740 redistribute it and/or modify it under the terms of the GPL (either
741 version 1, or at your option, any later version) or the Artistic
742 License 2.0. Refer to LICENSE for the full license text. In addition,
743 please see DISCLAIMER.txt for disclaimers of warranty.
744  
745 =cut
746  
747 1;