VMware - Sample Code - VMEventsMonitor.java

Example script to Monitoring VM related events.

VMEventsMonitor.java

Copyright © 2008 VMware, Inc. All rights reserved.

//# Copyright 2008 VMware, Inc.  All rights reserved.

//#######################################################################################
//# DISCLAIMER. THIS SCRIPT IS PROVIDED TO YOU "AS IS" WITHOUT WARRANTIES OR CONDITIONS 
//# OF ANY KIND, WHETHER ORAL OR WRITTEN, EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY 
//# DISCLAIMS ANY IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY 
//# QUALITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. 
//#######################################################################################


//#######################################################################################
//
// VMEventsMonitor.java
// Example script to Monitoring VM related events
// Parameters:
//  --url [webserviceurl]   : url of ESX/VC.
//  --username [username]   : user name   
//  --password  [password]  : password
//
// This script works with VMware VirtualCenter 2.0 or later.
//######################################################################################


package com.vmware.samples.events;

import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
import com.vmware.apputils.vim.VMUtils;
import java.util.*;
import java.io.*;
import java.net.URL;



public class VMEventsMonitor implements Runnable {
   private static AppUtil cb = null;   
   private VimPortType _service;           // All webservice methods   
   private ServiceContent _sic;            
   private ManagedObjectReference _propCol; // PropertyCollector Reference
   private ManagedObjectReference _searchIndex;
   private ManagedObjectReference _rootFolder;
   
   // EventManager and EventHistoryCollector References
   private ManagedObjectReference _eventManager;
   private ManagedObjectReference _eventHistoryCollector;      
   private static ManagedObjectReference propFilter;
   private static ManagedObjectReference propColl;
   private static Boolean shouldRun;

   /**
    * Initialize the necessary Managed Object References needed here
    */
   private void initialize() {
      _sic = cb.getConnection().getServiceContent();
      _service = cb.getConnection().getService();
      // The SearchIndex Reference is present in the ServiceInstanceContent
      _searchIndex = _sic.getSearchIndex();
      
      // The PropertyCollector and EventManager References are present
      // in the ServiceInstanceContent
      _propCol = _sic.getPropertyCollector();
      _eventManager = _sic.getEventManager();
      _rootFolder = _sic.getRootFolder();
   }
   
  
   private void createEventHistoryCollector() throws Exception {
      // Create an Entity Event Filter Spec to 
      // specify the MoRef of the VM to be get events filtered for 
      EventFilterSpecByEntity entitySpec = new EventFilterSpecByEntity();
      entitySpec.setEntity(_rootFolder);
      entitySpec.setRecursion(EventFilterSpecRecursionOption.children);

      // set the entity spec in the EventFilter
      EventFilterSpec eventFilter = new EventFilterSpec();
      eventFilter.setEntity(entitySpec);

      // we are only interested in getting events for the VM.
      // Add as many events you want to track relating to vm.
      // Refer to API Data Object vmEvent and see the extends class list for elaborate list of vmEvents
      eventFilter.setType( new String[]	
      						{"VmPoweredOffEvent", "VmPoweredOnEvent", 
      						 "VmSuspendedEvent","VmRenamedEvent"}
      					 );

      // create the EventHistoryCollector to monitor events for a VM 
      // and get the ManagedObjectReference of the EventHistoryCollector returned
      _eventHistoryCollector = 
      _service.createCollectorForEvents(_eventManager, eventFilter);
   }

   private PropertyFilterSpec createEventFilterSpec() {
      // Set up a PropertySpec to use the latestPage attribute 
      // of the EventHistoryCollector

      PropertySpec propSpec = new PropertySpec();
      propSpec.setAll(new Boolean(false));
      propSpec.setPathSet(new String[] { "latestPage" });
      propSpec.setType(_eventHistoryCollector.getType());

      // PropertySpecs are wrapped in a PropertySpec array
      PropertySpec[] propSpecAry = new PropertySpec[] { propSpec };
         
      // Set up an ObjectSpec with the above PropertySpec for the
      // EventHistoryCollector we just created
      // as the Root or Starting Object to get Attributes for.
      ObjectSpec objSpec = new ObjectSpec();
      objSpec.setObj(_eventHistoryCollector);
      objSpec.setSkip(new Boolean(false));
         
      // Get Event objects in "latestPage" from "EventHistoryCollector"
      // and no "traversl" further, so, no SelectionSpec is specified 
      objSpec.setSelectSet(new SelectionSpec[] { });
         
      // ObjectSpecs are wrapped in an ObjectSpec array
      ObjectSpec[] objSpecAry = new ObjectSpec[] { objSpec };
         
      PropertyFilterSpec spec = new PropertyFilterSpec();
      spec.setPropSet(propSpecAry);
      spec.setObjectSet(objSpecAry);
      return spec;
   }

   void handleUpdate(UpdateSet update) {
      ArrayList vmUpdates = new ArrayList();
      PropertyFilterUpdate[] pfus = update.getFilterSet();       
      for(int pfui=0; pfui 0) {
         System.out.println("Virtual Machine updates:");
         for(Iterator vmi = vmUpdates.iterator(); vmi.hasNext();) {
            handleObjectUpdate((ObjectUpdate)vmi.next());
         }
      }
   }
   
   void handleObjectUpdate(ObjectUpdate oUpdate) {
      PropertyChange[] pc = oUpdate.getChangeSet(); 
      if(oUpdate.getKind()==ObjectUpdateKind.enter) {
         System.out.println(" New Data:");
         handleChanges(pc);
      } else if (oUpdate.getKind()==ObjectUpdateKind.leave) {
         System.out.println(" Removed Data:");
         handleChanges(pc);
      } else if (oUpdate.getKind()==ObjectUpdateKind.modify) {
         System.out.println(" Changed Data:");
         handleChanges(pc);
      }
      
   }   
   
   void handleChanges(PropertyChange[] changes) {
      for(int pci=0; pci<changes.length; ++pci) {
         String name = changes[pci].getName();
         Object value = changes[pci].getVal();
         PropertyChangeOp op = changes[pci].getOp();
         if (value != null && !op.getValue().equalsIgnoreCase("remove")) {
            System.out.println("===============");
         	//System.out.println("value instance of " + value.getClass().getCanonicalName());
         	System.out.println("\nEvent Details follows:");
         	if(value instanceof ArrayOfEvent) {
                  ArrayOfEvent aoe = (ArrayOfEvent)value;
                  Event[] evts = aoe.getEvent();
                  for(int evtID=0; evtID<evts.length ; ++evtID) {
                  	Event anEvent = evts[evtID];
					System.out.println("\n----------" 
									+ "\n Event ID: " + anEvent.getKey() 
									+ "\n Event: " + anEvent.getClass().getName() 
									+ "\n FullFormattedMessage: " + anEvent.getFullFormattedMessage() 
									+ "\n VM Reference: " + anEvent.getVm().getVm().get_value() 
									+ "\n----------\n");
                  }
            } else if (value instanceof VmEvent) {
            	VmEvent anEvent = (VmEvent)value;
				System.out.println("\n----------" 
								+ "\n Event ID: " + anEvent.getKey() 
								+ "\n Event: " + anEvent.getClass().getName() 
								+ "\n FullFormattedMessage: " + anEvent.getFullFormattedMessage() 
								+ "\n VM Reference: " + anEvent.getVm().getVm().get_value() 
								+ "\n----------\n");
            }
            System.out.println("===============");
      	 }
      }
   }  

   public static void main(String[] args) {
      try {
         VMEventsMonitor eventMonitor = 
            new VMEventsMonitor();
         cb = AppUtil.initialize("VMEventsMonitor",
                                 args);
         cb.connect();        
         eventMonitor.initialize();
         eventMonitor.createEventHistoryCollector();
         
         PropertyFilterSpec eventFilterSpec = eventMonitor.createEventFilterSpec();
	     propColl = cb.getConnection().getPropCol(); 

	     propFilter = cb.getConnection().getService().
	     createFilter(propColl, eventFilterSpec, true);
	              
		 Thread watchUpdates = new Thread(eventMonitor);
		 shouldRun = true;
	     watchUpdates.start();
	     BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
	     do {
       	    System.out.println("");
	        System.out.println("Enter 'exit' <Enter> to exit the program");
	        String line = console.readLine();
	        if(line.trim().equalsIgnoreCase("exit"))
	           break;
	       }while(true);
	    shouldRun = false;
	    cb.getConnection().getService().cancelWaitForUpdates(propColl);
	   	System.out.println("Exiting the program performing required cleaning");
	    cb.getConnection().getService().destroyPropertyFilter(propFilter);    
	    cb.disConnect();
	   	
      } 
      catch (Exception e) {
         System.out.println("Caught Exception : " +
                            " Name : " + e.getClass().getName() +
                            " Message : " + e.getMessage() +
                            " Trace : ");
      }
   }
   public void run() {
     String version = "";
     try {
	     do {
		     try {	
		        System.out.println("Waiting for new Updates. \nEnter 'exit' <Enter> to exit the program");
		        UpdateSet update = cb.getConnection().getService().waitForUpdates(propColl, 
		                                                                           version);
		        if(update != null && update.getFilterSet() != null) {
		           
		           this.handleUpdate(update);
		           
		           version = update.getVersion();
		           System.out.println(" Current Version: " + version);
		        } else {
		           System.out.println("No update is present!");
		        }
		     } catch(Exception e) {
	               if(e instanceof org.apache.axis.AxisFault) {
	                  org.apache.axis.AxisFault fault = 
	                     (org.apache.axis.AxisFault)e;
	                  org.w3c.dom.Element [] errors = 
	                     fault.getFaultDetails();
	                  String faultString = fault.getFaultString();
	                  if(faultString.indexOf("java.net.SocketTimeoutException") != -1) {
	                  }
	                  else {
	                     throw e;
	                  }
	               }
	         }
	     }while(shouldRun);
	   } catch (Exception e) {
	   		if (e instanceof RequestCanceled) {
	   			System.out.println("OK");
	   		} else {
         	System.out.println("Caught Exception : " +
                            " Name : " + e.getClass().getName() +
                            " Message : " + e.getMessage() +
                            " Trace : ");
            }
      }
   }
}


The sample code is provided "AS-IS" for use, modification, and redistribution in source and binary forms, provided that the copyright notice and this following list of conditions are retained and/or reproduced in your distribution. To the maximum extent permitted by law, VMware, Inc., its subsidiaries and affiliates hereby disclaim all express, implied and/or statutory warranties, including duties or conditions of merchantability, fitness for a particular purpose, and non-infringement of intellectual property rights. IN NO EVENT WILL VMWARE, ITS SUBSIDIARIES OR AFFILIATES BE LIABLE TO ANY OTHER PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES, ARISING OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THE SAMPLE CODE.

You agree to defend, indemnify and hold harmless VMware, and any of its directors, officers, employees, agents, affiliates, or subsidiaries from and against all losses, damages, costs and liabilities arising from your use, modification and distribution of the sample code.

VMware does not certify or endorse your use of the sample code, nor is any support or other service provided in connection with the sample code.