Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- # Mostly based on code from William Lam
- # http://engineering.ucsb.edu/~duonglt/vmware
- use strict;
- use warnings;
- use VMware::VIRuntime;
- my %opts = (
- operation => {
- type => "=s",
- help => "Operation to perform [poweroff|suspend]",
- required => 1,
- },
- hostlist => {
- type => "=s",
- help => "Path to file containing list of hosts, one per line, for ordered shutdown.",
- required => 1,
- },
- );
- Opts::add_options(%opts);
- Opts::parse();
- Opts::validate();
- Util::connect();
- my ($host, $vm_name, $vm_view, $host_view, $hostlist, $operation, $task_ref);
- $operation = Opts::get_option("operation");
- $hostlist = Opts::get_option("hostlist");
- open(HOSTLIST, $hostlist) or die "Failed to open file, '$hostlist'";
- my @host_list = <HOSTLIST>;
- foreach $host( @host_list ) {
- chomp($host);
- $host_view = Vim::find_entity_view(
- view_type => "HostSystem",
- filter => { 'name' => $host }
- );
- # Find all VMs for this host.
- my @vms = map { Vim::get_view(mo_ref => $_) } @{$host_view->vm};
- # Perform some action on all these VMs.
- foreach $vm_view (@vms) {
- if($operation eq 'suspend') {
- print "Trying to suspend " . $vm_view->name . "\n";
- eval {
- $task_ref = $vm_view->SuspendVM_Task();
- my $msg = "\tSuccessfully suspended " . $vm_name . "\n";
- &getStatus($task_ref,$msg);
- };
- if($@) { print "Error: " . $@ . "\n"; }
- } elsif($operation eq 'poweroff') {
- print "Trying to poweroff " . $vm_view->name . "\n";
- eval {
- $task_ref = $vm_view->PowerOffVM_Task();
- my $msg = "\tSuccessfully poweredoff " . $vm_name . "\n";
- &getStatus($task_ref,$msg);
- };
- if($@) { print "Error: " . $@ . "\n"; }
- } else {
- die "Invalid operation!\n";
- }
- }
- # Now power the host off.
- eval {
- #$task_ref = $host_view->ShutdownHost_Task();
- #my $msg = "\tSuccessfully shut down " . $host_view->name . "\n";
- #&getStatus($task_ref,$msg);
- };
- if($@) { print "Error: " . $@ . "\n"; }
- }
- Util::disconnect();
- sub getStatus {
- my ($taskRef,$message) = @_;
- my $task_view = Vim::get_view(mo_ref => $taskRef);
- my $taskinfo = $task_view->info->state->val;
- my $continue = 1;
- while ($continue) {
- my $info = $task_view->info;
- if ($info->state->val eq 'success') {
- print $message;
- $continue = 0;
- } elsif ($info->state->val eq 'error') {
- my $soap_fault = SoapFault->new;
- $soap_fault->name($info->error->fault);
- $soap_fault->detail($info->error->fault);
- $soap_fault->fault_string($info->error->localizedMessage);
- die "$soap_fault\n";
- }
- sleep 5;
- $task_view->ViewBase::update_view_data();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement