Category Archives: HOME

Getting started with opensource JAVA SDK for VMware vSphere : Step by step guide for beginners

You might have read my last post on YAVI JAVA. In this post I am going to take you through setting up eclipse environment in order to get started with YAVI JAVA. This post is written by keeping not only existing VMware users in mind but also college students.

There are 4 ways listed here to get started with YAVI JAVA, one of the most used,easiest and quickest one is the first one i.e. obtaining YAVI JAVA package from Maven central repository. Here we go.

Step 1:: Download the Eclipse that has built in Maven integration. However, Maven is integrated with other IDEs such as NetBeans, Intelli IDEA etc. I like Eclipse so I am going to show you steps for eclipse, you could follow the same for other IDEs, it should work fine. Below is the Eclipse version I have downloaded which has Maven built in.
MavenEclipse

For getting started with YAVI JAVA, you are not required to be expert in Maven, even it is OK if you do not know anything about Maven. If you are interested, do read what is Maven here.

Step 2: Create a Maven project as shown in below screenshot.

Maven project

Step 3: Select the “Create Simple project” as shown below.

Maven_2

Step 4 : Next is to specify the Group id, Artifact id, version, Name etc. This can be anything of your choice as shown below and click on Finish.

Maven_3

Once clicked on FINISH, below is how it looks like when Maven project is created.

Maven_4

Step 5: Next we need to modify the POM.xml file. With every Maven project, one POM.xml file gets generated. Below is the overview of the existing POM.xml file got created when we created the project. POM.xml file is the one which tracks/resolves all the dependencies required for your project.

Maven_5

Step 6: Click on the dependencies tab in the bottom as shown below screenshot.

Maven_6

Now click on ADD button and enter the YAVI JAVA Maven group id, artifact id and version as shown in below screenshot
groupId : com.toastcoders
artifactId: yavijava
version :6.0.01 (or any YAVI JAVA version of your choice): Recommendation is to use latest available version on Maven central repository
Maven_9

Step 7: As soon as you click on OK in above step, make sure you can see entry in POM.xml file and required Maven dependencies jars as shown below.

Maven_10

That’s all. Now you are all set to play with new APIs introduced in vSphere 6.0. Let me know if you face any issues.

All the samples and tutorials specified in this post will work just fine.

Note: YAVI JAVA supports VMware vSphere 4.0 and above (4.1, 5.0, 5.1, 5.5, 6.0).

Please do stay tuned for all the interesting samples on new features introduced in vSphere 6.0.

How to edit DRS affinity rules using vSphere API: Bit tricky solution

Recently I got a question through mail on how to edit DRS affinity rules (VM VM rules)? It is bit tricky to edit VM VM rules and vSphere API beginners are likely to get bit confused. Hence I thought its better write a program on the same which can be used as sample when anybody would like to edit DRS affinity rules.

Below is the complete code sample for the same. Please do modify this sample as per your need.

[java]

//:: # Author: Vikas Shitole
//:: # Website: www.vThinkBeyondVM.com
//:: # Product/Feature: vCenter Server/DRS
//:: # Description: Script to edit VM VM affinity rules

package com.vmware.yavijava;

import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.ArrayUpdateOperation;
import com.vmware.vim25.ClusterAffinityRuleSpec;
import com.vmware.vim25.ClusterAntiAffinityRuleSpec;
import com.vmware.vim25.ClusterConfigInfoEx;
import com.vmware.vim25.ClusterConfigSpec;
import com.vmware.vim25.ClusterRuleInfo;
import com.vmware.vim25.ClusterRuleSpec;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.ClusterComputeResource;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.util.MorUtil;

public class EditVmVmDrsRule {

public static void main(String[] args) throws InvalidProperty,
RuntimeFault, RemoteException, MalformedURLException {
ServiceInstance si = new ServiceInstance(new URL(args[0]), args[1],
args[2], true); // Pass 3 argument as vCenterIP/username/password
String ClusterName = "Cluster"; // Cluster Name
String VMToBeRemoved="VM1";
String VMToBeAdded="VM3";
Folder rootFolder = si.getRootFolder();
VirtualMachine vm1 = (VirtualMachine) new InventoryNavigator(rootFolder)
.searchManagedEntity("VirtualMachine", VMToBeRemoved);
VirtualMachine vm2 = (VirtualMachine) new InventoryNavigator(rootFolder)
.searchManagedEntity("VirtualMachine", VMToBeAdded);
ManagedObjectReference vmMor1 = vm1.getMOR();
ManagedObjectReference vmMor2 = vm2.getMOR();

ClusterComputeResource cluster = null;
cluster = (ClusterComputeResource) new InventoryNavigator(rootFolder)
.searchManagedEntity("ClusterComputeResource", ClusterName);

// Number of rules in a cluster
ClusterRuleInfo[] ruleinfo = ((ClusterConfigInfoEx) cluster
.getConfigurationEx()).getRule();

if (ruleinfo == null || ruleinfo.length == 0) {
System.out.println("There is no DRS rule in the cluster:: "
+ cluster.getName());
}

for (ClusterRuleInfo rule : ruleinfo) {
if (((rule instanceof ClusterAffinityRuleSpec)) && (rule.getName().equals("VM VM Rule"))){
ManagedObjectReference[] vms=((ClusterAffinityRuleSpec) rule).getVm();
for(ManagedObjectReference vm:vms){
if(vm.getVal().equals(vmMor1.getVal())){
//Removed the VM from rule
vms=(ManagedObjectReference[]) ArrayUtils.removeElement(vms, vm );
break;
}

}
//Added the new VM to the rule
vms=(ManagedObjectReference[]) ArrayUtils.add(vms, vmMor2 );

ClusterAffinityRuleSpec cars=(ClusterAffinityRuleSpec) rule;
cars.setVm(vms);

ClusterRuleSpec crs1 = new ClusterRuleSpec();
crs1.setInfo(cars);
crs1.setOperation(ArrayUpdateOperation.edit);

ClusterConfigSpec ccs = new ClusterConfigSpec();
ccs.setRulesSpec(new ClusterRuleSpec[]{crs1} );

cluster.reconfigureCluster_Task(ccs, true);
System.out.println("Rule reconfigured successfully ");

}
}

}
}

[/java]

Note:
– For the sake of simplicity, I have hard-coded VM names, you can change those based on your environment.
– Also you need resolve the dependency on apache.commons.lang in your java project. Let me know if you have any more doubts.

If you have still not setup your VI JAVA Eclipse environment:Getting started tutorial
Important tutorials to start with: Part I & Part II

One more exciting news: VI JAVA open source project is forked into YA VIJAVA(Yet another VI JAVA), it will have support to all the new APIs introduced in vSphere 6.0. VI JAVA itself works fine even on vSphere 6.0 (except the new features in vSphere 6.0).

Great news: YAVI JAVA : fork of VI JAVA open source project : Supports VMware vSphere 6.0

Since last stable vSphere 5.5 release of VI JAVA open source project , for more than 15+ months there was not any update on VI java, no any questions on the community were getting answered. There was lot of uncertainty among VI JAVA users on the future of the VI JAVA, discussions were picking up among VI JAVA on how to mitigate the impact if VI JAVA becomes dead and Michael Rice came to the rescue and puts the end to this speculation. He forked the VI JAVA project into YAVI JAVA (Yet Another VI JAVA) in order to give new life to this project which is for sure asset to many VMware users. I really appreciate the great proactive work done by Michael, YAVI JAVA is result of Machael’s dedication & passion for contributing to open source community. I am sure so many VI JAVA users have reason to celebrate this. I would like to thank other contributors as well. At the same time we just can not forget awesome work done by Steve Jin by leading VI JAVA project for several past releases. YAVI JAVA now available on GIT HUB and community contribution is getting increased. I would recommend all of you to spread the word about this project, start contributing, using and help in making this project a great success. Without community contribution, no open source project can become great. Along with supporting VMware vSphere 6.0, there are several new features added to YAVI JAVA, great thing about this project is: your old projects those developed using VI JAVA will work just fine. how cool it is!

Below are some of important hyperlinks about YAVI JAVA links, releases, tutorials, samples etc.

1. YAVI JAVA website

2. GIT HUB repository

3. Basic tutorials

4. All the releases of YAVI JAVA

5. All the Samples : Do not worry as I specified all these samples will just work fine on YAVI JAVA as well. Please stay tuned for my blogs on sample wrt to new APIs introduced in vSphere 6.0

Please do stay tuned for step by step getting started guide on YAVI JAVA.

How to get datastore UUID across all the datastores in a vCenter server using vSphere APIs

There are several vSphere API which requires datastore UUID as one of its important properties. Some examples of such APIs are MountVmfsVolume(),mountVmfsVolumeEx(), UnmountForceMountedVmfsVolume(), unmapVmfsVolumeEx(), DeleteVmfsVolumeState(), unmountVmfsVolumeEx & unmountVmfsVolume(). Without vmfsUUID we can NOT operate on any of these APIs. Now question is how to get/know the datastore UUID of the VMFS datastores connected to hosts using vSphere APIs. I thought its better to write the vSphere API script to solve this. The script that I am sharing is going to get all hosts and all of its associated datastores and each datastore and its associated UUID. Here we go.

[java]
package com.vmware.vijava;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.vmware.vim25.DatastoreInfo;
import com.vmware.vim25.VmfsDatastoreInfo;
import com.vmware.vim25.mo.Datastore;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.HostDatastoreBrowser;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;

public class findVMFSUUIDs {
public static void main(String[] args) throws Exception {
ServiceInstance si = new ServiceInstance(new URL(
"https://10.120.30.40/sdk"), "administrator@vsphere.local",
"Administrator!23", true);
// Get the rootFolder
Folder rootFolder = si.getRootFolder();

// Get all the hosts in the vCenter server
ManagedEntity[] hosts = new InventoryNavigator(rootFolder)
.searchManagedEntities("HostSystem");

if (hosts == null) {
System.out.println("Host not found on vCenter");
si.getServerConnection().logout();
return;
}

// Map to store the datastore name as key and its UUID as the value
Map< String , String> vmfsdatastoreUUIDs = new HashMap< String , String>();

// Map to store host as key and all of its datastores as the value
Map< ManagedEntity , Datastore[]> hostDatastores = new HashMap< ManagedEntity , Datastore[]>();
for (ManagedEntity hostSystem : hosts) {
HostDatastoreBrowser hdb = ((HostSystem) hostSystem)
.getDatastoreBrowser();
Datastore[] ds = hdb.getDatastores();
hostDatastores.put(hostSystem, ds);
}

System.out.println("Hosts and all of its associated datastores");
for (Map.Entry < ManagedEntity , Datastore[]> datastores : hostDatastores
.entrySet()) {
System.out.println("");
System.out.print("[" + datastores.getKey().getName() + "::");
for (Datastore datastore : datastores.getValue()) {
System.out.print(datastore.getName() + ",");
DatastoreInfo dsinfo = datastore.getInfo();
if (dsinfo instanceof VmfsDatastoreInfo) {
VmfsDatastoreInfo vdinfo = (VmfsDatastoreInfo) dsinfo;
vmfsdatastoreUUIDs.put(datastore.getName(), vdinfo
.getVmfs().getUuid());
}

}
System.out.print("]");
}
System.out.println(" ");
System.out.println("Datastore and its UUID");
for (Map.Entry< String , String> dsuuid : vmfsdatastoreUUIDs.entrySet()) {
System.out.println("[" + dsuuid.getKey() + "::" + dsuuid.getValue()
+ "]");
}

}
}
[/java]

Program Output::

Hosts and all of its associated datastores

[192.168.1.1::DS3,DS2,Local DS,DS4,NFS1,]
[192.168.1.2::LocalDS2,LocalDS1,LocalDS3,]

Datastore and its UUID

[LocalDS1::55d9b324-bad019fa-147a-f04da20356f7]
[Local DS::55b5dee1-ebd2895d-1263-002219574957]
[DS2::51e3e9f7-8ab3eac5-4715-00221957495d]
[LocalDS2::5592e051-da224dfc-ad16-f04da20356f7]
[LocalDS3::55d9b367-d145aef6-dcfe-f04da20356f7]
[DS3::51398f9b-e591008a-1b35-002219574a65]
[DS4::55cc410f-604db805-6fc0-002219574a65]
[/java]

Now you could enhance this code to operate on any vSphere API that requires VMFS UUID as one of parameters. Please do comment if you have any doubts or need any help.

If you have still not setup your VI JAVA Eclipse environment:Getting started tutorial
Important tutorials to start with: Part I & Part II

Note: VI JAVA open source project is forked into YA VIJAVA(Yet another VI JAVA), it will have support to all the new APIs introduced in vSphere 6.0. VI JAVA itself works fine even on vSphere 6.0 (except the new features in vSphere 6.0). Please do stay tuned my post on YA VIJAVA.

vSphere API using Java : Getting started/Samples consolidated

Want to get started quickly with vSphere API using Java SDK coding but not getting easy to understand samples/tutorials? Want to get quick insight into vSphere APIs ? If you have these questions, this post is for you.

Some time back I had written 6 blog articles @vSphere API using Java SDK for VMware users and academic students. I thought to consolidate all the blog posts together in one short post so that it will be a one stop shop@vSphere API learning.

I recommend you to refer these 6 blog articles in below sequence. Blogs are written in a way that 1st year Engineering student should also understand easily.

Getting started with vSphere API using Java: How to quickly setup your eclipse environment (5-10 min)

Tutorial 1: How to initialize connection with ESXi host or vCenter server using vSphere API.

Tutorial 2:How to access/navigate vCenter server or ESXi host inventory using vSphere API

Sample 1: How to get datastore summary for all the datastores connected to a ESXi host.

Sample 2: How to create VM-Host DRS affinity rules using vSphere API

Sample 3: How to create VM-VM DRS affinity rules using vSphere API

You may also want to share these article with friends/students/customers. It will help them in their projects related to VMware. This also can be a trigger to start learning@VMware.