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

posting custom events and creating alarms on custom events

$
0
0

I m creating custom event on a VM in the following code.

 

            ExtendedEvent myEvent = newExtendedEvent();

 

            myEvent.chainId = 0;

            myEvent.key = 0;

            myEvent.createdTime = DateTime.Now;

            myEvent.fullFormattedMessage = "This is my first event message";

            myEvent.userName = "Administrator";

            myEvent.message = "This is my first event message";

            myEvent.eventTypeId = "com.my.trial.event1";

            myEvent.managedObject = vmor;// VM

 

            pg.service.PostEvent(pg.sic.eventManager, myEvent, null);

 

 

I can see com.my.trial.event1 displayed in the task and event tab in vSphere client. I have following queries-

1.       Is this correct and all that I need to post an event?

2.       Can somebody elaborate on eventTypeID? Significance of it?

3.    How can I create an alarm for this event? I tried it with  providing com.my.trial.event1 as event in the Triggers tab of Alarm settings dialog while creating new alarm. I tried selecting Suspend VM and Power off Vm actions. But the actions are not executed after this event is posted. L


Traffic shaping per VM, rather than vlan

$
0
0

As per VirtualMachineNetworkShaperInfo I tried to set bandwidth restrictions using Traffic shaping policy on VM using vmware API and it didn't work as expected.

 

Followed the below link,

https://www.vmware.com/support/developer/converter-sdk/conv50_apireference/vim.vm.NetworkShaperInfo.html

I tried to specify VirtualMachineNetworkShaperInfo  on VirtualMachineConfigSpec of CloneVM_Task API to create VM. API worked without any errors but the bandwidth limiting is not working as expected. The traffic shaping is working on vlan, but I want to implement on this per VM.

 

Any thoughts?

I want to use code to implement the function of console in VSphere Client to find that file

$
0
0
I want to use code to implement the function of console in VSphere Client to find that file

vix api to vSphere API

$
0
0

Hi,

 

I have a project which uses vix APIs to manage VMs in Workstation and esxi.

 

After the release of vix1.15, these vix APIs are deprecated and no longer be used to manage VMs present in ESXi.

 

The code was written in c++. Can any one please suggest me on below queries...

 

-     Can any one give suggestion on how to move to vSphere APIs from vix APIs?

-     What are all the additional tools required ? (Like openssl)

-     Is vCenter must for managing VMs in ESXI ? (If we use vix1.15)

 

Since I am new to these things, please correct me if my question is not understandable.

 

Thanks and Regards,

Bhargava

"A WebService annotation is not present on class: com.vmware.vim25.VimPortType" error with vim25.jar from vSphere 6.5 HTML SDK

$
0
0

Hi,

We have a vSphere HTML SDK plugin developed using vSphere 6.5 SDK. One of the dependencies for our plugin is vim25.jar (from the libs folder of vSphere 6.5 HTML SDK).

Our plugin gets loaded successfully on the vSphere Client. However, when we click on the plugin and when our main page loading occurs we hit an exception (as below). Since the call is failing inside vim25.jar, I was suggested to ask this in this forum than vSphere SDK forum.

The very first call to getVimPort is failing. Could you please let us know if you have any suggestions to fix this or if you need any further info?

 

com.sun.xml.internal.ws.model.RuntimeModelerException: A WebService annotation is not present on class: com.vmware.vim25.VimPortType
at com.sun.xml.internal.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:254)
at com.sun.xml.internal.ws.db.DatabindingImpl.<init>(DatabindingImpl.java:85)
at com.sun.xml.internal.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:59)
at com.sun.xml.internal.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:43)
at com.sun.xml.internal.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:105)
at com.sun.xml.internal.ws.client.WSServiceDelegate.buildRuntimeModel(WSServiceDelegate.java:875)
at com.sun.xml.internal.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:892)
at com.sun.xml.internal.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:855)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:435)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:404)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:386)
at javax.xml.ws.Service.getPort(Service.java:119)
at com.vmware.vim25.VimService.getVimPort(Unknown Source)
at com.mycompany.vsphere.ObjectStoreManager.getVimPort(ObjectStoreManager.java:82)

 

Regards,
Sunil

c# API getting VM name from MOR

$
0
0

Hello

I am able to get a list of VM's MOR but is there a way to translate that to the actual VM names?

I used the PropertySpec with Traversalspec to get the MOR of the VM's but how do I convert that to the actual names.

I have for example 'VirtualMachine-15'.  I cannot find a way to get the name.

 

I'm using the vmware.vim.dll.

 

Thanks

vSphere Server error: 0x803d0000 : The input data was not in the expected format or did not have the expected value.

$
0
0

Hi,

 

I am trying to connect esxi server using WWSAPI.

 

Generated the client side proxy stubs using WsUtil.exe comes with Microsoft SDK.

 

After setting all the things, when I call proxy stub for CurrentTime/Login (Tried with these two), it returns me with the below error:

0x803d0000 : The input data was not in the expected format or did not have the expected value.

 

Could any one please let me know how to resolve this issue?

 

also any one please suggest me on how to specify the managed object reference type and value attributes for vSphere APIs?

 

Below is the code which I tried:

 

HRESULT             hr  = NOERROR;
WS_ERROR        *   error   = NULL;
WS_HEAP         *   heap= NULL;
WS_SERVICE_PROXY*   proxy   = NULL;

 

// declare and initialize a Windows credential
WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL windowsCredential = {}; // zero out the struct

 

windowsCredential.credential.credentialType = WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL_TYPE; // set the credential type

 

// for illustration only; usernames and passwords should never be included in source files
windowsCredential.username.chars    = L"root";
windowsCredential.username.length   = (ULONG)wcslen(windowsCredential.username.chars);
windowsCredential.password.chars    = L"hvecu_12";
windowsCredential.password.length   = (ULONG)wcslen(windowsCredential.password.chars);

 

// declare and initialize properties to set the authentication scheme to Basic
ULONG scheme = WS_HTTP_HEADER_AUTH_SCHEME_BASIC;

 

WS_SECURITY_BINDING_PROPERTY httpAuthBindingProperties[1] =
{
    { WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_SCHEME, &scheme, sizeof(scheme) }
};

 

/*WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_SCHEME*/
// declare and initialize an HTTP header authentication security binding
WS_HTTP_HEADER_AUTH_SECURITY_BINDING httpAuthBinding = {}; // zero out the struct

 

httpAuthBinding.binding.bindingType = WS_HTTP_HEADER_AUTH_SECURITY_BINDING_TYPE; // set the binding type
httpAuthBinding.binding.properties  = httpAuthBindingProperties;
httpAuthBinding.binding.propertyCount   = WsCountOf(httpAuthBindingProperties);
httpAuthBinding.clientCredential    = &windowsCredential.credential;

 

DWORD dwIgnoreCnCertValue = WS_CERT_FAILURE_CN_MISMATCH | WS_CERT_FAILURE_UNTRUSTED_ROOT | WS_CERT_FAILURE_WRONG_USAGE | WS_CERT_FAILURE_REVOCATION_OFFLINE;

   

WS_SECURITY_BINDING_PROPERTY securityBindingPropertiesArray[1];

 

securityBindingPropertiesArray[0].id    = WS_SECURITY_BINDING_PROPERTY_CERT_FAILURES_TO_IGNORE;
securityBindingPropertiesArray[0].valueSize = sizeof(dwIgnoreCnCertValue);
securityBindingPropertiesArray[0].value = &dwIgnoreCnCertValue;

 

// declare and initialize an SSL transport security binding
WS_SSL_TRANSPORT_SECURITY_BINDING sslBinding = {}; // zero out the struct

 

sslBinding.binding.bindingType  = WS_SSL_TRANSPORT_SECURITY_BINDING_TYPE; // set the binding type
sslBinding.binding.properties   = securityBindingPropertiesArray;
sslBinding.binding.propertyCount= 1;

 

// declare and initialize the array of all security bindings
WS_SECURITY_BINDING* securityBindings[2] = { &sslBinding.binding, &httpAuthBinding.binding };

 

//- We also have to use SOAP 1.1

   /* WS_ENVELOPE_VERSION soapVersion = WS_ENVELOPE_VERSION_SOAP_1_1;

WS_ADDRESSING_VERSION addressingVersion = WS_ADDRESSING_VERSION_TRANSPORT;*/

 

WS_CHANNEL_PROPERTY channelProperties[2];
ULONG           channelPropertyCount        = 0;
WS_ADDRESSING_VERSION addressingVersion         = WS_ADDRESSING_VERSION_TRANSPORT;

 

WS_ENVELOPE_VERSION soapVersion                 = WS_ENVELOPE_VERSION_SOAP_1_1;
channelProperties[channelPropertyCount].id      = WS_CHANNEL_PROPERTY_ENVELOPE_VERSION;
channelProperties[channelPropertyCount].value   = &soapVersion;
channelProperties[channelPropertyCount].valueSize   = sizeof(soapVersion);
channelPropertyCount++;

 

channelProperties[channelPropertyCount].id      = WS_CHANNEL_PROPERTY_ADDRESSING_VERSION;
channelProperties[channelPropertyCount].value   = &addressingVersion;
channelProperties[channelPropertyCount].valueSize   = sizeof(addressingVersion);
channelPropertyCount++;

 

/*WS_CHANNEL_PROPERTY channelProperties[] = {
    { WS_CHANNEL_PROPERTY_ENVELOPE_VERSION, &soapVersion, sizeof(soapVersion) },
    { WS_CHANNEL_PROPERTY_ADDRESSING_VERSION, &addressingVersion, sizeof(addressingVersion) } };*/

 

// declare and initialize the security description
WS_SECURITY_DESCRIPTION securityDescription = {}; // zero out the struct
securityDescription.securityBindings    = securityBindings;
securityDescription.securityBindingCount= WsCountOf(securityBindings);

 

int                 result      = 0;
WS_ENDPOINT_ADDRESS address     = {};
WS_STRING           url         = WS_STRING_VALUE(_T("https://10.165.7.196/sdk/vimService"));
                        address.url = url;

 

// Create an error object for storing rich error information
hr = WsCreateError(
                    NULL,
                    0,
                    &error
                  );
if (FAILED(hr))
{
    goto Exit;
}

 

// Create a heap to store deserialized data
hr = WsCreateHeap(
                    /*maxSize*/ 2048,
                    /*trimSize*/ 512,
                    NULL,
                    0,
                    &heap,
                    error
                 );
if (FAILED(hr))
{
    goto Exit;
}

 

// Create the proxy
hr = WsCreateServiceProxy(
                            WS_CHANNEL_TYPE_REQUEST,
                            WS_HTTP_CHANNEL_BINDING,
                            &securityDescription,
                            NULL,
                            0,
                            channelProperties,
                            channelPropertyCount,
                            &proxy,
                            error
                         );
if (FAILED(hr))
{
    goto Exit;
}

 

hr = WsOpenServiceProxy(
                        proxy,
                        &address,
                        NULL,
                        error
                       );
if (FAILED(hr))
{
    goto Exit;
}

 

 

 

mor.type   = _T("SessionManager");
mor._value = _T("SessionManager");

 

UserSession * userSession;

   

hr = VimBinding_Login(
                        proxy,
                        &mor,
                        L"root",
                        L"hvecu_12",
                        NULL,
                        &userSession,
                        heap,
                        NULL,
                        NULL,
                        NULL,
                        error
                     );

   

WS_DATETIME serverDate;

 

hr = VimBinding_CurrentTime(
                            proxy,
                            &mor,
                            &serverDate,
                            heap,
                            NULL,
                            NULL,
                            NULL,
                            error
                          );

 

Thanks,

Bhargava

In the Java program of vSphere Management SDK, how do I call the vmRc SDK function?

$
0
0
In the Java program of vSphere Management SDK, how do I call the vmRc SDK function?

How to use SDK API to assign static IP address to VM

$
0
0

 

Hi All,

 

 

Can I use SDK API to assign static IP address to VM when cloning a new VM? I used VI Client to do it but it failed. Therefore, I am wondering if SDK API can do this. Can anyone give me a sample code?

 

 

Thank you very much.

 

 

Jeff

 

 

How to assign static IP to the VM while cloning the VM from template using java

$
0
0

Hello,

I am getting InvalidRequest exception while assigning static ip to the VM while cloning using java. Attached is the code and exception. Is there any mistake in my code?

Thanks

How to update IP and Network adapter using Java

$
0
0

 

Greetings,

 

 

would anybody have a working example on how to update the IP address and network adapter of an existing VM?  We are using ESX Server 3.5, and the VI SDK 2.5.0.  Similar to the code provided in the samples for VMpowerOps.java, where I provide the datacenter and name of the VM, along with the desired IP and network adapter name.  Context: I am setting up a fully automated test automation environment, where VMs get deployed on-demand, as requests for test execution are submitted.  As the VMs get deployed from previously built templates, I need to set the IP and network adapter (using the value displayed for the 'Network label' in VM Properties) programmatically.

 

 

Thanks in advance!

 

 

- Stephan

 

 

Using vCloud Suite SDK for tag management on vsphere 5.5 or earlier

$
0
0

Hello,

I researched alot about this topic and found out that  5.5 and earlier versions of vSphere have tagging capability but they do not provide public API for tag management so we won’t be able to access those tags using  SDK versions  5.5 and earlier. But now since vCloud suite SDK provides this capability, can we use this SDK to target it for vcenter 5.5 and earlier? I know PowerCLI is another option, but I do not want to use automation SDK and want to stick to Java management SDK.  

How to wait a task after cloning VM with VMWare.vim.dll ?

$
0
0

Hello everybody,

 

I work on a web interface which manage virtual machines on vsphere Esx 5.5. My interface is based on .net web forms (not MVC)

I followed jeffpaton posts (using VMware.Vim  ) which helped me (Thanks to you, Jeff).

 

But now i freeze on this subject. I do not know how to wait a task after cloning VM. I develop a little web page which launch vsphere command to my vsphere Esc with vmware.vim. I need to know when vpshere is finished his work to launch an another instruction.

 

I try to use PropertyCollector but i do not know how to use it :

i read this post but without success :

Synchronous versus Asynchronous Calls in vSphere API | DoubleCloud => Private Cloud + Public Cloud

What is the best way to wait for a Task in a concurrent environment?

 

Here is my code. i use jeffpaton functions.

 

...

using VMware.Vim;

...

VimClient client;

string serverUrl = "..."

client.Connect("https://" + serverUrl + "/sdk");

client.Login(userLogin, userPassword);

 

...

 

ManagedObjectReference cloneTask_MoRef = null;

cloneTask_MoRef = sourceVm.cloneVM_Task(sourceVm.Parent, "cloneName", mySpec);

if (cloneTask_MoRef == null) {

     //error

}else

     {

          PropertyCollector pc = new PropertyCollector(client, cloneTask_MoRef);

          //1 PropertyFilterSpec [] pfs;

          //ObjectSpec

          ObjectSpec objectSpec = new ObjectSpec();

                          

          //PropertySpec

          //What could i do to know if the task is over or in progress ? :-(

 

I need some help.

 

Thanks for all.                                                          

How to maintain session across VCP client and backend integration server?

$
0
0

Hi,

 

We are building a vSphere client plugin with workflows offloaded to a backend server.

Is there way using which I can use the logged in user session to run these flows in the backend server?

 

I am looking for a possibility to either using the logged on session on client to run server flows, or a possibility to impersonate based on logged on user.

 

Can someone point me to a best practices in case of VCP plugin in this respect.

 

Thanks

Imroz

Distributed Port Group assignment

$
0
0

How can we assign existing Distibuted port group to the VM using java?
I tried with below code but it shows disconnected...

VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
nicSpec.setOperation(VirtualDeviceConfigSpecOperation.edit);
for (int i = 0; i < vds.length; i++) {
if ((vds[i] instanceof VirtualEthernetCard)
&& (vds[i].getDeviceInfo().getLabel().equalsIgnoreCase("Network Adapter 1"))) {
VirtualEthernetCard nic = (VirtualEthernetCard) vds[i];
VirtualDeviceBackingInfo properties = nic.getBacking();
VirtualEthernetCardNetworkBackingInfo nicBaking = (VirtualEthernetCardNetworkBackingInfo) properties;
nicBaking.setDeviceName(network);
nic.setBacking(nicBaking);
nicSpec.setDevice(nic);
}
}
return nicSpec;


How can I create a user in VCenter Server, using vim25?

$
0
0

I can create a user account through the web client.

But I want to create users, using vim25 SDK(JAVA).

I can retrieve user information from UserDirectory(retriveUserGroups method) but I couldn't find the method to create a user in vCenter server.

HostLocalAccountManager  only works for ESXi.

Any suggestions?

I will really appreciate your help! Thanks!

Repository [MavenCentral ou autre] to add the management SDK as a dependency

$
0
0

Hello,

I'm trying to learn gradle for my project and I would add the VMware SDK Management 6.5 (vim25.jar) as a gradle dependency. However, i don't find in any repository (jcenter, mavenRepository) this sdk.

Is it possible to add this sdk or just the vim25.jar in a central repository ?

Thank you to take a few time to answer me.

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

Viewing all 1860 articles
Browse latest View live


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