Who Created That VM: Java Version of the Winning Script of VMware Contest

As you recall from my previous blog on the Script-O-Mania contest, Alan Renouf won the first prize with his Who Created That VM script written in PowerCLI. The script leverages implicitly several vSphere APIs, so I think it would be cool to have a Java version. At least we can illustrate how to use these related vSphere APIs.

The following is a sample I rewote using VI Java API for the same purpose except that Alan’s script shows full display name of a user while this Java version shows user name (see the following diagram). Although longer, the Java version can run on any OS, not just Windows.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

Here is the Java code.

package com.vmware.vim25.mo.samples.vm;

import java.net.URL;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;

import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.CustomFieldStringValue;
import com.vmware.vim25.CustomFieldValue;
import com.vmware.vim25.Event;
import com.vmware.vim25.EventFilterSpec;
import com.vmware.vim25.EventFilterSpecByEntity;
import com.vmware.vim25.EventFilterSpecRecursionOption;
import com.vmware.vim25.InvalidState;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.CustomFieldsManager;
import com.vmware.vim25.mo.EventHistoryCollector;
import com.vmware.vim25.mo.EventManager;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;

public class WhoCreatedThatVM
{
  private static final String CREATED_ON = "CreatedOn";
  private static final String CREATED_BY = "CreatedBy";
  static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

  public static void main(String[] args) throws Exception
  {
    ServiceInstance si = new ServiceInstance(
        new URL("https://vc_server/sdk"), "administrator", "password", true);

   ManagedEntity[] vms = new InventoryNavigator(
       si.getRootFolder()).searchManagedEntities("VirtualMachine");
    EventManager em = si.getEventManager();
    CustomFieldsManager cfm = si.getCustomFieldsManager();

    int CREATEDBY_KEY = -1;
    int CREATEDON_KEY = -1;

    ManagedEntity vm0 = vms[0];
    CustomFieldDef[] defs = vm0.getAvailableField();
    for(int i=0; defs!=null && i<defs.length; i++)
    {
      if(CREATED_BY.equals(defs[i].getName()))
      {
        CREATEDBY_KEY = defs[i].getKey();
      }
      else if(CREATED_ON.equals(defs[i].getName()))
      {
        CREATEDON_KEY = defs[i].getKey();
      }
    }
    if(CREATEDBY_KEY == -1)
    {
      CREATEDBY_KEY = cfm.addCustomFieldDef(CREATED_BY, "VirtualMachine",
          null, null).getKey();
    }
    if(CREATEDON_KEY == -1)
    {
      CREATEDON_KEY = cfm.addCustomFieldDef(CREATED_ON, "VirtualMachine",
          null, null).getKey();
    }

    for(ManagedEntity vm : vms)
    {
      CustomFieldValue[] values = vm.getCustomValue();

      if(alreadySet(values, CREATEDBY_KEY))
        continue;

      System.out.println("Finding creator for VM: " + vm.getName());
      Event event = findVmCreationEvent(em, vm);

      String user = "Unknown";
      String time = "Unknown";
      if(event!=null)
      {
        user = event.getUserName();
        time = sdf.format(event.getCreatedTime().getTime());
      }
      System.out.println("Adding info to vm:" + vm.getName());
      vm.setCustomValue(CREATED_BY, user);
      vm.setCustomValue(CREATED_ON, time);
    }
    si.getServerConnection().logout();
  }

  /**
   * Checks if the CreatedBy custom field has been assigned value in
   * the values array
   * @param values - an array of all the custom filed values
   * @param key - custom field definition
   * @return boolean for yes or no
   */
  private static boolean alreadySet(CustomFieldValue[] values, int key)
  {
    for(int i=0; values!=null && i<values.length; i++)
    {
      if(values[i].getKey() == key)
      {
        String sVal = ((CustomFieldStringValue)values[i]).getValue();
        if(sVal != null && ! sVal.isEmpty())
          return true;
      }
    }
    return false;
  }
  /**
   * This method finds the event of VM creation.
   * @param em - EventManageer object
   * @param vm - VirtualMachine object
   * @return an Event indicating VM creation. It could be null
   * @throws InvalidState
   * @throws RuntimeFault
   * @throws RemoteException
   */
  public static Event findVmCreationEvent(EventManager em, ManagedEntity vm)
      throws InvalidState, RuntimeFault, RemoteException
  {
    EventFilterSpec filter = new EventFilterSpec();

    //When it works with ESX, the event type filtering does NOT work.
    //For VC, it's fine.
    filter.setType(new String[] {"VmBeingDeployedEvent", "VmCreatedEvent",
        "VmRegisteredEvent", "VmClonedEvent" });
    EventFilterSpecByEntity entSpec = new EventFilterSpecByEntity();
    entSpec.setEntity(vm.getMOR());
    entSpec.setRecursion( EventFilterSpecRecursionOption.self);
    filter.setEntity(entSpec);
    EventHistoryCollector ehc = em.createCollectorForEvents(filter);
    Event[] es = ehc.getLatestPage(); //latest event comes first in the array
    ehc.destroyCollector(); //must destroy it otherwise exception comes up later

    if(es!=null && es.length >0)
    {
      return es[0];
    }
    return null;
  }
}
package com.vmware.vim25.mo.samples.vm;

This entry was posted in vSphere API and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Ken
    Posted August 4, 2010 at 9:18 am | Permalink

    that was the winning submission? really?

  2. Posted August 4, 2010 at 10:05 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.