Quantcast
Channel: VMware Communities : Discussion List - vSphere SDK for Perl
Viewing all 1577 articles
Browse latest View live

How to get the datastore name using Host name or vm name ??

$
0
0



Hi,


      any perl sdk or cli script to fetch the datasore name using Host  or vm name..


Memory Utilization

$
0
0

Hi

 

One of the ESX host has 256GB RAM, 7TB storage, 2 processor with 4 cores each.  On this host we have 39 VM running, but the memory utilization on the host is 242GB.

I still have disk space of 1.8TB.   All the VM on this host are windows 2008 R2 ,  the server are with  4GB, 8GB and two 16GB RAM.

 

How can I reclaim the host memory so that I can add more VM's to the host?

 

Please suggest.

 

Thanks

Venky

What would be the best way to identify ESXi and vCenter using vSphere API?

$
0
0

Let's assume I am getting a bunch of hosts IPs on my network without knowing who are they and I need to identify vCenter and ESXi hosts among others. AboutInfo data object returns properties that can indicate whether the host is vCenter or ESXi (apiType, osType and productLineId), is this the best way to do this?

 

Thanks.

How to track virtual machine migration between ESXi hosts (vMotion)?

$
0
0

I am looking to get a live update when virtual machine migrates between ESXi hosts. What would be the best practice to get this kind of update in my Perl or Java application?

 

Thanks.

poor performance script

$
0
0

hi,

I want to get the same info as using this powercli snippet:

 

get-view -ViewType HostSystem -Property Name,Config.Product |select Name,{$_.Config.Product.FullName}


And this is the code I came up with:


#!/usr/bin/env perl

use strict;

use warnings;

use VMware::VIRuntime;

use VMware::VILib;

 

$SIG{__DIE__} = sub{Util::disconnect();};

 

Opts::parse();

Opts::validate();

Util::connect();

 

my $esxhost_view = Vim::find_entity_views(view_type => 'HostSystem');

 

for my $host ( sort { $a->name cmp $b->name } @$esxhost_view ) {

    print $host->name . "\t" . $host->config->product->fullName . "\n" ;

}

 

Both get me the info I require, so that's cool. The performance difference between them is huge, though, so I was wondering if I was doing something wrong on the Perl side ;-). On a linux vm it takes 45 seconds to get the info, on a windows vm with similar resources I get the info with powercli in 10 seconds.

 

Thanks for any pointers.

Problems with applying ntp service configuration

$
0
0

Hi folks,

 

I'm stuck at configuring the ntp service to get started by default on an esxi server via perl.

 

This is what I'm trying to do:

 

my $hostServiceConfig = new HostServiceConfig(serviceId => 'ntpd', startupPolicy => 'on');

my $hsca=[];

push (@$hsca,$hostServiceConfig);

my $hostConfigSpec = new HostConfigSpec(service => $hsca );

my $taskRef=$hostProfileManager->ApplyHostConfig_Task(host => $host, configSpec => $hostConfigSpec);

 

When I ask for the status the command fails with:

 

SOAP Fault:

-----------

Fault string: The operation is not allowed in the current state.

Fault detail: InvalidState

 

I assume I'm just missing some little detail. Maybe someone sees my mistake right away :-)

Installing vSphere CLI on Debian

$
0
0

I'm attempting to install VMware-vSphere-SDK-for-Perl-4.0.0-161974.x86_64 on Debian 7 64-bit.  Install goes without error.  But when I try to use it (vmware-cmd), I get the error "/usr/bin/perl: symbol lookup error: /usr/lib/perl/5.14/auto/XML/LibXML/Common/Common.so: undefined symbol: Perl_Gthr_key_ptr"

 

This leads me to believe that it doesn't like perl 5.14.  Is there any way to fix it?

Having problems with create_vm() and storage pods

$
0
0



Hello everybody,


I have been having problems deploying vms using storage pods or datastore clusters. Basically what I am running into is while creating the VirtualMachineConfigSpec I need to specify a datastore for the disk backing. But I cannot do this without first getting a datastore reccomendation. Classic chicken before the egg scenario, does anybody know what I am missing here?


accessing host advanced settings from perl api

$
0
0



is it possible? i found a blog post about doing this for vm's, but I nee to get the NFS.maxqueuedepth value of the esx hosts in several clusters.


I could not find this in the api documentation. Maybe someone knows how to do this. Using esxcfg-advanced:

      

  1. esxcfg-advcfg -g /NFS/MaxQueueDepth



Thanks ik advance.

Perl SDK installation vs using lib\VMware\share\VMware\*.pm files

$
0
0

Hi,

 

It seems that adding lib\VMware\share\VMware\*.pm modules to my Perl application is enough to make it work with vSphere API, why is it necessary to install the whole SDK?

 

Thanks,

Y.M.

Expected behavior when enumerating snapshots

$
0
0

I am trying to write a script to build a report on every VM in my cluster. In the past, I have built this by hitting the vCenter database directly, but I am trying to redo it using the API. The ultimate goal is to be able to get, for every VM, a clear picture of basic CPU/RAM/Disk configuration as well as guest OS, consolidated storage usage and a snapshot tree (with age and storage). I can get all of this minus the snapshot info right now, but as soon as I try to include anything with snapshots I run into trouble.

 

I'm using vCenter Server 4.1 and SDK 4.1. I've tried the attached script on both Linux (Ubuntu Lucid, perl 5.10.1) and Windows (using the perl distributed w/ the SDK) with identical results.

 

If I get views for all VMs, like this:

 

my $entity_views = Vim::find_entity_views(

view_type => 'VirtualMachine',

properties => [

'name',

'config.hardware',
'config.guestFullName',
'summary.storage',
]

);

 

and then pull out configuration and storage information, my script completes in about 20 seconds. However, if I try to add 'rootSnapshot' to the property filter I get an InvalidPropertyFault, even though I see the property is available when browsing the MOB on the vcenter server. I am able to add 'snapshot.rootSnapshotList' to the property filter, and just doing that doesn't cause the script to take much more time to complete. However, as soon as I try to do something like this:

 

     $view->get_property("snapshot.rootSnapshotList");

 

the script never completes. Progress stops as soon as I call get_property() for the snapshot list. The perl.exe process takes 100% of its CPU as long as I let the script continue to run.

 

What am I doing wrong? Is this known behavior? Is there perhaps a better way to get the information I want?

There is a bug in VICommon.pm in get_property subroutine

$
0
0

Hello

 

VICommon.pm get_properties (line 1702 in build 1384587) the lines in bold prefixed ++ are what I add locally to avoid this problem

 

sub get_property {

   my ($self, $path) = @_;

   my @subpaths = ();

   my $val;

   while ($path) {

      if (exists $self->{$path}) {

         $val = $self->{$path};

         last;

      } elsif ($path =~ /^(.+)\.([^.]+)$/) {

         $path = $1;

         unshift @subpaths, $2;

++   } else {

++       last;

      }

   }

   if (defined($val)) {

      foreach (@subpaths) {

         $val = $val->{$_};

      }

   }

   return $val;

}

 

This bug causes a infinite loop when the value of $path is neither in the $self object/hash or matches the regex.

 

I get this quite a lot with values that show up as Undef in the mob object browser.  for example if a datastore summary object does not have uncommitted info available or a NIC has no IP address and I try to look at it via VMs guest data

 

My fix is less than elegant as I have to catch the return being undefined so perhaps someone can propose something better.

 

 

Neil

Perl SDK for ESXi/vCenter 5.0, 5,1 and 5.5

$
0
0

Hello,

 

My application needs to be ESXi/vCenter version agnostic and work the same with versions 5.0, 5,1 and 5.5. What SDK version I should use in this case?

 

Thanks,

Ymnick

Perl SDK: How to launch a RHEL kickstart install on an existing VM - inject keystrokes ?

$
0
0

Hello,

 

I would like to automatically install RHEL 6.4 on already existing virtual machines, using a kickstart script.

The thing is that in order to launch that kickstart install, I manually have to hit the ESC key before the boot and type "linux ks=cdrom:/kickstart.cfg".

 

How could I automate that process ? Is it possible to send keystrokes to the VM using the vSphere Perl SDK ?

 

Note: I do not have enough permissions on the vSphere environment to use templates, I only have a pool of VM provided by the administrator.

 

Thanks in advance for your help

How to list the DatastoreCluster of Datastore or Datacenter?

$
0
0

Hi All,

 

          I want to list the DatastoreCluster of Datastore or Datacenter.  Using Host or Datastore or Cluster. Can any one help to list the DatastoreCluster


Error changing IP address on Linux VM

$
0
0

I have pieced together a script from various postings in this forum that seems good to my eyes but it is returning a customization fault.

 

I set logging to verbose and here are the relative log entries:

 

[2010-12-17 15:16:03.016 01620 info 'App' opID=2663c49d] [VmCustomizer] hostVersion = 4.1.0, tools version = 8290
[2010-12-17 15:16:03.016 05492 trivia 'App' opID=2663c49d] GetVersion(vim.HostSystem:host-1143 [ec-esx01.ise.vdc])  = 4.1.0
[2010-12-17 15:16:03.016 01620 info 'App' opID=2663c49d] [VmCustomizer] hostVersion = 4.1.0, tools version = 8290
[2010-12-17 15:16:03.017 01620 info 'App' opID=2663c49d] [VmCustomizer] Successfully created file C:\Users\ADMINI~1.ISE\AppData\Local\Temp\imc88BB.tmp
[2010-12-17 15:16:03.017 01620 error 'App' opID=2663c49d] [VmCustomizer] Exception while creating customization package.
[2010-12-17 15:16:03.021 04344 trivia 'PropertyCollector'] ApplyQueuedOps (TriggerProcessGUReqs): Session DD74D25D-5543-405F-8069-EB6A4B38637A
[2010-12-17 15:16:03.021 04344 verbose 'App'] [VpxVmomi] Invoke done: vmodl.query.PropertyCollector.waitForUpdates session: DD74D25D-5543-405F-8069-EB6A4B38637A
[2010-12-17 15:16:03.022 04344 trivia 'App'] ResponseCompleted(false), request version 272, closeStream false
[2010-12-17 15:16:03.024 01620 info 'App' opID=2663c49d] [VmCustomizer] Successfully deleted file/directory C:\Users\ADMINI~1.ISE\AppData\Local\Temp\imc88BB.tmp
[2010-12-17 15:16:03.024 01620 error 'App' opID=2663c49d] vim.fault.CustomizationFault

 

As you can see it's a very generic error and I don't know where to look next to solve the problem.

I'm running vSpere V4.0

 

Any suggestions where to look next would be very welcome.

 

Here is the script I'm using to change the IP.

 

#!/usr/bin/perl -w

 

$|=1;
$ENV{VI_CONFIG}="visdk.rc";      # The SDK import of visdk.rc in Windows is broken
                                 # so I set it to visdk.rc in the current directory explicitly

 

use strict;                      # forces good/safe variable practices
use warnings;                    # display compile time warnings
use VMware::VILib;               # subroutines for basic SDK functionality
use VMware::VIRuntime;           # subroutines for basic SDK functionality
use VMware::VICredStore;         # for accessing login credentials

 

my %opts = (
   vm => {
      type => "=s",
      help => "Name of the Virtual Machine",
      required => 1,
   },
   IP => {
      type => "=s",
      help => "New IP address",
      required => 1,
   },
   mac => {
      type => "=s",
      help => "MAC address of the interface recieving the change",
      required => 1,
   },
   netmask => {
      Default => "255.255.255.0",
      type => "=s",
      help => "Name of the Virtual Machine",
      required => 0,
   },
   gateway => {
      type => "=s",
      help => "IP address of network gateway",
      required => 0,
   },
   dnsDomain => {
      default => "ise.vdc",
      type => "=s",
      help => "DNS domain name",
      required => 0,
   },
   dnsSuffixList => {
      default => "ise.vdc",
      type => "-s",
      help => "DNS suffix search list",
      required => 0,
   },
   dnsServer => {
      type => "=s",
      help => "IP address of the Primary DNS server",
      required => 0,
   },
);

 

Opts::add_options(%opts);                                # add in optional command line arguments
Opts::parse();                                           # parse all the command line arguments
Opts::validate();                                        # validate the command line arguments

 

Util::connect();                                         # connect to the vCenter server

 

my $vmName=Opts::get_option('vm');                       # virtual machine to apply changes too
my $ipAddress=Opts::get_option('IP');                    # IP address for virtual machine
my @gateway=Opts::get_option('gateway');                 # network gateway
my $netmask=Opts::get_option('netmask');                 # netmask for interface
my $dnsDomain=Opts::get_option('dnsDomain');             # DNS domain
my @dnsSuffixList=Opts::get_option('dnsSuffixList');     # DNS suffix search list
my @dnsServers=Opts::get_option('dnsServer');            # DNS server for doamin
my $interfaceMacAddress=Opts::get_option('mac');         # MAC address of interface (used to id the interface)

 

#
# $vm is a reference to the Virtual Machine Managed Object
#
my $vm = Vim::find_entity_view(view_type => 'VirtualMachine',
                                        filter => {name => $vmName});

 

#
# Make sure the VM exists
#
if (! $vm) {die "Virtual Machine: '" . $vmName . "' not found\n";}


my $dns_list = CustomizationGlobalIPSettings->new(
   dnsServerList => \@dnsServers,
   dnsSuffixList => \@dnsSuffixList);

 

my $linuxPrep = CustomizationLinuxPrep->new(
   domain => "$vmName\.$dnsDomain",
   hostName => CustomizationFixedName->new(name => "$vmName"),
   hwClockUTC => 0,
   timeZone => "America/New_York ");

 

my $customizationIPSettings = CustomizationIPSettings->new(
   dnsDomain => $dnsDomain,
   dnsServerList => \@dnsServers,
   ip => CustomizationFixedIp->new(ipAddress => "$ipAddress"),
   gateway => \@gateway,
   subnetMask => $netmask);

 

my $nic0_setting = CustomizationAdapterMapping->new(
   adapter => $customizationIPSettings,
   macAddress => $interfaceMacAddress);

 

my @nicsetting = ($nic0_setting);

 

my $customSpec = CustomizationSpec->new(
   globalIPSettings => $dns_list,
   identity => $linuxPrep,
   nicSettingMap => \@nicsetting);

 

#
# Change the IP address on $vm
#
print "\nChanging IP address to $ipAddress for $interfaceMacAddress on $vmName... ";
my $task=$vm->CustomizeVM_Task(spec => $customSpec);

 

&getStatus($task);

 

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 "Success!\n";
         return $info->result;
         $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);
         print "Failure!\n";
         print "Task ID = " . $taskRef->value . "\n";
         die "$soap_fault\n";
      }
      sleep 5;
      $task_view->ViewBase::update_view_data();
   }
}

ESXi Patching without Update Manager

$
0
0

Hello All,

 

I posted this over in the System Admin section, but thought it would be more relevant here:

 

I recently developed a script that patches ESXi hosts without the need for Update Manager.  This is probably most-applicable to Linux/Unix Admins that work with VMware technology, but potentially anyone could use it.  Checkout out my project on github: https://github.com/Z3r0Sum/ESXi_patch.  Let me know what you think...

Trying to create a script to duplicate resource pool/folder/vm layout

$
0
0

I'm trying to build a perl script(s) to duplicate the layout of a cluster from one vcenter server onto another.   For example, if I have cluster "mycluster1" on vcenter "VC1" with resource pools "RP1," "RP2" and "RP3"   I also have VM folders for "Dev" "Test" and "Sandbox" (the names are irrelevant - this is just for illustration).  I want to move this environment to a different VC server (VC2) but maintain the layout/hierarchy and not have to manually put VMs into their appropriate resource pools and folders.  To move the VMs over, I disconnect all the hosts from the cluster in VC1 and add them to a cluster in VC2, but this loses the resource pool and folder assignments.  In real life, I have dozens of resource pools and a few hundred VMs, so manual manipulation isn't practical. 

 

I contacted VMWare support and their answer was to take a backup of the DB from VC1 and restore it on VC2.  This really only works if you want to move the whole entire structure of all of the datacenters and clusters, which is not what I want to do.

 

I broke the task into an 'export' and 'import' script.  The export creates a text file with the layout, so I can make tweaks before I import, and the 'import' script will take that and create the appropriate pools and folders and shuffle the VMs around.  I've got the SDK installed and have written the 'export' script which works perfectly.  The problem I'm having is writing the 'import' script.

 

I looked at the CLI scripts for hints, such as vmmigrate.pl.  The first thing I ran into was the AppUtil module which doesn't appear to be part of the standard VMware module (ether that or I'm doing something wrong) - I had to forcibly include the cli app path with a BEGIN { push (@INC, "/usr/local/lib/vmware-vcli/apps"); }


So now that I've come this far, it seems like the functions for performing the various resource pool and folder manipulation tasks are way more complex than they need to be; I haven't been able to find simpler versions.  For instance the migrate_virtualmachine function wants the resource pool, target host name, priority and VM state!  Come on!  I just want to stuff a VM into a resource pool!  I shouldn't have to know what host on which it is currently running!  I know I can beat this into submission eventually, but it seems like it's taking a lot more work than it really should.

 

I'm certain that simpler functionality has to exist in perl, because I've also used the vijava package which has simple "moveIntoResourcePool" and "MoveInfoFolder" methods.

 

Ideas?  Am I re-inventing the wheel here?  Is there another perl library of which I'm not aware?


Long pause & timeout when requesting ServiceInstance

$
0
0

I'm using the latest VMWare CLI on linux which includes the vSphere SDK for Perl (I know not to install them both). I am connecting to a stand alone ESXi 5.5 host.

 

Whenever I call Util::connect() with tracing (verbose) enabled I see this:

 

REQUEST: $VAR1 = '<?xml version="1.0" encoding="UTF-8"?>

   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"

                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"

                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <soapenv:Body>

<RetrieveServiceContent xmlns="urn:vim25"><_this type="ServiceInstance">ServiceInstance</_this>

</RetrieveServiceContent></soapenv:Body></soapenv:Envelope>

';

 

And it hangs there for about 45 seconds and eventually gives me a response.

 

RESPONSE: $VAR1 = '<?xml version="1.0" encoding="UTF-8"?>

<soapenv:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"

xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<soapenv:Body>

<RetrieveServiceContentResponse xmlns="urn:vim25"><returnval><rootFolder type="Folder">ha-folder-root</rootFolder><propertyCollector type="PropertyCollector">ha-property-collector</propertyCollector><viewManager type="ViewManager">ViewManager</viewManager><about><name>VMware ESXi</name><fullName>VMware ESXi 5.5.0 build-1623387</fullName><vendor>VMware, Inc.</vendor><version>5.5.0</version><build>1623387</build><localeVersion>INTL</localeVersion><localeBuild>000</localeBuild><osType>vmnix-x86</osType><productLineId>embeddedEsx</productLineId><apiType>HostAgent</apiType><apiVersion>5.5</apiVersion><licenseProductName>VMware ESX Server</licenseProductName><licenseProductVersion>5.0</licenseProductVersion></about><setting type="OptionManager">HostAgentSettings</setting><userDirectory type="UserDirectory">ha-user-directory</userDirectory><sessionManager type="SessionManager">ha-sessionmgr</sessionManager><authorizationManager type="AuthorizationManager">ha-authmgr</authorizationManager><serviceManager type="ServiceManager">ha-servicemanager</serviceManager><perfManager type="PerformanceManager">ha-perfmgr</perfManager><eventManager type="EventManager">ha-eventmgr</eventManager><taskManager type="TaskManager">ha-taskmgr</taskManager><accountManager type="HostLocalAccountManager">ha-localacctmgr</accountManager><diagnosticManager type="DiagnosticManager">ha-diagnosticmgr</diagnosticManager><licenseManager type="LicenseManager">ha-license-manager</licenseManager><searchIndex type="SearchIndex">ha-searchindex</searchIndex><fileManager type="FileManager">ha-nfc-file-manager</fileManager><datastoreNamespaceManager type="DatastoreNamespaceManager">ha-datastore-namespace-manager</datastoreNamespaceManager><virtualDiskManager type="VirtualDiskManager">ha-vdiskmanager</virtualDiskManager><ovfManager type="OvfManager">ha-ovf-manager</ovfManager><dvSwitchManager type="DistributedVirtualSwitchManager">ha-dvsmanager</dvSwitchManager><localizationManager type="LocalizationManager">ha-l10n-manager</localizationManager><storageResourceManager type="StorageResourceManager">ha-storage-resource-manager</storageResourceManager><guestOperationsManager type="GuestOperationsManager">ha-guest-operations-manager</guestOperationsManager></returnval></RetrieveServiceContentResponse>

</soapenv:Body>

</soapenv:Envelope>';

 

 

Tracing with perl shows it's waiting on the ESXi host to respond (Verified with Debug::Trace). If I look on the ESXi side I see this right at the end of the pause just before I get the response.

 

[380C1B70 error 'SoapAdapter.HTTPService'] Failed to read request; stream: <io_obj p:0x38b00630, h:-1, <TCP '0.0.0.0:0'>, <TCP '0.0.0.0:0'>>, error: N7Vmacore16TimeoutExceptionE(Operation timed out)

pam_per_user: create_subrequest_handle(): doing map lookup for user "root"

pam_per_user: create_subrequest_handle(): creating new subrequest (user="root", service="system-auth-generic")

Accepted password for user root from 192.168.0.4

 

The Login continues and everything works. It's hanging before it even makes the request to login, so it's not an authentication system it's waiting on (it uses local auth anyways). I can't for the life of me figure out what this thing is trying to connect to and is waiting for.

Script to change guest NIC state (connect/disconnect)

$
0
0

Hey all,

 


I'm looking for a way to connect/disconnect a guest NIC state.

 

Actually, the following code does change the state (I see it using a Perl debugger) but it doesn't change the runtime state, so probably it requires me to reboot the machine.
I'm looking for a way to change the state on-the-fly:

#!/usr/bin/perl -w
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../";
use VMware::VIRuntime;
use AppUtil::HostUtil;
use AppUtil::VMUtil;
$Util::script_version = "0.1";
my %opts = (   network => {      type => "=s",      help => "Network name",      required =>0,      default => "Network adapter 1",   },   operation => {      type => "=s",      help => "connect or disconnect",      required => 0,      default => "connect",   },   vmname => {      type => "=s",      help => "Name of virtual machine",      required => 1   }
);
Opts::add_options(%opts);
Opts::parse();
Opts::validate();
Util::connect();
my $vm_views = VMUtils::get_vms('VirtualMachine',                                 Opts::get_option ('vmname'));
my $vm_view = shift (@$vm_views);
if ($vm_view) {        my $network = Opts::get_option('network');        my $operation = Opts::get_option ('operation');        my $chngspec = VMUtils::create_network_spec($vm_view, $network, $operation, undef);
}
Util::disconnect();

 


Here's the ouput:

 

it-vma:/usr/lib/vmware-vcli/apps/vm # perl eran.pl --server SERVER --operation disconnect --vmname VM

Enter username: eran

Enter password:

Disconnecting device 'Network adapter 1' from Virtual Machine VM

 

it-vma:/usr/lib/vmware-vcli/apps/vm # perl eran.pl --server SERVER --operation disconnect --vmname VM

Enter username: eran

Enter password:

Disconnecting device 'Network adapter 1' from Virtual Machine VM

it-vma:/usr/lib/vmware-vcli/apps/vm #


Nothing really happens..

Thanks for the advise!

-Eran

Viewing all 1577 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>