| 1 | #!/usr/local/bin/perl | ||
| 2 | |||
| 3 | # An example of creating a data snapshots | ||
| 4 | # Steps: | ||
| 5 | # 1. Provision a new server. | ||
| 6 | # 2. Create new data volume, attach and mount it. | ||
| 7 | # 3. Rsync the indicated data over | ||
| 8 | # 4. Unmount the volume, detach it. | ||
| 9 | # 5. Save the snapshot. | ||
| 10 | # 6. Delete the volume | ||
| 11 | # 7. Terminate the server. | ||
| 12 | |||
| 13 | use strict; | ||
| 14 | use VM::EC2; | ||
| 15 | use Getopt::Long; | ||
| 16 | use File::Find; | ||
| 17 | use File::Basename 'basename'; | ||
| 18 | use constant GB => 1_073_741_824; | ||
| 19 | |||
| 20 | $SIG{INT}=$SIG{TERM}= sub {cleanup(); exit 0}; | ||
| 21 | |||
| 22 | my $Program_name = basename($0); | ||
| 23 | $Program_name =~ s/\.pl$//; | ||
| 24 | |||
| 25 | my($Snapshot_name,$Filesystem,$Image,$Type,$Username,$Access_key,$Secret_key); | ||
| 26 | GetOptions('snapshot=s' => \$Snapshot_name, | ||
| 27 | 'filesystem=s' => \$Filesystem, | ||
| 28 | 'image=s' => \$Image, | ||
| 29 | 'username=s' => \$Username, | ||
| 30 | 'type=s' => \$Type, | ||
| 31 | 'access_key=s' => \$Access_key, | ||
| 32 | 'secret_key=s' => \$Secret_key) or die <<USAGE; | ||
| 33 | Usage: $Program_name [options] files/directories to copy... | ||
| 34 | Rsync the indicated files and directories to Amazon EC2 and store | ||
| 35 | in a named EBS snapshot. Snapshot will be incrementally updated | ||
| 36 | if it already exists. The Version tag will be updated. | ||
| 37 | |||
| 38 | This will use the default EC2 endpoint URL unless environment variable | ||
| 39 | EC2_URL is set. | ||
| 40 | |||
| 41 | Options: | ||
| 42 | --snapshot Snapshot name (required) | ||
| 43 | --access_key EC2 access key | ||
| 44 | --secret_key EC2 secret key | ||
| 45 | --image Server AMI ID (defaults to ami-ccf405a5, Ubuntu Maverick 32bit) | ||
| 46 | --type Server type (defaults to m1.small) | ||
| 47 | --username Username for logging into instance ("ubuntu") | ||
| 48 | --filesystem Type of filesystem to create (bfs,cramfs,ext*,minix,ntfs,vfat,msdos). | ||
| 49 | Anything with a /sbin/mkfs.* executable on the server side will work. | ||
| 50 | Defaults to ext4. | ||
| 51 | |||
| 52 | Options can be abbreviated. | ||
| 53 | USAGE | ||
| 54 | ; | ||
| 55 | |||
| 56 | #setup defaults | ||
| 57 | $ENV{EC2_ACCESS_KEY} = $Access_key if defined $Access_key; | ||
| 58 | $ENV{EC2_SECRET_KEY} = $Secret_key if defined $Secret_key; | ||
| 59 | $Filesystem ||= 'ext4'; | ||
| 60 | $Image ||= 'ami-ccf405a5'; | ||
| 61 | $Type ||= 'm1.small'; | ||
| 62 | $Username ||= 'ubuntu'; | ||
| 63 | |||
| 64 | $Snapshot_name or die "Please provide a snapshot name. Run $Program_name --help for help.\n"; | ||
| 65 | my @locations = @ARGV; | ||
| 66 | |||
| 67 | # These are variables that contain EC2 objects that need to be destroyed | ||
| 68 | # when script is done. | ||
| 69 | my ($ec2,$KeyPair,$KeyFile,$Group,$Volume,$Instance); | ||
| 70 | |||
| 71 | eval { | ||
| 72 | |||
| 73 | $ec2 = VM::EC2->new() or die "Can't create new VM::EC2"; | ||
| 74 | |||
| 75 | # find how large a volume we'll need. | ||
| 76 | print STDERR "Calculating needed size of staging volume...\n"; | ||
| 77 | my $bytes_needed = 0; | ||
| 78 | find(sub {$bytes_needed += -s $_},@locations); | ||
| 79 | |||
| 80 | # add 15% overhead for filesystem | ||
| 81 | $bytes_needed *= 1.15; | ||
| 82 | |||
| 83 | # and convert to GB | ||
| 84 | my $gb = int(0.5+$bytes_needed/GB); | ||
| 85 | $gb = 1 if $gb < 1; | ||
| 86 | |||
| 87 | die "Required volume exceeds EC2 1TB limit" | ||
| 88 | if $gb > 1024; | ||
| 89 | |||
| 90 | # Provision the volume | ||
| 91 | print STDERR "Provisioning a $gb GB volume...\n"; | ||
| 92 | my($volume,$needs_mkfs,$needs_resize) = provision_volume($gb,$Snapshot_name); | ||
| 93 | $Volume = $volume; | ||
| 94 | |||
| 95 | # Create a temporary key for ssh'ing | ||
| 96 | print STDERR "Creating a temporary ssh key...\n"; | ||
| 97 | my $keypairname = "${Program_name}_$$"; | ||
| 98 | $KeyFile = File::Spec->catfile(File::Spec->tmpdir,"$keypairname.pem"); | ||
| 99 | $KeyPair = $ec2->create_key_pair($keypairname); | ||
| 100 | my $private_key = $KeyPair->privateKey; | ||
| 101 | open my $k,'>',$KeyFile or die "Couldn't create $KeyFile: $!"; | ||
| 102 | chmod 0600,$KeyFile or die "Couldn't chmod $KeyFile: $!"; | ||
| 103 | print $k $private_key; | ||
| 104 | close $k; | ||
| 105 | |||
| 106 | # Create a temporary security group for ssh'ing | ||
| 107 | print STDERR "Creating a temporary security group with ssh enabled...\n"; | ||
| 108 | $Group = $ec2->create_security_group(-name => "${Program_name}_$$", | ||
| 109 | -description => "Temporary security group created by $Program_name" | ||
| 110 | ) or die $ec2->error_str; | ||
| 111 | $Group->authorize_incoming(-protocol => 'tcp', | ||
| 112 | -port => 'ssh'); | ||
| 113 | $Group->update or die $ec2->error_str; | ||
| 114 | |||
| 115 | # Provision an instance in the same availability zone | ||
| 116 | print STDERR "Provisioning staging instance...\n"; | ||
| 117 | my $zone = $Volume->availabilityZone; | ||
| 118 | $Instance = $ec2->run_instances(-image_id => $Image, | ||
| 119 | -zone => $zone, | ||
| 120 | -key_name => $KeyPair, | ||
| 121 | -instance_type => $Type, | ||
| 122 | -security_group_id => $Group) or die $ec2->error_str; | ||
| 123 | $Instance->add_tag(Name => "Staging instance for snapshot $Snapshot_name created by $Program_name"); | ||
| 124 | |||
| 125 | # wait until the instance is running and the ssh daemon is responding... | ||
| 126 | print STDERR "Waiting for instance to come up. This may take a while...\n"; | ||
| 127 | $ec2->wait_for_instances($Instance); | ||
| 128 | $Instance->current_status eq 'running' or die "Instance $Instance, status = ",$Instance->current_status; | ||
| 129 | wait_for_ssh_daemon(); # we may die on this step | ||
| 130 | |||
| 131 | my $device = eval{unused_device()} or die "Couldn't find suitable device to attach"; | ||
| 132 | |||
| 133 | # attach and initialize volume | ||
| 134 | print STDERR "Attaching staging volume...\n"; | ||
| 135 | my $s = $Instance->attach_volume($Volume=>$device) or die "Couldn't attach $Volume to $Instance via $device"; | ||
| 136 | $ec2->wait_for_attachments($s) or die "Couldn't attach $Volume to $Instance via $device"; | ||
| 137 | $s->current_status eq 'attached' or die "Couldn't attach $Volume to $Instance via $device"; | ||
| 138 | |||
| 139 | if ($needs_resize) { | ||
| 140 | die "Sorry, but can only resize ext volumes " unless $Filesystem =~ /^ext/; | ||
| 141 | print STDERR "Resizing previously-snapshotted volume to $gb GB...\n"; | ||
| 142 | ssh("sudo /sbin/resize2fs $device"); | ||
| 143 | } elsif ($needs_mkfs) { | ||
| 144 | print STDERR "Making $Filesystem filesystem on staging volume...\n"; | ||
| 145 | ssh("sudo /sbin/mkfs.$Filesystem $device"); | ||
| 146 | } | ||
| 147 | |||
| 148 | # do the rsync | ||
| 149 | print STDERR "Mounting staging volume...\n"; | ||
| 150 | ssh("sudo mkdir -p /mnt/transfer; sudo mount $device /mnt/transfer; sudo chown $Username /mnt/transfer"); | ||
| 151 | |||
| 152 | print STDERR "Beginning rsync...\n"; | ||
| 153 | my $Host = $Instance->dnsName; | ||
| 154 | system "rsync -Ravz -e'ssh -o \"StrictHostKeyChecking no\" -i $KeyFile -l $Username' @locations $Host:/mnt/transfer"; | ||
| 155 | |||
| 156 | ssh('sudo umount /mnt/transfer'); | ||
| 157 | $Instance->detach_volume($Volume); | ||
| 158 | |||
| 159 | # snapshot stuff | ||
| 160 | my $version = 1; | ||
| 161 | if (my $snap = $Volume->from_snapshot) { | ||
| 162 | $version = $snap->tags->{Version} || 0; | ||
| 163 | $version++; | ||
| 164 | } | ||
| 165 | |||
| 166 | print STDERR "Creating snapshot $Snapshot_name version $version...\n"; | ||
| 167 | my $snap = $Volume->create_snapshot($Snapshot_name); | ||
| 168 | $snap->add_tags(Version => $version); | ||
| 169 | $snap->add_tags(Name => $Snapshot_name); | ||
| 170 | print "Created snap $snap\n"; | ||
| 171 | }; | ||
| 172 | |||
| 173 | warn $@ if $@; | ||
| 174 | cleanup(); | ||
| 175 | |||
| 176 | exit 0; | ||
| 177 | |||
| 178 | sub ssh { | ||
| 179 | my @cmd = @_; | ||
| 180 | $Instance or die "Remote instance not set up correctly"; | ||
| 181 | my $host = $Instance->dnsName; | ||
| 182 | |||
| 183 | my $pid = open my $kid,"-|"; #this does a fork | ||
| 184 | die "Couldn't fork: $!" unless defined $pid; | ||
| 185 | if ($pid) { | ||
| 186 | my @results; | ||
| 187 | while (<$kid>) { | ||
| 188 | push @results,$_; | ||
| 189 | } | ||
| 190 | close $kid; | ||
| 191 | die "ssh failed with status ",$?>>8 unless $?==0; | ||
| 192 | if (wantarray) { | ||
| 193 | chomp(@results); | ||
| 194 | return @results; | ||
| 195 | } else { | ||
| 196 | return join '',@results; | ||
| 197 | } | ||
| 198 | } | ||
| 199 | |||
| 200 | # in child | ||
| 201 | exec '/usr/bin/ssh','-o','CheckHostIP no','-o','StrictHostKeyChecking no','-i',$KeyFile,'-l',$Username,$host,@cmd; | ||
| 202 | } | ||
| 203 | |||
| 204 | sub unused_device { | ||
| 205 | my %devices = map {$_=>1} ssh('ls /dev/*d[a-z][0-9]*'); | ||
| 206 | my $base = $devices{'/dev/sda1'} ? '/dev/sd' | ||
| 207 | :$devices{'/dev/xvda1'} ? '/dev/xvd' | ||
| 208 | :die "can't figure out whether to use /dev/sd or /dev/xvd"; | ||
| 209 | for my $major ('f'..'p') { | ||
| 210 | for my $minor (1..15) { | ||
| 211 | my $candidate = $base.$major.$minor; | ||
| 212 | return $candidate unless $devices{$candidate}; | ||
| 213 | } | ||
| 214 | } | ||
| 215 | } | ||
| 216 | |||
| 217 | sub provision_volume { | ||
| 218 | my ($size,$snapshot_name) = @_; | ||
| 219 | my @zones = $ec2->describe_availability_zones({state=>'available'}); | ||
| 220 | my $zone = $zones[rand @zones]; | ||
| 221 | |||
| 222 | my @snaps = sort {$b->startTime cmp $a->startTime} $ec2->describe_snapshots(-owner => $ec2->account_id, | ||
| 223 | -filter => {description=>$snapshot_name}); | ||
| 224 | my ($vol,$needs_mkfs,$needs_resize); | ||
| 225 | if (@snaps) { | ||
| 226 | my $snap = $snaps[0]; | ||
| 227 | print STDERR "Reusing existing snapshot $snap...\n"; | ||
| 228 | my $s = $size > $snap->volumeSize ? $size : $snap->volumeSize; | ||
| 229 | $vol = $snap->create_volume(-availability_zone=>$zone, | ||
| 230 | -size => $s); | ||
| 231 | $needs_resize = $snap->volumeSize < $s; | ||
| 232 | } else { | ||
| 233 | $vol = $ec2->create_volume(-availability_zone=>$zone, | ||
| 234 | -size =>$size); | ||
| 235 | $needs_mkfs++; | ||
| 236 | } | ||
| 237 | return unless $vol; | ||
| 238 | $vol->add_tag(Name=>"Staging volume for snapshot $snapshot_name created by $Program_name"); | ||
| 239 | return ($vol,$needs_mkfs,$needs_resize); | ||
| 240 | } | ||
| 241 | |||
| 242 | sub wait_for_ssh_daemon { | ||
| 243 | open SAVERR,">&STDERR"; | ||
| 244 | open STDERR,">/dev/null"; # inhibit error messages temporarily | ||
| 245 | eval { | ||
| 246 | local $SIG{ALRM} = sub {die 'timeout'}; | ||
| 247 | alarm(60); # do not wait more than one minute | ||
| 248 | while (!eval{ssh('echo running')}) {sleep 2; } | ||
| 249 | alarm(0); | ||
| 250 | }; | ||
| 251 | open STDERR,">&SAVERR"; | ||
| 252 | if ($@ =~ /timeout/) { | ||
| 253 | die "Timed out while waiting for ssh daemon to come up"; | ||
| 254 | } | ||
| 255 | } | ||
| 256 | |||
| 257 | sub cleanup { | ||
| 258 | return unless $ec2; | ||
| 259 | |||
| 260 | print STDERR "Deleting temporary keypair...\n"; | ||
| 261 | $ec2->delete_key_pair($KeyPair) if $KeyPair; | ||
| 262 | unlink $KeyFile if -e $KeyFile; | ||
| 263 | |||
| 264 | print STDERR "Deleting staging volume...\n"; | ||
| 265 | $ec2->delete_volume($Volume) if $Volume; | ||
| 266 | |||
| 267 | print STDERR "Terminating staging instance...\n"; | ||
| 268 | $Instance->terminate() if $Instance; | ||
| 269 | |||
| 270 | if ($Group) { | ||
| 271 | print STDERR "Waiting for staging instance to terminate...\n"; | ||
| 272 | $ec2->wait_for_instances($Instance); | ||
| 273 | print STDERR "Deleting temporary security group...\n"; | ||
| 274 | $ec2->delete_security_group($Group); | ||
| 275 | } | ||
| 276 | undef $KeyPair; | ||
| 277 | undef $Instance; | ||
| 278 | undef $Volume; | ||
| 279 | undef $KeyFile; | ||
| 280 | undef $Group; | ||
| 281 | } | ||
| 282 | |||
| 283 | END { | ||
| 284 | cleanup(); | ||
| 285 | } |