Home > vSphere API > Who Created That VM: Java Version of the Winning Script of VMware Contest

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

August 3rd, 2010 Leave a comment Go to comments

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.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App

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;

Categories: vSphere API Tags: ,
  1. Ken
    August 4th, 2010 at 09:18 | #1

    that was the winning submission? really?

  2. August 4th, 2010 at 10:05 | #2
  1. No trackbacks yet.