Quantcast
Channel: VMware Communities : All Content - vSphere Management SDK
Viewing all 1860 articles
Browse latest View live

Deploy OVF C#

$
0
0

I'm trying to deploy OVF by using C#, When I'm deploying the OVF with my tool I'm getting and "Operating system not found" error. however when I'm deploying the same OVF manually  the machine is up and running perfectly. I'm not sure what I'm doing wrong.

        public VsphereResponse CreateOvf(string datacenterName, string path, string teamFolder, WindowsIdentity userIdentity, string rpName, string teamName, string envName, string machName, string ovfFile)
        {
            VsphereResponse response = new VsphereResponse();

            ManagedObjectReference dataStoreWithMostFreeSpace = GetDataStoreWithMostFreeSpace(datacenterName, userIdentity);
            ManagedObjectReference datacenterRef = vsHandler.Connection.Service.FindByInventoryPath(vsHandler.Connection.ServiceContent.searchIndex, datacenterName);
            ManagedObjectReference moRpRef = vsHandler.GetDecendentMoRef(datacenterRef, NodeTypeEnum.ResourcePool.ToString(), rpName);
            ManagedObjectReference temp = vsHandler.GetDecendentMoRef(datacenterRef, NodeTypeEnum.Folder.ToString(), teamName);
            ManagedObjectReference vmFolder = vsHandler.GetDecendentMoRef(temp, NodeTypeEnum.Folder.ToString(), envName);
            ManagedObjectReference hostmor = vsHandler.GetFirstDecendentMoRef(null, NodeTypeEnum.HostSystem.ToString());

            OvfCreateImportSpecParams importSpecParams = CreateImportSpecParams(machName, hostmor);
            string ovfDescriptor = getOvfDescriptorFromLocal(ovfFile);
            
            OvfCreateImportSpecResult ovfImportResult = vsHandler.Connection.Service.CreateImportSpec(vsHandler.Connection.ServiceContent.ovfManager, ovfDescriptor, moRpRef, dataStoreWithMostFreeSpace, importSpecParams);
            OvfFileItem[] fileItemAttr = ovfImportResult.fileItem;
            if (fileItemAttr != null)
            {
                ManagedObjectReference httpNfcLease = vsHandler.Connection.Service.ImportVApp(moRpRef, ovfImportResult.importSpec, vmFolder, hostmor);
                HttpNfcLeaseInfo httpNfcLeaseInfo = vsHandler.GetDynamicProperty(httpNfcLease, "info") as HttpNfcLeaseInfo;
                while (httpNfcLeaseInfo == null)
                {
                    httpNfcLeaseInfo = vsHandler.GetDynamicProperty(httpNfcLease, "info") as HttpNfcLeaseInfo;
                }
        
                HttpNfcLeaseDeviceUrl[] deviceUrlArr = httpNfcLeaseInfo.deviceUrl;
                if (deviceUrlArr != null)
                {
                    int step = 100/fileItemAttr.Length;
                    int progress = 0;
                    foreach (HttpNfcLeaseDeviceUrl deviceUrl in deviceUrlArr)
                    {
                        string deviceKey = deviceUrl.importKey;
                        foreach (OvfFileItem ovfFileItem in fileItemAttr)
                        {
                            if (deviceKey.Equals(ovfFileItem.deviceId))
                            {
                                SendVMDKFile(ovfFileItem.create, ovfFile, deviceUrl.url, ovfFileItem.size);

                                progress += step;
                                vsHandler.Connection.Service.HttpNfcLeaseProgress(httpNfcLease, progress);
                                break;
                            }
                        }
                    }
                    vsHandler.Connection.Service.HttpNfcLeaseProgress(httpNfcLease, 100);
                    vsHandler.Connection.Service.HttpNfcLeaseComplete(httpNfcLease);
                }

            }

            return response;
        }

    private void SendVMDKFile(Boolean put, string fileName, string url, long diskCapacity)
        {
            Console.WriteLine("Destination host URL: " + url);
            Uri uri = new Uri(url);
            WebRequest request = HttpWebRequest.Create(uri);
            if (put)
            {
                request.Method = "PUT";
            }
            else
            {
                request.Method = "POST";
            }
            request.ContentLength = diskCapacity;
            request.ContentType = "application/x-vnd.vmware-streamVmdk";

            using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //// Read the source file into a byte array.
                Stream dataStream = request.GetRequestStream();

                // Write the byte array to the other FileStream.
                int len = 0;
                byte[] buffer = new byte[1024 * 1024];

                while ((len = fileStream.Read(buffer, 0, buffer.Length-len)) > 0)
                {
                    dataStream.Write(buffer, 0, len);
                }
                dataStream.Flush();
                dataStream.Close();
            }
        }

    private string getOvfDescriptorFromLocal(string ovfDescriptorUrl)
        {
            string strContent = "";
            StreamReader sr = new System.IO.StreamReader(ovfDescriptorUrl);
            strContent = sr.ReadToEnd();
            return strContent;
        }

    private OvfCreateImportSpecParams CreateImportSpecParams(string newVmName, ManagedObjectReference hostmor)
        {
            OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
            importSpecParams.hostSystem = hostmor;
            importSpecParams.locale = "";
            importSpecParams.entityName = newVmName;
            importSpecParams.deploymentOption = "";
            return importSpecParams;
        }

public VsphereResponse CreateOvf(string datacenterName, string path, string teamFolder, WindowsIdentity userIdentity, string rpName, string teamName, string envName, string machName, string ovfFile)
        {
            VsphereResponse response = new VsphereResponse();
 
            ManagedObjectReference dataStoreWithMostFreeSpace = GetDataStoreWithMostFreeSpace(datacenterName, userIdentity);
            ManagedObjectReference datacenterRef = vsHandler.Connection.Service.FindByInventoryPath(vsHandler.Connection.ServiceContent.searchIndex, datacenterName);
            ManagedObjectReference moRpRef = vsHandler.GetDecendentMoRef(datacenterRef, NodeTypeEnum.ResourcePool.ToString(), rpName);
            ManagedObjectReference temp = vsHandler.GetDecendentMoRef(datacenterRef, NodeTypeEnum.Folder.ToString(), teamName);
            ManagedObjectReference vmFolder = vsHandler.GetDecendentMoRef(temp, NodeTypeEnum.Folder.ToString(), envName);
            ManagedObjectReference hostmor = vsHandler.GetFirstDecendentMoRef(null, NodeTypeEnum.HostSystem.ToString());

vMotion of a virtual machine with multiple data stores in vmmigrate.pl

$
0
0

Hello

 

I am using vmmigrate.pl to write a shell script to vMotion a virtual machine.

 

System configuration is vCenter x 1, ESXi x 2, Stgege x 1, physical server x 1. We plan to run vSphere cli based script on physical server.

 

The target virtual machine has more than one datastore and it does not know how to apply it to the vmmigrete.pl option (--targetdatastore).

                       

I want to know how to specify multiple datastores in the vmmigrete.pl option (-targetdatastore). If you can not specify option, I would like to know another method (without vSphere Web Client).

 

regard.

PHP - vSphere WSDL Primer

$
0
0
I'm not sure if this is the "correct" place for this, but after spending HOURS of searching and many, many curse words, I wanted to share a quick little guide to using PHP to interface with the vSphere WSDL. I'm doing this because there is a lot of information spread out all over the Internet, however no one source ever really brought it all together. That is my goal here in this post. Note that I don't claim any of this to be really my own work, but rather my collection of other's work put together in one place. I would link to all the places I found this info, but honestly it came from so many places and was crosslinked to others that I can't even remember where I found most of this stuff. I've also interspersed this with my ramblings and thoughts on the whole process.

 

Please note I am NOT a developer. I'm just an admin trying to write a few scripts that I can use on some webpages to make my life (and some of my fellow admins lives) easiser. So I don't use a lot of functions and constants, I'll just write a new script if I need to do something else. (I think one of my major stumbling blocks was that the documentation was written for people creating large complicated applications, but that's just IMHO.)

 

Step 1 - What you'll need
-- You'll need PHP installed (Duh). I'm using version 5.3.3 but that shouldn't matter all that much. Newer versions may change some things slightly. I'm also using the built in soap client.
--You'll need vCenter (double Duh). I've tested this on 5.0 and 5.1. I'm sure there are differences, but I don't know what they are (and I don't care as long as my stuff works).
--You'll need your vcenter name or IP address. and you'll want to verify that the WSDL is at the correct location. You should be able to browse to your WSDL by going to "https://vcenter/sdk/vimService.wsdl". If you can't find it there, you'll need to figure out where it is.
--You'll also need to have a username and password to log into vCenter with. You should be able to use whatever credentials you log into the (Web or Destop) vSphere client. You should also probably know a little something about vSphere and stuff like "what a datastore is" vs "what a VM is".
--Finally you'll want to access your "MOB" at http://vcenter/mob. It will help navigating VMware's object structure.

 

Step 2 - Create SOAP client object
This probably shouldn't be your first ever PHP and SOAP script you attempt. So I assume you already know how to request a stock quote from webservicex.net or something. That being said, here's the setup:

 

$client = new SoapClient(https://vcenter/sdk/vimService.wsdl,     array (          "trace" => 1,          https://vcenter/sdk/,          )
);

 

Here we create a new soapclient and point it to our Vcenter WSDL. Note that you don't provide login information here (that stumped me for a good little while). Replace the "vcenter" with your Vcenter name or IP. The may be more "options" you want to play with for creating the soap client, you can add those to the array.

 


Step 3 - Let's start to do something that might seem productive
For whatever reason, the first thing you'll have to do is invoke the "ServiceInstance". I have no idea why, but you do. Here is how to do that:

 

$soapmessage["_this"] = new Soapvar ("ServiceInstance", XSD_STRING, "ServiceInstance");
$result = $client->RetrieveServiceContent($soapmessage);
$serviceContent = $result->returnval;

 

Here we create a "SoapVar" object, and give it some data. For some reason, I wasn't able to use a standard Object, not sure why. (Maybe I'm just not that smart? Standard objects always worked for me with other WSDLs, but w/e). We then invoke the "RetrieveServiceContent" method to create a ServiceInstance, which returns a bunch of data to the variable $result. We then load that information into a variable called "serviceContent". (You'll find that some of my variable names make no sense. That's because I was somewhat clueless as to what this was all doing when I wrote it. Feel free to change it to something else. Like I care what you call your own variables...)

 

Step 4 - Log in so it knows who we are
So if we want to do something productive, we're going to have to tell it who we are. The $result variable has some info we need, specifically the "sessionManager" object. SessionManager has a method called "Login", which sounds like what we're trying to do.

 

$soapmessage2["_this"] = $serviceContent->sessionManager;
$soapmessage2["userName"]='username';
$soapmessage2["password"]='password';
$result = $client->Login($soapmessage2);
$usersession = $result->returnval;

 

The "_this" refers to which object we're referencing (This is the session manager object that we got from the service instance above) Username and password are (TRIPLE DUH) your username and password. You'll probably want to change that to your actual username and password, unless your username and password really are "username" and "password". (If they are, please send me your IP address in a PM. Also, please include your ATM pin, mother's maiden name, and SSN.)

 

We then invoke the Login method, and get a result. I loaded that result into another variable, not sure why.

 

Step 5 - Um, can we actually do something now?
Here is where EVERY OTHER LINK I EVER SAW really failed epically. Most posts have you log out here. WHY WOULD I LOG OUT? WE DIDN'T DO ANYTHING YET!

 

Normally at this point you're probably going to need to get a "Managed Object ID", aka MOID. Think of the MOID as a name that never changes. You might have a VM called "Bob", but it's MOID is something like "vm-1234". If you rename your VM from "Bob" to "Weave", the MOID stays the same. They seem to follow a standard of some sort of identifier followed by a number. So your datacenter may be something like "datacenter-4893" and a datastore might be "datastore-6969". Folders are called "antifungalcream-123..." okay I'm kidding, they look something like "group-1231".

 

The reason you're going to need your MOID is because that's what you reference when you call your methods. So if you want to rename something, you'll need to tell it what you're renaming. The method for renaming a folder/host/VM is the same method, you just reference a different object.

 

I got my MOID by using the "FindByDNSName" method, under "SearchIndex". SearchIndex (and everything else???) is under the the "serviceContent".
Here is the code for that:

 

$soapmessage3["_this"] = $serviceContent->searchIndex;
$soapmessage3["dnsName"]='servername.domain.org';
$soapmessage3["vmSearch"]='true';
$result = $client->FindByDnsName($soapmessage3);
$vmentity = $result->returnval;

 

(Why did I have to tell it "Vmsearch = true". Did they think I was calling a search method but didn't want to search???)

 

The return is going to have your MOID

 

Step 6 Okay NOW we REALLY DO SOMETHING!
After you have your MOID, you just have to call a method that is valid for it. So if you're using a VM, your methods are "Rename_Task, PowerOnVM_Task, etc. For testing purposes, I was using "QueryFaultToleranceCompatibility" method. It just returns some data (no idea what this data really means), but it will tell you if your MOID is correct.

 

$soapmessage4["_this"] = $vmentity;
$result = $client->QueryFaultToleranceCompatibility($soapmessage4);

 

That's it! HOORAY WE DID SOMETHING! After four soap calls, we've actually done something that might be considered productive.

 

Step 7 NOW WE CAN LOG OUT

 

$soaplogout["_this"] = $serviceContent->sessionManager;
$result = $client->Logout($soaplogout);

 

Not much to figure out here.

 

Step 8 PROFIT!
The "ace trick" is finding your MOID. You'll need to figure out which search or method is best for you to use. This is where your "MOB" (referenced above in step 1) will be helpful, as you can browse and find methods and which MOIBs they can be called on. You might want to start in the "rootFolder". In the MOB click on "RetrieveServiceContent", then click "invoke method", then click "Group-d1" (apparently this is the default root folder, and it's always called that). From here you should see your data centers, you can click on them and browse folders/datastores/etc. The MOIDs are referenced as well as the properties and methods.

 

Final thoughts : This is by far the most complicated and obtuse WSDL I've ever had to work with. I thought I was getting good at it until I saw this one. Normally I can just read the WSDL and figure it out from there, but there's no way any human could do that with this one IMO. It also wasn't helpful to read people's responses like "You should use Java/Perl". Um, if I wanted to write Java, I'd write Java. Isn't the whole point of a WSDL to be language independant? Why should I go learn a whole new programming language?

 

Also, 4 soap calls to rename a VM? Does that seem reasonable? Usually I can do stuff like this in 1 or 2.

 

Message was edited by: Tyknee - Of course I had to go into the HTML and edit this to get it to look right. Board software was probably written by the same guy who wrote the WSDL...

SOAP 'Login': Cannot complete login due to an incorrect user name or password

$
0
0

Hello all --

 

I'm attempting to perform a 'Login' SOAP method, but am receiving a ServerFaultCode with the string of "Cannot complete login due to an incorrect user name or password." The username and password are correct (I can login via HTML or Flash management or via the REST API with the same credentials).

 

My flow is as follows:

>> Request

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

   <soapenv:Header/>

   <soapenv:Body>

      <urn:RetrieveServiceContent>

         <urn:_this>ServiceInstance</urn:_this>

      </urn:RetrieveServiceContent>

   </soapenv:Body>

</soapenv:Envelope>

 

<< Response

<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 Workstation</name>

               <fullName>VMware Workstation 14.0.0 build-6661328</fullName>

               <vendor>VMware, Inc.</vendor>

               <version>14.0.0</version>

               <build>6661328</build>

               <localeVersion>INTL</localeVersion>

               <localeBuild></localeBuild>

               <osType>linux-x64</osType>

               <productLineId>ws</productLineId>

               <apiType>HostAgent</apiType>

               <apiVersion>r30428</apiVersion>

               <licenseProductName>VMware Workstation</licenseProductName>

               <licenseProductVersion>14.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>

            <eventManager type="EventManager">ha-eventmgr</eventManager>

            <taskManager type="TaskManager">ha-taskmgr</taskManager>

            <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>

            <ovfManager type="OvfManager">ha-ovf-manager</ovfManager>

            <localizationManager type="LocalizationManager">ha-l10n-manager</localizationManager>

            <storageResourceManager type="StorageResourceManager">ha-storage-resource-manager</storageResourceManager>

         </returnval>

      </RetrieveServiceContentResponse>

   </soapenv:Body>

</soapenv:Envelope>

 

>> Request

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

   <soapenv:Header/>

   <soapenv:Body>

      <urn:Login>

         <urn:_this type="SessionManager">ha-sessionmgr</urn:_this>

         <urn:userName>administrator@myhost.com</urn:userName>

         <urn:password>supersecretpassword</urn:password>

      </urn:Login>

   </soapenv:Body>

</soapenv:Envelope>

 

<< Response

<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>

      <soapenv:Fault>

         <faultcode>ServerFaultCode</faultcode>

         <faultstring>Cannot complete login due to an incorrect user name or password.</faultstring>

         <detail>

            <InvalidLoginFault xsi:type="InvalidLogin" xmlns="urn:vim25"/>

         </detail>

      </soapenv:Fault>

   </soapenv:Body>

</soapenv:Envelope>

 

Can someone point out what's wrong here? Everything seems OK according to docs.

 

Thanks for any help!

vSphere SDK / API wmks.min.js Idle Timeout

$
0
0

Hi there,

 

We have developed our own client portal for various reason beyond the scope of this discussion, however we have hit a snag and I would greatly appreciate any input or assistance in this regard:

 

The problem we are experiencing is that when a customer opens a console screen to his VM but is not active on it that it automatically closes the session after about 30 seconds. I have tested this where I opened a session just Desktop with explorer window open on a VM then it disconnects after 30 seconds. If however I open a command prompt and do a simple localhost ping then the console screen stays open for 2 hours with zero other interaction with the console.

 

We are using WMKS.buildNumber = "4504321", WMKS.version = "2.1.0"

 

We are not able to find anything that is forcing this disconnect nor any parameter to send when connecting to the console to keep it open for N minutes. I.e. unable to set an Idle Timeout.

 

Any help or pointers in this regard would be massively appreciated.

 

Regards,

Riaan

 

EDIT: We are not using vCloud director at all, this is a vanilla portal using vCenter v6 APIs only.

 

Thanks much for any assistance.

Noob trying to create simple C# exe from SDK, can't find apputil.dll

$
0
0

I'm a fairly proficient C# and C++ Windows developer, and I'm getting started with this whole SDK.

 

Not being sure which one I need, so I downloaded VMware-vSphereSDK-6.5.0-4571253. The samples, even the main sample, in the "SDK\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\cs" folder, won't build.

 

I ran the VMware PowerCLI powershell installation and was able to get VimService65.dll.

 

However, there is no apputil.dll. There is a vmapputil.dll, but that cannot be loaded as a Reference in Visual Studio 2017 b/c it complains it's not a COM component.

 

Any help to help me get started is much appreciated.

Rest Java - VM creation

$
0
0

1. Is it possible to create VM with template configuration using REST Java?

2. Is it possible to apply OS customization on VM using REST Java ?

vSphere SDK windows authentication

$
0
0

Hi,

 

I'm using .NET c# and so far I'm connection to the vCenter in next way:

 

VimClient client1 = new VimClient();

client1.Connect("https://<hostname>/sdk");

client1.Login("user", "pass");

 

However, since from vShpere client is possible to use windows authentication I suppose that somehow I can manage to do it from my implementation as well, but I couldn't find how to do it.

 

 

Is somebody know how I can do it from the code?

 

Thank you,

dragon


how can i use Python script to login to config network information?

$
0
0

guys,i got a question here: when i finished building a esxi vm through vCenter and installed an OS,can i or how to use Python code to login to config network service? any help?much thanks  

Attach vmware tools image to PXE booted host

$
0
0

I am trying to boot my host using PXE, as I need to change the image frequently.

But the problem is, I don't see any vmware-tools image attached to the host.

Which in turn, gives me error whenever I try to install or upgrade the tools on vm.

 

so is there a way I can do it programmatically, so once host are booted, vmware tools image can be attached to the host.

CloneVM_Task throws error "The request refers to an unexpected or unknown type."

$
0
0

Hi,

 

I trying to Clone a VM, It works perfect when i specify host managed object Reference(MOR) in VirtualMachineRelocateSpec.

 

http://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.RelocateSpec.html

 

When i try with Cluster managed object Reference (MOR) I'm getting this error "The request refers to an unexpected or unknown type."

 

   // Get clone specifications

  VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();

     relocSpec.datastore = targetDataStore;

 

     relocSpec.pool = resourcePoolRootRef;

 

// assgining cluster compute resource pool...

 

relocSpec.host = hostParentCompResRef;

 

If i change it to Host it works fine...

relocSpec.host = hostRef;

 

I don't want to specify particular host, the Cluster is DRS enabled ....

 

Still I get this error can anyone help...

 

Anand.

 

 

 

 

 

Get ESXi local filesystem details like capacity and freespace

can not find HostSystem mob on vpshere mob webpage.

$
0
0

Hello,

 

     I am trying to check some iscsi infomation, I followed this discussion How to get the iscsi initiator name(iqn) of esx using vsphere sdk , I login into the (version 6.0) vcenter's mob webpage and entered ServiceContent entity, but I can not find HostSystem entity.

    anyone knows where is the HostSystem entity is ? please help , thanks in advance.

 

     this is what my ServiceContent shown.

72CE4C86-6730-4585-9105-F4CA0B8C86BC.jpg

Expanding VMDK in 6.5 with c#

$
0
0

I would like to expand a VMDK on a VM in our 6.5 environment via the c# Management SDK, and if I understand the documentation correctly the best way to do this would be to leverage HostExtendDisk_Task from HostVStorageObjectManager. The problem i'm having is how do I get the HostVStorageObjectManager object?  I have a feeling my method is close but I just can't figure it out Here is what i'm trying, but it is failing on a type conversion so it's definitely not correct. Do I need to get it from the VM host somehow?

HostVStorageObjectManager vDiskMan = (HostVStorageObjectManager)vimClient.GetView(vimClient.ServiceContent.VStorageObjectManager, null);

Any help is appreciated

Need help with SOAP request for guest operations

$
0
0

I'm working on a php script to do some automation. This is using the standard SOAP/WSDL and PHP. Mostly things are going well, but I have ran into an issue with guest operations. Can anyone either post the XML request/response or give an example using the MOB. I've been working with listFilesInGuest, but anything will do. I just need to understand how the guest authorization works. I've been able to use pyvmomi to get this, but I can't seem to figure out how to output the request/response in python. My requirement is for PHP so I can't move to python either.

 

Any help is greatly appreciated.


Get cluster name from VM with API via python script

$
0
0

I have a script to get a few details from VMware VSphere 6.0 on my VMs using a python script, but can't seem to find the cluster name anywhere with regards to a VM. My python script looks like this

 

from __future__ import print_function

import atexit

import creds

from pyVim.connect import SmartConnectNoSSL, Disconnect

from pyVmomi import vim

from tools import cli

 

 

 

 

MAX_DEPTH = 10

 

 

vm_info = []

 

def printvminfo(vm, depth=1):

 

 

    if hasattr(vm, 'childEntity'):

        if depth > MAX_DEPTH:

            return

        vmlist = vm.childEntity

        for child in vmlist:

            printvminfo(child, depth+1)

        return

   

    network = vm.network

    summary = vm.summary

    hardware = vm.config.hardware.device

  

    test = {}

    mac_addresses = []

 

 

    test['name'] = summary.config.name

    test['vCPU'] = summary.config.numCpu

    test['memory'] = summary.config.memorySizeMB

    test['IP'] = summary.guest.ipAddress

    for d in hardware:

        if hasattr(d, 'macAddress'):

            mac_addresses.append(d.macAddress)

        test['mac'] = mac_addresses

        if isinstance(d, vim.vm.device.VirtualDisk):

    #disk_gb = d.capacityInKB / 1024 / 1024

            test['disksizeGB'] = int((d.capacityInKB / 1024 / 1024))

 

    vm_info.append(test)

 

 

def get_vm_stuff():

    print(vm_info)

 

 

def main():

    si = None

 

    host = creds.host

    user = creds.user

    password = creds.password

 

 

    try:

        si = SmartConnectNoSSL(host=host,

                               user=user,

                               pwd=password)

        atexit.register(Disconnect, si)

    except vim.fault.InvalidLogin:

        raise SystemExit("Unable to connect to host "

                         "with supplied credentials.")

    content = si.RetrieveContent()

 

    for child in content.rootFolder.childEntity:

        if hasattr(child, 'vmFolder'):

            datacenter = child

            vmfolder = datacenter.vmFolder

            vmlist = vmfolder.childEntity

 

 

            for vm in vmlist:

                printvminfo(vm)

 

 

    get_vm_stuff()

 

 

 

 

if __name__ == "__main__":

    main()

 

Is there anyway I can return the cluster name for a VM from the vmFolder directory?

How to set properties OVF properties?

$
0
0

I'm trying to use vSphere Management SDK using Java to install NSX Manager.

Normally when we manually install NSX Manager, we set the Admin and Privilaged Mode password. I was wondering how to do this using vSphere Management SDK. Can someone help me with this?

Vcenter SOAP API call HELP

$
0
0

Hi Guys

Could you guide or provide sample SOAP xml to create datastore cluster or Create cluster using SOAP API call. I am able to create datacenter using SOAP API call, but i am unable to perform any other additional operation using SOAP API Call..

 

Could you please let me know any documentation available to create SOAP call for the vcenter basic operation . Thanks

vCenter API description about instance for virtual disk performance counter "totalReadLatency"

$
0
0

We are invoking queryPerf method (vCenter API) and trying to get virtual disk performance parameter "totalReadLatency". In queryPerf output, we are getting "scsi0:0" and "scsi0:1" as instance for totalReadLatency performance counter. Can you please add more information about instance for virtual disk counters?

By instance I am referring to - https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.PerformanceManager.MetricId.html#instance

 

We are not able to identify "scsi0:0" is referring to which virtual disk. From DataObject - VirtualHardware, we are getting virtual disk key as 2000 and 2001. Is there any relation between scsi0:0 and 2000?

We are also getting unitNumber on VirtualHardware as 0 and 1. Does it resemble anything out of scsci0:0 and scsi0:1?

 

Please provide more information about instance or let us know if we are looking at wrong parameters

vvol datastore became inactive

$
0
0

 

Hello there

 

After we registered our VASA Provider to the webclient(Version 6.5.0 Build 4240420),we successfully created datastores.

But after we refreshing the datastores,their status came into "inactive" and the capacity was "0.00B"

 

We searched the vvold logs and found something below:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap: https://100.115.195.31:18543/XXXXXX/vasaService session state (TransportError) - recreating soap

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap: Soap client deleted successfully

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap: Master soap client created successfully

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap: _masterSoap=02c70940, iomode=33558544

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap VVold using 15 secs for soap connect timeout

2016-10-18T03:39:45.704Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::InitSoap VVold using 75 secs for soap receive timeout

2016-10-18T03:39:46.270Z warning vvold[6039B70] [Originator@6876 sub=Default] vvol_ssl_auth_init: Will skip CRL check as env variable VVOLD_DO_CRL_CHECK is not set!

2016-10-18T03:39:46.270Z info vvold[6039B70] [Originator@6876 sub=Default] VasaSession::KillAllConnections VP (vvol), purged 0 connections, 0 currently active, new genId (2978) (broadcast wakeup to all threads waiting for free connection)

2016-10-18T03:39:46.287Z error vvold[6039B70] [Originator@6876 sub=Default] VasaSession::DoSetContext: setContext for VP vvol (url: https://100.115.195.31:18543/XXXXXXX/vasaService) failed [connectionState: AuthorizationError]: INVALID_LOGIN (SSL_ERROR_SSL

--> error:14082174:SSL routines:ssl3_check_cert_and_algorithm:dh key too small / SSL_connect error in tcp_connect())

2016-10-18T03:39:46.287Z error vvold[6039B70] [Originator@6876 sub=Default]

--> VasaOp::ThrowFromSessionError [#21779]: ===> FINAL FAILURE getEvents, error (INVALID_SESSION / Bad session state (TransportError)) VP (vvol) Container (vvol) timeElapsed=583 msecs (#outstanding 0)

2016-10-18T03:39:46.287Z error vvold[6039B70] [Originator@6876 sub=Default] VasaSession::EventPollerCB VP vvol: getEvents failed (INVALID_SESSION, Bad session state (TransportError)) [session state: TransportError]

2016-10-18T03:40:15.540Z info vvold[5FF8B70] [Originator@6876 sub=Default] VVolUnbindManager::UnbindIdleVVols called

2016-10-18T03:40:15.540Z info vvold[5FF8B70] [Originator@6876 sub=Default] VVolUnbindManager::UnbindIdleVVols done for 0 VVols

2016-10-18T03:40:16.297Z info vvold[5B97B70] [Originator@6876 sub=Default]

--> VasaOp::EventPollerCB [#21781]: ===> Issuing 'getEvents' to VP vvol (#outstanding 0/4) [session state: TransportError]

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

While we executed the ESXcli command of "esxcli storage vvol vasaprovider list "on the ESXi host,we found that the "Status" of the VP was "syncError".

Otherwise,if we run the command of "esxcli storage vvol storagecontainer list",we could see the status of the VVOL datastore was "inaccessible"

 

We didnot quite sure if there was something wrong with the SSL protocol and where need we modify.

Does anybody have any suggestions to this issue please?

Thank you very much!

 

Viewing all 1860 articles
Browse latest View live


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