Vous êtes sur la page 1sur 182

vSphere Web Services SDK Programming Guide

vSphere Web Services SDK 4.0

EN-000145-00

vSphere Web Services SDK Programming Guide

You can find the most up-to-date technical documentation on the VMware Web site at: http://www.vmware.com/support/ The VMware Web site also provides the latest product updates. If you have comments about this documentation, submit your feedback to: docfeedback@vmware.com

2009 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and intellectual property laws. VMware products are covered by one or more patents listed at http://www.vmware.com/go/patents. VMware, the VMware boxes logo and design, Virtual SMP, and VMotion are registered trademarks or trademarks of VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.

VMware, Inc. 3401 Hillview Ave. Palo Alto, CA 94304 www.vmware.com

VMware, Inc.

Contents

AboutThisBook

1 IntroductiontotheVirtualDatacenter 11
VirtualizationandVMwarevSphereComponents 11 SummaryofNewFeaturesforDevelopersUsingtheSDK 12 NewManagedEntities 13 SupportforPreviousAPIsinvSphere4.0 13 InteroperabilityofSDK2.5ClientsandvSphere4.0Servers 13 ClientLibrariesandExistingSDK2.5ClientApplications 14 ModifyingVISDK2.5basedClientApplicationstousevSphereAPI4.0Features 14

2 vSphereObjectModel 15
UsingtheVMwarevSphereClienttoExploretheObjectModel 15 UsingtheManagedObjectBrowsertoExploretheObjectModel 16 AccessingtheMOB 17 NavigatingtheObjectModelintheMOB 17 UnderstandingtheServiceContentDataObject 18 UnderstandingtheObjectModelasDataStructures 21 UnderstandingtheUnifiedModelingLanguageUsedinthisGuide 21 TheManagedObjectTypeasDataStructureandServiceInterface 22 ServiceInstanceManagedObjectasStartingPointtoOtherServiceInterfaces 23 ReferencestoManagedObjects 24

3 UnderstandingtheInventory 25
OverviewofManagedEntities 25 UnderstandingContainerObjectsandtheInventory 26 FolderasContainer 27 InventoryObjectsandPrivileges 28 FolderasFactory 30 vCenterServerandUnmanagedESX/ESXiHostInventories 30

4 OverviewofUserModelsandServerAccessControlConcepts 33
IntroductiontoAuthenticationandAuthorization 33 UnderstandingSystemPrivileges 34 PrivilegesDefinedinthevSphereAPIReference 34 HTTPBasedFileAccessandPrivileges 34 OverviewofESX/ESXiUserModel 35 UsingHostLocalAccountManagerManagedObject 35 OverviewofvCenterServerUserModel 36 EnablingSingleSignonSupportandIntegrationwithMicrosoftActiveDirectory 37 ObtainingInformationaboutUsersandGroupsfromUserDirectory 37 AuthenticatingUsersthroughSessionManager 39 OverviewoftheAuthorizationManager 39 UsingRolestoConsolidateSetsofPrivileges 40 ModifyingSampleRolestoCreateNewRoles 42

VMware, Inc.

vSphere Web Services SDK Programming Guide

GrantingPrivilegesthroughPermissions 42 ObtainingInformationaboutPermissions 43 Setting,Changing,orDeletingPermissions 43 ImpactofGroupMembershiponPermissions 44

5 vSphereAPIProgrammingModel 45
APIasaWebService 45 APIDefinedinWSDLFile 45 ClientApplicationCharacteristics 46 AsynchronousClientServerApplicationStyle 46 DistributedObjectOrientedApplicationStyle 46 ObtainingManagedObjectReferences 49 DoNotStoreManagedObjectReferenceValues 49 WorkingwithDataStructuresinClientApplicationCode 49 AccessingPropertyValues 49 AccessingtheAPIontheWebService 50 UsingthevSphereAPIReference 51 IdentifyingDeprecatedItemsinthevSphereAPIReference 51 IdentifyingVersionInformationinthevSphereAPIReference 51 MappingtheWSDLtotheClientsideProxyCode 51 ObtainingValuesfromNestedProperties 52 MappingXMLDatatypestoJavaandC#Datatypes 53 EscapeCharacterUsedinNameandPathProperties 53 InvokingOperationsthroughtheMOB 53 PassingPrimitiveDatatypestoOperationsthroughtheMOB 54 PassingArraysofPrimitivestoOperationsthroughtheMOB 54 PassingComplexStructurestoOperationsthroughtheMOB 54

6 ClientApplicationPattern 59
MinimalClientApplicationPattern 59 ConnectingtotheWebService 59 ObtainingaSessionTokenandCreatingaConnectionObject 59 LoggingIntotheServer 60 ClosetheServerConnection 60 OverviewofaJavaSampleApplication 61 SavingandReusingaWebServerSessionTokenorCookie 63 SupportingMultipleAPIVersions 63 IdentifyingtheAPIVersionSupportedbytheServer 64 HelperClassesforSampleApplications 64 JavaHelperClasses 65 C#HelperClasses 65

7 AutomatingClientApplicationLogin 67
IntroductiontotheCredentialStore 67 OverviewoftheCredentialStoreBackingFile 68 CredentialStoreBackingFileStructure 68 UsingSamplestoUnderstandtheCredentialStore 69 SecurityBestPracticesandtheCredentialStore 69 UsingthePrincipleofLeastPrivilegewiththeCredentialStore 69 UsingtheCredentialStoreAdminTool 70 UsingAuthorizationManagertoLimitAccess 70 CreatingNewUserAccounts 70 ApplyingPermissiontoanEntity 71

VMware, Inc.

Contents

8 ObtainingReferencestoObjectsandPropertyValuesfromtheServer 73
SampleCodeReference 73 IntroductiontothePropertyCollector 74 PropertyCollectorOperations 74 UnderstandingthePropertyFilterSpec 75 TraversalSpecDataObjectandRecursion 76 RetrievePropertiesOperation 76 CreateFilterandUpdateOperations 77 KeepingClientDatainSynchwithServerObjects 78 PropertyCollectorPerformance 79 ImprovingCollectionPerformancebyUsingtheViewManagerandView Objects 79 UsingtheSearchIndextoObtainManagedObjectReferences 80

9 OverviewoftheTaskInfrastructure 83
SampleCodeReference 83 UnderstandingTaskManagerandTaskManagedObjects 84 UnderstandingtheTaskInfoDataObject 85 MonitoringTaskInfoProperties 88 CancellingaTask 88 UsingtheTaskManagertoObtainInformationaboutTasks 88 ObtainingInformationaboutRecentTasksUsingaPropertyCollector 89 OperationsThatReturnTaskManagedObjects 90 IntroductiontotheEventDataObject 92

10 WorkingwithVirtualMachines 93
SampleCodeReference 93 CreatingVirtualMachines 93 OverviewofVirtualMachineOperations 94 OverviewofSnapshots 97 CreatingSnapshots 97 RevertingtoSnapshots 97

11 ManagingStorage 99
SampleCodeReference 99 OverviewofPhysicalandVirtualStorageConcepts 99 RequirementsforStorage 100 OverviewofInternetSCSIStorage 101 IntroductiontoManagedObjectsthatSupportStorage 101 IntroductiontotheHostStorageSystemManagedObject 102 IntroductiontotheHostDatastoreSystemManagedObject 106 ObtainingInformationaboutConfiguredStorage 107 CreatingNewDatastores 108 ModifyingDatastoreConfiguration 110

12 MonitoringPerformance 111
SampleCodeReference 111 IntroductiontoPerformanceManager 112 OverviewofCounterGroupsandthePerfCounterInfoDataObject SamplingPeriodsandIntervals 114 ObtainingStatistics 115 112

VMware, Inc.

vSphere Web Services SDK Programming Guide

vCenterServerandPerformanceManager 117 HistoricalIntervals 117 ModifyingHistoricalIntervals 117 OptimizingQueryResponseTime 118

13 UsingvCenterServerforVirtualMachineOperations 119
SampleCodeReference 120 OverviewoftheVirtualMachineManagedObjectType 120 UsingTemplatestoDeployStandardVirtualMachines 124 CreatingTemplates 124 RevertingaTemplatetoItsActiveVirtualMachineStatus 125 MigratingVirtualMachinesUsingVMotion 125 CheckingtheValidityofaMigrationInAdvance 126 UsingtheMigrateVM_TaskOperation 126 MovingStorageDynamicallyUsingStorageVMotion 127

14 EventandTaskManagementUsingvCenterServer 129
SampleCodeReference 129 UnderstandingEventManagerandtheEventDataObject 129 EventManagerManagedObject 130 EventDataObjects 130 FormattingEventMessageContent 131 CreatingCustomEvents 132 ObtainingInformationaboutEventsUsingaHistoryCollector 133 OverviewofHistoryCollectorManagedObjects 133 NewObjectsAppendedtoaHistoryCollector 135 DeletingaHistoryCollector 135

15 UsingtheAlarmInfrastructure 137
SampleCodeReference 137 OverviewofAlarmManagerandAlarmManagedObjects 137 ObtainingaListofAlarms 138 DefininganAlarm 138 OverviewoftheAlarmSpecDataObject 139 OverviewoftheAlarmExpressionDataObject 139 OverviewoftheAlarmActionDataObject 141 DeletingorDisablinganAlarm 142

16 SchedulingvCenterServerOperations 143
SampleCodeReference 143 ScheduledTaskManagerManagedObject 143 RetrievingScheduledTasksforaSpecificManagedEntity 144 CreatingaScheduledTaskObject 144 DefiningtheScheduleforthevCenterServerOperation 145 DefiningtheActions 146 SchedulingRecurringOperations 146 DeletingaScheduledTask 148

A ManagedObjectPrivilegesReference 149
PrivilegesRequiredtoInvokeOperations 149 PrivilegesRequiredtoReadProperties 156 PrivilegesDefinedfortheAdministratorRole 158

VMware, Inc.

Contents

B DiagnosticsandTroubleshooting 161
BestPracticesforTroubleshooting 161 OverviewofConfigurationFilesandLogFiles 162 ESXLogFile 163 VirtualMachineLogFiles 163 vCenterServerLogFiles 164 ModifyingtheLogLeveltoObtainDetailedInformation 164 LogLevelSettings 165 SettingtheLogLevelonESXSystems 165 GeneratingLogs 166 SettingtheLogLevelonvCenterServerSystem 167 UnderstandingandUsingtheDiagnosticManager 167 UsingtheMOBtoExploretheDiagnosticManager 169 GeneratingDiagnosticBundles 171

C DeployingClientApplications 173
UnderstandingtheClientApplicationDeploymentModel 173 CredentialStoreAdministrationToolforNonInteractiveClients 173 GuidelinesforUsingtheCredentialStoreAdminTool 173 CredentialStoreAdminToolandtheBackingFile 174

Index 177

VMware, Inc.

vSphere Web Services SDK Programming Guide

VMware, Inc.

About This Book

ThevSphereWebServicesSDKProgrammingGuide,providesinformationaboutdevelopingapplicationsusing theVMwarevSphereWebServicesSDK4.0. VMwareprovidesseveraldifferentAPIsandSDKsforvariousapplicationsandgoals.Thisbookprovides informationaboutusingthevSphereWebServicesSDKfordevelopersthatareinterestedincreatingclient applicationsformanagingVMwarevSpherecomponentsavailableonVMwareESX,VMwareESXi,and VMwarevCenterServersystems. ToviewthecurrentversionofthisbookaswellasallVMwareAPIandSDKdocumentation,goto http://www.vmware.com/support/pubs/sdk_pubs.html.

Revision History
Thisguideisrevisedwitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontainminor ormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide. Table 1. Revision History
Revision 20090507 Description FirstversionofthevSphereWebServicesSDK4.0ProgrammingGuide.

Intended Audience
ThisbookisintendedforanyonewhoneedstodevelopapplicationsusingtheVMwarevSphereWebServices SDK.vSphereWebServicesSDKdeveloperstypicallyincludesoftwaredeveloperscreatingclientapplications usingJavaorC#(intheMicrosoft.NETenvironment)targetingVMwarevSphere.

Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Sendyourfeedbackto docfeedback@vmware.com.

Technical Support and Education Resources


Thefollowingsectionsdescribethetechnicalsupportresourcesavailabletoyou.Toaccessthecurrentversions ofotherVMwarebooks,gotohttp://www.vmware.com/support/pubs.

Online and Telephone Support


Touseonlinesupporttosubmittechnicalsupportrequests,viewyourproductandcontractinformation,and registeryourproducts,gotohttp://www.vmware.com/support.

VMware, Inc.

vSphere Web Services SDK Programming Guide

Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto http://www.vmware.com/support/services.

VMware Professional Services


VMwareEducationServicescoursesofferextensivehandsonlabs,casestudyexamples,andcoursematerials designedtobeusedasonthejobreferencetools.Coursesareavailableonsite,intheclassroom,andlive online.Foronsitepilotprograms andimplementationbestpractices,VMwareConsultingServicesprovides offeringsto helpyouassess,plan,build,andmanageyourvirtualenvironment.Toaccessinformationabout educationclasses,certificationprograms,andconsultingservices,gotohttp://www.vmware.com/services.

10

VMware, Inc.

Introduction to the Virtual Datacenter

TheVMwarevSphereWebServicesSDKgivesWebservicesdevelopersprogrammaticaccesstothevirtual datacentercomponents.VMwarevSphereprovidesacompleteplatformtosupportrobust,faulttolerant virtualizedapplications,networking,storage,andallotherdatacenterresources. VirtualizationandVMwarevSphereComponentsonpage 11 SummaryofNewFeaturesforDevelopersUsingtheSDKonpage 12 SupportforPreviousAPIsinvSphere4.0onpage 13

Virtualization and VMware vSphere Components


VMwaresoftwareproductsvirtualizecomputingresources,includingCPU,memory,storage,andnetworks, forexample,sothatphysicalresourcescandeliveroptimalvalue.Figure 11showssomeofthekeyVMware vSphereinthecontextofphysicalcomponents,suchasenterpriseservers,networks,andstorage. Figure 1-1. VMware vSphere Components

Virtualizationprovidesanabstractionlayerbetweencomputingresources,physicalstorage,andnetworking hardware,andtheapplicationsthatusealloftheseresources.Forexample,virtualmemoryenablessoftware tousemorememorythanisphysicallyinstalledinacomputerbyswappingdatafromphysicalmemoryto physicaldisk.

VMware, Inc.

11

vSphere Web Services SDK Programming Guide

WithitsVMwarevSphereproductsuite,VMwarevirtualizesalllayersofanITinfrastructure,fromnetworks, storage,laptopanddesktopcomputers,toserverhardware,operatingsystems,andapplications. VMwarevSphereincludesESX/ESXi,vCenterServer,andseveraladditionalserverproductsfordistributed resourcemanagement(DRS),disasterrecovery,andhighavailability(HA)(Figure 11). ESX/ESXiprovidesthefoundationhypervisorcapableofsupportingmultiplevirtualmachinesandother virtualcomponents,suchasstorageandnetworks. vCenterServerisadatabasebackedWindowsservicethatprovidescentralmanagementformultiple ESX/ESXisystems. IfyouarenewtoVMwarevSphereornewtotheVMwarevSphereWebServicesSDK,seeoneoftheseguides formorebackgroundinformationaboutvSphere: IntroductiontoVMwarevSphere vSphereBasicSystemAdministration ESXConfigurationGuideandESXiConfigurationGuide vSphereResourceManagementGuide FormoreinformationaboutESX/ESXiandvCenterServer,seetheVMwarevSpheredocumentationpageon theVMwarewebsite.

Summary of New Features for Developers Using the SDK


ThissectionlistsjustsomeofthehighlightsofthevSphere4.0,withafocusonchangestotheAPIandthe objectmodel.Forallnewmanagedobject,dataobject,andothertypes,seethevSphereAPIReference. Rapid, Compliant Host Provisioning Using Profiles Configurehostsquicklyusingprofilesthatcomplywithspecificconfigurationpolicies.Severalnewmanaged objectsandassociateddataobjectssupportprovisioningnewhostsusingprofiles.Forexample,youcanusea newserviceinterface,theHostProfileManager,todefineconfigurationsandpolicies.Withprofiles,you configuresettingsfortheenvironmentonceandusetheprofiletoprovisionnewhosts.Useprofilesto configurenetworking,storagesettings,security,andothersettingsacrossanynumberofhosts. Distributed Virtual Switch VMwareDistributedVirtualSwitch(DVS)providesnextgenerationvirtualnetworkingmanagementthat spanstheentirevirtualinfrastructure.Italsoenablesyoutoquicklyincreasenetworkingcapacityandreduce ongoingnetworkmaintenancetasks,bysimplifyingmonitoringandtroubleshootingactivities. Inaddition,DVSsupportsthelatestinVMotiontechnology,soyoucanbuildcompleteVMotionaware networkingapplicationsontopofvSphere.NetworkVMotiontracksthenetworkingstateofavirtualmachine asitmigratesthroughoutthevirtualinfrastructure. SeethevSphereAPIReferenceforcompletedetailsaboutthenewmanagedobjecttypesthatsupportDVS, startingwiththeDistributedVirtualSwitchandDistributedVirtualSwitchManager. More Granular Permissions Model for Delegated Administration vCenterServernowsupportsamorediscretepermissionsmodelfordatastoresandnetworks.Theseentities canbegrantedpermissionsdistinctfromthedatacenter. Accesstoadatastoreornetworkcanbegrantedtoordeniedforaspecificsetofusersorgroups.Thisfeature issupportedintheobjectmodelbyelevatingtheDatastoreandNetworkmanagedobjectsinthehierarchy. TheseobjectsarenowdirectdescendentsoftheManagedEntitybaseclassandcansupportpermissions independentlyofDatacenter(Figure 12).

12

VMware, Inc.

Chapter 1 Introduction to the Virtual Datacenter

New Managed Entities


Manynewfeaturesareimplementedasoneormorenewmanagedobjects.Thoseavailablethroughthe inventoryasmanagedentitiesareshowninFigure 12. Figure 1-2. ManagedEntity and Its Descendents

TheVirtualApp,DistributedVirtualSwitch,andDistributedVirtualPortgrouparenewmanaged entitieswithmanyassociateddataobjects,faulttypes,andenumerationstosupportthem.SeethevSphereAPI Referencefordetails. Virtualized Application Services AVirtualizedApplicationService(VirtualApp)isacontainerforoneormorevirtualmachines.AVirtualApp allowsanapplicationtobemanagedasaunit,includingpoweroperations,cloneanddeployoperations, resourceallocation,andmonitoring.vCenterServersupportscreating,running,importing,andexporting virtualizedapplicationsasfilesusingtheindustrystandardOpenVirtualizationFormat(OVF)1.0.

Support for Previous APIs in vSphere 4.0


YoucanusetheVMwarevSphereWebServicesSDK4.0withallvSphereserverproducts,includingESX4, ESXi4,vCenterServer4,ESX3,ESXi3,ESXServer3.0.x,VirtualCenterServer2.5,VirtualCenterServer2.0.x. BothESX/ESXiandvCenterServerprovideanewversionoftheWebservicesbasedAPI,vSphereAPI4.0, whichisasupersetofallAPIsreleasedsinceVIAPI2.5. UnlikepriorreleasesoftheAPI,thevSphereAPI4.0hasnodependencyontheWSDLnamespaceattribute forversioninformation.TargetingmultipleversionsoftheAPIinpriorreleasesrequiredtheclientapplication toexaminetheWSDLfileontheserverandobtainthevalueofthenamespaceannotation. WithvSphereAPI4.0,allSOAPmessagesfromtheclienttotheserverincludetheversioninformationusing apreviouslyunusedattributeintheSOAPheader.Thesedetailsaretransparenttodevelopers. BecausetheversioningmodelhaschangedandnolongerdependsontheWSDLnamespaceattributeto identifytheversionoftheAPI,thenamespaceforvSphere4.0APIremainsurn:vim25.InthevSphereWeb ServicesSDK4.0,thetwosubdirectoriesfortheWSDLfilesareasfollows: vim25,whichistheWSDLforVIAPI2.5,andsubsequentreleases,includingvSphereAPI4.0 vim,whichistheWSDLforVIAPI2.0andpriorreleases

Interoperability of SDK 2.5 Clients and vSphere 4.0 Servers


AsVMwareevolvestheAPItosupportnewcapabilities,newparametersforexistingoperationsandnew propertiesforexistingdataobjectsarealwaysdefinedasoptionalsothatclientsthatweredevelopedwithone versionoftheAPIcancontinuetoworkwithnewreleasesofthevSphereInfrastructureserverproducts.The resultofthisapproachisthatclientapplicationsdevelopedusingtheVISDK2.5canworkunchangedwith ESX4.0,ESXi4.0,orvCenterServer4.0servers.However,modifyinganexistingVISDK2.5basedclienthas someimplications,detailedinModifyingVISDK2.5basedClientApplicationstousevSphereAPI4.0 Features.
VMware, Inc. 13

vSphere Web Services SDK Programming Guide

Client Libraries and Existing SDK 2.5 Client Applications


ClientapplicationsthatweredevelopedusingtheVISDK2.5canworkwithvSphere4.0serversaslongthe applicationscontinuetousetheclientlibrariesfromtheVISDK2.5package.DonotusethevSphere4.0client librarieswithclientapplicationsthatwerecreatedusingVISDK2.5. UsethelibrariesfromthevSphereSDK4.0withVISDK2.5basedapplicationsonlyifyouaremodifyingsuch anapplicationtousenewfeaturesinthevSphereAPI4.0.Inaddition,youmightneedtomodifysomeofyour existingcode,asdetailedinthenextsection.

Modifying VI SDK 2.5-based Client Applications to use vSphere API 4.0 Features
TomodifyanSDK2.5clientapplicationtoincorporatenewAPI4.0functionality,youmustusetheclient libraries(vim25.jar)fromtheVMwareWebServicesSDK4.0package. Inaddition,youmustcheckyourexistingcodeforoperationsanddataobjectsthatmightcontainnew parametersandpropertiesinvSphereAPI4.0.Manyofthedataobjectsavailableinpreviousversionsofthe APIhavenewpropertiesinvSphereAPI4.0.Forexample,theEventdataobjecthasseveralnewpropertiesto supportmanagedobjectreferencestonewmanagedentitiesassociatedwithanEvent,suchasthe DistributedVirtualSwitch. Inaddition,manyoperationshavenewparametersinthisrelease.Forexample,theoperationslistedin Table 11wereavailableinVIAPI2.5andhavenewparametersinvSphereAPI4.0. Table 1-1. Operations with New Parameters in vSphere API 4.0
Operation addHost_Task addStandaloneHost_Task createTask extendVirtualDisk_Task findByUuid Operation queryVmfsDatastoreExtendOptions relocateVM_Task revertToCurrentSnapshot_Task revertToSnapshot_Task updateInternetScsiAuthenticationProperties

IfyourexistingVISDK2.5basedclientapplicationusesanyoftheoperationslistedinthetable,youmust modifythecodetopassnullforthe4.0specificparameter,asshowninthecodesnippetinTable 12. Table 1-2. Example of Modified Code for New Parameter
Original Code ...revertToSnapshot_Task(snapmor,null) Modified Code ...revertToSnapshot_Task(snapmor,null,null)

SeethevSphereAPIReferenceforcompleteinformationabouttheseoperations.

14

VMware, Inc.

vSphere Object Model

AswithphysicalITinfrastructurecomponents,virtualinfrastructurecomponentsmustbeprovisioned, deployed,monitored,andmanaged.TheVMwarevSphereobjectmodelisacomprehensivesetofrobust serversidecompositeobjectsthatprovidesthecompletemanagementcapabilities. Theobjectmodelincludesserviceinterfacesformanaging,monitoring,configuring,obtaininginformation, andcontrollinglifecycleoperationsassociatedwithvirtualinfrastructure,andobjecttypesthatinstantiatethe virtualcomponentsontheserveratruntime. Externalclientapplicationsaccessthismanagementframework,theVMwarevSphereobjectmodel,through thevSphereAPI,whichisavailablethroughtheWebserviceonESX,ESXi,andvCenterServersystems.Client applications,boththirdpartyandVMwareclientapplicationssuchasVMwarevSphereClient,usethe vSphereAPItoperformalllifecycle,management,andmonitoringoperations. UnderstandingthevSpheremanagementobjectmodeliskeytousingtheVMwarevSphereAPIforsuccessful clientapplicationdevelopmentandintegration.Thechapterincludesthesetopics: UsingtheVMwarevSphereClienttoExploretheObjectModelonpage 15 UsingtheManagedObjectBrowsertoExploretheObjectModelonpage 16 UnderstandingtheObjectModelasDataStructuresonpage 21

Using the VMware vSphere Client to Explore the Object Model


TheVMwarevSphereClientisagraphicaluserinterfacetoolthatconnectstovCenterServerandESX/ESXi systemsforadministeringandmanagingvirtualinfrastructurecomponents.DeveloperscanusethevSphere Clientasatoolforexploringtheobjectmodel. ThevSphereClientrendersvirtualcomponentsasahierarchicaltreeintheleftpaneofthedisplay(Figure 22). WhenconnectedtoavCenterServer,thevSphereClientdisplaysalltheoptionsavailabletotheVMware vSphereenvironment,basedontheconfiguredlicensingandthepermissionsoftheuser.Whenconnectedto anESX/ESXihost,thevSphereClientdisplaysoptionsappropriateforsinglehostmanagement. ThevSphereClientlayoutisasinglewindowwithamenubar,anavigationbar,atoolbar,astatusbar,anda panelsection.Theleftpaneshowstheinventoryofobjectsontheserver(vCenterServer,ESX,orESXi). SeeManagingthevSphereClientInventoryUnderstandingvSphereClientObjectsintheVMwarevSphereonline libraryformoreinformationabouthowthevSphereClientgraphicallydepictsserversideobjects. TheVMwarevSpheremanagementframeworkusestheconceptofaninventorytokeeptrackofvirtual infrastructureassets,includingdatacenters,hosts,virtualmachines,storage,networkswitches,andsoon. A VMwarevSphereserverinventoryincludesbothcontainerobjects,suchasfolders,andnoncontainer objects,suchasvirtualmachines.SeeUnderstandingtheInventoryonpage 25formoreinformation. TherootFolderobjectandthedefaultDatacenterobjectarenotdisplayedinthevSphereClient(Figure 21), butthesedoexist.YoucanseethemintheManagedObjectBrowser,forexample.EveryServiceInstance hasarootFolderpropertyconsistingoftherootFolderobject,whichhasareferencetothedefault Datacenter.
VMware, Inc. 15

vSphere Web Services SDK Programming Guide

Figure 2-1. vSphere Client Connected to an ESX/ESXi System

Figure 21andFigure 22highlightsomeofthedifferencesbetweenvCenterServerandESX/ESXi.Figure 21 showshowtheinventoryofanESX/ESXisystemdisplays,intheleftpane. Intermsofmanagementservices,vCenterServerprovidesadditionalservicecapabilitiesandadministrative functions.Forexample,vCenterServersupportsScheduledTasks,Events,andMaps(notetheseiconsinthe menubarofFigure 22),whileESXorESXidoesnot(seethemenubaroftheESXinstanceshownin Figure 22). Figure 2-2. vSphere Client Connected to a vCenter Server System

TheinventoryasdisplayedinthevSphereClientisrenderedfromthecontentoftheserversideobjectsatany givenpointintime.TheinventoryshowninFigure 22andFigure 21consistsofasingledatacenterwiththree differentvirtualmachines.Thesesameobjectsandservicescanbeseen,renderedasHTMLpages,inthe ManagedObjectBrowser.TheManagedObjectBrowserprovidesalowerlevelviewoftheactualserverside objectsthatmakeupthecomponentsthatdisplayinthevSphereClient.

Using the Managed Object Browser to Explore the Object Model


TheManagedObjectBrowser,orMOB,isawebbasedserverapplicationavailableonallESX/ESXiand vCenterServersystems.UsetheMOBtolookattheobjectsthatexistontheserverandnavigatethroughthe hierarchyofinstantiatedobjectsbyclickingonhyperlinksthatarepopulatedwithactualruntimeinformation. Youcanviewthenamesofproperties,forexample. CAUTIONDespitethewordbrowserinitsname,theMOBisnotareadonlymechanism.TheMOBisa powerfultoolthatcanbeusedtomakechangestotheserver,byclickingtheInvokeMethodlinkassociated withmethodsavailableonanymanagedobjectpage.WheneveryouexploreaVMwarevSphereserverusing theMOB,beawareofitscapabilitiessothatyoudontmakeunintendedchangestotheserver.

16

VMware, Inc.

Chapter 2 vSphere Object Model

Accessing the MOB


TheMOBrunsinawebbrowserandisaccessedbyusingthefullyqualifieddomainnameorIPaddressfor theESX/ESXiorvCenterServer. To access the managed object browser (MOB) 1 2 LaunchaWebbrowser,suchasFirefoxorInternetExplorer. Enterthefullyqualifieddomainname(ortheIPaddress)fortheESX/ESXihostorvCenterServersystem:
https://<hostname.yourcompany.com>/mob

Youllbenotifiedthattheobjectbrowserrequiresausernameandpassword,withapromptrequiringa usernameandpassword. 3 Entertheuseraccountandpasswordfortheserversystem.Typically,thisisroot/<password>forthe ESX/ESXisystem,andAdministrator/<password>forvCenterServersystem. SomepreliminarywarningmessagesregardingtheauthorityoftheSSLcertificate,suchasWebsite Certified by an Unknown Authoritymightdisplayassumingthatthedefaultservercertificate providedbyVMwarehasnotbeenreplaced.Thespecificmessagetextvariesbywebbrowser. DisregardsuchwarningsandcontinuetologintotheMOB,aslongasVMwareisthecertificateauthority. IMPORTANTIftheESX/ESXiorvCenterServersystemhasbeenconfiguredtosupportregularHTTP (nonSSL)connections,apromptforusernameandpassworddoesnotdisplay,nordoany SSLcertificaterelatedwarnings. UnlikewiththevSphereClient,theMOBrevealstheunderlyingstructuresoftheVMwarevSphere managementobjectmodel,whichcanbeveryusefultodeveloperstryingtounderstandtheobjectmodel. UsedinconjunctionwiththevSphereAPIReference,theMOBcanhelpyougainafairlycomplete understandingofthemodel.

Navigating the Object Model in the MOB


UponsuccessfulconnectiontotheMOB,thebrowserdisplaysthemanagedobjectreferencefortheservice instance(Figure 23).Clientapplicationsdonotusemanagedobjectsdirectly.Rather,clientapplications interactwithserversidemanagedobjectsbyreference,usinginstancesoftheManagedObjectReferencedata object,thedatastructurecreatedforthispurpose.Invokingoperationsontheservertypicallyrequiresoneor morereferencestoamanagedobject. Forexample,thetitleofthepageshowninFigure 23identifiestheobjectasamanagedobjectreferencetothe ServiceInstance.ThepagealsoliststhepropertiesandmethodsavailablethroughServiceInstance. Figure 2-3. Managed Object Browser Connected to a vCenter Server System

VMware, Inc.

17

vSphere Web Services SDK Programming Guide

AlthoughServiceInstancehasonlyafewmethodsandproperties(Table 21),theseultimatelyprovide accesstotheentiresetofservicesandinventoryobjectsavailableontheserver. ClientapplicationsmustalwaysobtainareferencetotheserversServiceInstanceobjectfromthe appropriateVMwarevSphere(ESX,ESXi,orvCenterServer)target. Table 2-1. ServiceInstance Properties


Property capability Datatype Capabilitydataobject Description AninstanceofaCapabilitydataobject.ACapabilitydataobject consistsofseveralflagsthatindicatesupportorlackofsupportfor featuresontheserverinstance.Forexample,multiHostSupported capabilityistrueforvCenterServerbutfalseforESX.A provisioningSupportedflagthatreturnstrueenablesactions,such ascloningavirtualmachine.Somecapabilitiesareversionspecific. AninstanceofaServiceContentdataobject.AServiceContentdata objectcontainsreferences(managedobjectreferences)toalltheservice interfacesavailabletothespecificServiceInstance,suchasthe sessionmanager(sessionManagerproperty)andtherootfolderofthe inventory(rootFolderproperty). Serverdateandtime.

content

ServiceContentdataobject

serverClock

xsd:dateTime

YoucanusetheMOBtodirectlyexaminetherelationshipsamongobjectsbylookingatthepropertiesandtheir valuesandthenclickingthelink,ifoneisavailable,inthevaluecolumnofthepage.Forexample,tofindout moreaboutServiceContent,clickonthecontentlinktodisplaytheServiceContentdataobjectinstance (Figure 24). FromtheServiceContentpage,youcanclickonthelinksintheValuecolumntodisplaythecontentsofthe associatedobjects.Forexample,clickontheaboutlinktodisplaythecurrentvalueoftheaboutproperty, whichdisplaysthecontentoftheAboutInfodataobjectforthisserver.However,mostobjectscontainmany otherobjectsandnestedobjects. AccesstotheinventorybeginsfromtherootFolderpropertyofServiceContent.(Theinventoryiscovered inmoredetailinChapter 3,UnderstandingtheInventory,onpage 25.)

Understanding the ServiceContent Data Object


Insimpleterms,ServiceContentisalargegrainedserverobjectthatprovidesaccesstotheserviceinterfaces andtheinventorysupportedbytheserver.ServiceContentisadataobjectwhosepropertiesincludemany managedobjectreferences(instancesofManagedObjectReference)thatpointtospecificinstancesof managedobjects(Figure 24). Forexample,therootFolderpropertyisaManagedObjectReferencetoaninstanceofaFoldermanaged object.TheperfManagerisaManagedObjectReferencetoaspecificinstanceofaPerformanceManager managedobject,andsoon.

18

VMware, Inc.

Chapter 2 vSphere Object Model

Figure 24showsapartialServiceContentdataobjectdisplayedintheMOBofavCenterServer4.0system. Figure 2-4. ServiceContent Data Object Contains References to Instances of Managed Objects

Table 22summarizestheServiceContentpropertynamesandvaluesforanexampleESXandvCenter Serversystem,sidebyside,asdisplayedintheMOB.TheexamplevalueslistedinTable 22aretheinstance namesfortheobjects.ThepropertiesthatdisplayanUnsetvalueindicatethatthemanagedobjecttypeisnot availableontheserver. Forexample,thepropertyforaccountManagerwhichhasareferencetoasingleton HostLocalAccountManagerobjectonESXsystemshasnovalueonvCenterServersystems,becausevCenter ServerusesWindowsuseraccountmanagementfacilities(suchasActiveDirectory). Conversely,thepropertyforalarmManageronESXisunset,becausealarmsarenotsupportedonan unmanagedhost.TheAlarminfrastructureismanagedbyvCenterServer.Manyothermanagedobjecttypes requirevCenterServer,includingthese: ClusterProfileManager DistributedVirtualSwitchManager ExtensionManager HostProfileManager HostSnmpSystem IpPoolManager LocalizationManager OvfManager ProfileComplianceManager ScheduledTaskManager VirtualMachineCompatibilityChecker VirtualMachineProvisioningChecker

VMware, Inc.

19

vSphere Web Services SDK Programming Guide

Table 2-2. ServiceContent Property Names, Return Types, and Values


Example values Property name about accountManager alarmManager authorizationManager clusterProfileManager complianceManager customFieldsManager customizationSpecManager diagnosticManager dvSwitchManager Type AboutInfo ManagedObjectReference: HostLocalAccountManager ManagedObjectReference: AlarmManager ManagedObjectReference: AuthorizationManager ManagedObjectReference: ClusterProfileManager ManagedObjectReference: ProfileComplianceManager ManagedObjectReference: CustomFieldsManager ManagedObjectReference: CustomizationSpecManager ManagedObjectReference: DiagnosticManager ManagedObjectReference: DistributedVirtualSwitchMa nager ManagedObjectReference: EventManager ManagedObjectReference: ExtensionManager ManagedObjectReference: FileManager ManagedObjectReference: HostProfileManager ManagedObjectReference: IpPoolManager ManagedObjectReference: LicenseManager ManagedObjectReference: LocalizationManager ManagedObjectReference: OvfManager ManagedObjectReference: PerformanceManager ManagedObjectReference: PropertyCollector ManagedObjectReference: Folder ManagedObjectReference: ScheduledTaskManager ManagedObjectReference: SearchIndex ManagedObjectReference: SessionManager ESX about halocalacctmgr Unset haauthmgr Unset Unset Unset Unset hadiagnosticmgr Unset vCenter Server about Unset AlarmManager AuthorizationManager ClusterProfileManager MoComplianceManager CustomFieldsManager CustomizationSpecManager DiagMgr DVSManager

eventManager extensionManager fileManager hostProfileManager ipPoolManager licenseManager localizationManager ovfManager perfManager propertyCollector rootFolder scheduledTaskManager searchIndex sessionManager

haeventmgr Unset hanfcfilemanager Unset Unset halicensemanager Unset Unset haperfmgr hapropertycollector hafolderroot Unset hasearchindex hasessionmgr

EventManager ExtensionManager FileManager HostProfileManager IpPoolManager LicenseManager LocalizationManager OvfManager PerfMgr propertyCollector groupd1 ScheduledTaskManager SearchIndex SessionManager

20

VMware, Inc.

Chapter 2 vSphere Object Model

Table 2-2. ServiceContent Property Names, Return Types, and Values (Continued)
Example values Property name setting snmpSystem taskManager userDirectory viewManager virtualDiskManager vmCompatibilityChecker Type ManagedObjectReference: OptionManager ManagedObjectReference: HostSnmpSystem ManagedObjectReference: TaskManager ManagedObjectReference: UserDirectory ManagedObjectReference: ViewManager ManagedObjectReference: VirtualDiskManager ManagedObjectReference: VirtualMachineCompatibilit yChecker ManagedObjectReference: VirtualMachineProvisioning Checker ESX HostAgentSettings Unset hataskmgr hauserdirectory ViewManager havdiskmanager Unset vCenter Server VpxSettings SnmpSystem TaskManager UserDirectory ViewManager VirtualDiskManager CompatChecker

vmProvisioningChecker

Unset

ProvChecker

Understanding the Object Model as Data Structures


ThevSphereobjectmodelcanalsobeviewedfromadatastructuresperspective.TheVMwarevSphere managementobjectmodelcomprisestwobroadcategoriesofdatastructures: Managedobjecttypes.Amanagedobjecttypeisadatastructurethatcontainsbothpropertiesand operations.Theoperationssupportspecific,expectedbehaviorsthatadheretoacontract.Forexample,a VirtualMachinemanagedobjecttypesupportsvirtualmachinepoweroffandpoweron,recordingall virtualmachineoperations,andmanyoperationsthatcontroltheguestoperatingsystemrunningona virtualmachine,suchasrebootingtheguest.Thesearejustsomeexamples:theVirtualMachine managedobjecttypeprovidescloseto50operations.SeeChapter 10,WorkingwithVirtualMachines, onpage 93andChapter 13,UsingvCenterServerforVirtualMachineOperations,onpage 119. Dataobjecttypes.Adataobjectisadatastructurethatcontainspropertiesonly.Instancesofdataobjects donotprovideanyoperations.Dataobjectsareanalogoustostructures(struct)inC,C++,andseveral otherprogramminglanguages,orabstractdatatypes(classdefinition)inJava.Javadoesnotusethe conceptofastruct,butratherusesclassdeclarationstodefineabstractdatatypes. Thepropertiesofthemanagedobjecttypesaredefinedasprimitivedatatypes,suchasstringorint,oras specifictypesofdataobjects.Likewise,propertiesofdataobjectsaredefinedasprimitivevaluesorasspecific instancesofotherdataobjects. NOTEAlthoughmanymanagedobjecttypeshavewordslikesystemormanagerintheirnames,somedata objecttypesdoaswell.Forexample,theHostConfigManagerisadataobjecttype.AlwayscheckthevSphere APIReferencefordetailsaboutdataobjectandmanagedobjecttypes.

Understanding the Unified Modeling Language Used in this Guide


Figure 25showstheunifiedmodelinglanguage(UML)notationusedtodepictthetwoprimarytypesofdata structuresrepresentedinthisguide:managedobjecttypes,anddataobjecttypes.Thediagramsuseatildeto denoteabsenceofanypropertiesormethods(operations).Ellipsesareusedtodenoteadditionalcontent deliberatelynotshown.

VMware, Inc.

21

vSphere Web Services SDK Programming Guide

Figure 2-5. Legend for UML Class Diagrams

NOTEThefiguresshowninthisguidehighlightvariouscharacteristicsoftheobjectmodelusingUML diagrams.Forthesakeofsimplicity,thesediagramsdonotincludecompletedetails.Forexample,alldata objecttypesextendtheDynamicDatadataobject.However,thebasepropertiesofDynamicDataarerarely relevantforthetopic,sothatobjectrelationshipistypicallynotshown. Inadditiontoclassdiagrams,thisguidealsoincludesseveralinstancediagrams,especiallyinthosesections thatdiscussnavigatingtheinventory,whichisbestexplainedinthecontextofactualobjectinstances.Many detailsareleftoutoftheinstancediagramsaswell. Thisguideusesthesetermsandabbreviationsinfiguresandtext. MOR.Managedobjectreference.Anopaquedataobjectthatisusedasaremotereferencetomanaged objects.Managedobjectreferencesarealsocalledreferencesintext,andmo_reforMoRefincodesamples. MOR>ManagedObjectType.Amanagedobjectreferenceidentifiesaspecificinstanceofaspecifictypeof managedobject,onaVMwarevSphereserver.TheabbreviationMOR>ManagedObjectspecifiesthetype ofmanagedobjectinstancetowhichagivenMORrefers.Thisnotationisusedthroughoutthisguideto replacethewordstoa,asinMORtoaVirtualMachine,orMORtoaHostDatastoreSystem.

The Managed Object Type as Data Structure and Service Interface


Amanagedobjecttypeisacoredatastructureoftheserversideobjectmodel.Itisanyoneofabout60 serversidedatastructureshavingpropertiesandoperationsavailableontheserver.Differentmanaged objectsofferdifferentoperations.AnoperationisWebservicesterminologyforwhatmightbecalledamethod inanotherprogramminglanguage,suchasJava.Thewordsmethodandoperationareusedinterchangeably inthedocumentation. Instancesofmanagedobjecttypesareoftenreferredtogenericallyasmanagedobjectsthroughoutthis guide.However,managedobjectsincludethefollowingbroadcategories: ManagedobjectsthatextendtheManagedEntitymanagedobjecttype.Thesemanagedobjecttypesare referredtogenericallyasmanagedentities.Managedentitiesmakeuptheinventoryofvirtual components.Forexample,instancesofhostsystems(HostSystem),virtualmachines(VirtualMachine), anddatastores(Datastore)areinventoriedobjectsandextendthemanagedentity(ManagedEntity) type.InventoriedobjectsdisplayintheleftpaneofthevSphereClient. ManagedobjectsthatcomprisetheinterfacetoavSpheremanagementservice.Forexample, PerformanceManagerprovidestheinterfaceformonitoringsystemperformance. DistributedVirtualSwitchManagerprovidestheinterfaceformanaging DistributedVirtualSwitchmanagedobjects.AlarmManageristheserviceinterfaceforsettingalarms torespondtovariouseventsorstatechangesonspecificmanagedentities. Managedobjectswhoselifecycledependsuponorexistssolelyinthecontextofanothermanagedobject typeorserviceinterface.Forexample,instancesofTaskmanagedobjectsarereturnedbymethod invocationsonmostallmanagedobjectsinthesystem.PropertyFilterisamanagedobjecttype associatedwithaninstanceofPropertyCollector.HostNetworkSystemmanagedobjectsare associatedwithspecificinstancesofHostSystemmanagedobjects.Thesearejustafewexamples.

22

VMware, Inc.

Chapter 2 vSphere Object Model

ServiceInstance Managed Object as Starting Point to Other Service Interfaces


ThechiefmanagedobjectintheserviceinterfacecategoryisServiceInstance,whichistheentrypointfor allotherserviceinterfacesandinventoryobjects.Allinteractionwiththeserverbeginsthrough ServiceInstance.AServiceInstancehasonlyafewpropertiesandmethods.Thecontentpropertyis definedasaninstanceofServiceContent,whichisadataobjectcontainingreferencestoallavailableservice interfacesontheserverinstance. Figure 26highlightstherelationshipbetweenServiceInstanceandServiceContent,andtherelationship betweenServiceContentandsomeofthemanagedobjectreferences(MOR)tomanagementservices.Some services,suchasAlarmManager,aresupportedonvCenterServeronly,notonunmanagedhosts.Other services,suchasHostLocalAccountManager,aresupportedonESXorESXisystemsonly,notonvCenter Server.Figure 26isnottheentiresetofservicesavailable.VMwarevSphereAPI4.0providesaccesstoalmost 60managementservices. Figure 2-6. Simplified UML of ServiceInstance Managed Object and ServiceContent Data Object

Figure 27showsamoredetailedUMLdiagramofServiceInstanceandServiceContent. ServiceContent,Capability,andAboutInfoarealldataobjects,denotedbythetildeinsectionoftheclass definitionwhereoperations(methods)aredepictedformanagedobjects.

VMware, Inc.

23

vSphere Web Services SDK Programming Guide

Figure 2-7. The ServiceInstance Managed Object Type and Some of Its Properties

References to Managed Objects


Theclientapplicationdevelopmentmodelinvolvesworkingdirectlywithdataobjectsonly.Managedobjects areneverpassedbetweenserverandclient.Clientapplicationsusereferencestothemanagedobject,orwith thedataobjectsthatcomprisethevariouspropertiesofthemanagedobject.Somereferencescanbeobtained throughthepropertiesoftheServiceContentdataobject. Thereferenceisaninstanceofaspecificdataobjecttype,theManagedObjectReference.Instancesofthis dataobjecttypefacilitateremoteinvocationofoperationsonthemanagedobjectslocatedontheserver. InstancesofManagedObjectReferencedataobjectsaresentbetweenclientandserver. Tocreateaninstanceofaspecificmanagedentity,youmustpopulateoneormoredataobjectsandpassthe dataobjectstotheserverwiththeappropriatereference(ManagedObjectReference)toinvoketheoperation ontheserver. NOTEThroughoutthisguide,managedobjectreferencesarereferredtoasreferences.Codesamplesmight useMoRef,mo_ref,orMORasavariablenameforspecificinstancesoftheManagedObjectReferencedata object.Intext,amanagedobjectreferenceorreferencemeansaspecificinstanceofthe ManagedObjectReferencedataobjecttype.

24

VMware, Inc.

Understanding the Inventory

ThevSphereinventorycontainsvirtualassets,includingdatacenters,hosts,virtualmachines,virtual applications,storage,networks,andsoon.AdministratorscanviewtheinventoryusingthevSphereClient. ThevSphereClientobtainsinformationaboutalltheobjectsintheinventoryofaserverandrendersthe informationintheGUI. Developerswhowanttocreateclientapplicationsmustunderstandthecomponentsthatmakeupthe inventory.Youmustunderstandtherelationshipofoneobjecttoanotherintheinventory,withrespecttothe theparentchildrelationshipsamonginventoryobjectsandthepermissionsmodel,amongotherdetails. This chaptercoversthebasics.Itincludesthesetopics: OverviewofManagedEntitiesonpage 25 UnderstandingContainerObjectsandtheInventoryonpage 26 InventoryObjectsandPrivilegesonpage 28 vCenterServerandUnmanagedESX/ESXiHostInventoriesonpage 30

Overview of Managed Entities


IntermsofthevSphereobjectmodel,thecomponentsthatmakeupaninventorybelongtotheclassofobjects generallycalledmanagedentities.Amanagedentityisanyofthedozenmanagedobjecttypesthatextend directlyorindirectlyfromtheManagedEntitymanagedobjecttype.Managedentitiesinclude VirtualMachine,Datacenter,Datastore,Network,ResourcePool,ComputeResource,HostSystem, VirtualAppandtheothermanagedobjecttypesshowninFigure 31. Figure 3-1. ManagedEntity and ManagedEntity Subtypes

TheManagedEntitymanagedobjecttypeisanabstracttype.Itincludesseveralpropertiesandoperationsthat areinheritedbyeachsubtype.

VMware, Inc.

25

vSphere Web Services SDK Programming Guide

Forexample,thename,effectiveRole,permission,andparentaresomeofthepropertiesdefinedinthe ManagedEntitybasetypethatareinheritedbyeachsubtype.Lifecycleoperationsfortheobject,suchas destroyinganobjectinstance,arealsopartoftheManagedEntitybasetype. Figure 3-2. Datacenter and Folder Managed Object Types Extend ManagedEntity

InadditiontothepropertiesandoperationsinheritedfromManagedEntity,eachsubtypehasitsown propertiesandspecialpurposeoperationsthatmodelitsexpectedbehavior.Forexample,aHostSystem managedobjecthasanEnterMaintenanceMode_Taskoperation.Theothermanagedentitiesdonot. Instancesofspecificmanagedentitiesarecreatedbyadministratorsusingvarioustools,includingvSphere Client.Somemanagedentitiesarecreatedwhentheserversoftwareisfirstinstalled.Forexample,a HostSystemmanagedentityexistsintheinventoryofanewlyinstalledESX/ESXisystem.Itisnotexplicitly created.TheHostSystemmanagedentitycontainsthephysicalcharacteristicsofanESX/ESXihostsystem. ThedataobjectsthatmakeupthepropertiesofaHostSystemmanagedentitycontainthespecificproperties oftheunderlyinghardwareanditscapabilities.Forexample,thevaluesofthecapabilitypropertyof HostSystemaresetduringinstallation,basedonthespecificsofthehardwareonwhichESX/ESXiisinstalled. AllotherentitiesinaninventoryareexplicitlycreatedusingthevSphereClientorotherclienttools,orby usingtheAPI.Theentitiesthatcancompriseanyspecificinventoryareconstrainedbythephysicalresources ofthehardwareandtherulesofcontainment,ownership,andotherpropertiesofthemanagedentitytypes andsubtypes.

Understanding Container Objects and the Inventory


ThevSphereobjectmodelincludesseveralobjectsthatservespecificpurposes,includinginventory organization,applicationpackaging,delegatedadministration,andresourceallocation.Someobjectsareused toorganizetheinventoryandestablishassociationsamongtheentitiesintheinventory.Forexample,Folder, Datacenter,andVirtualApparegenerallycalledcontainerobjecttypes. VirtualAppisanewmanagedentitytypeinvSphereAPI4.0designedforapplicationpackaging. VirtualAppextendstheResourcePooltypewithadditionalpropertiesandoperationstosupportproduct andvendornaming,licensing,powercyclingtheapplication,andimportexportcapabilities.VirtualApp instancesareexportedandimportedtheindustrystandardOVF(openvirtualformat)files.AVirtualApp consistsofthevirtualmachinesandotherVirtualAppcontainersthatoperateasaunit.UnmanagedESX/ESXi hostsystemsdonotsupportVirtualApp. SeethevSphereAPIReferenceformoreinformationaboutVirtualApp.

26

VMware, Inc.

Chapter 3 Understanding the Inventory

Folder as Container
TheFoldermanagedobjecttypeisthechiefcontainerobjectinaninventory.Containmentisconceptual,not literal,andreliesontheparentchildrelationshipamongtheobjectsasdefinedincertainpropertiesofactual instances.Specifically,everymanagedentityhasaparentpropertythatcanbeusedtoidentifyitsrelative positionintheinventoryhierarchy.Inaddition,theFoldermanagedobjecttypehasachildEntityproperty thatidentifiesobjectscontainedbythespecificfolderinstance. Figure 33showsaninstancediagramhighlightingthechildEntityandfolderpropertiesthatdefinethe defaultobjectsintheinventoryofanunmanagedESX/ESXisystem.Theinventorybeginsfromthe rootFolderpropertyoftheServiceContentdataobject.TherootFolderistherootnodeoftheinventory. IthasachildEntitythatconsistsofamanagedobjectreferencetoaDatacentermanagedobject. Figure 3-3. Instance Diagram of Root Folders in an Inventory

ChildentitiesareidentifiedthroughtheirchildEntityproperty,throughaparentproperty,orthrougha specificfolderreferenceinthecontainingobject. Figure 3-4. Parent-Child Associations Among Inventory Objects

VMware, Inc.

27

vSphere Web Services SDK Programming Guide

Forexample,everyDatacenterobjectinaninventoryisguaranteedtohavefourspecificFolderobjects associatedwithit,oneeachfordatastores,networks,hosts,andvirtualmachines.ThefoldersforDatastore objectsandNetworkobjectsarenewasofvSphereAPI4.0.Thesefoldersareassociatedwiththe datastoreFolderandthenetworkFolderpropertiesofaDatacentermanagedobject(seealsoFigure 32 onpage 26). TheinventoryhierarchyshowninFigure 34,ParentChildAssociationsAmongInventoryObjects,on page 27includestherootfolderobject,aFolderobjectnamedha-root-folderhasachildEntitythatisa referencetoaDatacenter.TheVirtualMachineinstancewhoseIDis32isthechildEntityoftheFolder identifiedasha-folder-vm. Variousothernodesinthehierarchyarecalledrootnodesfortheirtypeofobject.Forexample,the ha-folder-datastore,ha-folder-host,ha-folder-network,andha-folder-vmareconsideredtheroot foldersforthetypeofentitiesthateachcontains.

Inventory Objects and Privileges


WhetherthroughthevSphereClientorbyusingtheAPI,navigatingtheentitiesintheinventoryrequiresa useraccountthatcanconnecttotheserverandobtainavalidsession.Theuseridentityassociatedwiththe sessioniscalledaprincipal.Whenaclientapplicationattemptstoaccessobjectsinaninventory,itdoesso usingtheprivilegesgrantedtoaspecificrolethatisassociatedwiththeprincipal.Theserverchecksthe permissionobjectorobjectsassociatedwiththeentitybeforeallowingaprincipaltovieworoperateonan entity. SeeChapter 4,OverviewofUserModelsandServerAccessControlConcepts,onpage 33formore informationaboutauthentication,authorization,roles,anduseridentity. Forinventorynavigation,itisimportanttounderstandtheaffectofparentchildrelationshipsamong inventoryentitiesandhowprivilegerequirementsmightapplytotheobject. Toviewcertainpropertiesortoinvokecertainoperationsonmanagedobjects,aprincipalmusthavethe appropriateprivileges.AprivilegeisasystemdefinedrequirementassociatedwithaVMwarevSphere managementobject.PrivilegesaredefinedbyVMware.Privilegesarestatic,anddonotchangeforasingle versionofaproduct.Table 31showstheformatinwhichprivilegesarespecifiedforVMwarevSphere components. Table 3-1. Privilege Definition Format and Examples
Format Datacenter.Create <group>[.<group>].privilege Datacenter.Delete Datacenter.Move Examples Host.Config.Connection Host.Config.Memory Host.Config.Snmp

SomeprivilegesarespecifictoobjectsonvCenterServerorESX/ESXionly.Forexample,theAlarm.Create privilegeisassociatedwithAlarmManager,whichistheserviceinterfaceforcreatingandmanagingalarms thatisavailablethroughvCenterServersystemsonly. Completeinformationaboutrequiredprivilegesfortheoperationsofamanagedentityisavailableinthe vSphereAPIReference. ToviewanypropertyofamanagedentitytypicallyrequirestheSystem.Viewprivilegeontherootfolderof theinventoryandtheSystem.Read privilegeonthespecificFolderandVirtualMachineobjects. Forexample,creatingavirtualmachinerequiresthattheprincipalassociatedwiththesessionhavethe followingprivileges: TheVirtualMachine.Inventory.Createprivilegeonthefolderinwhichtocreatethevirtualmachine TheResource.AssignVMToPoolprivilegeontheresourcepoolfromwhichthevirtualmachineobtains itsallocationofCPUandmemoryresources.

28

VMware, Inc.

Chapter 3 Understanding the Inventory

ToreadtheperfCounterpropertyofthePerformanceManagermanagedobject,ausermusthavethe System.View privilegeontherootfolder. Achildentitytypicallyinheritsthepermissionsofitsparent.Ifyousetthepermissiononaparentobjectand setitspropagatepropertytotrue,thechildentitiesaccruethesamepermissionsettingastheparent.However, youcansetapermissiondirectlyonachildentitythatisdifferentthanitsparent. TheAuthorizationManagerserviceinterfaceprovidesoperationsforqueryingandsettingpermissions.See Chapter 4,OverviewofUserModelsandServerAccessControlConcepts,onpage 33formoreinformation aboutAuthorizationManager. Figure 3-5. A ManagedEntity Has One or More Permission Objects

ThePermissiondataobjectappliestothechildEntityassociatedwiththemanagedentitywhenthe propagatepropertyofPermissionissettotrue. Soforexample,inFigure 36thehafolderrootobjecthastwopermissionobjectsinthearraythatmakesup itspermissionproperty.Bothpermissionobjectshavetheirpropagateflagsettotrue.ThechildEntityof ha-folder-rootisha-datacenter,soha-datacenterinheritsthepermissionsofha-folder-root. AssigningpermissionstotheDatacenternodeandsettingthePermissionobjectspropagateflagsettotrue effectivelygrantspermissionattheDatacenterlevelandallchildentitiesthathaveaspecificDatacenter objectastheirparent. Figure 3-6. Inventory and Permissions

VMware, Inc.

29

vSphere Web Services SDK Programming Guide

Figure 36showsthatusersrootandvpxuserbothhavepermissionsontherootFolderoftheinventory. The vpxuseristheaccountcreatedonthehostbythevCenterServersystemwhenthehostisaddedtothe vCenterServer.ThevCenterServerneedsaccesstotheinventoryobjectsofthehostsystemsthatitmanages, sothevpxuseraccountisgrantedprivilegestotherootFolderofeachhost. Forexample,toinvoketheDestroy_Taskoperationonaspecificdatacenterinstancerequirestheusertohave theDatacenter.DeleteprivilegeonthedatacenterandontheparentFoldercontainingtheDatacenter.

Folder as Factory
TheFoldermanagedentityisafactoryobject.Itprovidesoperationsforcreatinginstancesofothermanaged entities,includingthefollowingtypes: Datacenters Distributedvirtualswitches Virtualmachines Clusters Folders ForanunmanagedESX/ESXisystem,theFoldermanagedentitydoesnotsupportcreatingadditionalFolder objectsorDatacenterobjects.

vCenter Server and Unmanaged ESX/ESXi Host Inventories


TheinventoryofavCenterServersystemsupportsmultipleESX/ESXihosts.ThehostsareaddedtoavCenter ServerusingthevSphereClient,orprogrammaticallybyusingtheAPI.AddingahosttoavCenterServer systemaddsthehosttotheinventoryofthevCenterServer,afterwhichitbecomesamanagedhost.Youcan configuretwoormoreofhostsinavCenterServersystemintoclusters. Theinventoryofanunmanagedhostcansupportmultiplevirtualmachinesandmultipleresourcepools,but itcontainsasingledefaultdatacenterandasinglerootfolder.Thedefaultdatacenterandrootfolderarenot visibleinthevSphereClient,buttheyexistintheinventoryofanunmanagedhostandtheyarevisibleinthe MOB.TherootFolderisapropertyavailableintheServiceContentdataobject,andthedefaultdatacenter isactuallythechildEntityassociatedwiththerootfolder,asshowninFigure 33,InstanceDiagramofRoot FoldersinanInventory,onpage 27. Youmustaccountfortheseobjectswhenyounavigatetheinventoryprogrammatically,suchaswhenyouuse aPropertyCollectorinyourcode.Table 32summarizesthedifferencesbetweenthenumberofobjectsthat aninventorycancontain. Table 3-2. Comparison of Unmanaged ESX/ESXi and vCenter Server Inventories
ManagedEntity Subtype ClusterComputeResource ComputeResource Description AbstractsmultipleHostSystemobjects intoaunifiedcomputeresource. Abstractsthephysicalresourcesofahost systemandenablesthemtobe associatedwiththevirtualmachinesthat runonthehost. Containerobjectforestablishing associationsamongmanagedentities, includingfolders,virtualmachines,host systems. Logicalstoragevolumesonwhichto storevirtualmachinefiles. InterfaceforDistributedVirtualSwitch (vNetworkDistributedSwitch). ESX/ESXi Inventory None. Exactlyoneonly. vCenter Server Inventory Multipleinstances supported. Multipleinstances supported.

Datacenter

Exactlyoneonly. Cannotbe destroyed. Transparent. Multipleinstances supported. Multipleinstances supported.

Multipleinstances supported.

Datastore DistributedVirtualSwitch

Multipleinstances supported. Multipleinstances supported.

30

VMware, Inc.

Chapter 3 Understanding the Inventory

Table 3-2. Comparison of Unmanaged ESX/ESXi and vCenter Server Inventories (Continued)
ManagedEntity Subtype Folder Description Containerobjectusedtoorganizevirtual machinesandhostsinaninventory. ESX/ESXi Inventory Exactlyoneonly. Cannotbe destroyed. Transparent. Exactlyoneonly. Multipleinstances supported. Multipleinstances supported. None. vCenter Server Inventory Multipleinstances supported.

HostSystem Network ResourcePool

Abstractionforasinglephysical machine. Abstractionforaphysicaloravirtual network(VLAN). Abstractionforphysicalresourcesthat canpartitionedintosmallerunitsforuse byvirtualmachines. Containerobjectforoneormorevirtual machinesandassociatedobjects packagedusingopenvirtualformat (OVF)1.0. Abstractionforavirtualmachine.

Multipleinstances supported. Multipleinstances supported. Multipleinstances supported. Multipleinstances supported.

VirtualApp

VirtualMachine

Multipleinstances supported.

Multipleinstances supported.

VMware, Inc.

31

vSphere Web Services SDK Programming Guide

32

VMware, Inc.

Overview of User Models and Server Access Control Concepts

VMwarevSphereimplementsmechanismstoensurethatonlyvaliduserscanaccessvirtualinfrastructure components.TheusermodelforESX/ESXisystemsisdifferentthantheusermodelforvCenterServer systems.Thischapterdiscussestheseusermodelsandthemanagedobjects(serviceinterfaces)thatprovide variousmechanismstosecurethesystem.Itincludesthesetopics: IntroductiontoAuthenticationandAuthorizationonpage 33 OverviewofESX/ESXiUserModelonpage 35 OverviewofvCenterServerUserModelonpage 36 ObtainingInformationaboutUsersandGroupsfromUserDirectoryonpage 37 AuthenticatingUsersthroughSessionManageronpage 39 OverviewoftheAuthorizationManageronpage 39 GrantingPrivilegesthroughPermissionsonpage 42

Introduction to Authentication and Authorization


Severalserversidemechanismsinteractivelyauthenticateahumanuserwhenaclientapplication,suchasthe vSphereClientoracustomapplicationdevelopedusingthevSphereWebServicesSDK,connectstotheserver. TheVMwarevSphereinterfacesforauthenticatingusersandprotectingvirtualinfrastructurefrom unauthorizedaccessinclude: HostLocalAccountManagerisusedtocreateandmanageuseraccountsandgroupsonESX/ESXi systems.Dependingonthepermissionsassociatedwiththerolesassignedtotheuseraccountsorgroups, authenticateduserscanviewobjectsorinvokeoperationsontheserver.SeeOverviewofESX/ESXiUser Modelonpage 35formoreinformationabouttheHostLocalAccountManager. SessionManagerprovidesaninterfacetotheserverauthenticationinfrastructureonthetargetserver system. ForvCenterServersystems,SessionManagersupportsintegrationwithMicrosoftSSPI(Security ServiceProviderInterface),whichenablessinglesignonusingMicrosoftWindowslocalaccountsor ActiveDirectory. ForESX/ESXisystems,SessionManagersupportsauthenticatinguseraccountsasdefinedonthe hostsystem,suchasaccountscreatedusingvSphereClientorthosecreatedprogrammatically throughtheHostLocalAccountManagerAPI.

VMware, Inc.

33

vSphere Web Services SDK Programming Guide

AuthorizationManagerprotectsVMwarevSpherecomponentsfromunauthorizedaccess.Accessto componentsisrolebased:Usersandgroupsareassignedrolesthatencompasstheprivilegesneededto performoperationsonsomemanagedentities,ortoviewobjects.AuthorizationManagerhas operationsforcreatingnewroles,modifyinguserroles,settingpermissionsonentities,andhandlingall otheraspectsoftherelationshipmanagedobjectsandthepermissionsgrantedtoprincipals(users, groups)toaccessthem. UserDirectoryprovidesalookupmechanismthatreturnsuseraccountinformationto AuthorizationManagerortoanotherrequestor,suchasaclientapplication.SeeOverviewofESX/ESXi UserModelonpage 35formoreinformationabouttheUserDirectory. TheseservicesworktogethertoensurethatonlyauthenticateduserscanconnecttoESX/ESXiorvCenter Serversystems,andthattheycanaccessonlythoseobjectsfolders,virtualmachines,datacenters,virtual services,andsoonforwhichtheyhavetherequiredprivilegesandareauthorizedtouseortoview. Accessinganobjectmightmeanreadingapropertyvalue,orinvokinganoperation.Inmanycases,the privilegesrequiredtoreadapropertyvaluearelessrestrictivethantheprivilegesrequiredtoperform operations.Forexample,ausermightbeabletoseeavirtualmachineintheinventory,butmightnotbe allowedtocreateanewvirtualmachine.

Understanding System Privileges


AprivilegeisasystemdefinedrequirementassociatedwithaVMwarevSphereobject.Privilegesaredefined byVMware.Privilegesarestatic,anddonotchangeforasingleversionofaproduct.Eachmanagedobjecthas oneormoreprivilegesrequiredonthepartofaprincipal(user,groupmember)toinvokeanoperationorto viewaproperty.Forexample,managedentitiessuchasFolderandVirtualMachinerequiretheprincipalto havetheSystem.Readprivilegeontheentitytoviewthevaluesofitsproperties.

Privileges Defined in the vSphere API Reference


ThevSphereAPIReferenceincludesinformationaboutprivilegesrequiredtoinvokeoperationsandtoview properties.Inthedocumentationpageofthespecificmanagedobject,lookfortheRequiredPrivilegeslabel tofindoutaboutspecificprivileges,ifany,requiredtoviewthepropertyorinvoketheoperation.Table 41 showstheformatusedtospecifyprivileges. Table 4-1. Privilege Specification Format and Examples
Format Datacenter.Create <group>[.<group>].privilege Datacenter.Delete Datacenter.Move Examples Host.Config.Connection Host.Config.Memory Host.Config.Snmp

AprivilegemightbespecifictovCenterServerortoESX/ESXisystems.Forexample,theAlarm.Create privilegeisdefinedonvCenterServer.SettingalarmsrequiresvCenterServer,whichhasanAlarmManager serviceinterfacethatintegrateswithmanyoftheothermanagementobjectsontheserver. Usersaregrantedprivilegestoobjectsthroughroles.SeeUsingRolestoConsolidateSetsofPrivilegeson page 40formoreinformation.SeeTable A3,PrivilegesGrantedtotheAdministratorRole,onpage 158for acompletelistofprivilegesencompassedbytheAdministratorroleasdefinedonavCenterServer4.0system.

HTTP-Based File Access and Privileges


Privilegerequirementsapplytosystemobjectsregardlessofhowagivenclientapplicationattemptstoaccess servercontent.Forexample,supportforHTTP/HTTPSaccesstothefilescomprisingDatastoreobjectswas addedinESX/ESXi3.5.Filescomprisingtheobjectsthatmakeupvirtualmachinedatastorescanbeaccessed byspecifyingaURLinthisformat:
https://<hostname>/folder[/<path>]/?dcPath=<datacenter_path>[&dsName=<datastore_name>]

34

VMware, Inc.

Chapter 4 Overview of User Models and Server Access Control Concepts

Becausetheobjectsbeingaccessedaredatastoreobjectsintheinventoryandtheseobjectsareassociatedwith aspecificfolderstructure,theprivilegesrequiredtoaccessthesefilesarethesameprivilegesrequiredtoobtain thesefilesusinganyothermechanism,suchasthevSphereClient. Table 4-2. Privileges Required for Datastore Objects Apply Regardless of Access Mechanism
Object associated with file Rootfolder Datacenter Portion of URL /folder ?dcPath Required privileges System.View Datastore.Browse Datastore.FileManagement Datastore &dsName Datastore.Browse Datastore.FileManagement Host /host /tmp/ Host.Config.AdvancedConfig Host.Config.SystemManagement

Overview of ESX/ESXi User Model


Whenusersentertheiruseraccountandcredentialfromaclientapplication,theserverconsultsthe appropriateuseraccountstoreandvalidatestheauthenticityoftheuseraccountandtheassociatedcredential. Currently,thecredentialconsistsofapassword,buttheVMwarevSpherealsosupportscertificates,suchas X.509certificates.Authenticateduserscanthenaccessobjectstheyvebeenauthorizedtouse.Auseridentity mustexistonthetargetsystemorinasupporteddirectoryservice,asauseraccount,tobeauthenticated. ESX/ESXileveragesstandardLinuxinfrastructure,includingtheLinuxpluggableauthenticationmodule(PAM) mechanismforuseraccountcreationandmanagement.TheVMwareauthenticationdaemon(vmwareauthd) isimplementedasaPAMmodule.YoucancreateuseraccountsonanESX/ESXisystemusinganyofthe VMwareclienttools,orusingtheHostLocalAccountManager.

Using HostLocalAccountManager Managed Object


TheHostLocalAccountManagermanagedobjectprovidesoperationsforcreatingusers,creatinggroups, assigninguserstogroups,andotheruserandgroupadministrationtasks.TheHostLocalAccountManager serviceinterfaceisavailablethroughtheWebserviceonESX/ESXionly.vCenterServerusestheWindowsuser managementfacilities.SeeOverviewofvCenterServerUserModelonpage 36fordetails. Figure 4-1. HostLocalAccountManager Managed Object

YoumustdefinetheHostAccountSpecdataobjectusingthecharacteristicsrequiredforthetargetsystem,as configuredbythesystemadministrator.Thesecharacteristicsincludepasswordlengthrequirements,restrict useofdictionarywords,andsoon. Inadditiontocreatinguseraccountsandgroups,HostLocalAccountManagerprovidesseveralother operations: AssignUserToGroup,whichassignsaspecifieduseraccounttoagroup. UnAssignUserFromGroup,whichremovesauserfromagroup.UseRetrieveUserGroupsfirstif necessary,toobtaingroupinformationfortheuseraccount. UpdateUser,whichallowsyoutomodifyinformation,includingpasswordanddescription,foran existinguseraccount.

VMware, Inc.

35

vSphere Web Services SDK Programming Guide

Table 43summarizestheAPIreferencedocumentationfortheseoperations.Forcompleteinformationabout HostLocalAccountManager,seethevSphereAPIReference. Table 4-3. HostLocalAccountManager Operations for User and Group Management
Operation AssignUserToGroup Parameter _this Type MOR > HostLocalAccountManager string Description Referencetothe HostLocalAccountManagerused tomakethecall. UserID(thegeneratednumber fromtheuserstoreofthehost system). Grouptowhichtheuseraccount (userID)isbeingadded. Referencetothe HostLocalAccountManagerused tomakethecall. Nameofuserbeingremovedfrom agroup. Groupfromwhichtoremoveuser. Referencetothe HostLocalAccountManagerused tomakethecall. Dataobjectthatcontains description,useraccountID,anda passwordfortheprincipalbeing updated.

user

group UnAssignUserFromGroup _this

string MOR > HostLocalAccountManager string string MOR > HostLocalAccountManager HostAccountSpecdataobject

user group UpdateUser _this

user

Afteruseraccountsandgroupsonthehostsystem(ESX/ESXi),youcangranttheseusersaccesstovirtual componentsbyusingtheAuthorizationManageroperations.SeeOverviewoftheAuthorizationManager onpage 39formoreinformation.

Overview of vCenter Server User Model


vCenterServerisaWindowsbasedservicethatusesnativeWindowsfacilitiesandusermodelfor identificationandauthentication.TheserviceisassociatedwiththeWindowsuseraccountthatwaslogged ontothemachineforthevCenterServerinstallationprocess.ThisvCenterServeradministratoraccountmust beamemberofthelocalWindowsAdministratorgrouponthemachine.OthervCenterServeruserswho connecttotheWebservicemustalsohaveaWindowsaccountonthelocalAdministratorgroup.Ifyouuse WindowsdomainloginaccountsforvCenterServer,theaccountmustbeamemberofthelocalhostsystem Administratorgroup.VMwarerecommendscreatingaWindowsuseraccountspecificallyforinstallingand managingthevCenterServer. Bydefault,vCenterServerandVirtualCenter2.5canobtainuseraccountinformationfromMicrosoftActive Directory,theuseraccountrepositoryforMicrosoftWindowsdomaincontroller. To create an Administrator account for vCenter Server 1 2 3 4 5 6 LogintotheWindowsserveraslocalAdministrator. CreateauseraccountforvCenterServer. AddtheuseraccounttotheAdministratorgroupofthemachine. LogoutasAdministrator. LogintotheWindowsserveragain,usingthenewaccount. InstallvCenterServer.

Fordetails,seetheBasicSystemAdministrationguideintheVMwarevSpheredocumentationset.

36

VMware, Inc.

Chapter 4 Overview of User Models and Server Access Control Concepts

Enabling Single Sign-on Support and Integration with Microsoft Active Directory
OrganizationsthatareusingMicrosoftActiveDirectorycanleveragetheuseridentitiescontainedina Windows2003ServerdomaincontrollerorActiveDirectoryserviceacrosstheirvirtualinfrastructure,for clientsthatrunvSphereWebServicesSDKclientapplicationsfromWindowsbasedsystems. VMwarevSphereWebServicesSDKclientapplicationscanuseSSPItoauthenticatetothelocalmachineand thenestablisharemoteconnection.SeethevSphereAPIReferenceformoreinformation.

Obtaining Information about Users and Groups from UserDirectory


TheUserDirectorymanagedobjectenablesaclientapplicationtoobtaininformationaboutusersandgroups onaVMwarevSphereserver.Propertiesandresultsvary,dependingonwhethertheserverisavCenterServer oranESX/ESXisystem. Table 4-4. Server Source Data for UserManager
vCenter Server Domaincontroller,ActiveDirectory,orlocalWindows accountrepository ESX, ESXi /etc/passwd

Forexample,vCenterServeruseraccountscanbemanagedinaWindowsActiveDirectoryserverordomain controllerfromwhichthedomainListpropertyofUserDirectoryisderived.ForESX/ESXisystems,the domainListpropertyisempty. Figure 4-2. UserDirectory Managed Object

UserDirectoryprovidestwooperationsforobtaininginformationaboutusersandgroups: RetrieveCertificatePrincipals,whichreturnsanarrayofCertificatePrincipaldataobjects (principalsthatuseX.509certificatesforauthenticationtotheserver,ratherthanapassword). RetrieveUserGroups,whichcanobtainalistofalluseraccountsfromthehost,andcansearchfor specificusersorgroupsbasedonspecificcriteriatofiltertheresults: Byusername Bygroupname Foranexactmatch Forforapartialstring(substring) ForvCenterServer,searchislimitedtothespecifiedWindowsdomain.Ifthedomainisomitted,thesearchis performedonlocalusersandgroups. ForESXsystems,searchreturnsallusersandgroupsfromthepasswdfile.IfthisfilecontainsNetwork InformationSystem(NIS)orNIS+usersandgroups,RetrieveUserGroupsreturnstheseaccountsaswell. IMPORTANTDonotconfigureanESXorESXisystemtouseNISorNIS+,unlessitisacceptabletohaveNIS (orNIS+)userandgroupinformationavailablethroughtheRetrieveUserGroupsAPI.

VMware, Inc.

37

vSphere Web Services SDK Programming Guide

Figure 43showsthesetwodifferentusermanagementmechanismsassociatedwiththeVMwarevSphere server. Figure 4-3. Managed Objects for Handling Local User Accounts

BothRetrieveCertificatePrincipalsandRetrieveUserGroupsrequireamanagedobjectreferenceto theUserDirectory.BothoperationsreturnanarrayofUserResearchResultdataobjectsbasedonthestring orsubstringusedforthefilter. Table 4-5. UserManager Operations


Operation RetrieveCertificate Principals Parameter _this searchStr Type MOR > UserDirectory string Description ReferencetotheUserDirectory. Caseinsensitivestringthatfiltersresults.Matchesthe subjectNameofCertificatePrincipaldataobjects.Leave blanktoreturnallCertificatePrincipaldataobjects. ReferencetotheUserDirectory. Optional.Domainthatshouldbesearchedforuseraccount orgroupinformation.Leaveunsettosearchlocalmachine. Required.Caseinsensitivestringusedtofilterresults. Matchesonloginandfullnameforusers.Matchesname anddescriptionforgroups. Optional.ESXonly.Returnsusersorgroupsthatexplicitly containthespecifiedgroup.Indirectmembers(usersor groupsthataremembersofacontainedgroup)arenot returned. Optional.Returnsgroupsthatexplicitlycontaintheuser. Indirectusers(usersthataremembersofacontained group)arenotreturned. Required.Settofalsetorestrictresultstoprecisematchof userorgroupname. Required.Settotruetoincludeusersintheresult. Required.Settotruetoincludegroupinformationinthe result.

RetrieveUser Groups

_this domain searchStr

MOR > UserManager string string

belongsToGroup

string

belongsToUser

string

exactMatch findUsers findGroups

boolean boolean boolean

38

VMware, Inc.

Chapter 4 Overview of User Models and Server Access Control Concepts

Authenticating Users through SessionManager


TheSessionManagerprovidesseveraloperationsforloggingintotheserver,obtainingasession,andlogging out.TheSessionManagerdefinesthelifetimeandvisibilityofmanyobjects.Sessionspecificobjectsarenot visibleoutsidethesessioninwhichtheyarecreated. Figure 4-4. SessionManager Managed Object

Uponsuccessfulauthenticationoftheuseraccount,theSessionManagerreturnsaUserSessiondataobject totheclientapplication.Thesessionisassociatedwiththatspecificuseraccountforthedurationofthesession. Theclientapplicationcansavethesessionlocally,toasecurefile,andreusethesessionlatertoreconnectto theserver.YoucanalsoconfigureanESX/ESXiorvCenterServersystemtosupportlocalsessions,which enableuserswithcredentialsonthehosttologinbasedonthoseprivileges. TheSessionManagerprovidesthesecapabilities: Loginandlogout.BasicoperationstologintoESXorvCenterServer,obtainasession,andlogout.When asessionterminates,allsessionspecificobjectsaredestroyed. Impersonation.Oneusersessionadoptstheauthorizationlevelofanotherusersession.Impersonationis commoninWebbasedscenariosinwhichamiddletierapplicationfunctionsasacentralaccountthat interactswithotherbackendserversorprocesses.Windowsservicesimpersonateaclientwhenaccessing resourcesonbehalfoftheclient.SesssionManagersupportsimpersonationthroughits ImpersonateUseroperation. Delegation.AclientapplicationexecutingonbehalfofalocalusercaninvoketheAcquireLocalTicket operationofSessionManagertoobtainaonetimeusernameandpasswordforloggingonwithout enteringasubsequentpassword.Delegationisusefulforhostbasedutilitiesthatruninthelocalconsole. Iftheuseraccountassociatedwiththesessiondoesnothaveappropriatepermissionstoperformanaction, theAuthorizationManagerreturnsaNoPermissionfaulttotheclientapplication.

Overview of the AuthorizationManager


TheAuthorizationManageristheserviceinterfaceforhandlingpermissionsandroles.Itincludesclosetoa dozenoperationsforcreating,modifying,andmanagingrolesandpermissions,andforobtaininginformation abouttherolesandpermissionsdefinedinthesystem.TheAuthorizationManagerenablesaccessand preventsaccesstospecificserverobjectsbasedonthepermissionsassociatedwiththeobject. OperationsformanagingrolesincludeAddAuthorizationRole,RemoveAuthorizationRole,and UpdateAuthorizationRole.SeeTable 47,AuthorizationManagerOperationsforCreating,Updating,and DeletingRoles,onpage 41foremoreinformationabouttheseoperations. OperationsformanagingpermissionsincludeMergePermissions,RemoveEntityPermission, ResetEntityPermissions,RetrieveAllPermissions,RetrieveEntityPermissions, RetrieveRolePermissions,andSetEntityPermissions.

VMware, Inc.

39

vSphere Web Services SDK Programming Guide

Figure 45showstheseoperationsinthecontextofaUMLdiagramforAuthorizationManagerandsomeof itsassociateddataobjects. Figure 4-5. AuthorizationManager Managed Object

AuthorizationManageralsoprovidespropertiesthatcanbeusedtoobtaininformationfast.Forexample: TheprivilegeListpropertyreturnsthelistofallprivilegesdefinedonthesystem,asanarrayof AuthorizationPrivilegedataobjects.PrivilegesaredefinedbyVMware,onthevariousobjectsand propertiescontainedinthesystem.Theseprivilegesarefixedandcannotbechangedbyclient applications.SeeAppendix A,ManagedObjectPrivilegesReference,onpage 149forlistsofprivileges. TheroleListpropertyreturnslistofallcurrentlydefinedroles,includingthesystemdefinedroles,as anarrayofAuthorizationRoledataobjects. Youcanseethesepropertyvaluesforyourself,onyourESXorvCenterServersystem,bynavigatingtoyour theAuthorizationManagerusingtheMOBonyoursystem.SeeUsingtheManagedObjectBrowserto ExploretheObjectModelonpage 16formoreinformation.

Using Roles to Consolidate Sets of Privileges


Aroleisanamedsetofoneormoreprivileges,groupedforconvenience.Assigningarolethatencompasses allthenecessaryprivilegestoperformanactioniseasierandfasterthangrantingeachindividualprivilege separately.ESXdefinestwotypesofroles: Systemroles,whichcannotbemodifiedordeleted. Userroles,whichapplytodifferentusercommunitiesorthatrestrictaccessforaddontools.Several predefineduserrolesareincludedwithvCenterServerandwithESX/ESXisystems.Youcancreatenew rolesusingthesepredefineduserrolesasastartingpoint.

40

VMware, Inc.

Chapter 4 Overview of User Models and Server Access Control Concepts

Table 46describesthesetwotypesofrolesinmoredetail. Table 4-6. System and Pre-Defined User Roles


Type Systemroles Role name Administrator Role ID 1 Description Superuseraccess.Encompassesthesetofalldefinedprivileges. SeeTable A3,PrivilegesGrantedtotheAdministratorRole, onpage 158foranexamplelistfromavCenterServersystem. Thisrolecannotbedeleted.Bydefault,theAdministratorroleis grantedtotheuserorgroupthatownstherootnode. Cannotbegranted.Defaultaccessroleassociatedwithanyuser accountthathasloggedin. Noaccess.Explicitlydeniesaccesstotheuserorgroupwiththis role.Assigningthisroletoauseraccountpreventstheuserfrom seeinganyobjects.UsetheNoAccessroletomasksubobjects underahigherlevelobjectthathaspropagatedpermissions defined. Readonlyaccess.Encompassesthesetofallnonmutable privileges.(System.Anonymous,System.Read,and System.View).Equivalenttoauserrolewithnopermissions. Userswiththisrolecanreaddataorpropertiesandinvoke querymethods,butcannotmakeanychangestothesystem. VisibilityaccessconsistingofSystem.Anonymousand System.Viewprivileges.Cannotbegranted. Setofprivilegesnecessarytomanagevirtualmachinesand hostswithinthesystem. Setofprivilegesnecessarytomanageresourcesbutnotinteract withvirtualmachines. Setofprivilegesnecessarytoprovisionresources. Setofprivilegesforavirtualmachineuserthatcanalsomake configurationchangesandcreatenewvirtualmachines. Setofprivilegesnecessarytousevirtualmachinesonly.Cannot reconfigurevirtualmachines. AvailableonvCenterServersystemsonly. AvailableonvCenterServersystemsonly.Setofprivileges necessarytoruntheConsolidatedBackupUtility.

Anonymous NoAccess

4 5

ReadOnly

View Userroles (predefined samples) VirtualMachine Administrator Datacenter Administrator VirtualMachine Provider VirtualMachinePower User VirtualMachineUser ResourcePool Administrator VMwareConsolidated BackupUtility

3 1 2 3 4 5 6 7

Table 47listsseveralAuthorizationManageroperationsavailableformanagingroles. Table 4-7. AuthorizationManager Operations for Creating, Updating, and Deleting Roles
Operation AddAuthorizationRole Parameter _this Type MOR > AuthorizationManager Description Managedobjectreferencetothe serversAuthorizationManager obtainedthrough ServiceInstance. Nameforthenewrole. Listofprivilegestoassigntotherole intheformat: <group>[.<group>].privilege

name privIds

string string[]

VMware, Inc.

41

vSphere Web Services SDK Programming Guide

Table 4-7. AuthorizationManager Operations for Creating, Updating, and Deleting Roles (Continued)
Operation UpdateAuthorizationRole Parameter _this Type MOR > AuthorizationManager Description Managedobjectreferencetothe serversAuthorizationManager obtainedthrough ServiceInstance. Integerthatidentifiestheroletobe modified. Newnamefortherole. Stringarrayofprivilegestoassignto therole. Managedobjectreferencetothe AuthorizationManagerobtained fromtheServiceInstanceofthe server. Integerthatidentifiestherole.The roleIdisgeneratedby AddAuthorizationRolewhena newroleisdefined. Settotruetoensuretherolecannot beremovedifitisbeingused.

roleId newName privIds RemoveAuthorizationRole _this

int string string[] MOR > AuthorizationManager

roleId

int

failIfUsed

boolean

Modifying Sample Roles to Create New Roles


ThesystemroleslistedinTable 46cannotbemodifiedordeleted.However,youcancreatecompletelynew roles,ormodifythesampleuserrolestosuityourneeds. SeetheBasicSystemAdministrationguideorthevSphereClientonlinehelpforinformationaboutcreating newrolesormodifyingthesamplerolesusingthevSphereClient. SeethevSphereCommandLineInterfaceInstallationandReferenceGuideforinformationaboutusingthe vicfg-uservSphereCLIcommandtocreatenewrolesormodifythesampleroles. To create new roles using the API 1 2 Obtainareference(specificinstanceofManagedObjectReference)totheAuthorizationManagerfor theserver,fromtheServiceContentobjectfortheServiceInstance. InvoketheAddAuthorizationRolemethod,passingthereferenceintheinvocationalongwithaname fortherole(asastring)andanarrayofprivileges(arrayofstrings)thathasthelistofprivilegesthat shouldbeassignedtotherole. AddAuthorizationRolereturnsaninteger(xsd:int)valuefortheroleIdthatthesystemassignstothe newlydefinedrole. 3 UsetheroleIDinsubsequentcode,toassigntheroletospecificusersorgroups.

Granting Privileges through Permissions


APermissiondataobjectassociatesaprincipalwithasetofprivileges.Apermissionidentifies: Theuserorgroup(principal)towhichthepermissionapplies. Therolecontainingtheprivilegesthatshouldbegrantedtotheuserorgroup. Themanagedobjectreferencetotheentitytowhichthepermissionapplies EverymanagedentityhasatleastonePermissionobjectassociatedwithit.Amanagedentitycanhavemore thanonePermissionassignedtoit,effectivelygrantingdifferentprivilegestodifferentusersorgroups. Permissionsaredefinedformanagedentitieseitherexplicitlyorthroughinheritance.

42

VMware, Inc.

Chapter 4 Overview of User Models and Server Access Control Concepts

Obtaining Information about Permissions


UserswiththeAdministratorrolecanobtaininformationaboutPermissionobjectsatdifferentgranularities ofdetail,including: ForallusersdefinedinthesystembyinvokingtheRetrieveAllPermissionsoperation,whichreturns anarrayofPermissiondataobjects. Forspecificinventoryobjects,suchmanagedentities,suchasfolders,datacenters,orvirtualservicesby invokingtheRetrieveEntityPermissionsoperation. ForaroledefinedinthesystembyinvokingtheRetrieveRolePermissionsoperation. SeethevSphereAPIReferenceformoreinformation.However,youcaninvokeanyoftheseoperationsfromthe MOBtoobtaininformationaboutyoursystem,asyoudevelopyourcode.

Setting, Changing, or Deleting Permissions


ThePermissiondataobjectassociatestheprivilegesrequiredtoperformanactionwiththeprincipals(user, group)thathavebeengrantedthoseprivilegesbyvirtueoftheroleassignedtotheprincipals. TheAuthorizationManagerprovidesseveraloperationsformanagingPermissionobjects,includingthose listedinTable 48. Tosetorupdatepermissionsonanentity,usetheSetEntityPermissionsoperation.Settingorchanging permissionsonentitiesrequirestheAuthorization.ModifyPermissionsprivilegeonthetargetmanaged entity. To set permissions on an entity 1 ObtainareferencetotheAuthorizationManagerfortheserver,fromtheServiceInstances ServiceContentobject.Forexample:
ManagedObjectReference hostAuthorizationManager = cb.getConnection().getServiceContent().getAuthorizationManager();

CreateaPermissiondataobjectthatidentifiestheuser(orgroup)name,therole,theentitytowhichthe permissionshouldapply,andwhetherthepermissionshouldbeappliedtotheentityschildren. Forexample,tocreateapermissionontherootfolderoftheinventorygrantingauserAdministratorrole totherootfolderandallitschildren:


Permission per = new Permission(); per.setGroup(false); per.setPrincipal(new_user_name); per.setRoleId(-1); per.setPropagate(true); per.setEntity(rootFolder);

Tocompletelyreplaceexistingpermissionswithanewsetofpermissions,usetheResetEntityPermissions operation. Table 4-8. AuthorizationManager Operations for Setting, Changing, and Removing permissions
Operation SetEntityPermissions, ResetEntityPermissions Parameter _this Type MOR > AuthorizationManager Description Managedobjectreferencetothe servers(ServiceInstance) AuthorizationManager. Managedentityforwhichyouwant tograntordenyaccess. ArrayofPermissionobjectsthat defineaccessrulesfortheentity. Passinganemptyarrayremovesall permissionsfromtheentity.

entity

MOR > ManagedEntity [HostSystem,Folder, ComputeResource...] Permission[]

permission

VMware, Inc.

43

vSphere Web Services SDK Programming Guide

Table 4-8. AuthorizationManager Operations for Setting, Changing, and Removing permissions (Continued)
Operation RemoveEntityPermission Parameter _this entity Type MOR > AuthorizationManager MOR > ManagedEntity [HostSystem, Folder, ComputeResource...] Description Deletethepermissionfromanentity forspecifiedprincipal(user,group). Managedobjectreferencethat identifiesthemanagedentityfrom whichtodisassociateaPermission. UsetherootFoldermanagedobject referenceifthePermissionis associatedwithamanagedobjectthat isnotamanagedentity. Usethespecificmanagedentity subclasstype(Folder,Datacenter, andsoon)forPermissionbeing removedisassociatedwitha managedentity. user isGroup string boolean Principal(user,group)forwhichthe permissionsweredefined. Specifiesthattheuservalueisagroup (true)orasingleuser(false).

Permissionscannotbesetdirectlyonchildreninacomplexentity.Forcomplexentities,setpermissionsonthe parententityandsetthepropagateflagtotruetoapplypermissionstoitschildentities.

Impact of Group Membership on Permissions


Userscanbemembersofmultiplegroups.Ifauseraccountwithmembershipinmultiplegroupshasnoother explicitlydefinedpermissions,thentheaccountisgrantedthecombinedset(union)ofallgroupassigned permissions. Usersalsoobtaintheunionofpermissionsassociatedwiththecontainingresourcepoolandfolderforvirtual machinesforwhichtheyhavebeengivenpermission.However,userspecificpermissionsalwaystake precedenceoveranygrouppermissions.Table 49summarizesthesedetails. Table 4-9. User and Group Permissions Summary
User-level permissions Alwaystakeprecedenceoveranygrouplevel permissions. Group-level permissions Membershipinmultiplegroupswithpermissionson thesameobjectresultsinunionofpermissions. Absentexplicituserpermissions,grouplevel permissionsapplyasifgrantedtouserdirectly.

Permissionsareappliedtotheassociatedobjectsthatmakeuptheinventoryitem,fromthecontainingobject toeachofitschildentities.

44

VMware, Inc.

vSphere API Programming Model

TheVMwarevSpheremanagementobjectmodelprovidesaserversideframeworkforprovisioning, instrumenting,managing,andmonitoringVMwarevSpherecomponents,suchasvirtualmachines,host systems,andvirtualizedapplications.ProgrammaticaccesstotheVMwarevSphereobjectmodeland managementframeworkfromaclientapplicationisthroughthevSphereAPI.Thischapterincludesthese topics: APIasaWebServiceonpage 45 ClientApplicationCharacteristicsonpage 46 AccessingtheAPIontheWebServiceonpage 50 UsingthevSphereAPIReferenceonpage 51 MappingtheWSDLtotheClientsideProxyCodeonpage 51 InvokingOperationsthroughtheMOBonpage 53

API as a Web Service


ThevSphereAPIislanguageneutral.ItisimplementedasindustrystandardWebservicesthatarehostedon ESX/ESXiandvCenterServersystems.ThevSphereAPIcomplieswiththeWebServicesInteroperability Organization(WSI)BasicProfile1.0.TheWSIBasicProfile1.0includessupportfor: XMLSchema1.0 SOAP1.1 WSDL1.1 ForinformationabouttheWSIBasicProfile1.0,visittheWebServicesInteroperabilityOrganization(WSI) Websiteathttp://www.wsi.org. Webservicestechnologyprovidesoperations,whichisthesamebasicconceptasmethodsinother programminglanguages.TheWebserviceprovidesaccesstoalloperationsnecessaryformonitoringand managingthevirtualinfrastructurecomponents,suchascomputeresources,virtualmachines,networks, storage,andsoon.

API Defined in WSDL File


TheWebservicesAPIisdefinedinaWSDL(WebServicesDescriptionLanguage)file.TheWSDLfileisused byWebservicesclientapplicationdevelopmenttools(SOAPtoolkits,suchasAxisorMicrosoft.NET)to createclientsideproxycode(stubs)thatfacilitateremotemethodinvocation,marshallingandmarshalling objectdata,andotherlowleveldetailsofdistributedobjectorientedapplicationsprogramming. ClientapplicationsinvokeoperationsbysendingSOAP(SimpleObjectAccessProtocol)formattedmessages. SOAPisanXMLformatandisprogramminglanguageneutral.OneofthejobsoftheclientsideWebservices toolsisformattingtheSOAPmessagesfromtheprogramminglanguagethatyouuse.

VMware, Inc.

45

vSphere Web Services SDK Programming Guide

CommunicationsbetweenclientandserveroccuroverHTTPS(HTTPoveranencryptedSecureSockets Layer (SSL)connection).ThedefaultisHTTPS.However,theservercanbeconfiguredtosupportHTTP. See theDevelopersSetupGuidefordetails.

Client Application Characteristics


TheVMwarevSphereapplicationmodelisasynchronous,distributed,andreliesoninstancesofthe ManagedObjectReferencedataobjectforremotemethodinvocation.

Asynchronous Client-Server Application Style


TheVMwarevSphereapplicationmodelusesanasynchronousclientservercommunicationschemeby default.Thatis,mostmethodinvocationsarenonblocking,returningareferencetoaTaskmanagedobject. SeeChapter 9,OverviewoftheTaskInfrastructure,onpage 83foracompleteoverview.

Distributed Object-Oriented Application Style


VMwarevSphereclientapplicationsinvokeoperationsontheserverremotely,overanetwork.Onlydata objectsaresentbackandforthbetweenserverandclient.Managedobjectsareaccessedbyreference.Youuse instancesoftheManagedObjectReferencedataobjecttypetoinvokeoperationsontheserverobjectsfrom yourclientapplication.Eachmanagedobjectreferenceidentifiesaspecificmanagedobjectontheserverwith itstypeandavalue(Figure 51). Figure 5-1. ManagedObjectReference Data Object Diagram

Table 51listsallpossiblevalidstringsforthevaluepropertyofManagedObjectReference. Table 5-1. Valid Values for ManagedObjectReference Type Property
Type Property Alarm AlarmManager AuthorizationManager ClusterComputeResource ClusterProfile Refers to Alarmmanagedobject AlarmManagermanagedobject AuthorizationManagermanagedobject ClusterComputeResourcemanagedobject ClusterProfilemanagedobject

46

VMware, Inc.

Chapter 5 vSphere API Programming Model

Table 5-1. Valid Values for ManagedObjectReference Type Property (Continued)


Type Property ClusterProfileManager ComputeResource ContainerView CustomFieldsManager CustomizationSpecManager Datacenter Datastore DiagnosticManager DistributedVirtualPortgroup DistributedVirtualSwitch DistributedVirtualSwitchManager EnvironmentBrowser EventHistoryCollector EventManager ExtensibleManagedObject ExtensionManager FileManager Folder HistoryCollector HostAutoStartManager HostBootDeviceSystem HostCpuSchedulerSystem HostDatastoreBrowser HostDatastoreSystem HostDateTimeSystem HostDiagnosticSystem HostFirewallSystem HostFirmwareSystem HostHealthStatusSystem HostKernelModuleSystem HostLocalAccountManager HostMemorySystem HostNetworkSystem HostPatchManager HostPciPassthruSystem HostProfile HostProfileManager HostServiceSystem HostSnmpSystem HostStorageSystem HostSystem
VMware, Inc.

Refers to ClusterProfileManagermanagedobject ComputeResourcemanagedobject ContainerViewmanagedobject CustomFieldsManagermanagedobject CustomizationSpecManagermanagedobject Datacentermanagedobject Datastoremanagedobject DiagnosticManagermanagedobject DistributedVirtualPortgroupmanagedobject DistributedVirtualSwitchmanagedobject DistributedVirtualSwitchManagermanagedobject EnvironmentBrowsermanagedobject EventHistoryCollectormanagedobject EventManagermanagedobject ExtensibleManagedObjectmanagedobject ExtensionManagermanagedobject FileManagermanagedobject Foldermanagedobject HistoryCollectormanagedobject HostAutoStartManagermanagedobject HostBootDeviceSystemmanagedobject HostCpuSchedulerSystemmanagedobject HostDatastoreBrowsermanagedobject HostDatastoreSystemmanagedobject HostDateTimeSystemmanagedobject HostDiagnosticSystemmanagedobject HostFirewallSystemmanagedobject HostFirmwareSystemmanagedobject HostHealthStatusSystemmanagedobject HostKernelModuleSystemmanagedobject HostLocalAccountManagermanagedobject HostMemorySystemmanagedobject HostNetworkSystemmanagedobject HostPatchManagermanagedobject HostPciPassthruSystemmanagedobject HostProfilemanagedobject HostProfileManagermanagedobject HostServiceSystemmanagedobject HostSnmpSystemmanagedobject HostStorageSystemmanagedobject HostSystemmanagedobject

47

vSphere Web Services SDK Programming Guide

Table 5-1. Valid Values for ManagedObjectReference Type Property (Continued)


Type Property HostVirtualNicManager HostVMotionSystem HttpNfcLease InventoryView IpPoolManager LicenseAssignmentManager LicenseManager ListView LocalizationManager ManagedEntity ManagedObjectView Network OptionManager OvfManager PerformanceManager Profile ProfileComplianceManager ProfileManager PropertyCollector PropertyFilter ResourcePlanningManager ResourcePool ScheduledTask ScheduledTaskManager SearchIndex ServiceInstance SessionManager Task TaskHistoryCollector TaskManager UserDirectory View ViewManager VirtualApp VirtualDiskManager VirtualizationManager VirtualMachine VirtualMachineCompatibilityChecker VirtualMachineProvisioningChecker VirtualMachineSnapshot VmwareDistributedVirtualSwitch
48

Refers to HostVirtualNicManagermanagedobject HostVMotionSystemmanagedobject HttpNfcLeasemanagedobject InventoryViewmanagedobject IpPoolManagermanagedobject LicenseAssignmentManagermanagedobject LicenseManagermanagedobject ListViewmanagedobject LocalizationManagermanagedobject ManagedEntitymanagedobject ManagedObjectViewmanagedobject Networkmanagedobject OptionManagermanagedobject OvfManagermanagedobject PerformanceManagermanagedobject Profilemanagedobject ProfileComplianceManagermanagedobject ProfileManagermanagedobject PropertyCollectormanagedobject PropertyFiltermanagedobject ResourcePlanningManagermanagedobject ResourcePoolmanagedobject ScheduledTaskmanagedobject ScheduledTaskManagermanagedobject SearchIndexmanagedobject ServiceInstancemanagedobject SessionManagermanagedobject Taskmanagedobject TaskHistoryCollectormanagedobject TaskManagermanagedobject UserDirectorymanagedobject Viewmanagedobject ViewManagermanagedobject VirtualAppmanagedobject VirtualDiskManagermanagedobject VirtualizationManagermanagedobject VirtualMachinemanagedobject VirtualMachineCompatibilityCheckermanagedobject VirtualMachineProvisioningCheckermanagedobject VirtualMachineSnapshotmanagedobject VmwareDistributedVirtualSwitchmanagedobject

VMware, Inc.

Chapter 5 vSphere API Programming Model

Obtaining Managed Object References


Withareferencetoamanagedobject,youcanobtaininformationaboutthestateoftheserversideinventory objectsandpopulateclientsideobjectsbasedonthevalues.Generally,thesearethedifferentwaysof obtaininginformationaboutobjectsfromtheserver: Useanaccessormethodifyourtargethasone.Theclientstubsprovideaccessormethodsforeach propertyofadataobject.Youcanuseanyoftheseaccessormethodstoobtainthevaluesoftheobject. UseaPropertyCollectortonavigatetoaselectedpointontheserverandobtainvaluesfromspecific properties.SeeObtainingReferencestoObjectsandPropertyValuesfromtheServeronpage 73for moreinformationaboutPropertyCollector. UsingtheSearchIndexmanagedobjecttoobtainamanagedobjectreferencetothemanagedentityof interest.TheSearchIndexcanreturnmanagedobjectreferencestospecificmanaged entitiesComputeResource,Datacenter,Folder,HostSystem,ResourcePool, VirtualMachinegivenaninventorypath,IPaddress,orDNSname.

Do Not Store Managed Object Reference Values


Managedobjectreferencesmustbeunique.Toensurethattheyare,VMwarevSphereserverseachhavetheir ownnamespaceformanagedobjectreferencevaluesthatensuresgloballyuniquevaluesthroughoutthe serverinstance.ManagedobjectreferencestoanobjectinanESX/ESXinamespaceisdifferentthanthe managedobjectreferencetothesameobjectinthevCenterServernamespace(assumingtheESX/ESXiinstance isbeingmanagedbythevCenterServerinstance).vCenterServermustensurethatmanagedobjectreferences acrossallthesystemsitmanagesareunique.Forthesereasons,youmustnotstoreamanagedobjectreference fromavCenterServerduringonesessionandexpecttouseitinasubsequentsession.

Working with Data Structures in Client Application Code


Propertiescontaininformationabouttheserversideobjectsatagivenpointintime.Eachpropertyisdefined asaspecificdatatype.Datatypesinclude: Simpledatatypes,suchasastring,boolean,orinteger(orothernumeric)datatype.Forexample,the ManagedEntitymanagedobjecthasanamepropertythattakesastringvalue. Arraysofsimpledatatypesordataobjects.Forexample,aHostSystemmanagedobjectcontainsanarray ofmanagedobjectreferences(atypeofdataobject)tovirtualmachineshostedbythatphysicalmachine. Asanotherexample,theSessionManagermanagedobjecthasasessionListpropertythatisanarray ofUserSessiondataobjects. Enumeratedtypes(enumeration,enum)ofpredefinedvalues.Thevaluescanbeacollectionofsimple datatypesordataobjects.Forexample,avirtualmachinespowerstatecanbeoneofthreepossiblestring valuespoweredOn,poweredOff,orsuspended. Complexdatatypes.DataobjectssuchasAboutInfo,Action,andServiceContent,thathavebeen specificallydefinedfortheVMwarevSphereobjectmodel.

Accessing Property Values


Workingwithcompositedatastructuresrequiressomeunderstandingofnestedpropertiesandhowtoaccess thedatatheycontain. Nested Properties and Property Paths TheVMwarevSphereobjectmodelismadeupofcompositedatastructures.Objecttypescanincludedata members(properties)definedasprimitivedatatypes,suchasanxsd:intorxsd:string,orascomplexdata types,suchasdataobjects.Propertiescannesttoseverallevels. Forexample,Figure 52showsaUMLclassdiagramoftheVirtualMachinemanagedobjecttype,whichhas aproperty(runtime)thatisdefinedasanxsd:dateTimedatatype.VirtualMachinealsohasaproperty namedsummarythatismodeledasaVirtualMachineSummarydataobject.TheVirtualMachineSummary dataobjectcontainsaproperty(config)thatismodeledasaVirtualMachineConfigSummarydataobject.

VMware, Inc.

49

vSphere Web Services SDK Programming Guide

Figure 5-2. VirtualMachine Managed Object Type and Nested Properties

Torefertoanestedpropertyatanydepthinyourcode,usedotnotationbetweenthevariousobjectnamesto definethepathtotheproperty,beingawaretohandlethereturntypecorrectly.Thereturntypeobtained dependsonthedatatypeattheendofthepath. Forexample,thepropertydefinedatthepathsummary.config.guestIdisastringvalue,whiletheproperty definedaspathsummary.configreturnsacompleteVirtualMachineSummarydataobject. Table 52showsseveralexamplesofhowtoaccesssomeofthenestedpropertiesoftheVirtualMachine managedobjecttypeshowninFigure 52. Table 5-2. Nested Properties and Return Datatypes
Example summary summary.config summary.config.guestID Returns VirtualMachineSummarydataobject VirtualMachineConfigSummarydataobject string

Properties Defined as Key-Based Arrays and Indexed Arrays Nestedpropertiescanalsorefertopropertiesthatarekeybasedarrays.Forexample,a.b.c["xyz"]refersto thepropertycthathasthekeyvalueofxyz.Anarraypropertyisanypropertywhosetypeisanarray.The VMwarevSpheredatastructuresincludebothindexedarraysandkeybasedarrays. Indexedarraysareaccessedbyusinganindexinteger.Indexedarraysareusedforarraysofdatatypes whosepositioninthearraydoesnotchange.Forexample,theroleListpropertyofthe AuthorizationManagermanagedobjectisanarrayofauthorizationroles.Addinganewroletothe arraydoesnotchangethepositionofexistingelementsinthearray. Keybasedarraysareusedforinformationwhosepositionissubjecttochange.Akeybasedarray(same basicconceptasaPerlhash)usesaunique,unchangingvalueasakeytoaccessanelementsvalue. Typically,thekeyisspecifiedasastring,butintegerscanalsobeused.Forexample,Eventarraysuse integersaskeys. Nestedpropertiescanalsorefertopropertiesthatarekeybasedarrays.Forexample, a.b.c["xyz"]refers tothepropertycthathasthekeyvalueofxyz. TheVMwarevSpheremanagementobjectmodeluseskeybasedarraystokeeptrackofmanagedobject references.Thecontentsofakeybasedarraypropertyareaccessedbythevalueofeitherthekeypropertyor, inthecaseofamanagedobjectreference,itsvalueproperty.Thevalueofthesefieldsisuniqueacrossallthe componentsofanarray.

Accessing the API on the Web Service


ThevSphereAPIisavailableonESX/ESXiandvCenterServersystems,asasecureWebservice,availableover HTTPSatport443.AsistypicalofotherWebservicesclientapplicationdevelopmentprojects,developing clientapplicationsusingthevSphereWebServicesSDKrequiresaccesstotheWebServicesDescription Language(WSDL)filedescribingtheoperationsanddatatypesavailableontheWebservice.

50

VMware, Inc.

Chapter 5 vSphere API Programming Model

ThevSphereWebServicesSDKincludestheWSDLthatdefinestheAPI. IMPORTANTThevSphereWebServicesSDKshipswithJavaclientsideproxycodethathasbeengenerated usingtheAxistoolkit.IftheversionsofJavaandAxisonyourdevelopmentplatformarethesameasthose usedtogeneratethestubsshippedintheSDK,youdonothavetogenerateclientsideproxycodefromthe WSDL.SeetheDevelopersSetupGuideforinformationaboutconfiguringadevelopmentenvironmentforthe vSphereWebServicesSDK. TheVMwareclientlibrariesmustbeimportedintoclientapplications(Table 53). Table 5-3. Import Statements for Including the vSphere API Client Library
Java import com.vmware.vim25.*; C# usingVimApi;

TheAPIisdocumentedinthevSphereAPIReference,whichisincludedintheVMwarevSphereWebServices SDKpackage.

Using the vSphere API Reference


ThevSphereAPIReferenceistheHTMLreferencedocumentationgeneratedfromtheVMwarevSphereobject modelinterfacedefinitions.Thisdocumentationsetisalanguageneutralreferencethatprovidescomplete informationaboutalldatastructuresthatmakeuptheVMwarevSpheremanagementframeworkmanaged objecttypes,dataobjecttypes,faulttypes,enumerations,andassociatedpropertiesandoperationsavailable throughtheWebservice. TheAPIreferencedocumentationisavailableinthe\SDK\doc\ReferenceGuidesubdirectoryofthevSphere WebServicesSDKpackage. ThevSphereAPIidentifiesdeprecatedtypesandmethodsandprovidescrossreferencestothenewproperty, operation,ortype.

Identifying Deprecated Items in the vSphere API Reference


Thedeprecatedlabelonatype,operation,orpropertydocumentedinthevSphereAPIReferencemeansthata new,betterwaytomeetaspecificrequirementisavailable.Forexample,VIAPI2.5deprecatedthe HostSystemmanagedobjecttypesQueryMemoryOverheadoperation,infavorofanewoperation, QueryMemoryOverheadEx.Althoughclientapplicationsusingdeprecatedfeaturescontinuetowork,VMware recommendsthatyouusethenewtype,operation,orproperty(ratherthanthedeprecation)fornewclient applicationdevelopment.

Identifying Version Information in the vSphere API Reference


VersioninformationinthevSphereAPIReferenceisavailablestartingwithAPI2.5andsubsequentreleases. If thevSphereAPIReferencedocumentationdoesnotincludetheversionlabel,youcanassumeitissupported onAPI2.0andpriorreleases.NewfeaturesinthisreleaseareidentifiedasSincevSphereAPI4.0,for example.Theversioninformationisusefulespeciallyforclientapplicationsthatmusttargetmultipleversions ofVMwarevSphereservers,someofwhichmaysupportfeaturesprovidedinoneversion,butnotinanother.

Mapping the WSDL to the Client-side Proxy Code


ClientapplicationdevelopersuseSOAPtoolssuchasAxisWSDL2Java,orMicrosoft.NETwsdl.exeto generateclientsideproxycodefromtheWSDL.Thegeneratedproxycodehandlestheremotemethod invocation,datatypemappingfromservertoclient,andothersuchdetails. Thegeneratedclientsideproxycodeincludesaccessor(getter)andmutator(setter)methodsforeachproperty definedinserversidedataobjecttypes.

VMware, Inc.

51

vSphere Web Services SDK Programming Guide

Table 54showsanexampleofthemethodsignaturesasdefinedintheJavaandC#clientproxycodeforthe AfterStartupTaskSchedulerdataobjectsminuteproperty. Table 5-4. Example of Generated Accessor and Mutator Methods in Client Proxy Code
Data Object AfterStartup TaskScheduler Property minute Type xsd:int Java public int getMinute() { return minute; } public void setMinute(int minute) { this.minute = minute; } C# public int minute { set; get; }

YoucanextrapolatefromthedocumentationintheVMwarevSphereAPIReferencetoidentifygetterandsetter methodsthatareavailabletoyourclientapplication,withoutexaminingthe*.java,*.cs,orothergenerated clientsidestubstofindtheactualmethods. Forexample,giventhattheManagedObjectReferencedataobjecttypehasatypeproperty,youcansafely assumethatyoucanassignavaluetoamanagedobjectreferencebyusingsetType,passingoneofthevalid stringvaluesasaparameter.YoucanobtainthestringvaluebyusinggetType. Table 55showssomevalidstringvaluesamanagedobjectreferencedataobjectcanacceptorreturn. Table 5-5. ManagedObjectReference Data Object Default Methods and Valid String Values
Property (Datatype) type (string) Default Getter Method getType Default Setter Method setType Valid values Alarm,"AlarmManager","AuthorizationManager", "ClusterComputeResource","ComputeResource", "ContainerView","CustomFieldsManager",andsoon. See completelistofsupportedvaluesinTable 51.

Asanotherexample,theServiceContentdataobjecthasanaboutpropertythatisdefinedasaninstanceof theAboutInfodataobjecttype.ByexaminingtheAPIReference,youseethattheAboutInfodataobjecthas severalotherproperties,includingapiVersionandapiType,bothofwhicharedefinedasxsd:stringdata types.Thesedetailsprovidethefollowinginformation: Theclientstubscontaingetterandsettermethodsfortheproperties(getApiVersion,setApiVersion, getApiType,setApiType). Thedatatypethatcanbeacceptedasinputtoandreturnedbythesemethodsisastring. ThemethodscanbeinvokedoninstancesoftheServiceContentobject. SeeChapter 6,ClientApplicationPattern,onpage 59formoreinformation.

Obtaining Values from Nested Properties


Accessingnestedpropertiesrequiresdotnotationfromthetoplevelobjecttotheembeddedobject(see NestedPropertiesandPropertyPathsonpage 49).Thedatatypeoftheresultdependsonthedatatypeat theendoftheseries.Forexample,toobtainthevalueofaspecificvirtualmachinespowerState:
VirtualMachineRuntimeInfo().powerState()

Inaddition,yourcodemustbesetuptohandlethespecificdatatypereturnedbyanymethodinvocationor byobtainingthepropertyvalue.Forexample,intheseriesa.b.c,ifcisaninteger,yourcodemustbe preparedtohandleaninteger.Ifcisadataobjecttype,thenyouobtainaninstanceofthattype.Ifcisa ManagedObjectReference,yougetaninstanceofaManagedObjectReference.


... private ServiceContent =_sic; private String myServerVersion; ... myServerVersion = _sic.getAbout().getApiVersion(); ...

52

VMware, Inc.

Chapter 5 vSphere API Programming Model

Mapping XML Datatypes to Java and C# Datatypes


Tosimplifythepresentation,theUMLclassandobjectdiagramsinthisguideusetheprimitivedatatype namessuchasstringandinteger,withouttheXMLSchemadefinitionnamespaceprefix(xsd:).ThevSphere APIReferencecontainsthecompletedatatypename,suchasxsd:string.Thedatatypesmaptotheprimitive datatypesoftheprogramminglanguageusedfortheclientapplication. Table 56listssomeofthemorecommonXMLprimitivedatatypemappings. Table 5-6. Standard XML Schema Primitives to Java and .NET Data Type Mappings
XML Schema xsd:base64binary xsd:boolean xsd:byte xsd:dateTime xsd:decimal xsd:double xsd:float xsd:int xsd:string Java byte[] boolean byte java.util.Calendar java.math.BigDecimal double float int java.lang.String .NET Data Type Byte[] Boolean SByte DateTime Decimal Double Single Int32 String
De

Escape Character Used in Name and Path Properties


Thepercentsign(%)isusedasanescapecharactertoembedspecialcharactersinstrings.Forexample,%2f (or%2F)isinterpretedastheslash(/)character.Toincludeapercentsignasaliteralinastring,use%%.The pathtotheinventorystartsfromtherootfolder(rootFolderpropertyofServiceContent),denotedbythe /(slash)character. Table 5-7. Special Characters
Character % / \ . Description Percentsign Slash Backslash Dash Dot Doublequotationmark Representation in URL %25 %2F,%2f %5C,%5c %2D,%2d %2E,%2e %2B,%2b

Invoking Operations through the MOB


ThissectiondiscusseshowtopassvaluestotheserverusingtheMOB.YoucanusetheMOBtonavigatethe objectsontheserverandinvokeoperations.AnychangesyoumakethroughtheMOBtakeeffectontheserver. TheexamplesinthissectioninvokevariousqueryoperationsofthePerformanceManagerAPItodemonstrate howtopassprimitivedatatypes,arrays,andcomplexdatatypes(dataobjects,includingmanagedobject references)usingtheMOB. CAUTIONTheMOBisnotareadonlymechanism.ByclickingtheInvokeMethodlinkintheMOB,youmight changetheserverstate(dependingontheoperation).Ontheotherhand,manyoperationsarequeryonly operationsthatonlyreturnobjectsfromtheserver. InputfieldsfortheMOBarepresentedassingleentrytextfieldsorasscrollabletextareas.Atextfieldaccepts primitivedatatypes.Thescrollabletextareasareforenteringarraysandcomplextypes.Theremainderofthis sectiondiscusseshowtoentervaluesusingtheMOB.

VMware, Inc.

53

vSphere Web Services SDK Programming Guide

Passing Primitive Datatypes to Operations through the MOB


ThedatatypesaredefinedintheWSDLusingXMLSchemamarkup.Theprimitivedatatypesarespecified usingthexsdnamespace.Forexample,astringvalueforapropertyisdefinedasdatatypexsd:string. The APIReferencedocumentationprovidesthisdetail.ToenteraprimitivevalueintheMOB,enterthevalue asplaintext,withoutanyquotationmarksorothermarkup.Forexample,toenteranintegervalueof10,type 10inthefield. Figure 53showsanexample.Toobtaininformationabouttheavailableperformancecountersatlevel4onthe server,entera4inthelevelfieldoftheQueryPerfCounterByLeveloperation.(Thisoperationisavailable onlyonthevCenterServerPerformanceManagerAPI,notfromanESX/ESXisystem.) Figure 5-3. Using the MOB to Pass Primitive Datatypes to an Operation, as a Parameter

Figure 54showstheresultsofsubmittingthequery.ThearrayofPerfCounterInfodataobjectsandnested objects,withpopulatedvaluesfromtheserver,displaysintheWebbrowser. Figure 5-4. Example of Returned Object Displayed in the MOB

Passing Arrays of Primitives to Operations through the MOB


Foranarray,usethenameoftheparameterasthenameofthepropertyasifitwereanXMLelement,byusing openingandclosingtagsmadeupoftheparametername.Forexample,theQueryPerfCounteroperationof PerformanceManagerrequiresanarrayofintegersforthecounterIdparameter.Heresanexample:
<counterId>58</counterId><counterId>65603</counterId><counterId>65604</counterId>

Evenifyouwanttosubmitasinglevalueforasinglearrayelement,youmustwraptheparametername aroundthevalueinthisway.

Passing Complex Structures to Operations through the MOB


Forcomplexdatatypes,enterthevalueasdefinedbytheXMLSchemaintheWSDL.YoucanobtaintheWSDL definitionfromthevSphereAPIReferenceusingtheShowWSDLtypedefinitionlinks.Eachdataobjecttype hasanassociatedlink.

54

VMware, Inc.

Chapter 5 vSphere API Programming Model

Simple Content ThedataobjecttypeManagedObjectReferenceisoneofthemostcommonlyrequiredparameterstobe passedtotheserver.Forexample,theMOBfortheQueryPerfProviderSummaryoperationin PerformanceManagershowsthattheoperationrequiresasingleparameter,themanagedobjectreference(an instanceofManagedObjectReference)oftheentityforwhichyouwanttoobtainthePerfProviderSummary object. UsingthevSphereAPIReferenceforManagedObjectReferencetype,youcanobtaintheschemainformation fromtheShowWSDLtypedefinitionlinkatthebottomofthedocumentationpagefor ManagedObjectReference. Example 5-1. XML Schema Definition of ManagedObjectReference Data Object
<complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="ManagedObjectReference"> <simpleContent> <extension base="xsd:string"> <attribute name="type" type="xsd:string"/> </extension> </simpleContent> </complexType>

Example 51showsthatamanagedobjectreferenceisdefinedasa<SimpleContent> elementthatconsists ofastringthatshouldspecifytheattributetypewithitsassociatedvalue,alsoasstring.Usethisinformation toconstructtheappropriatestructurebyreplacingtypewiththeparameternamefromtheMOB,settingthe valueasneeded,andsubmittingintheentryfieldoftheMOB.(ThevaluefortheDatacenterisdisplayedin theMOB.)


<entity type=Datacenter>datacenter-21</entity>

Figure 55showstheresultofusingthedefinitionlistedinExample 51tospecifythemanagedobject referenceforatargetdatacentertotheQueryPerfProviderSummaryoperation. Figure 5-5. Using the MOB to Pass Complex Types to an Operation as a Parameter

Asanotherexample,oneoftheparametersrequiredbytheCloneVM_Taskoperation(oftheVirtualMachine managedobject)isafolder.Inthiscase,theparameterisdefinedasamanagedobjectreferencetoaspecific Folderobject.UsingthesamedefinitionshowninExample 51,theresultisasfollows:


<folder type=Folder>folder-87</folder>

AlthoughbothexamplessubmitaManagedObjectReferencetotheMOB,eachisspecifictotheparameter namerequiredbytheoperation(entitytypeforQueryPerfProviderSummaryoperationin PerformanceManager,foldertypefortheCloneVM_TaskoperationinVirtualMachine). Complex Content Unlikethe<simpleContent>showninExample 51,manyofthedataobjectsrequiredfortheMOBconsist ofXMLSchemaelementsdefinedas<complexContent>thatmayencompassmanyotherelements. Forexample,theCreateFilteroperationinPropertyCollectorhasaspecparameterthatmustbedefined priortoinvokingtheoperation.ThespecparameterisdefinedasaninstanceofaPropertyFilterSpec.

VMware, Inc.

55

vSphere Web Services SDK Programming Guide

Figure 56showstherelationshipsamongseveraldataobjectsthatPropertyFilterSpecconsistsof. Figure 5-6. PropertyFilterSpec and Associated Data Objects

TosubmitcomplexdatastructuressuchasthistotheMOB,startbynavigatingthevSphereAPIReference.Find thePropertyFilterSpecdataobject.FindtheShowWSDLtypedefinitionlink,andclickittodisplaythe XMLSchemadefinition(seeExample 52). Example 52showsthatthePropertyFilterSpecdataobjectisa<complexContent>elementthatextends theDynamicDataclasswithasequenceoftwoadditionalproperties(propSet,objectSet),eachofwhichhas itsowntypedefined(PropertySpecandObjectSpec,respectively). Example 5-2. XML Schema Definition of PropertyFilterSpec Data Object Type
<complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="PropertyFilterSpec"> <complexContent> <extension base="vim25:DynamicData"> <sequence> <element name="propSet" type="vim25:PropertySpec" maxOccurs="unbounded"/> <element name="objectSet" type="vim25:ObjectSpec" maxOccurs="unbounded"/> </sequence> </extension> </complexContent> </complexType>

Becausebothelementsaredefinedasasequence,theymustexistintheorderlisted.Toobtainthedefinitions ofpropSetandobjectSet,youmustnavigatefurtherintothevSphereAPIReference.Example 53showsonly therelevantpartsoftheXMLSchemadefinitionforPropertySpec.TheminOccurs=0attributemeansthat theelementdoesnothavetoexist.ThemaxOccurs=unboundedattributedenotesthattheelementcanbe populatedasanarrayofanysize.(WhenminOccursisnotsetbutmaxOccursisset,thedefaultforminOccurs defaultsto1,meaningoneinstanceisrequired.) Example 5-3. XML Schema Extract for PropertySpec
<sequence> <element name="type" type="xsd:string"/> <element name="all" type="xsd:boolean" minOccurs="0"/> <element name="pathSet" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> </sequence>

56

VMware, Inc.

Chapter 5 vSphere API Programming Model

NavigatethroughthevSphereAPIReferencetotheObjectSpecdefinition.Example 54showstheexcerpt. Example 5-4. ObjectSpec Definition as XML Schema


... <sequence> <element name="obj" type="vim25:ManagedObjectReference"/> <element name="skip" type="xsd:boolean" minOccurs="0"/> <element name="selectSet" type="vim25:SelectionSpec" minOccurs="0" maxOccurs="unbounded"/> </sequence> ...

ExtrapolatingfromtheWSDLdefinitionsshowninExample 52,Example 53,andExample 54might produceresultssimilartothoseshowninExample 55. Example 5-5. CreateFilter Spec Property Entry
<spec> <propSet> <type>VirtualMachine</type> <all>false</all> <pathSet>config.guestFullName</pathSet> </propSet> <objectSet> <obj type=Folder>group-v4</obj> <skip>true</skip> </objectSet> </spec>

Inthisexample,the<spec> elementidentifiesthespecparameteroftheCreateFilteroperation.Theorder oftheelementtagsisasdefinedintheXMLSchemafortheproperty(Example 52).ThepathSetproperty definesthefullpathtothenesteddataobjectofinterest.InExample 55,thepathSetpropertydefinesthepath totheguestFullNamepropertyofthetargetvirtualmachine.Figure 57showstheUMLofthesenesteddata objects. Figure 5-7. Nested Data Objects

VMware, Inc.

57

vSphere Web Services SDK Programming Guide

AllthesedetailsarepresentedinthevSphereAPIReference.ByexaminingtheWSDLdefinition,youcan constructthestringsneededtosubmitparametersthroughtheMOB.Table 58providesabriefsummaryof thestepsinvolvedwhenyouusetheMOBandthevSphereAPIReferencetogether. Table 5-8. Comparison of Datatypes for MOB Usage
Datatype Primitive Array Complex How to Input Values for Operations Enterthevalueasplaintextregardlessofitsdatatype(int,string,boolean).Donotusequotation marksorothermarkup. Usingthenameoftheparameterasthenameoftheelement,wrapthevaluesinaseriesofopeningand closingtagsforeacharrayelement. ObtainXMLSchemaformatinformationfromthevSphereAPIReferenceforthetype(fromtheShow WSDLtypedefinitionlink). Usetheschemadefinitiontoconstructthesequenceoftagsaroundthevalue(orvalues)youwanttopass totheMOB.

58

VMware, Inc.

Client Application Pattern

AnyclientapplicationthatyoucreateusingthevSphereWebServicesSDKmustconnecttotheserver,pass theappropriateuseraccountcredentialstoauthenticatetotheserver,andobtainingasessionfromtheserver. Thisgeneralpatternisdescribedinthischapter.Thechapterincludesthesetopics: MinimalClientApplicationPatternonpage 59 OverviewofaJavaSampleApplicationonpage 61 SavingandReusingaWebServerSessionTokenorCookieonpage 63 SupportingMultipleAPIVersionsonpage 63 HelperClassesforSampleApplicationsonpage 64

Minimal Client Application Pattern


Regardlessoftheprogramminglanguageusedfordevelopment,clientapplicationsthattargetthevSphere APItypicallyfollowthisbasicpattern: 1 2 3 4 5 ObtainasessiontokenandcreateaconnectiontotheWebService. InstantiatelocalproxyobjectforreferencetoServiceInstance. Logintotheserverusingappropriatecredentials. Processtheobjects. Closetheconnection.

Example 61providesashortclientapplicationthatfollowsthisbasicpattern.

Connecting to the Web Service


ToestablishaconnectionwiththeWebservice,youmustfirstpassintheuniformresourcelocator(URL)of theWebservice,useraccount,andpassword,intheconnectionstring. CAUTIONAlwaysgothroughavCenterServersystemtoperformoperationsonmanagedESX/ESXihosts. Invokingoperationsonmanagedhostsdirectly(ratherthanthroughvCenterServer)cancauseproblems.

Obtaining a Session Token and Creating a Connection Object


AswithotherWebservices,thevSphereWebservicemaintainssessionstateforeachclientconnectionby usingatokenintheHTTPheadertoidentifythesession.Thissessiontokenisreturnedtotheclientfromthe Webserviceandisthenusedtransparentlyinthemessagessentbetweenclientandserver.

VMware, Inc.

59

vSphere Web Services SDK Programming Guide

Table 61showstwoexamplesofsessiontokensreturnedfromconnectionstoVirtualCenterServer2.5and ESX/ESXi3.5. Table 6-1. Session Tokens as Strings


vCenterServer ESX/ESXi vmware_soap_session="63869259-F0FF-4DB5-9B3B-6493212AB9CD" vmware_soap_session="52b1910a-31ad-df35-95d1-210f86c55efb"

Witheveryconnection,theidentifierispassedintheHTTPheaderfromtheclienttotheserver.Sessiontokens canbepassedacrossmultipleconnectionstotheWebservice.Bydefault,sessionsexpireafter30minutesof inactivity,butthevaluecanbechanged.Forexample,tosetthetimeoutvalueto45minutes(2700seconds)of inactivity:


... _locator = new VimServiceLocator(); _locator.setMaintainSession(true); _service = _locator.getVimPort(new URL(url)); ((org.apache.axis.client.Stub)_service).setTimeout(2700); ...

TheWebservicessessiontokencanbesavedtoafileforlateruse.Forexample,ifyourclientapplicationis multithreaded,savethesessionanduseitforeachthreadintheapplication.SeeIntroductiontothe CredentialStore,inChapter 7,AutomatingClientApplicationLogin,onpage 67formoreinformation.

Logging In to the Server


AfterobtainingtheWebserversessiontoken,logintotheserverbypassingitavaliduseraccountand password,andsettingthelocale.Youcanpassanullvalueforthelocale.Theresultoftheloginprocessisa connectionobject. NOTESeeIntroductiontotheCredentialStoreonpage 67forinformationaboutthevSphereWebServices SDKcredentialstore,whichcanbeusedtostreamlinetheauthenticationprocessandmitigatetheriskthat administratorsorotherusersofyourclientapplicationsmightstorepasswordsinscriptsorotherfiles,such ascronorWindowsTaskdefinitions. Setting the Locale TheLoginoperationofSessionManagerhasanoptionalstringparameterforlocale.Example 61,Simple JavaClientApplication,onpage 61leavesthevalueforthelocaleunset:
_service.login(_sic.getSessionManager(), userName, password, null);

Whenthisoptionalparameterisnotprovided,theoperationusestheserverdefaultlocale. Tosetaspecificlocale,passtheappropriatestringvaluethatidentifiesthetwocharacterISO639languageID (forexample,en).YoucanalsoincludeanoptionaltwocharacterISO3166countryID.Forexample,en_US, de,fr_CA,zh,zh_CN,orzh_TW.


_service.login(_sic.getSessionManager(), userName, password, "en");

Alternatively,youcanuseSetLocaleoperationoftheSessionManagertosetthelocaleinaseparatestep.

Close the Server Connection


Forsecurityreasons,alwayscloseyourconnectionstotheserverwhentheapplicationcompletesitswork:
_service.logout(_sic.getSessionManager()); _service = null; _sic = null;

60

VMware, Inc.

Chapter 6 Client Application Pattern

Overview of a Java Sample Application


Example 61isacompleteclientapplicationthatdemonstratesthisminimalclientpattern.Thesampledoes notusethehelperclassesdiscussedinHelperClassesforSampleApplications,nordoesitfollowbest practices.Itdoesnothandleexceptions,forexample,anditusestheSunFakeTrustSocketFactoryclassto facilitatethesecuresocketslayer(SSL)handshakewithoutusingalocalJavaSSLcertificate.Thistechniqueis recommendedfordevelopmentenvironmentsonly.Donotusethistechniqueforproductionapplications. Example 61demonstratesthefollowingcommonclientapplicationtasks: Connectingtotheserver CreatingalocalmanagedobjectreferencetoServiceInstance ObtainingsomebasicinformationabouttheserveravailablefromtheServiceContentdataobject, withoutusingaPropertyCollector. Example 6-1. Simple Java Client Application
import com.vmware.vim25.*; import java.net.URL; public class MyClient { private ManagedObjectReference _svcRef; private VimServiceLocator _locator; private VimPortType _service; private ServiceContent _sic; private String fileName; private void createServiceRef() throws Exception { _svcRef = new ManagedObjectReference(); _svcRef.setType("ServiceInstance"); _svcRef.set_value("ServiceInstance"); } private void connectAndLogin(String hostName, String userName, String password) throws Exception { System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); String url = "https://"+hostName+"/sdk/vimService"; createServiceRef(); _locator = new VimServiceLocator(); _locator.setMaintainSession(true); _service = _locator.getVimPort(new URL(url)); _sic = _service.retrieveServiceContent(_svcRef); if (_sic.getSessionManager() != null) { _service.login(_sic.getSessionManager(), userName, password, null); } System.out.println(_sic.getAbout().getFullName()); System.out.println("API type is " + _sic.getAbout().getApiType()); System.out.println("API version is " + _sic.getAbout().getApiVersion()); } public static void main(String [] args) throws Exception { MyClient obj = new MyClient(); String serverName = args[0]; String userName = args[1]; String password = args[2]; obj.connectAndLogin(serverName, userName, password); } }

VMware, Inc.

61

vSphere Web Services SDK Programming Guide

Connectingtoaserverandobtainingamanagedobjectreferencerequiresthatanapplicationperforma numberoftasks,illustratedinExample 61. To connect to a server and obtain a managed object reference to the ServiceInstance 1 DefinealocalproxyobjectforthevimServiceport(vimServiceLocator,VimPortType).InJava,the variabledefinitionsmightlooklikethis:
private VimServiceLocator _locator; private VimPortType _service; ... _locator = new VimServiceLocator(); _locator.setMaintainSession(true); ...

2 3

Connecttotheserver,passingtheURL,useraccount,andpassword. CreateamanagedobjectreferencetoServiceInstance.ThecreateServiceRef()methodin Example 61createsthemanagedobjectreferencetoServiceInstanceandassignsitto_svcRef:


_svcRef = new ManagedObjectReference(); _svcRef.setType("ServiceInstance"); _svcRef.set_value("ServiceInstance");

ToobtaintheServiceContentobject,the_svcRefmanagedobjectreferenceisusedintheinvocationon thelocalserviceproxyobject(_service):
_sic = _service.retrieveServiceContent(_svcRef);

AftercheckingthataninstanceofSessionManagerexistsforthecurrentServiceContentobject,the examplecodeinvokestheloginmethodonthelocalproxyobject(_service).The _sic.getSessionManager()effectivelypassesthemanagedobjectreferenceofthecurrent SessionManagerinstancetotheloginmethod,alongwiththeusernameandpassword:


if (_sic.getSessionManager() != null) { _service.login(_sic.getSessionManager(), userName, password, null);

ThenullvalueintheargumentlistisfortheLoginoperationslocaleparameter. 6 Obtaintherootfolderoftheinventory,obtainareferencetooneormoreofthemanagers (PerformanceManager,forexample),andperformothertasksdefinedbyyourapplication.In Example 61,theonlyrealtaskperformedbytheapplicationisobtainingtheaboutpropertyfromthe ServiceContentdataobjectandprintingoutsomeofthevaluesfromtheAboutInfodataobject instance:


System.out.println(_sic.getAbout().getFullName()); System.out.println("API type is " + _sic.getAbout().getApiType()); System.out.println("API version is " + _sic.getAbout().getApiVersion());

Thecompiledclassisexecutedasfollows:
C:\>java MyClient pubslab01.vmware.com tooluser password

Table 62showstheoutputfromrunsofExample 61targetingESX/ESXiandvCenterServersystems. Table 6-2. Sample Runs of Simple Client Application
ESX VMware ESX 4.0.0 build-139526 API type is HostAgent API version is 4.0 vCenter Server VMware vCenter Server 4.0.0 build-139524 API type is VirtualCenter API version is 4.0

62

VMware, Inc.

Chapter 6 Client Application Pattern

Saving and Reusing a Web Server Session Token or Cookie


InExample 61,thesessiontokenisnotexplicitlyhandledbytheclientapplication.However,afteryourclient applicationobtainsasessiontoken,youcansaveittoalocalfile,forreuselater.Example 62showsan exampleofusingJavaandAxisclientlibrariestoobtainthesessiontokenfromthecurrentSOAPmessage context,andcastingittoaString.WiththesessiontokeninStringform,youcansaveitlocallytoafileon theclientforsubsequentreuse.Inyourconnectionsetupcode,youcancheckforanexistingsessionfileand usethatsessionfilewhenitsappropriatetodoso. Example 6-2. Obtaining Session Token from the Web Services Context
org.apache.axis.client.Stub clientStub = (org.apache.axis.client.Stub)_service; org.apache.axis.client.Call callObj = clientStub._getCall(); org.apache.axis.MessageContext msgContext = callObj.getMessageContext(); String sessionString = (String)msgContext.getProperty( org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE);

ThesampleapplicationsincludedwiththevSphereWebServicesSDKincludebothC#andJavahelperclasses thathandlethedetailsofcreatingsessions,obtainingsessiontokens,savingthesessionasastringtoafile,and reusingthesession.TheMicrosoft.NETWebservicesimplementationusestheCookieclasstohandlethe sessioninformationfromtheserver.

Supporting Multiple API Versions


WhenaclientapplicationconnectstoaWebservicerunningonanvSphereserver(ESX/ESXiorvCenterServer system),theserverdetectstheversionoftheAPIthatwasusedtodeveloptheclientandmakesavailableonly thoseoperationssupportedbytheclient. ClientapplicationsconveyinformationabouttheAPIversionusedintheSOAPmessagestheysendtoa vSphereserver.TheseSOAPmessagesincludeaversionIDinthesoapActionattribute.Thedetailsare handledtransparentlybytheSOAPtoolkitandtheclientproxycode.Theserveradjustsitsbehaviorasneeded basedontheclientsversioninformation,exposingtotheclienttheAPIversionsupportedbytheclient. StartingwithvSphere4.0,informationaboutthesupportedAPIversionsiscontainedinanXMLfile, vimServiceVersions.xml,locatedontheserver(Example 63). Example 6-3. Service-Versions File (vimServiceVersions.xml)
<?xml version="1.0" encoding="UTF-8" ?> - <!-Copyright 2008 VMware, Inc. All rights reserved. --> - <namespaces version="1.0"> - <namespace> <name>urn:vim25</name> <version>4.0</version> - <priorVersions> <version>2.5u2</version> <version>2.5</version> </priorVersions> </namespace> - <namespace> <name>urn:vim2</name> <version>2.0</version> </namespace> </namespaces>

Ifyouaredevelopingaclientapplicationthatmustsupportmultipleserverversionsatthesametime (ESX/ESXi4andESX/ESXi3.5,forexample),youmustobtaininformationabouttheAPIversionsthatare supportedontheserverandprovidelogicinyourcodetouseornotusefeatures,basedupontheversion information.

VMware, Inc.

63

vSphere Web Services SDK Programming Guide

ThevSphereWebServicesSDKpackageincludesseveralsampleapplicationsdemonstratinghowtowork withmultipleserverversions(Table 63). Table 6-3. Sample Applications that Demonstrate Working with Multiple API Version
Java SDK\samples\Axis\java\com\vmware\samples\version displaynewproperties displaynewpropertieshost displaynewpropertiesvm getvirtualdiskfiles hostpowerops installhostpatch querymemoryoverhead recordsession apputils\version C# SDK\samples\DotNet\cs\ DisplayNewProperties DisplayNewPropertiesHost DisplayNewPropertiesVM GetVirtualDiskFiles HostPowerOps ~ QueryMemoryOverhead RecordSession AppUtil\VersionUtil.cs

Identifying the API Version Supported by the Server


OneapproachtotargetingmultipleversionsoftheAPIfromthesameclientapplicationcodeistocheckfor theexistenceoftheserverversionsfileontheserver.IfyoudonotfindavimServiceVersions.xmlfileonthe server,youcanassumethattheserverisnotESX/ESXi4.0orvCenterServer4.0. Example 64isanexcerptfromtheVersionUtil.javasamplethatdemonstratesthisgeneralapproach. See thegetTargetNameSpaceAndVersion()methodofVersionUtil.javalocatedinthevSphereWeb ServicesSDKpackageformoreinformation. Example 6-4. Determining the URL from Which to Obtain the API Version Information
try { String wsdlUrlString = ""; String vimServiceXmlUrlString = ""; if((urlString.indexOf("https://") !=-1) || (urlString.indexOf("http://") !=-1)){ wsdlUrlString = urlString.substring(0,urlString.indexOf("/sdk")+4) + "/vimService?wsdl"; vimServiceXmlUrlString = urlString.substring(0,urlString.indexOf("/sdk")+4) + "/vimServiceVersions.xml"; } else{ wsdlUrlString = "https://"+ urlString + "/sdk/vimService?wsdl"; vimServiceXmlUrlString = "https://"+ urlString + "/sdk/vimServiceVersions.xml"; }

Helper Classes for Sample Applications


ThevSphereWebServicesSDKincludesmanysampleapplications,writteninC#andinJava,that demonstratefeaturesofthevSphereAPIandobjectmodel.Thesamplesrelyonseveralutilityclasses(or helperclasses).Thehelperclassesformthebasisofconsolestyle,commandlineapplications.Theseclasses (listedinTable 64andTable 65)handlecommandlineinputsuchascommonparameters,servername,and otherdetails.ThesehelperclassesarelocatedintheunpackedSDKdownload,intheselocations: Java Helper Classes %SDKHOME%\samples\Axis\java\apputils C# Helper Classes %SDKHOME%\samples\DotNet\cs\AppUtil

64

VMware, Inc.

Chapter 6 Client Application Pattern

Java Helper Classes


Table 64summarizestheJavaversionsoftheclienthelperclasses. Table 6-4. Helper Classes for Java Sample Applications
Package com.vmware.apputils Java Class ClientUtil.java Functional Description Providesconveniencemethodsforhandlinguser inputfromcommandline.Catcheserrors(faults). Logsoutputtoconsole. ProvideswrappermethodsforthevimService methods(thelocalproxycodemethods). CreatesinstancesofServiceConnectionand AppUtil,handlesconnectiontotheserviceand Supportsobtaininginitialmanagedobjectreferences forrootfolderandallitsdescendents. com.vmware.apputils.vim ServiceConnection.java Createsaninstanceoflocalproxyforconnectingto theserver,andobtainsmanagedobjectreferencesto severalmanagedobjects(ServiceInstance, ServiceContent,rootFolder)thatserveas startingpointsforobtainingobjects. Includesmethodsforsavingsessionsforreuseand loadingsavedsessions. IncludesignoreCertmethodforcircumventingthe localSSLcertificatehandling. com.vmware.apputils com.vmware.apputils.version AppUtil.java VersionUtil.java Setsuplogging,instantiateslocalClientUtil.Uses thecredentialstore. IdentifiestheversionoftheWSDLontheserver. ExtractspriorAPIversioninformationfromthe vimServiceVersions.xmlfileontheserver(ifit exists). ExtendstheAppUtilclasswithadditional functionalityforhandlingmultipleAPIversions. Conveniencemethodsforworkingwithvirtual machineobjects.Provisioning,lifecycle management.

com.vmware.apputils.vim

ServiceUtil.java

com.vmware.apputils.version com.vmware.apputils.vim

ExtendedAppUtil.java VMUtils.java

C# Helper Classes
Table 65liststhehelperclassesavailableforC#. Table 6-5. Helper Classes for C# Sample Applications
AppUtils AppUtil.cs ClientUtil.cs OptionSpec.cs ServiceUtil.cs ServiceUtilV25.cs TrustAllCertificatePolicy.cs Functional Description Conveniencemethodsforhandlinguserinputfromcommandline.Catcheserrors (faults).Logsoutputtoconsole. Conveniencemethodsforhandlinguserinputfromcommandline.Catcheserrors (faults).Logsoutputtoconsole. Helperclassforhandlingdefaultandcustomcommandlinearguments. WrappermethodsforthevimServicemethods(thelocalproxycodemethods)for API2.0andpriorreleases. WrappermethodsforthevimServicemethods(thelocalproxycodemethods)for API4.0,API3.5U2,API3.5U1,API3.5,andotherrecentreleases. Createsaninstanceoflocalproxyforconnectingtotheserver,andobtains managedobjectreferencestoseveralneededmanaged objectsServiceInstance,ServiceContent,rootFolder. HelperclassforidentifyingAPIversion.

VersionUtil.cs

VMware, Inc.

65

vSphere Web Services SDK Programming Guide

66

VMware, Inc.

Automating Client Application Login

Clientapplicationsthatlaunchautomaticallyforunattendedoperation,suchasasoftwareagentorcronjob, requirespecialtreatmenttofacilitatethelogonprocess.Noninteractiveclientapplicationslendthemselvesto poorsecuritypractices.Forexample,administratorsmaystorepasswordsinscriptorbatchfiles,tologin automatically. Tofacilitateautomatedloginforunattendedapplications,thevSphereWebServicesSDKincludesclientside credentialstorelibrariesandtoolsforautomatingtheloginprocessinamoresecuremanner.Theclient librariesobviatetheneedforsystemadministratorstokeeppasswordsinlocalscripts.Thischaptercontains informationaboutusingcredentialstorelibraries,andaboutcreatinguseraccountstousethesetools. The chapterincludesthesetopics: IntroductiontotheCredentialStoreonpage 67 OverviewoftheCredentialStoreBackingFileonpage 68 SecurityBestPracticesandtheCredentialStoreonpage 69 UsingtheCredentialStoreAdminToolonpage 70 UsingAuthorizationManagertoLimitAccessonpage 70

Introduction to the Credential Store


ThecredentialstoreincludedinthevSphereWebServicesSDKenablesmoreadvancedclientapplication capabilities,suchasautomatedlogintoservers.TheSDKincludesbothC#andJavaclientlibraries(Table 71) thatyoucanuseinyourownapplicationstosimplifytheloginandauthenticationprocess.Thecredentialstore includes: Apersistencefile(credentialstorebackingfile)thatstoresauthenticationcredentials.Currently,only passwordsaresupported.ThepersistencefilemapsaremoteuseraccountfromanESX/ESXihosttothe passwordforthatuserontheserver. C#,Java,andPerllibrariesformanagingthecredentialstoreprogrammatically.SeeTable 72foravailable methods. JavaandMicrosoftPowerShellbasedcommandlineutilitiesformanagingthecredentialstore. Table 7-1. Credential Store Client API Libraries
Namespace VMware.Security.CredentialStore(C#) CredentialStoreFactory.cs ICredentialStore.cs Package com.vmware.security.credstore (Java) CredentialStore.java CredentialStoreFactory.java

VMware, Inc.

67

vSphere Web Services SDK Programming Guide

Severalofthehelperclassesprovidedwiththesampleapplicationsusethecredentialstoremechanism. Table 7-2. Credential Store Client API Methods


Java addPassword(hostname, username, password) C# AddPassword(hostname, username, password) Description Storesthepasswordforthespecifiedhost anduser.Overwritesanyexisting passwordfortheuserifonealreadyexists inthecredentialstore.Createsthedefault credentialstorebackingfileinthedefault location(ifitdoesnotexist). Deletesthepasswordforthespecified userfromthecredentialstore. Deletesallpasswordsfromthecredential store. Returnsthepasswordforthespecified hostanduserfromthecredentialstore. Returnsthesetofhostscontainedinthe credentialstore. Returnsthecollectionofallusernames thathavepasswordsstoredforthe specifiedhostname. Closesthecredentialstore,preventing furthermethodinvocations.Releases associatedresources.

removePassword(hostname, username) clearPasswords() getPassword(hostname, username) getHosts() getUsernames(hostname)

RemovePassword(hostname, username) ClearPasswords() GetPassword(hostname, username) GetHosts() GetUsernames(hostname)

close()

Close()

ThecredentialstoreclientAPIsuseaplatformdependentdefaultfilelocationwhenthefilelocationisnot specifiedexplicitly.

Overview of the Credential Store Backing File


ThecredentialstorebackingfileisatextbasedfileformattedasXMLthatissavedlocallyontheclientmachine foraccessatruntime.Unlessotherwisespecified,thebackingfileislocatedinthedefaultlocationshownin Table 73.Thecredentialstorepersistslocallyonaperuserbasiseachuserhashisorherowncredentialstore backingfilethatshouldbeprotectedbyappropriatefileaccesspermissions. CAUTIONThecredentialstorebackingfileusesfilesystemlevelpermissionstoensurethatpasswordsremain confidential.Administratorsoruserswhoshareworkstationsshouldsettheappropriatefilepermissionson theirrespectivecredentialstorebackingfiletoensurethattheyalonecanaccessthefileanditscontents.

Credential Store Backing File Structure


Example 71showsthevalidXMLelementsthatarereadandwrittentothefile. Example 7-1. Credential Store File Format
<?xml version="1.0" encoding="UTF-8"?> <viCredentials> <version>1.0</version> <passwordEntry> <host>mi6.vmware.com</host> <username>agent007</username> <password>IhWS1saIhtsw2FbIh0w2F2...</password> </passwordEntry> <passwordEntry> ... </passwordEntry> ... </viCredentials>

68

VMware, Inc.

Chapter 7 Automating Client Application Login

Using Samples to Understand the Credential Store


ThevSphereWebServicesSDKCreateUserandSimpleAgentsampleapplicationsdemonstratethe functionalityavailablethroughthecredentialstoreclientlibraries(Table 71). TheCreateUserapplicationcreatesauseraccountandpasswordbasedonrandomnumbergeneration schemefortheserver,andpopulatesthelocalcredentialstorebackingfilewiththisinformation.Ifthebacking filedoesnotexist,itiscreatedinthedefaultlocation(Table 73). ToruntheCreateUserapplication,youmustenterthenameoftheserverwithanESX/ESXiadministrator accountandpassword.Agenerateduseraccountnameandgeneratedpasswordarecreatedontheserver.
java com.vmware.samples.simpleagent.CreateUser --server <servername> --url https://<servername>/sdk --username <adminuser> --password <pwd> --ignorecert ignorecert

TheCreateUsersampleprintsoutasfollowsuponsuccessfulexecution:
Started Successfully created user and populated the credential store Ended CreateUser

TheSimpleAgentsampleapplicationdemonstrateshowthecredentialstorelibrariescanbeusedtoextract theuseraccountandpasswordatruntimetoauthenticateauseraccount,noninteractively.Torunthe SimpleAgentsample:


java com.vmware.samples.simpleagent.SimpleAgent <servername>

Theconsoleshoulddisplayamessagesimilartothefollowing:
Connected Successfully VMware ESX Server 3.5.0 build-78591

CAUTIONTheCreateUsersampleapplicationCreateUserisfordemonstrationpurposesonlyandshould notbeusedasamodelforproductioncode.CreateUserbreaksoneofthecardinalrulesofsecuritybest practices:Nevergiveuseraccountsmoreprivilegesthanneededdothetasksrequiredofthem.

Security Best Practices and the Credential Store


Theprincipleofleastprivilegeshouldbeappliedtoanyagentlikesoftwareorautomatedapplicationthat takesadvantageofthecredentialstore.Thiscommonsecuritytenetdictatesthatuseraccountsbegiventhe minimalnumberofprivilegesonthesystemthattheyrequiretodotheirjobs.

Using the Principle of Least Privilege with the Credential Store


Tofollowthiscommonsensebestpractice,VMwarerecommendsthatthecredentialstorebeusedonlyas describedhereinaproductionenvironment.Indevelopmentandtestenvironments,securitymightnotbeas muchofaconcern. To follow security best practices while using the credential store 1 2 Nevergrantadministratorprivilegestoauseraccountassociatedwithanautomatedscriptorsoftware agent,especiallyonethatusesthecredentialstore. CreatespecificrolessolelyforpurposesofusinganySDKbasedapplicationthatusesthecredentialstore. Or,selectapredefinedsampleuserroleifoneexiststhatmeetsyourneeds. Forexample,ifyouaredevelopinganagentlikeapplicationtoautomaticallylaunchtheVMware ConsolidatedBackuputility,youmightusetheVMwareConsolidatedBackupUtilityrole(roleID7). Ifapredefineduserrolethatmeetstheneedsofyourapplicationdoesnotexist,createarolewithonly thoseprivilegesneededfortheapplication.SeeTable 46,SystemandPreDefinedUserRoles,on page 41formoreinformationaboutroles. 3 Createauseraccountexpresslyforusewiththeagentorapplication.

VMware, Inc.

69

vSphere Web Services SDK Programming Guide

4 5

Applythespecificrolecreatedinstep2totheuseraccountcreatedinstep3. Storethespecialuseraccountandpasswordinthecredentialstore,usingthe CredentialStoreAdministrationtoolasdetailedinCredentialStoreAdministrationToolfor NonInteractiveClientsonpage 173.

CAUTIONTheCreateUsersamplebreakstheprincipleofleastprivilege,bygrantingtheuseraccountthe Administratorrole(1).Neverdothisinaproductionenvironment.

Using the CredentialStoreAdmin Tool


InadditiontothefileslistedinTable 71,thevSphereWebServicesSDKalsoincludesanadministrationtool forcreatingandmanagingthecredentialstore.YoucanusetheCredentialStoreAdmintooltoexaminethe contentsofthecredentialstore.Forexample,youcanusetheCredentialStoreAdmintooltoseethe generateduseraccountsandpasswordscontainedinthefile. Table 7-3. Default Credential Store Locations
Client Linux WindowsVista WindowsXP Windows2000 Default Location $HOME/.vmware/credstore/vicredentials.xml C:\Users\[User Name]\AppData\Roaming\VMware\credstore\vicredentials.xml C:\Documents and Settings\[User Name]\Application Data\VMware\credstore\vicredentials.xml

Ifyouusetheclientlibrariesforthecredentialstoreinanapplicationthatyoucreate,youmustalsomanage thecredentialstoreontheclientmachinesthatmightrunyourapplication.SeeCredentialStore AdministrationToolforNonInteractiveClients,inAppendix C,DeployingClientApplications,on page 173formoreinformation.

Using AuthorizationManager to Limit Access


AuthorizationManagerprovidesoperationsforaddingrolesandassociatingpermissionswithmanaged entitiesinavSphereinventory.YoumightwanttocreatenewrolesiftheexistingrolesdefinedforESX/ESXi orvCenterServerdonotmeetyourneeds. Forexample,agentstyleclientapplicationsthatlogonandauthenticateautomaticallyusingthecredential store,shouldbeassignedrolesthatencompassonlytheprivilegesneeded.Ifapredefinedroledoesnotmeet thisneed,youshoulddefineanewonethatcontainsonlytheminimumsetofrequiredprivileges. Itisalsobestpracticetocreatespecificuseraccountsforsuchagentstyleclientapplicationsandmanyother clientapplicationsthatperformadministrativetasks.Ratherthanusetherootorotheraccountfromthe administratorsgroup,createanewuseraccountwithonlythenecessaryprivilegesontheserver.

Creating New User Accounts


NewuseraccountsforvSphereservers(ESX/ESXi)canbecreatedthroughtheAPIbyusingthe HostLocalAccountManagerserviceinterface. To create a user account on ESX/ESXi through the API 1 2 ObtainamanagedobjectreferencetotheHostLocalAccountManagerofthetargetsystem. CreateaHostAccountSpecdataobjectthatdefinesthepropertiesoftheuseraccount,including descriptionandpassword. DefineaccountnamesandpasswordsaccordingtotheconfigurationrequiredbyyourESX/ESXisystem foruseraccountnamingconventionsandpasswordrequirements,suchasminimumlength,characterset, andotherrequirements.

70

VMware, Inc.

Chapter 7 Automating Client Application Login

InvoketheCreateUserAccountoperation,passingthemanagedobjectreference(fromstep1)andthe HostAccountSpecdataobject(step2)intheinvocation. Atthispoint,youcancreateagroup(ifitdoesnotyetexist).

4 5

CreateaHostAccountSpecdataobjectthatdefinesthepropertiesofthegroup(description,id).No passwordisneeded. InvoketheCreateGroupoperation,passingthemanagedobjectreference(fromstep1)andthe HostAccountSpecdataobject(fromstep4)intheinvocation. Nowthattheuserandgroupbothexist,youcanaddtheusertothegroup.

InvoketheAssignUserToGroupoperation,passingthemanagedobjectreferencetothe HostLocalAccountManager,theuserid,andthegroupidintheinvocation.

Applying Permission to an Entity


Example 72showssomeofthecoderequiredtocreateanewuseraccountandapplyapermissiontoanentity thatgrantsaccesstotheuseraccountbasedonarole.Therole(4)assignedinthisexampleisdefinedasa VirtualMachinePowerUser.ThesampleusesAuthorizationManagertograntpermissionstotheuserand toassociatethepermissionwiththemanagedentityintheinventoryinthisexample,therootFolder. Example 7-2. Creating a User Account
... anagedObjectReference _authManRef = _sic.getAuthorizationManager(); public class CreateUser { private static AppUtil appUtil= null; private void createUser() throws Exception { ManagedObjectReference hostLocalAccountManager = appUtil.getConnection().getServiceContent().getAccountManager(); ManagedObjectReference hostAuthorizationManager = appUtil.getConnection().getServiceContent().getAuthorizationManager(); // Create a user HostAccountSpec hostAccountSpec = new HostAccountSpec(); hostAccountSpec.setId(userName); hostAccountSpec.setPassword(password); hostAccountSpec.setDescription("my delegated admin auto-agent software"); appUtil.getConnection().getService().createUser(hostLocalAccountManager, hostAccountSpec); ManagedObjectReference rootFolder = appUtil.getConnection().getServiceContent().getRootFolder(); Permission permission = new Permission(); permission.setGroup(false); permission.setPrincipal(userName); // Assign the Virtual Machine Power User role permission.setRoleId(4); permission.setPropagate(true); permission.setEntity(rootFolder); appUtil.getConnection().getService().setEntityPermissions(hostAuthorizationManager, rootFolder, new Permission [] {permission}); ...

VMware, Inc.

71

vSphere Web Services SDK Programming Guide

72

VMware, Inc.

Obtaining References to Objects and Property Values from the Server

ForanyclientapplicationyoudevelopusingthevSphereAPI,youmustobtainoneormoremanagedobject referencestotheserviceinterfacesthatyouwanttouse,andtospecificobjectsintheinventorythatyouwant tomanageoruseinyourapplication.ThePropertyCollectortheserviceinterfacethatyouusetoobtain referencestomanagedobjects,toobtainvaluesofthepropertiesfrommanagedobjects,andtomonitor changesandupdateyourclientsidewithnewvaluesforserversideobjectsasneededintheapplication. This chapterincludesthesetopics: SampleCodeReferenceonpage 73 IntroductiontothePropertyCollectoronpage 74 UnderstandingthePropertyFilterSpeconpage 75 RetrievePropertiesOperationonpage 76 CreateFilterandUpdateOperationsonpage 77 PropertyCollectorPerformanceonpage 79 UsingtheSearchIndextoObtainManagedObjectReferencesonpage 80

Sample Code Reference


Table 81liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesomeof thetopicsdiscussedinthischapter. Table 8-1. Sample Applications that Demonstrate PropertyCollector and SearchIndex Operations
Java SDK\samples\Axis\java\com\vmware\samples\general GetUpdates.java PropertyCollector.java SearchIndex.java SimpleClient.java TaskList.java C# SDK\samples\DotNet\cs\ GetUpdates PropertyCollector SearchIndex SimpleClient TaskList WatchVM

ThesampleslistedinTable 81dependonseveralhelperclassesthatusethePropertyCollectorextensively tonavigatethroughtheinventory,toobtainreferencesandvaluesofproperties,andtokeeptheclientside objectstatesynchronizedwiththestateofserverobjects.SeetheclasseslocatedintheAppUtilsubdirectory oftheJavaandC#samples,respectively,foradditionalexamplesofusingPropertyCollector.

VMware, Inc.

73

vSphere Web Services SDK Programming Guide

Introduction to the PropertyCollector


BeyondthebasicclientapplicationpatternintroducedinChapter 6,ClientApplicationPattern,onpage 59, anyclientapplicationtypicallyperformsmanydifferentoperationstoobtaininformationabouttheserver objectsatanygiventime.ThePropertyCollectorisaserviceinterfacethatsupportsthesekindsoftasks fromaclientapplication: Navigatetheinventoryandobtaininformationaboutspecificmanagedobjectsfromtheinventory,such aswhetheravirtualmachineispoweredonornot,whetherahostinaclusterisofflineoron,andsoon. Keepdataaboutserverstateintheclientapplicationsynchronizedwiththestateofserverobjectsasmuch asrequiredbytheapplication. UsingaPropertyCollectorrequiressomeknowledgeoftherelationshipsamongmanagedobjects. You mustunderstandthegeneralhierarchicalarrangementofentitiesintheinventorybeforeyoucancreatea filterthatstartscollectingobjectsorpropertiesatanypointintheinventoryhierarchy. Forexample,aninventoryalwaysstartsfromarootFolderwhoseparentpropertyvalueisalwaysUnset. ObjectsintheinventorydescendfromthisrootFolderintheorderdeterminedbytherelationshipofparent propertiesandchildEntityproperties,followingtheconstraintsimposedbytheunderlyingmanagedentity types.StepthroughsomeofthesampleslistedintheSampleCodeReferenceonpage 73,includingthe helperclasses,forexamplesofusingPropertyCollectortonavigateallobjectsavailableinthehierarchy. SeeChapter 3,UnderstandingtheInventory,onpage 25formoreinformationaboutinventoryentitiesand theirrelationships.

PropertyCollector Operations
TheServiceInstanceofavSphereserverprovideseachclientsessionwithitsowninstanceofthe PropertyCollector.APropertyCollectorhasasingleproperty,filter,thatisdefinedasanarrayof referencestoPropertyFiltermanagedobjects. Figure 8-1. PropertyCollector and PropertyFilter Managed Object Types

Thefilterpropertyissessionspecific.Itdoesnotexistbeyondthesession,norcanitbesharedwithanother session.Whenasessionends,theserverdestroysanyfiltersassociatedwiththesession. ThePropertyCollectorprovidesoperationsforcreatingfilterstoobtainspecificpropertiesandobjects, checkforupdatesonspecifiedobjects,andmonitorchangestopropertiesontheserver.Table 82provides summaryinformationaboutalltheoperationsavailableinaPropertyCollector. Table 8-2. PropertyCollector Operations
Operation CancelWaitForUpdates Parameter _this Type MOR >PropertyCollector Description Cancelsaninprogress WaitForUpdatesoperation.Upon successfulcancellation,thisoperation throwsaCancelledfault. ReturnsanUpdateSetdataobjectthat containsallrequestedpropertiesforthe specifiedversion. Returnsareferencetoa PropertyFiltermanagedobjectthat meetsthespecificationsdefinedinthe specparameter.

CheckForUpdates

_this version

MOR > PropertyCollector string MOR > PropertyCollector PropertyFilterSpec boolean

CreateFilter

_this spec partialUpdates

74

VMware, Inc.

Chapter 8 Obtaining References to Objects and Property Values from the Server

Table 8-2. PropertyCollector Operations (Continued)


Operation RetrieveProperties Parameter _this specSet WaitForUpdates _this version Type MOR > PropertyCollector PropertyFilterSpec[] MOR > PropertyCollector string Description ReturnsanarrayofObjectContent dataobjectscontainingmanagedobject referencesandpropertiesformanaged objects. ReturnsanUpdateSetdataobject containingthechangesbetweenthe previousversionandthecurrentvalues oftheproperties.

ThroughtheoperationslistedinTable 82, PropertyCollectorsupportstwogeneralapproachesto obtainingobjectsandpropertiesfromtheserver: Ifyoudonotneedyourclientapplicationtokeepclientstatesynchronizedwithserverstate,youusethe RetrievePropertiesoperation.Theserverinstantiatesafilter,collectsyourspecifiedobjectsand propertiesasaObjectContentdataobjectandreturnsittotheclientapplication.SeeRetrieveProperties Operationonpage 76formoreinformation. Ifyourapplicationmustkeepclientstatesynchronizedwiththeserverstate,youusetheCreateFilter operationinconjunctionwithCheckForUpdatesorWaitForUpdatesoperations.SeeKeepingClient DatainSynchwithServerObjectsonpage 78formoreinformation. BothapproachesrequireyoutocreateacomplexdatastructurecalledaPropertyFilterSpecthatdefines thepropertiesandobjectsyouwanttoretrievefromtheserver.

Understanding the PropertyFilterSpec


AsshowninFigure 82,PropertyFilterSpecdataobjecthastwoproperties,objectSetandpropSet, definedasinstancesofanarrayofObjectSpecdataobjectsandanarrayofPropertySpecdataobjects, respectively. Figure 8-2. PropertyFilterSpec and Associated Data Objects

PropertyFilterSpecrequiresatleastoneinstanceofanObjectSpec,butthearrayofPropertySpecobjects canbeempty.YouusetheObjectSpectospecifythestartingpointintheinventorythatyouwantthefilterto useforthecollection.TheobjpropertyofObjectSpecspecifiesthetypeofobject(themanagedobjecttype name,asastring)tocollectfromtheserver. Fortheobjproperty,youuseanyofthevalidstringsdefinedforthetypepropertyofthe ManagedObjectReferencedataobject.Validstringsarethenearly60managedobjecttypes,fromAlarm throughVmwareDistributedVirtualSwitch.SeeTable 51,ValidValuesforManagedObjectReference TypeProperty,onpage 46forthelistofvalidtypestrings.

VMware, Inc.

75

vSphere Web Services SDK Programming Guide

TheobjpropertyofObjectSpecisdefinedasaninstanceoftheManagedObjectReferenceforwhichyou wanttostartthecollection.UsingObjectSpecwithoutaPropertySpecreturnsthecompleteobjectfromthe specifiedlocation.Toreturnspecificpropertiesfromtheobject,youmustuseObjectSpecinconjunctionwith oneormorePropertySpecobjectsthatidentifiestheproperties. SeethevSphereAPIReferenceforcompleteinformation.

TraversalSpec Data Object and Recursion


TheTraversalSpecdataobjecttypeextendstheSelectionSpecdataobjectwithseveralpropertiesthat enableyourapplicationtoretrievepropertiesandobjectsrecursively.Youcancreateextensivenavigational specificationsusingtheTraversalSpecinconjunctionwithSelectionSpecdataobjects. Figure 8-3. Nested TraversalSpec

InaseriesofmultipleTraversalSpecdataobjectsassociatedwithaSelectionSpec,thenameofthelast TraversalSpecdataobjectintheseriesmustmatchthenameoftheSelectionSpec(Figure 83).

RetrieveProperties Operation
TheRetrievePropertiesoperationisdesignedforonetimeoradhocuse.Itcollectsalltheobjectsand propertiesyouspecifyinoneormorePropertyFilterSpecobjects.Thefilterisnotaddedtothearraythat makesupthefilterpropertyofPropertyCollector,butisinsteadusedimmediatelybytheserverto collecttheobjectsandpropertiesspecifiedinyourPropertyFilterSpecobjects,andthendestroyedafterthe serverreturnstheresultstoyourclient. TheRetrievePropertiesoperationacceptsanarrayofPropertyFilterSpecobjectsforitsspecSet parameter.TheoperationreturnsanObjectContentdataobject(Figure 84). Figure 8-4. ObjectContent Data Object Returned by RetrieveProperties Operation

Inyourclientcode,youobtainthevaluesfromthiscompositedatastructureandprocessfurtherinyourclient applicationasneeded.

76

VMware, Inc.

Chapter 8 Obtaining References to Objects and Property Values from the Server

Example 81showsanexcerptfromtheServiceUtil.javahelperclasscontainedinthevSphereWeb ServicesSDKsamplespackage. Example 8-1. Loop that Obtains References from an ObjectContent Data Object
... ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] propary = null; String propval = null; boolean found = false; for (int oci = 0; oci < ocary.length && !found; oci++) { oc = ocary[oci]; mor = oc.getObj(); propary = oc.getPropSet(); propval = null; if (type == null || typeIsA(type, mor.getType())) { if (propary.length > 0) { propval = (String)propary[0].getVal(); } found = propval != null && name.equals(propval); } } if (!found) { mor = null; } return mor; } // close for loop ...

CreateFilter and Update Operations


Tokeepclientsideobjectssynchronizedwiththeserverobjects,youstartbyusingCreateFiltertodefine thefilter.YouobtainservercontentusingCheckForUpdatesorWaitForUpdates,afteryourfiltersexistin yourPropertyCollector. TheCreateFilteroperationhasonlythreeparameters.However,thespecproperty,definedasaninstance ofaPropertyFilterSpec,consistsofseveralotherdataobjects,mostnotably,anObjectSpecanda PropertySpec.SeeUnderstandingthePropertyFilterSpeconpage 75foradditionalbackground informationaboutthesedataobjects.Figure 85showsthegeneralrelationshipoftheseobjectsasinputto PropertyCollectorCreateFilteroperation. Figure 8-5. Using the PropertyCollector

VMware, Inc.

77

vSphere Web Services SDK Programming Guide

To define the data objects needed to create a filter 1 IdentifythestartingobjectforthecollectionbycreatinganObjectSpecthatspecifiesthetypeofobjectin intheobjpropertyofObjectSpec.Ifyouwantthecollectiontoincludethestartingobject,settheskip propertyofObjectSpectofalse. DefinethespecificationforthePropertySpec,orpassnullfortheselectSetparametertoretrieve completeobjects. InstantiatethePropertyFilterSpecusingthearraysofObjectSpecandPropertySpecobjectsthat specifythedetailsyouwanttogatherinthecollection. UsetheCreateFilteroperationofPropertyCollector,passingthePropertyFilterSpecwiththe referencetothePropertyCollector.WhenyouinvokeCreateFilter,youalsopassavalueforthe partialUpdateproperty: SetpartialUpdatetofalsetoobtaincompletepropertyvalues. SetpartialUpdatetotruetoobtainnestedpropertyvaluesonly. 5 ThePropertyCollectorinstantiatesthePropertyFilterandaddsittothearrayoffiltersthatmake upthefilterpropertyonthatPropertyCollectorinstance.Theoperationreturnsthemanagedobject referencetothefiltertoyourclientapplication.

2 3 4

Keeping Client Data in Synch with Server Objects


WhenyouusetheCreateFilteroperationtospecifytheobjectsorpropertiesthatyouwanttoworkwithin yourapplication,theservercreatesfilterobjectsthatmeetyourspecification,populatingthefilterpropertyof thePropertyCollectorwiththearrayofreferencestoPropertyFilterobjects.CreateFilterdoesnot returnanyobjectsorpropertyvaluestotheclient. Toobtaindataontheclientside,youmustuseCheckForUpdatesorWaitForUpdatestoobtainUpdateSet objectsfromtheserver,usingthefilterorfiltersdefinedduringthesessionwiththeCreateFilteroperation. Table 83listssomeoftheadvantagesanddisadvantagesofthesetwooperations. Table 8-3. PropertyCollector Operations Compared
Operation CheckForUpdates Advantages Pollingmechanismthatreturnsonlyproperties thathavechangedsincetheversionspecified. Returnschangeddataonly,sobetternetwork utilizationthanRetrieveProperties. Notificationmechanismthatblocksuntilan updateoccurs.Efficientuseofnetwork resources.Theonlyoperationofthethreethat youcancancel. Disadvantages Returnsanemptysetevenwhennothinghas changedontheserver.Dependingonyour clientapplication,thismightbeinefficient. Blocksprocessingthreaduntilupdatesoccur. However,thiscallcanbecancelledsoyoucan monitorthetimetheoperationistakingand cancelifnecessary.

WaitForUpdates

BothoperationsreturnUpdateSetdataobjects,thecompositedatastructureshowninFigure 86.Both CheckForUpdatesandWaitForUpdatesapplythecompletearrayoffiltersdefinedforthe PropertyCollectortotheserverandreturnanUpdateSetobject.

78

VMware, Inc.

Chapter 8 Obtaining References to Objects and Property Values from the Server

Figure 8-6. UpdateSet Data Object Returned by CheckForUpdates and WaitForUpdates Operations

BothCheckForUpdatesandWaitForUpdatesreturnonlychangedobjectsandpropertiesbasedontheunion ofallfiltersassociatedwiththePropertyCollectorforthesession. Thefirsttimeyouinvokeeitheroftheseoperationsaftercreatingyourfilter,useanemptystring()forthe versionparameter,toobtainacompletesetofresults.Theresultreturnedcontainsanewversionnumber thatyouuseinthenextcall. SeetheGetUpdates.java,GetUpdates.cs,ServiceUtil.java,andServiceUtil.cssamplesinthe vSphereWebServicesSDKpackageforsomeexamplesofusingtheseoperations.

PropertyCollector Performance
ThesefactorscanaffecttheperformanceofaPropertyCollectorforanygivensession: Numberofobjects Numberofproperties Densityofpropertydata(composite,nesteddataobjects) Frequencyofchangestotheobjectsandpropertiesontheserver Depthoftraversal(numberofpropertiestraversed) Inaddition,avSphereserverisaffectedbythenumberofPropertyCollectorinstancesandthenumberof filterseachissupportingacrossallsessionsontheserver. ForVirtualCenterServer2.5,foraninventoryof2,000virtualmachinessupportingabout25clientapplications simultaneously,performanceisacceptableuptoabout12moderatelycomplexfiltersmonitoringupdateson all2,000virtualmachines.Ifthefiltersincludecomplextraversalobjects,performancemightdegrade appreciablyunlessyoureducethenumberoffiltersacrossthesystem. ConsiderusingtheViewManagerandViewobjectsinconjunctionwithPropertyCollectortominimizeboth theoverheadonPropertyCollectorandtheamountofnetworktrafficforyourclientapplication. See ImprovingCollectionPerformancebyUsingtheViewManagerandView Objectsonpage 79.

Improving Collection Performance by Using the ViewManager and View Objects


TheViewManagerserviceinterfacesupportsclientaccesstoservermanagedobjectcontent.Youusethe ViewManagertocreatecustomizedobjectsthatrepresentsubsets,orviews,ofspecificinstancesofselect managedobjecttypesontheserver.

VMware, Inc.

79

vSphere Web Services SDK Programming Guide

TheViewManagerprovidesoperationsforcreatingseveraldifferentkindsofviews.Theseviewsextendfrom theViewandManagedObjectViewbasetypes(seeFigure 87). Figure 8-7. ViewManager and View Managed Object Types and View Subtypes

YouusetheappropriatecreateoperationofViewManagertocreateaview.AsshowninFigure 87,viewtypes includeContainerView,InventoryView,andListView. Forexample,youusetheCreateContainerViewtocreateaContainerView.TheContainerViewenables youtomonitorobjectsassociatedwithanyofthecontainerobjectssupportedontheserver,includingFolder, Datacenter,ComputeResource,HostSystem,ResourcePool,andVirtualAppobjects.Youusethe CreateInventoryViewtocreateanInventoryView. TheInventoryViewprovidesoperationsforopeningandclosingfoldersonaninventory.Itsviewproperty containsanarrayofthemanagedobjectreferencestotheobjectsthatmakeuptheinventory.Aswith PropertyCollector,thelifetimeofanyViewobjectisthedurationofthesession,oruntiltheobjectis explicitlydestroyed,byinvokingitsDestroyViewoperation. AfteryoucreatetheappropriateViewobjectsforyourapplication,insteadofusingaPropertyCollector withtheentireserverstructure,youusePropertyCollectorwiththeviews.Theappropriateviewsofserver objectsenableyoutocreatemuchsimplerPropertyFilterSpecobjectstodefineyourfilters,andtheback andforthcommunicationbetweentheclientandserverismoreefficient. SeethevSphereAPIReferenceformoreinformationaboutViewManager,aboutViewmanagedobjecttypesand subtypes,andabouthowtousetheseobjectsinconjunctionwithPropertyCollector.

Using the SearchIndex to Obtain Managed Object References


TheSearchIndexmanagedobjectistheserviceinterfaceforretrievingmanagedentitiesbyusingspecific propertyvalues,suchasinventorypath,datastorepath,DNSname,andvariousothermanagedentity propertyvalues. Forexample,ifyouknowtheIPaddressofavirtualmachine,youcanobtainitsmanagedobjectreferenceby usingtheFindByIpoperationofSearchIndex.YoucanusethePropertyCollectortofirstobtainthevalue ofaspecificproperty,andthenusethatvalueasinputtoSearchIndex.Seethesampleapplications SearchIndex.javaandSearchIndex.csformoreinformationaboutusingSearchIndex.

80

VMware, Inc.

Chapter 8 Obtaining References to Objects and Property Values from the Server

Figure 8-8. PropertyCollector and SearchIndex Managed Objects

Table 84listsallSearchIndexoperations.WiththeexceptionoftheFindChildandFindByInventoryPath operations,SearchIndexoperationsacceptanoptionaldatacenter,tolimitthesearchtoaspecific Datacenterintheinventory.UnmanagedESX/ESXisystemshaveasingledatacenter,ha-datacenter. Table 8-4. SearchIndex Operations


Operation FindAllByDnsName Parameter _this datacenter dnsName vmSearch FindAllByIp _this datacenter ip vmSearch FindAllByUuid _this datacenter uuid vmSearch instanceUuid FindByDatastorePath _this datacenter path FindByDnsName _this datacenter dnsName vmSearch FindByInventoryPath _this inventoryPath Type MOR>SearchIndex MOR>Datacenter string boolean MOR>SearchIndex MOR>Datacenter string boolean MOR>SearchIndex MOR>Datacenter string boolean string MOR>SearchIndex MOR>Datacenter string MOR>SearchIndex MOR>Datacenter string boolean MOR>SearchIndex string Returnsanarrayofreferencestomanaged entitiesthatmatchtheBIOSUUIDspecified. Set vmSearchtotruetoincludevirtual machinesinthesearchresults.IfvmSearchisset totrue,youcanalsosetinstanceUuidtotrueto usevirtualmachineinstanceUUIDinthesearch results. Returnsareferencetoavirtualmachineatthe specifieddatastorelocation.Thepathisthe locationofthe.vmxfilethatcomprisesthevirtual machine. Returnsareferencetothemanagedentitythat matchesthefullyqualifieddomainnameofthe hostorvirtualmachine,asconfiguredusing VMwareTools.SetvmSearchtotruetosearch forvirtualmachines.Otherwise,thisoperation returnshosts. Returnsareferencetothemanagedentityatthe specifiedlocationintheinventory.Inventory pathsmustincludethecontainingfolders. For example,theinventorypathtoavirtual machineonanunmanagedESX/ESXihostmust includethecontainingdefaultdatacenterfolder andthedefaultvmFolder,asinthisexample: ha-datacenter/vm/pubslab-linux FindByIp _this datacenter ip vmSearch MOR>SearchIndex MOR>Datacenter string boolean Returnsareferencetothemanagedentitythat matchestheIPaddressofthehostorvirtual machine,asconfiguredusingVMwareTools. Set vmSearchtotruetoincludevirtual machinesinthesearch.Otherwise,search includeshostsonly. Description Returnsanarrayofreferencestomanaged entitiesthatmatchthefullyqualifieddomain nameofthehostorvirtualmachine,as configuredusingVMwareTools.Ifnoentities matchthednsNamesubmitted,returnsanempty array. Returnsanarrayofreferencestomanaged entitiesthatmatchtheIPaddressofthehostor virtualmachine,asconfiguredusingVMware Tools.IfnoentitiesmatchtheIPaddress,returns anemptyarray.

VMware, Inc.

81

vSphere Web Services SDK Programming Guide

Table 8-4. SearchIndex Operations (Continued)


Operation FindByUuid Parameter _this datacenter uuid vmSearch instanceUuid FindChild _this entity name Type MOR>SearchIndex MOR>Datacenter string boolean boolean MOR>SearchIndex MOR>ManagedEntity string Returnsareferencetothemanagedentitythat matchesthenameofthechildobject.Thesearch includesonlytheimmediatechildren,suchasthe datastoreFolder,hostFolder, networkFolder,andvmFolderofaDatacenter. Description Returnsareferencetothemanagedentitythat matchtheBIOSUUIDspecified.SetvmSearchto truetoincludevirtualmachinesinthesearch results.IfvmSearchissettotrue,youcanalso setinstanceUuidtotruetousevirtualmachine instanceUUIDinthesearchresults.

SeethevSphereAPIReferenceformoreinformationabouttheseoperations.

82

VMware, Inc.

Overview of the Task Infrastructure

AsdiscussedinAsynchronousClientServerApplicationStyleonpage 46,manyoftheoperationsavailable throughthevSphereAPIareasynchronous.Ratherthanblockingothercallerswhileexecutingtocompletion, asynchronousoperationsreturnareferencetoaTaskmanagedobject.Operationsassociatedwithan ESX/ESXihostanditsvirtualmachinesalsogenerateoneormoreEventdataobjectsthatprovidestatus, source,andotherinformationabouttheoperation.ThischapterprovidesanoverviewoftheTaskand TaskManagermanagedobjectsasfundamentalbackgroundfortheprogrammingmodel,andanintroduction toEventdataobjects.Thechapterincludesthesetopics: SampleCodeReferenceonpage 83 UnderstandingTaskManagerandTaskManagedObjectsonpage 84 UnderstandingtheTaskInfoDataObjectonpage 85 OperationsThatReturnTaskManagedObjectsonpage 90 IntroductiontotheEventDataObjectonpage 92 NOTEInadditiontotheTaskManagerandTaskmanagedobjectsdiscussedinthischapter,vCenterServer providesaScheduledTaskManagerthatsupportsschedulingoperationsinadvance.SeeChapter 16, SchedulingvCenterServerOperations,onpage 143forinformationaboutschedulingserveroperations usingtheScheduledTaskManager.

Sample Code Reference


Table 91liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesomeof thetopicsdiscussedinthischapter. Table 9-1. Sample Applications
Java SDK\samples\Axis\java\com\vmware\samples general\TaskList.java events\EventFormat.java events\EventHistoryCollectorMonitor.java events\VMEventHistoryCollectorMonitor.java C# SDK\samples\DotNet\cs\ TaskList EventFormat EventHistoryCollectorMonitor VMEventHistoryCollectorMonitor

InadditiontothesampleslistedinTable 91,thehelperclassesassociatedwiththesampleapplicationsuse Taskobjectsextensively.

VMware, Inc.

83

vSphere Web Services SDK Programming Guide

Understanding TaskManager and Task Managed Objects


TheTaskManagerisusedextensivelybyvSphereserverstosupportasynchronousoperations.Atruntime, varioussubsystemsuseTaskManagertoinstantiateTaskobjectsinresponsetooperationinvocationsfrom clientapplications. NOTETaskandEventobjectsinthecontextofanunmanagedESX/ESXisystemarenonpersistent. See Chapter 14,EventandTaskManagementUsingvCenterServer,onpage 129forinformationabouttasks andeventsfrommultipleESX/ESXisystemsthatarestoredandmanagedbyavCenterServersystem. AlthoughmanyoperationsavailablethroughtheAPIareasynchronousandreturnareferencetoaTask object,someoperationsaresynchronousanddonot.Forexample,operationsavailablethroughthe PerformanceManagerandseveralotherserviceinterfacesdonotreturnTaskobjects.Onlythoseoperations thatincludethesuffix_TaskintheirnamesreturnTaskreferences.SeeTable 95,OperationsthatReturna ReferencetoaTaskManagedObject,onpage 90foralistofallvSphereAPI4.0operationsthatreturn referencestoTaskobjects. ATaskobjectprovidesinformationaboutthestatusoftheinvokedoperationthroughitsTaskInfodata object.AninstanceofTaskInfopopulatestheinfopropertyoftheTaskmanagedobjectatruntime.By monitoringvariouspropertiesoftheTaskInfoobject,aclientapplicationcantakeappropriateactionwhen theTaskcompletes,orcanhandleerrorsiftheTaskdoesnotcompletesuccessfully. ATaskanditsassociatedobjectsaresessionspecific.Theuseraccountassociatedwiththesessionislimited toobtaininginformationabouttheTaskobjectsthatitisauthorizedtoview. TheTaskManagerencompassesthepropertieslistedinTable 92. Table 9-2. TaskManager Properties
Property description Type TaskDescription Description TaskDescriptionincludesamethodInfopropertythatcontainsa keybasedarrayusedbyTaskManagertopopulatethevalueofa TaskInfodataobjectsdescriptionIdpropertywiththenameofthe operation.Examplesoftwoelementsfromthiskeybasedarrayinclude methodInfo["Folder.createVm"]and methodInfo["Folder.createClusterEx"]. IdentifiesthenumberofTaskHistoryCollectorobjectsperclient sessionthattheservercancreate.Thispropertyissetbytheserver. ForESX/ESXi,maxCollectorissetto0.A TaskHistoryCollectorcannotbecreatedonanunmanaged ESX/ESXisystem. ForvCenterServer,maxCollectorissetto32,whichspecifiesthe numberofTaskHistoryCollectorobjectsperclientsession supportedbytheserver.SeeObtainingInformationaboutEvents UsingaHistoryCollectoronpage 133. recentTask MOR[ ]>Task [ ] ContainsanarrayofmanagedobjectreferencesTaskobjectsthatmeet anyofthefollowingconditions: TheTaskisqueuedtorun. TheTaskisrunning. TheTaskcompletedwithinthepast10minutes.

maxCollector

int

84

VMware, Inc.

Chapter 9 Overview of the Task Infrastructure

Figure 91showsaUMLclassdiagramforTaskManageranditsassociatedobjects. Figure 9-1. TaskManager and Task Managed Object Types

InadditiontothepropertieslistedinTable 92,TaskManagerhasthefollowingoperations: CreateCollectorForTasksoperation.YoucanusetheCreateCollectorForTasksoperationtocreate anobjectthatcontainsallTasksfromthevCenterServerdatabasethatmeetspecificcriteria.See ObtainingInformationaboutEventsUsingaHistoryCollectoronpage 133. CreateTaskoperation. TheCreateTaskoperationisusedbyallotheroperationsavailablethroughthe API,tocreateamanagedobjectreferencetoaTaskobject.Developerscreatingextensionscanalsousethe TaskManagertocreateTaskobjectsfortheoperationssupportedbytheirextension.

Understanding the TaskInfo Data Object


TheTaskInfodataobjectmakesuptheinfopropertyofaspecificTaskobject.Aninstanceofaspecific TaskInfoobjectcontainsinformationabouttheTaskreturnedbytheservertoyourclientapplication. Table 93liststhepropertiesofTaskInfodataobject. Table 9-3. TaskInfo Data Object Properties
T

Property cancelable cancelled changeTag completeTime descriptionId

Data Type boolean boolean string dateTime string

Description IndicateswhethertheTaskcanbecancelled(true)ornot(false). Indicatesthattheclienthasattemptedtocancel(true)theTask. Userenteredtagthatidentifiesoperationsandtheirsideeffects. TimestampthatidentifiesthedateandtimethattheTaskcompleted. Indicatesneithersuccessnorfailure. Identifiestheoperation,includingpubliclyvisibleinternaltasks. ReturnsvaluesfromtheTaskDescriptiondataobjectmethodInfo property. Managedentitytowhichtheoperationapplies. Localespecificmanagedentitynameretainedforthe HistoryCollectordatabase. Whenstatepropertyissettofault,identifiesthefault.Otherwise, notset. EventchainIDthatleadstotheassociatedTaskobjects. UniquekeyfortheTask. Whenthestatepropertyisrunning,thispropertyidentifiesthelist ofmanagedentities(ifany)lockedbytheoperation(usingashared lock).Otherwise,notset.

entity entityName error eventChainId key locked

MOR>ManagedEntity string LocalizedMethodFault int string MOR[ ]>ManagedEntity[]

VMware, Inc.

85

vSphere Web Services SDK Programming Guide

Table 9-3. TaskInfo Data Object Properties (Continued)


Property name parentTaskKey progress queueTime reason result rootTaskKey startTime state Data Type string string int dateTime TaskReason anyType string dateTime TaskInfoState Description NameoftheoperationthatcreatedtheTask.Notsetforinternaltasks. TaskscanbecreatedbyanotherTask.IdentifiesthekeyoftheTaskthat spawnedthisTask.IdentifiescausalitybetweenTaskobjects. Whenstatepropertyissettorunning,identifiespercentageofTask completed,from0to100.Otherwise,notset. TimestampthatidentifiesdateandtimetheTaskwascreated. SourceresponsibleforcreatingtheTask.Thesourcecanbeanalarm, schedule,system,oruser. Whenstatepropertyissettosuccess,containsthereturnvalueof thecompletedoperation.Otherwise,notset. ATaskcancreatenewtasks,tomultiplelevels.TherootTaskKey identifiesthekeyoftheTaskthatstartedthechainoftasks. TimestampthatindicatesdateandtimetheTaskstartedrunning. RuntimestatusoftheTaskspecifiedasonethefollowing: error queued running success task MOR>Task ManagedobjectreferencetoTask.

TheresultpropertyoftheTaskInfodataobject(listedinTable 93andshowninFigure 92)isdefinedas anyType.WhentheTaskisinstantiatedbytheserver,thevalueoftheresultpropertyisinitializedasUnset. Onlyuponsuccessfulcompletionofanoperationistheresultpropertypopulatedwiththeactualreturntype specifictotheoperation.BecausetheresultpropertyisdefinedasanyType,theresultmightbeadata object,areferencetoamanagedobject,oranyotherdatastructureasdefinedbytheoperation. Forexample,theAddHost_Task(oftheClusterComputeResourcemanagedobject)returnsaTaskobject whoseinfopropertycontainsaTaskInfodataobject.Atthestartoftheoperation,theresultpropertyis Unset.Uponsuccessfulcompletionoftheoperation,theresultpropertyofTaskInfocontainsthemanaged objectreferenceofthenewlyaddedHostSystem.IntheexampleoftheCreateVM_TaskshowninTable 94, theresultisamanagedobjectreferencetoaVirtualMachinewhosemanagedobjectidis64. SeethevSphereAPIReferencefordetailsaboutthereturntypeinstantiateduponcompletionofthespecific Taskassociatedwiththeinvokingoperation.

86

VMware, Inc.

Chapter 9 Overview of the Task Infrastructure

Figure 9-2. The Result Property of a TaskInfo Data Object Can Contain Any Type

Table 94liststhevaluesobtainedfromaTaskInfodataobjectatthebeginningandtheendoftheTask instantiatedbytheCreateVM_Taskoperationforcreatinganewvirtualmachine. Table 9-4. Sample TaskInfo Values from an ESX/ESXi 4.0 System During Creation of a VirtualMachine
Sample Values Property cancelable cancelled changeTag completeTime description descriptionId dynamicProperty dynamicType entity entityName error eventChainId key locked name parentTaskKey progress queueTime reason result rootTaskKey startTime Datatype boolean boolean string dateTime LocalizableMessage string DynamicProperty[] string ManagedObjectRefere nce:Folder string MethodFault int string MOR>ManagedEntity[] string string int dateTime TaskReason anyType string dateTime Start of Task false false Unset Unset Unset "Folder.createVm" Unset Unset ha-folder-vm "vm" Unset 159740 "haTask-ha-folder-vm-vim.Folder .createVm-159740" Unset "vim.Folder.createVm" Unset 36 "2009-02-19T22:50:39.111604Z" reason Unset Unset "2009-02-19T22:50:39.111604Z" End of Task false false Unset "2009-02-19T22:53:35.015338Z" Unset "Folder.createVm" Unset Unset ha-folder-vm "vm" Unset 159740 "haTask-ha-folder-vm-vim.Folder .createVm-159740" Unset "vim.Folder.createVm" Unset 100 "2009-02-19T22:50:39.111604Z" reason 64 Unset "2009-02-19T22:50:39.111604Z"

VMware, Inc.

87

vSphere Web Services SDK Programming Guide

Table 9-4. Sample TaskInfo Values from an ESX/ESXi 4.0 System During Creation of a VirtualMachine (Continued)
Sample Values Property state task Datatype TaskInfoState MOR>Task Start of Task "running" haTask-ha-folder-vm-vim.Folder. createVm-159740 End of Task "success" haTask-ha-folder-vm-vim.Folder. createVm-159740

Monitoring TaskInfo Properties


ThevaluesofTaskInfopropertieschangeovertimeastheTaskrunstocompletion.Dependingonthe requirementsofyourapplication,youmightmonitoroneormoreofthepropertiesofTaskInfo. Forexample,youcancheckthevaluesofstartTime,queueTime,completeTime,progress,result,and stateastheoperationprogressesuntilcompletion.Monitorthesepropertiesinyourcodeinaseparatethread untiltheTaskcompletes,whilethemainlineofyourcodecontinueswithotheractivities. YourcodemusthandlethedatatypereturnedwhentheTaskcompletes(managedobjectreference,data object,andsoon).Youmustalsohandlepossibleexceptions.Forexample,inadditiontosuccess,queued, andrunning,anoperationcanenteranerrorstateforanynumberofreasons.Inyourcode,youmusthandle errorsandexceptions. TomonitorthestateoftheTask,usetheCheckForUpdatesoperationofthePropertyCollector.See KeepingClientDatainSynchwithServerObjectsonpage 78.ATaskobjecthasalifecyclethatis independentoftheTaskManagerthatcreatesitandindependentoftheentitywithwhichitisassociated.It existstoconveystatusaboutanoperation,soyoucandiscardthereferencetoityourapplicationnolonger needstheinformation.

Cancelling a Task
TocancelaTaskthatisstillrunning,invoketheCancelTaskoperation,passingthemanagedobjectreference totheTaskyouwanttocancelasshowninthisexample:
my_conn.cancelTask(taskMoRef);

However,onlyaTaskthathasitscancelablepropertysettotrueanditsstatepropertysettorunningcan becancelled.TheoperationthatinitiatestheTasksetsthevalueofcancelablewhenitcreatestheTask. For example,theCreateVM_Taskcannotbecancelled.AsshowninTable 94,thevalueofthecancelable booleanisfalse.BeforeattemptingtocancelarunningTask,youcancheckthevaluesofthecancelable propertyandthestatepropertyoftheTaskInfodataobjectassociatedwiththeTask.

Using the TaskManager to Obtain Information about Tasks


FromthemomentaTaskisqueuedtorununtil10minutesafteritcompletes,areferencetotheTaskisheld intherecentTaskarrayofTaskManager.YoucanusethispropertytoobtaininformationabouttheTask objectsrunningonthesystem. ThevSphereClientapplicationusestherecentTaskarrayinthisway,forexample.Whenconnectedtoan ESX/ESXisystem,thevSphereClientdisplaysqueued,running,andcompletedtasksintheRecentTaskspane. ElementsfromthisarrayalsodisplayintheMOB.YoucanalsoviewrecenttasksintheMOB,bynavigating totheTaskManager(onanESX/ESXisystem)usingtheServiceInstance>ServiceContent>hataskmgrlink. Figure 93showsanexampleoftheTaskManagerdisplayedintheMOBofanESX4.0systemduringthe CreateVM_Taskoperation.Thearraycontainsonlyoneelement,thereferencetotheTaskforcreatingavirtual machine.ClickinganyoftherecentTasklinksintheMOBdisplaysthereferencetotheTaskmanagedobject whoseinfopropertycontainsalinktotheTaskInfodataobjectpopulatedwiththedetailsabouttheTask operation,suchasthoselistedinTable 94.

88

VMware, Inc.

Chapter 9 Overview of the Task Infrastructure

Figure 9-3. TaskManager as Displayed in an ESX System MOB

AllcompletedTaskobjectsageoutoftherecentTasksarrayafter10minutes.However,thevCenterServer collectsinformationaboutTaskobjectsforallthehoststhatitmanages.Youcanobtaininformationabout TaskobjectsfromvCenterServerusingaTaskHistoryCollector.SeeObtainingInformationaboutEvents UsingaHistoryCollectoronpage 133.

Obtaining Information about Recent Tasks Using a PropertyCollector


Toobtainthelistofrecenttasksprogrammatically,useaPropertyCollectortoobtainreferencestothe TaskManagerandtoallTaskobjectsfromtherecentTaskpropertyoftheTaskManager.Example 91shows anexcerptfromtheTaskList.javasamplethatcreatestheObjectSpec,PropertySpec,anda TraversalSpectoobtainreferencestoallTaskobjectsontheserverfromtheTaskList. Example 9-1. PropertyFilterSpec Definition to Obtain recentTask Property Values
private PropertyFilterSpec[] createPFSForRecentTasks(ManagedObjectReference taskManagerRef) { PropertySpec pSpec = new PropertySpec(); pSpec.setAll(Boolean.FALSE); pSpec.setType("Task"); pSpec.setPathSet(new String[] {"info.entity", "info.entityName", "info.name", "info.state", "info.cancelled", "info.error"}); ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(taskManagerRef); oSpec.setSkip(Boolean.FALSE); TraversalSpec tSpec = new TraversalSpec(); tSpec.setType("TaskManager"); tSpec.setPath("recentTask"); tSpec.setSkip(Boolean.FALSE); oSpec.setSelectSet(new SelectionSpec[]{tSpec}); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.setPropSet(new PropertySpec[]{pSpec}); pfSpec.setObjectSet(new ObjectSpec[]{oSpec}); return new PropertyFilterSpec[]{pfSpec}; }

VMware, Inc.

89

vSphere Web Services SDK Programming Guide

Example 92showsanexcerptofsomeofthecodethatobtainsvaluesfortheinfopropertyfromeachTask objectinthearray. Example 9-2. Displaying TaskInfoState Values for Each Task in the recentTask Array
... private void displayTasks(ObjectContent[] oContents) { for(int oci=0; oci<oContents.length; ++oci) { System.out.println("Task"); DynamicProperty[] dps = oContents[oci].getPropSet(); if(dps!=null) { String op="", name="", type="", state="", error=""; for(int dpi=0; dpi<dps.length; ++dpi) { DynamicProperty dp = dps[dpi]; if("info.entity".equals(dp.getName())) { type = ((ManagedObjectReference)dp.getVal()).getType(); } else if ("info.entityName".equals(dp.getName())) { name = ((String)dp.getVal()); } else if ("info.name".equals(dp.getName())) { op = ((String)dp.getVal()); } else if ("info.state".equals(dp.getName())) { TaskInfoState tis = (TaskInfoState)dp.getVal(); if(TaskInfoState.error.equals(tis)) { state = "-Error"; } else if(TaskInfoState.queued.equals(tis)) { state = "-Queued"; } else if(TaskInfoState.running.equals(tis)) { state = "-Running"; } else if(TaskInfoState.success.equals(tis)) { state = "-Success"; } } else if ("info.cancelled".equals(dp.getName())) { Boolean b = (Boolean)dp.getVal(); if(b != null && b.booleanValue()) { state += "-Cancelled"; } }...

Example 93showsoutputfromarunoftheprogram.SeethesourcecodelistingforTaskList.javaorfor TaskList.csinthevSphereWebServicesSDKpackagefordetails. Example 9-3. Sample Run of the TaskList Java Application
java com.vmware.samples.general.TaskList --url https://srv/sdk --username root --password ******* Started Task Operation AcquireCimServicesTicket Name srv Type HostSystem State -Success Error ====================== Ended TaskList

Operations That Return Task Managed Objects


Table 95liststheoperationsavailableinvSphereAPI4.0thatreturnareferencetoaTaskmanagedobject.See thevSphereAPIReferenceformoreinformationabouteachoftheseoperations. Table 9-5. Operations that Return a Reference to a Task Managed Object
AddHost_Task AddStandaloneHost_Task CheckCompatibility_Task PowerDownHostToStandBy_Task PowerOffVApp_Task PowerOffVM_Task

90

VMware, Inc.

Chapter 9 Overview of the Task Infrastructure

Table 9-5. Operations that Return a Reference to a Task Managed Object (Continued)
CheckHostPatch_Task CheckMigrate_Task CheckRelocate_Task CloneVApp_Task CloneVM_Task ComplianceManagerCheckCompliance_Task CopyDatastoreFile_Task CopyVirtualDisk_Task CreateChildVM_Task CreateDVS_Task CreateScreenshot_Task CreateSecondaryVM_Task CreateSnapshot_Task CreateVirtualDisk_Task CreateVM_Task CustomizeVM_Task DefragmentVirtualDisk_Task DeleteDatastoreFile_Task DeleteVirtualDisk_Task Destroy_Task DisableSecondaryVM_Task DisconnectHost_Task DVPortgroupReconfigure_Task DVSAddPortgroups_Task DVSMerge_Task DVSMovePort_Task DVSPerformProductSpecOperation_Task DVSReconfigure_Task DVSRectifyHost_Task EagerZeroVirtualDisk_Task EnableSecondaryVM_Task EnterMaintenanceMode_Task ExitMaintenanceMode_Task ExtendVirtualDisk_Task GenerateLogBundles_Task HostProfileApply_Task InflateVirtualDisk_Task InstallHostPatch_Task InstallHostPatchV2_Task MakePrimaryVM_Task MigrateVM_Task MoveDatastoreFile_Task PowerOnMultiVM_Task PowerOnVApp_Task PowerOnVM_Task PowerUpHostFromStandBy_Task ProfileCheckCompliance_Task PromoteDisks_Task QueryHostPatch_Task QueryVMotionCompatibilityEx_Task RebootHost_Task ReconfigureCluster_Task ReconfigureComputeResource_Task ReconfigureHostForDAS_Task ReconfigurePort_Task ReconfigVM_Task ReconnectHost_Task RegisterChildVM_Task RegisterVM_Task RelocateVM_Task RemoveAllSnapshots_Task RemoveSnapshot_Task Rename_Task ResetVM_Task ResignatureUnresolvedVmfsVolume_Task RevertToCurrentSnapshot_Task RevertToSnapshot_Task ScanHostPatch_Task ScanHostPatchV2_Task SearchDatastore_Task SearchDatastoreSubFolders_Task ShrinkVirtualDisk_Task ShutdownHost_Task StageHostPatch_Task StartRecording_Task StartReplaying_Task StopRecording_Task StopReplaying_Task SuspendVM_Task TerminateFaultTolerantVM_Task TurnOffFaultToleranceForVM_Task UninstallHostPatch_Task UnregisterAndDestroy_Task unregisterVApp_Task

VMware, Inc.

91

vSphere Web Services SDK Programming Guide

Table 9-5. Operations that Return a Reference to a Task Managed Object (Continued)
MoveHostInto_Task MoveInto_Task MoveIntoFolder_Task MoveVirtualDisk_Task UpgradeTools_Task UpgradeVM_Task ZeroFillVirtualDisk_Task ~

Introduction to the Event Data Object


InadditiontocreatingTaskreferences,manyoperationsonhostsandvirtualmachinesalsogenerateoneor moreEventdataobjectsastheoperationexecutesontheserver.AnEventisadataobjectthatconveys informationaboutchangesinthestateofmanagedentities. ForunmanagedESX/ESXisystems,Eventobjectsarenonpersistent.Eventsareretainedonlyforaslongas thehostsystemslocalmemorycancontainthem.RebootinganunmanagedESX/ESXihostorpoweringoffa virtualmachineremovesEventobjectsfromlocalmemory. AnunmanagedESX/ESXisystemmightretainabout15minutesworthofEventdataaboutthehostand virtualmachineoperations,butthiscanvary,dependingontheprocessingloadofthehost,thenumberof virtualmachines,andotherfactorsthataffectmemory. Figure 9-4. Events Exported from an Unmanaged ESX/ESXi System

FormanagedESX/ESXisystems,Eventobjectsarepersistent.ManagedESX/ESXisystemssendEventdatato thevCenterServersystemthatmanagesthem,andthevCenterServerstorestheinformationitsdatabase. ThesampleapplicationsincludedintheSDKpackageforhandlingeventscanbeusedwitheitherunmanaged ESX/ESXiorvCenterServersystems. UsingaHistoryCollector,youcanobtaininformationabouttheseobjectsastheyarebeingcollectedona specificESX/ESXisystem,orfromaspecifichistoricalperiodfromthedatabase.SeeObtainingInformation aboutEventsUsingaHistoryCollectoronpage 133. SeeUnderstandingEventManagerandtheEventDataObjectonpage 129formoreinformation.

92

VMware, Inc.

10

Working with Virtual Machines

10

AVirtualMachineisassociatedwithbothitscontainingFolderandtheResourcePoolfromwhichit obtainsresourcesatruntime,soitacquirespermissionsfromboththeseobjects. ManycapabilitiesofvirtualmachinesrequirethatVMwareToolsisinstalledontheguestoperatingsystemof thevirtualmachine.Forexample,VMwareToolsprovidesthememorymanagementdriverthatsupports ballooning,andthenetworkingdriverthatprovidesaDNSnameforthevirtualmachine.Inaddition,some oftheAPIavailabletovirtualmachinesrequireVMwareTools.Forexample,thequiesceparameteroftheis supportedonlyifVMwareToolsisinstalledonthevirtualmachine. TheVirtualMachineAPIsupportsprogrammaticallyupgradingtheVMwareToolssoftwareonthevirtual machineguestOS. Thischapterincludesthesetopics: SampleCodeReferenceonpage 93 CreatingVirtualMachinesonpage 93 OverviewofVirtualMachineOperationsonpage 94 OverviewofSnapshotsonpage 97

Sample Code Reference


Table 101liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 10-1. Sample Applications that Demonstrate VirtualMachine Operations
Java SDK\samples\Axis\java\com\vmware\samples VMCreate.java VMPowerOps.java VMReconfig.java VMSnapshot.java C# SDK\samples\DotNet\cs VMCreate VMPowerOps VMReconfig VMSnapshot

Creating Virtual Machines


ForunmanagedESX/ESXisystems,youcreatevirtualmachinesusingtheFolderfactoryobjectinconjunction withinstancesofthevariousdataobjectsthatdefineallaspectsofthevirtualmachine,andreferencesforthe Folder,ResourcePool,andHostSystemmanagedobjectinstancesthatyouwanttousetosupportthe VirtualMachine.

VMware, Inc.

93

vSphere Web Services SDK Programming Guide

ThedataobjectsyoupasstotheCreateVM_TaskoftheFoldermanagedobjectincludeaninstanceofthe VirtualMachineConfigSpec.AVirtualMachineConfigSpecisacomplexdataobjectconsistingofalmost 50differentpropertiesthatmakeuptheconfigurationofthevirtualmachineyouwanttocreate.However,to createavirtualmachineonanunmanagedhostsystemyoumustprovideonlyafewpropertyvaluesfora minimalnumberofproperties,suchasthoseshowninExample 101. Example 10-1. Creating a VirtualMachineConfigSpec Data Object
ManagedObjectReference resourcePool = cb.getServiceUtil().getMoRefProp(crmor, "resourcePool"); ManagedObjectReference vmFolderMor = cb.getServiceUtil().getMoRefProp(dcmor, "vmFolder"); VirtualMachineConfigSpec vmConfigSpec = vmUtils.createVmConfigSpec(cb.get_option("vmname"), cb.get_option("datastorename"), Integer.parseInt(cb.get_option("disksize")), crmor, hostmor); vmConfigSpec.setName(cb.get_option("vmname")); vmConfigSpec.setAnnotation("VirtualMachine Annotation"); vmConfigSpec.setMemoryMB(new Long(Integer.parseInt(cb.get_option("memorysize")))); vmConfigSpec.setNumCPUs(Integer.parseInt(cb.get_option("cpucount"))); vmConfigSpec.setGuestId(cb.get_option("guestosid")); ManagedObjectReference taskmor = cb.getConnection().getService().createVM_Task( vmFolderMor, vmConfigSpec, resourcePool, hostmor);

Table 102listssomeofthepropertiesoftheResourceAllocationInfodataobjectthatareusedtoallocate CPUandmemoryresources. Table 10-2. ResourceAllocationInfo Data Object Properties


Unit of Measure Property reservation CPU MHz Memory MB Description Minimumamountoftheresourceguaranteedtobeavailableifitis needed.Anyunusedamountofareservationcanbeconsumedby othervirtualmachinesorresourcepoolsthatneedit. Maximumamountofresourcethatcanbeutilized,regardlessof availableresourcesonothervirtualmachinesorresourcepools. Usethelimitsettingtoensureconsistentperformanceofvirtual machinesandresourcepools,regardlessofavailableresources. Setto1toremoveallrestrictionsontheresourceutilization.The resourceislimitedtoavailableresourcesandshares. shares Relativeamountofresource(ascomparedtolevelsofothervirtual machines)thatcanbeutilized,specifiedusingtheSharesLevel enumeration(high,normal,low,orcustom).Forcustomshares, defineusingthesharespropertyand Whensettotrue,specifiesthatachildresourcepoolcangrow beyonditsreservationamountifitsparentresourcepoolhas unreservedresourcesavailable.

limit

MHz

MB

expandableReservation

Overview of Virtual Machine Operations


Table 103listsVirtualMachineoperationsavailabletovirtualmachinesrunningonunmanagedESX/ESXi systems.ForanyhostmanagedbyvCenterServer,usetheAPIavailableonthevCenterServerWebservice whencreatingormanagingvirtualmachines.SeeChapter 13,UsingvCenterServerforVirtualMachine Operations,onpage 119.

94

VMware, Inc.

Chapter 10 Working with Virtual Machines

Table 10-3. Basic VirtualMachine Operations Summary


Operation AcquireMksTicket Description Createsandreturnsaonetimecredentialforestablishingaremote mousekeyboardscreenconnectiontothisvirtualmachine.thismethoddepends onbeingabletoretrieveTCPbindinginformationabouttheserverendofthe clientconnectionthatisrequestingtheticket.Ifsuchinformationisnotavailable, theNotSupportedfaultisthrown.ThismethodisappropriateforSOAPand authenticatedconnections,whicharebothTCPbasedconnections. Respondstoaquestionthatisblockingthisvirtualmachine. Checksthecustomizationspecificationagainstthevirtualmachineconfiguration. Forexample,thisisusedonasourcevirtualmachinebeforeacloneoperationto catchcustomizationfailurebeforethediskcopy.Thischecksthespecifications internalconsistencyandforcompatibilitywiththisvirtualmachinesconfiguration. Createascreenshotofavirtualmachine. Createsanewsnapshotofthisvirtualmachine.Asasideeffect,thisupdatesthe currentsnapshot.Any%(percent)characterusedinthisnameparametermustbe escaped,unlessitisusedtostartanescapesequence.Clientsmayalsoescapeany othercharactersinthisnameparameter. Customizesavirtualmachinesguestoperatingsystem. Defragmentallvirtualdisksattachedtothisvirtualmachine. MountstheVMwareToolsCDinstallerasaCDROMfortheguestoperating system.YoucancheckthestatusoftheVMwareToolsinstallationbycheckingthe guest.toolsStatusproperty. Powersoffthisvirtualmachine.Ifthisvirtualmachineisafaulttolerantprimary virtualmachine,thiswillresultinthesecondaryvirtualmachine(s)getting poweredoffaswell. Powersonthisvirtualmachine.Ifthevirtualmachineissuspended,thismethod resumesexecutionfromthesuspendpoint.Whenpoweringonavirtualmachine inacluster,thesystemmightimplicitlyorduetothehostargument,doanimplicit relocationofthevirtualmachinetoanotherhost.Hence,errorsrelatedtothis relocationcanbethrown.IftheclusterisaDRScluster,DRSisinvokedifthe virtualmachinecanbeautomaticallyplacedbyDRS.Becausethismethoddoes notreturnaDRSClusterRecommendation,neitherVMotionnorhostpower operationsaredoneaspartofaDRSfacilitatedpoweron.IfyouwantDRSto considersuchoperations,usePowerOnMultiVM_Task.Ifthisvirtualmachineisa faulttolerantprimaryvirtualmachine,itssecondaryvirtualmachinesisstartedon systemselectedhosts.IfthevirtualmachinesareinaVMwareDRSenabled cluster,DRSisinvokedtoobtainplacementsforthesecondaries.However,neither VMotionnorhostpoweroperationsareconsideredforthesepowerons. ForallfilesthatbelongtotheVM,checkthatthefileownerissettothecurrent datastoreprincipaluser,assetby HostDatastoreSystem.ConfigureDatastorePrincipal. Issuesacommandtotheguestoperatingsystemaskingittoperformareboot. Returnsimmediatelyanddoesnotwaitfortheguestoperatingsystemtocomplete theoperation. Reconfiguresthisvirtualmachine.Allthechangesinthegivenconfigurationare appliedtothevirtualmachineasanatomicoperation. Explicitlyrefreshesthestorageinformationofthisvirtualmachine,updating propertieslayoutExandstorage. Removeallthesnapshotsassociatedwiththisvirtualmachine.Ifthevirtual machinedoesnothaveanysnapshots,thisoperationreturnssuccess. Clearscachedguestinformation.Guestinformationcanbeclearedonlyifthe virtualmachineispoweredoff.Thismethodcanbeusefulifstaleinformationis cached,preventinganIPaddressorMACaddressfrombeingreused.

AnswerVM CheckCustomizationSpec

CreateScreenshot_Task CreateSnapshot_Task

CustomizeVM_Task DefragmentAllDisks MountToolsInstaller

PowerOffVM_Task

PowerOnVM_Task

QueryUnownedFiles

RebootGuest

ReconfigVM_Task RefreshStorageInfo RemoveAllSnapshots_Task ResetGuestInformation

VMware, Inc.

95

vSphere Web Services SDK Programming Guide

Table 10-3. Basic VirtualMachine Operations Summary (Continued)


Operation ResetVM_Task Description Resetspoweronthisvirtualmachine.IfthecurrentstateispoweredOn,thenthis methodfirstperformspowerOff(hard).OncethepowerstateispoweredOff, thenthismethodperformspowerOn(option).Althoughthismethodfunctionsas apowerOfffollowedbyapowerOn,thetwooperationsareatomicwithrespectto otherclients,meaningthatotherpoweroperationscannotbeperformeduntilthe resetmethodcompletes. Revertsthevirtualmachinetothecurrentsnapshot.Thisisequivalenttorunning snapshot.currentSnapshot.revert.Ifnosnapshotexists,thentheoperation doesnothing,andthevirtualmachinestateremainsunchanged. Setstheconsolewindowsdisplaytopologyasspecified. Setstheconsolewindowsresolutionasspecified. Issuesacommandtotheguestoperatingsystemaskingittoperformaclean shutdownofallservices.Returnsimmediatelyanddoesnotwaitfortheguest operatingsystemtocompletetheoperation. Issuesacommandtotheguestoperatingsystemaskingittoprepareforasuspend operation.Returnsimmediatelyanddoesnotwaitfortheguestoperatingsystem tocompletetheoperation. Initiatesarecordingsessiononthisvirtualmachine.Asasideeffect,thisoperation createsasnapshotonthevirtualmachine,whichinturnbecomesthecurrent snapshot. Startsareplaysessiononthisvirtualmachine.Asasideeffect,thisoperation updatesthecurrentsnapshotofthevirtualmachine. Stopsacurrentlyactiverecordingsessiononthisvirtualmachine. Stopsareplaysessiononthisvirtualmachine. Suspendsexecutioninthisvirtualmachine. UnmountsVMwareToolsinstallerCD. UsetheFolder.RegisterVMmethodtorecreateaVirtualMachineobjectfrom thesetofvirtualmachinefilesbypassinginthepathtotheconfigurationfile. However,theVirtualMachinemanagedobjectthatresultstypicallyhasdifferent objectsIDandmayinheritadifferentsetofpermissions. Beginsthetoolsupgradeprocess.Monitorthestatusoftheinstallationusingthe guest.toolsStatusproperty. Upgradesthisvirtualmachinesvirtualhardwaretothelatestrevisionthatis supportedbythevirtualmachinescurrenthost.

RevertToCurrentSnapshot_Task

SetDisplayTopology SetScreenResolution ShutdownGuest

StandbyGuest

StartRecording_Task

StartReplaying_Task StopRecording_Task StopReplaying_Task SuspendVM_Task UnmountToolsInstaller UnregisterVM

UpgradeTools_Task UpgradeVM_Task

Workingwithanyvirtualmachinesfromaclientapplicationrequiresthevirtualmachinetobeconfigured properlyfornetworking.Specifically,theappropriateversionofVMwareToolsmustbeinstalledand configuredontheguestoperatingsystem(guestOS). ForeachguestOS,suchasWindows2003Server,RedHatEnterpriseServerLinux,orUbuntuLinux,VMware providesaspecificbinarycompatibleversionofVMwareTools.TheVMwareToolssoftwareprovidesmany benefits,suchasenhancingthedisplayinteractionforendusers.Italsoprovidesthevmxnetdriverneededfor thevirtualnetworkinterfacecontroller(vNIC)andvirtualmachinenetworkconfiguration.WithVMware ToolsinstalledontheguestOS,thevirtualmachineobtainsitsDNS(domainnameserver)nameandanIP addressandisthereforereachableoverthenetwork. IMPORTANTSelectingInstallVMwareTools fromthevSphereClientmenuonlydownloadstheappropriate installationpackagetothevirtualmachine.Youmustunpackthefile,runtheinstallationscriptorlaunchthe executable,andconfigureVMwareToolsontheguestoperatingsystemofthevirtualmachinetoenable networking,memorymanagement,andothercapabilitiesonthevirtualmachine.

96

VMware, Inc.

Chapter 10 Working with Virtual Machines

Overview of Snapshots
Asnapshotpreservesthestateanddataofavirtualmachineataspecificpointintime. Stateincludesthevirtualmachinespowerstate(poweredon,poweredoff,suspended,forexample). Dataincludesallthefilesthatmakeupthevirtualmachine,includingdisks,memory,andotherdevices, suchasvirtualnetworkinterfacecards. AVirtualMachineobjectprovidesseveraloperationsforcreatingandmanagingsnapshots.Theseoperations letyoucreatesnapshots,reverttoanysnapshotinthetree,andremovesnapshots.Youcancreateextensive snapshottreesthatyoucanusetosavevirtualmachinestateatanypointintime,andrestoreitlater,if necessary.

Creating Snapshots
Creatingasnapshotofavirtualmachinestartswithareference(instanceofManagedObjectReference)tothe targetvirtualmachine.PassthereferencetotheCreateSnapshot_Taskoperation,providinganameand description(bothstrings)forthesnapshot. TheCreateSnapshot_Taskoperationalsohastwobooleanproperties: memory,whichcanbesettotruetoincludethevirtualmachinesmemorydumpinthesnapshot. Includingmemoryinthesnapshotwilltakelonger(tocompletethesnapshotoperation)andcreatea largersnapshotfile. quiesce,whichcan(andshould)besettotruesothatthesnapshotwillincludethevirtualmachines diskdatainaconsistentstate:thispropertyquiescesthevirtualmachinesfilesystempriortoinitiating theoperation. SeethevSphereAPIReferenceformoreinformation.

Reverting to Snapshots
Afterasnapshotexistsonthesysteminatreeofsnapshots,youcanreinstatethesnapshotbyusingthe RevertToSnapshot_Taskoperation.SeethevSphereAPIReferencefordetails.

VMware, Inc.

97

vSphere Web Services SDK Programming Guide

98

VMware, Inc.

11

Managing Storage

11

vSphereserversrequirededicatedstoragespacefortheoperatingsystemfilesandforthecomponentsthat makeuptheinventory.Storageincludesphysical,logical,andvirtualconstructs.Thischapterincludesthese topics: SampleCodeReferenceonpage 99 OverviewofPhysicalandVirtualStorageConceptsonpage 99 IntroductiontotheHostStorageSystemManagedObjectonpage 102 IntroductiontotheHostDatastoreSystemManagedObjectonpage 106 ObtainingInformationaboutConfiguredStorageonpage 107 CreatingNewDatastoresonpage 108 ModifyingDatastoreConfigurationonpage 110

Sample Code Reference


Table 111liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 11-1. Sample Applications that Demonstrate Storage and Datastore Operations
Java SDK\samples\Axis\java\com\vmware\samples\scsilun SCSILunName C# SDK\samples\DotNet\cs\GetVirtualDiskFiles GetVirtualDiskFiles.cs

Overview of Physical and Virtual Storage Concepts


Avirtualmachineismadeupoffilesthatcanbecopiedandmoved,justasanyothercomputerbasedfile. Thesefilesarestoredonthephysicalmediathatbacksthelogicalrepresentationofthestorage(thedevice isthelogicalrepresentation,inthiscontext). Thehostsystemcandiscoverstoragedevicesthatithasaccesstoandcanformatthesestoragedevices (or portionsofthem)asdatastores.Adatastoreisanabstractionthatprovidesaccesstothevirtualdisksofa virtualmachine.Adatastoreisalogicalcontainer(analogoustoastoragevolume)forthevirtualdiskand otherfilesthatencapsulateavirtualmachine. ThevirtualSCSIdisksaretypicallycontainedinaVirtualMachineFileSystem(VMFS)volume.VMFSisa clusteredfilesystem,optimizedforvirtualmachinesandisthedefaultfilesystemforthesetoffilesthat encapsulateseachvirtualmachineonphysicalSCSIdisksorpartitions. AVMFSvolumecontainsfiles,directories,symboliclinks,rawdevicemappings(RDMs),andmetadataabout itscontents.AnRDMisaspecialfileonaVMFSvolumethatmediatescommandstorawdevices.Rawdevices canalsobeusedtostorevirtualmachinefiles,buttheRDMfilemustbeavailableonaVMFSfilesystem.

VMware, Inc.

99

vSphere Web Services SDK Programming Guide

Virtualmachinesusevirtualdisksfortheiroperatingsystem,applicationsoftware,andotherdatafiles. A virtualdiskisstoredasaVMDKfileinsideadatastore. Figure 111providesaconceptualoverviewofthevariousstoragearchitecturessupportedbyvSphereservers, whichinclude: Storageareanetworks(SAN).SANscanbeimplementedusingvarioustechnologies,includingFibre Channel(FC)andInternetSCSI(iSCSI). Networkattachedstorage(NAS).NASstorageusesfilebasedprotocolssuchasNFS(networkfile system),NTFS(NTfilesystem),orSMB/CIFS(Microsoftlegacyservermessageblock/commoninternet filesystem). Directattachedstorage(DAS).Alsocalledlocalstorage.Localstoragehassomelimitationswhen comparedtoSANandNASsystems. Figure 11-1. Overview of Local, NAS, and SAN Storage

NOTEFigure 111isforillustrationpurposesonly.Itisnotarecommendedconfiguration.Detailshavebeen oversimplifiedonpurpose. WhenyoucreateavirtualmachineusingthevSphereClient,awizardguidesyouthroughtheconfiguration ofallsettings,includingstorage.Bydefault,avirtualmachineiscreatedwithonevirtualharddiskandone virtualSCSIcontroller. VirtualmachinesalwaysuseavirtualSCSIadapterandcommunicateusingtheSCSIcommandsetregardless ofthetypeofphysicalstorageSCSI,iSCSI,fibrechannel,orfilesystembased.Atruntime,theguest operatingsystemrunningonthevirtualmachineissuesSCSIcommandstoitsvirtualdisks.Thevirtualization layertranslatestheSCSIcommandsintoVMFSfileoperations.

Requirements for Storage


AnytypeofnetworkattachedstoragerequirescompleteconfigurationofnetworkingintheVMkernel,to supportnetworkbasedaccesstothestoragemedia.TheVMkernelrequiresitsownIPaddress.

100

VMware, Inc.

Chapter 11 Managing Storage

Overview of Internet SCSI Storage


iSCSIpackagesSCSIcommandsinsideinternetprotocol(IP)packetsandsendsfromahosttoastorage volume. Figure 11-2. Overview of iSCSI Storage

Figure 112showstwodifferentapproachestoInternetSCSI(iSCSI)storagesupportedbyvSphereservers. HardwarebasediSCSIusesaniSCSIhostbusadapter(HBA),whichservesasthesource(orinitiator) ofSCSIcommands. SoftwarebasediSCSIusesahighspeednetworkinghardware,suchas1GBEthernetNICsandswitches. ESX/ESXihasitsowniSCSIinitiator,builtintotheVMkernel.Bydefault,thesoftwareiSCSI implementationintheVMkernelisdisabled.(TheisSoftwareBasedpropertyofthe HostInternetScsiHbaissettofalse. NOTEDonotuse100MBEthernetNICsforiSCSIbasedstorage:itistooslow.Use1GB(orfaster)Ethernet. Aninitiatorspropertiesincludeitsmodelname,IPaddress,iSCSIname,discoverymethods,iSCSIalias,and alistofanytargetsthatithasalreadydiscovered.

Introduction to Managed Objects that Support Storage


TheHostSystemmanagedobjecthasaconfigManagerpropertythatisdefinedasaninstanceofa HostConfigManagerdataobject.TheHostConfigManagerdataobjectcontainsclosetotwentyproperties, eachofwhichcomprisesamanagedobjectreferencetoaspecificserviceinterfaceforthehostsystem.A HostConfigManagerdataobjecthastwopropertiesassociatedwithmanagingstorageatthefilesystemlevel, theotheratthelogical(volume)managementlevel: ThedatastoreSystemproperty,whichprovidesamanagedobjectreferencetothe HostDatastoreSystemoftheserver.HostDatastoreSystemprovidesoperationsforcreating, configuring,extending,andremovingthedatastoresavailableforusebythehostsystem(ESX/ESXi). HostDatastoreSystemistheabstractionforlogicalstorage,thevolumes(Datastoremanagedobjects) thatcanbeusedbythehostforvirtualmachines.

VMware, Inc.

101

vSphere Web Services SDK Programming Guide

ThestorageSystemproperty,whichprovidesamanagedobjectreferencetotheHostStorageSystemof theserver.HostStorageSystemprovidesoperationsassociatedwiththeconfigurationandmanagement ofthephysicalstorageimplementation.Itprovidesoperationsforcreating,configuring,andmanaging thehostsstoragesubsystem.AHostStorageSystemistheserviceinterfacetousetomakestorage availableforvirtualmachines. TheHostStorageSystemobjectprovidesanabstractionforphysicalstorageresources. The HostDatastoreSystemprovidesaccesstostorageresourcesaspresentedbythefilesystem. TheDatastoremanagedentityprovidesoperationsformountingdatastores,browsingdatastores,and obtaininginformationaboutthedatastoresassociatedwithavirtualmachine. Figure 11-3. Datastore Managed Object As a ManagedEntity

Introduction to the HostStorageSystem Managed Object


TheHostStorageSystemmanagedobjectcanbeusedtoobtaininformationabout,configure,andmanagethe storagesystemsusedbyVMwarevSphereservers.SpecifictypesofstoragearemodelledinthevSphere managementobjectassubtypesoftheHostHostBusAdapterbasedataobjecttype.AsshowninFigure 114, thesesubtypessupportFibreChannel(FC),SCSI,internetSCSI,anddirectlyattachedstorage. Figure 11-4. HostHostBusAdapter Data Object Type and Subtypes

102

VMware, Inc.

Chapter 11 Managing Storage

Table 112liststheoperationsavailabletoHostStorageSystemmanagedobjects. Table 11-2. HostStorageSystem Operations Summary


Operation AddInternetScsiSendTargets AddInternetScsiStaticTargets Description Addssendtargetentriestothehostbusadapterdiscoverylistifthe DiscoveryProperties.sendTargetsDiscoveryEnabledflagissettotrue. Addsstatictargetentriestothehostbusadapterdiscoverylist. The DiscoveryProperty.staticTargetDiscoveryEnabledflagmustbesetto true. ExtendsaVMFSbyattachingadiskpartitionasanextent. Computesthediskpartitioninformationbasedonthespecifieddisklayout. The servercomputesanewpartitioninformationobjectforaspecificdisk representingthespecifiedlayout. Computesthediskpartitioninformationtosupportresizingagivenpartition. Disablesanenabledpathforalogicalunit.Usethepathnamefrom HostMultipathStateInfoPathorHostMultipathInfoPath. Enablesadisabledpathforalogicalunit.Usethepathnamefrom HostMultipathStateInfoPathorHostMultipathInfoPath. ExpandsaVMFSextentasspecifiedbythediskpartitionspecification. FormatsanewVMFSonadiskpartition. Obtainsthesetofpathselectionpolicyoptions.Theseoptionsdeterminethepath thatcanbeusedbyadevicemanagedbynativemultipathing.A HostMultipathInfodataobjectidentifiesthedevicesthataremanagedthrough nativemultipathing. Obtainsthesetofstoragearraytypepolicyoptions.Theseoptionsdeterminethe storagearraytypepoliciesthatcanbeusedbyadevicemanagedbynative multipathing.AHostMultipathInfodataobjectidentifiesthedevicesthatare managedthroughnativemultipathing. ObtainsthelistofunboundVMFSvolumes.Forsharingavolumeacrosshosts,a VMFSvolumeisboundtoitsunderlyingblockdevicestorage.Whenalowlevel blockcopyisperformedtocopyormovetheVMFSvolume,thecopiedvolumewill beunbound. Refreshthestorageinformationandsettingstopickupanychangesthatmight haveoccurred. Removessendtargetentriesfromthehostbusadapterdiscoverylist. The DiscoveryProperty.sendTargetsDiscoveryEnabledmustbesettotrue.If anyofthetargetsprovidedasparametersarenotfoundintheexistinglist,the othertargetsareremovedandanexceptionisthrown. Removestatictargetentriesfromthehostbusadapterdiscoverylist. The DiscoveryProperty.staticTargetDiscoveryEnabledmustbesettotrue. Ifanyofthetargetsprovidedasparametersarenotfoundintheexistinglist,the othertargetsareremovedandanexceptionisthrown. Issuearequesttorescanallvirtualmachinehostbusadaptersfornewstorage devices. Issuearequesttorescanaspecificvirtualmachinehostbusadapterfornewstorage devices. RescansfornewVMFSinstancesthatmighthavebeenadded. ResignatureorforcemountlistofunboundVMFSvolumes.VMFSvolumesare boundtotheirunderlyingblockstoragedevices. Returnsanarraycontaininginformationaboutthepartitionsonthehost(anarray ofHostDiskPartitionInfoobjects). UpdatesthepathselectionpolicyforaLogicalUnit.UsetheLUNUUIDfrom HostMultipathInfoLogicalUnit.

AttachVmfsExtent ComputeDiskPartitionInfo

ComputeDiskPartition InfoForResize DisableMultipathPath EnableMultipathPath ExpandVmfsExtent FormatVmfs QueryPathSelection PolicyOptions

QueryStorageArrayType PolicyOptions

QueryUnresolved VmfsVolume

RefreshStorageSystem RemoveInternetScsi SendTargets

RemoveInternetScsi StaticTargets

RescanAllHba RescanHba RescanVmfs ResolveMultiple Unresolved VmfsVolumes RetrieveDiskPartitionInfo SetMultipathLunPolicy

VMware, Inc.

103

vSphere Web Services SDK Programming Guide

Table 11-2. HostStorageSystem Operations Summary (Continued)


Operation UnmountForceMounted VmfsVolume Description UnmounttheforcemountedVMFSvolume.Whenalowlevelblockcopyis performedtocopyormovetheVMFSvolume,thecopiedvolumeisunresolved. FortheVMFSvolumetobeusable,aresolutionoperationisapplied.Aspartof resolutionoperation,usermaydecidetokeeptheoriginalVMFSUUID.Oncethe resolutionisapplied,theVMFSvolumeismountedonthehostforitsuse.Usercan unmounttheVMFSvolumeifitisnotbeingusedbyanyregisteredVMs. Changesthepartitionsonthediskbysupplyingapartitionspecificationandthe devicename. UpdatestheadvancedoptionstheiSCSIhostbusadapterorthediscovery addressesandtargetsassociatedwithit. UpdatesthealiasofaniSCSIhostbusadapter. Updatestheauthenticationpropertiesforoneormoretargetsordiscovery addressesassociatedwithaniSCSIhostbusadapter. UpdatesthedigestpropertiesfortheiSCSIhostbusadapterorthediscovery addressesandtargetsassociatedwithit. UpdatesthediscoverypropertiesforaniSCSIhostbusadapter. UpdatestheIPpropertiesforaniSCSIhostbusadapter. UpdatesthenameofaniSCSIhostbusadapter. UpdatethemutabledisplaynameassociatedwithaSCSILUN.TheSCSILUNto beupdatedisidentifiedusingthespecifiedUUID. EnablesanddisablessoftwareiSCSIintheVMkernel. UpgradestheVMFStothecurrentVMFSversion. Iteratesoverallregisteredvirtualmachines.ForeachVMwhichVMXfileislocated ontheserviceconsoleandalldisksareavailableonVMFS3orNAS,relocatesthe disksintodirectoriesifstoredintheROOT,andrelocatetheVMXfileintothe directorytoo.Eventsareloggedforeachvirtualmachinethatisrelocated.

UpdateDiskPartitions UpdateInternetScsi AdvancedOptions UpdateInternetScsiAlias UpdateInternetScsi AuthenticationProperties UpdateInternetScsiDigest Properties UpdateInternetScsiDiscovery Properties UpdateInternetScsiIP Properties UpdateInternetScsiName UpdateScsiLunDisplayName UpdateSoftware InternetScsiEnabled UpgradeVmfs UpgradeVmLayout

IftheDiscoveryProperties.sendTargetsDiscoveryEnabledflagissettotrue,the AddInternetScsiSendTargetoperationaddssendtargetentriestothestorageadaptersdiscoverylist. Toobtainmanagedobjectreferences,createaPropertyFilterSpectoobtainHostSystemmanagedobjects andtheappropriateproperty. To enable the VMkernel to support software iSCSI 1 2 ObtainamanagedobjectreferencetothehostsystemsHostStorageSystem. InvoketheUpdateSoftwareInternetScsiEnabledoperation,passingthereferencetothe HostStorageSystemandthevaluetrue.

iSCSIinitiatorsandtargetshaveunique,permanentiSCSInamesandaddresses.AniSCSInamecorrectly identifiesaspecificiSCSIinitiatorortarget,regardlessofphysicallocation.Namesconformtooneoftwo alternativeformatswhicharespecifictothestoragevendorshardware(Table 113).

104

VMware, Inc.

Chapter 11 Managing Storage

Table 11-3. Format for iSCSI Names


Description Extendeduniqueidentifier.A64bitglobalidentifierassignedbythe hardwaremanufacturer.AnEUIaddressincludesthe24bitcompany name(theorganizationallyuniqueidentifier,orOUI,assignedbythe IEEEtothevendor),anda40bituniqueID,suchasaserialnumber. iSCSIqualifiedname.Beginswithinitialsiqn followedbythe companydomaininreverseorder.Forexample, iqn.2000-04.com.qlogic:qle4060c.my-san-server55.1 Format eui.0123456789ABCDEF

Name EUI

IQN

iqn.yyyy-mm.com.company: san-server-name

To configure iSCSI Initiators 1 AccessthelistofavailableHBAsonthehostsystembyobtainingthenestedvalueforhostbusadapters configuredonthehost.YoucandothisbycreatingapropertycollectorwithHostSystemasthestarting point.FromtheHostSystemconfigproperty,youcanobtainthelist(array)ofhostbusadaptersby specifyingthispropertypath:


config.storageDevice.hostBusAdapter

Thispropertypathreturnsanarrayofhostbusadapters.Forexample:
hostBusAdapter["key-vim.host.BlockHba-vmhba32"] hostBusAdapter["key-vim.host.BlockHba-vmhba33"] hostBusAdapter["key-vim.host.BlockHba-vmhba34"] hostBusAdapter["key-vim.host.BlockHba-vmhba35"] hostBusAdapter["key-vim.host.BlockHba-vmhba1"] ...

2 3 4

Fromthearray,selectthehostbusadapter(instanceofHostHostBusAdapter)thatyouwanttoconfigure andobtainitskeyproperty,whichisastringconsistingofthedevicenameofthehostbusadapter. DeterminethecapabilitiesoftheiSCSIHostBusAdapterHBA. Configuretheinitiator. Forahardwareinitiator,configuretheIPaddress. Forasoftwareinitiator,enablethesoftwareinitiatorintheVMkernel.

5 6 7 8 9

ConfiguretheiSCSInameandalias. Configuretargetdiscovery. Settheauthenticationinformation.(SkipthisstepifyouarenotusingCHAP.) Configureaccesstothetargets. Invokearescanoperationonthehostbusadapters.RescanenablestheHBAstodiscoverthenewstorage devices.YoucaneitherissuearescanforasingleHBAusingtheRescanHbaoperationwiththeHBAID asaparameterorissuearescanonallHBAsusingRescanAllHba.

VMware, Inc.

105

vSphere Web Services SDK Programming Guide

Figure 11-5. HostHostBusAdapter Data Object and Associated Data Objects

Introduction to the HostDatastoreSystem Managed Object


Figure 116showssomeoftherelationshipsamongHostSystemmanagedobjects,datastores,andstorage. Figure 11-6. HostSystem and HostDatastoreSystem

Theobjectsreturneddependonthespecificsofthequery.Forexample,theQueryAvailableDisksForVmfs returnsanarrayofreferencestoanarrayofHostVmfsDatastoreOptiondataobjectsthatrepresentthe configuredstorageforthehost. Table 11-4. Summary of HostDatastoreSystem Operations


Operation ConfigureDatastore Principal Description Configuresdatastoreprincipaluserforthehost.Allvirtualmachinerelated fileI/Oisperformedunderthisuser.Usethisoperationifyouwanttothe virtualmachinefilesconfiguration,disk,andsoontobecheckedfor properaccess.Hostmustbeplacedinmaintenancemodeforthisoperation. Requiresareboottoeffectchanges.Doesnotapplytovirtualmachinefiles storedonNFS. Createsanewlocaldatastoreonthehostsystem,inthespecifieddirectory. Createsanewnetworkattachedstoragedatastoreusingthespecifications suppliedintheHostNasVolumeSpecdataobject. CreatesanewVMFSdatastoreusingthespecificationssuppliedinthe VmfsDatastoreCreateSpecdataobject.

CreateLocalDatastore CreateNasDatastore CreateVmfsDatastore

106

VMware, Inc.

Chapter 11 Managing Storage

Table 11-4. Summary of HostDatastoreSystem Operations (Continued)


Operation ExpandVmfsDatastore Description ExpandsanexistingVMFSdatastoreusingthespecificationprovidedinthe VmfsDatastoreExpandSpecdataobject(whichcontainsthenameofthe extentandpartitioninformation). ExtendsanexistingVMFSdatastoreusingthespecificationprovidedinthe VmfsDatastoreExtendSpecdataobject. ObtainlistofdisksthatcanbeusedtocontainVMFSdatastoreextents. Optionally,provideadatastorenametoobtainlistofdisksthatcancontain extentsforthespecifiedVMFSdatastore.Theoperationdoesnotreturndisks currentlyusedbytheVMFSdatastore,nordoesitreturnmanagementLUNs anddisksreferencedbyRDMs(whicharentusableforVMFSdatastores). ObtainthelistofunboundVMFSvolumes.Forsharingavolumeacrosshosts, aVMFSvolumeisboundtoitsunderlyingblockdevicestorage.Whenalow levelblockcopyisperformedtocopyormovetheVMFSvolume,thecopied volumewillbeunbound. ObtaininformationaboutoptionsforcreatinganewVMFSdatastoreforadisk. Obtaininformationaboutoptionsforexpandingtheextentsofanexisting VMFSdatastore. ObtaininformationaboutoptionsforextendinganexistingVMFSdatastore foradisk. Removesadatastorefromahost. AssignsanewDiskUuidtoaVMFSvolumebutkeepsitscontentsintact. This operationfacilitatessafevolumesharingacrosshosts.VMFSvolumesare boundtotheirunderlyingblockdevice. ChoosethelocalSwapDatastoreforthishost.Anychangetothissettingwill affectvirtualmachinesthatsubsequentlypoweronorresumefroma suspendedstateatthishost,orthatmigratetothishostwhilepoweredon. Virtualmachinesthatarecurrentlypoweredonatthishostarenotaffected.

ExtendVmfsDatastore QueryAvailableDisksForVmfs

QueryUnresolvedVmfsVolumes

QueryVmfsDatastoreCreateOptions QueryVmfsDatastoreExpandOptions QueryVmfsDatastoreExtendOptions RemoveDatastore ResignatureUnresolvedVmfs Volume_Task UpdateLocalSwapDatastore

TheExpandVmfsDatastoreoperationincreasesthesizeofthedatastoreuptothefullsizeprovisionedforthe datastore,ifnecessary. SeethevSphereAPIReferenceformoreinformationabouttheHostDatastoreSystemoperations,including constraintsandlimitations.

Obtaining Information about Configured Storage


Table 115listsseveralqueryoperationsavailableonHostDatastoreSystem.Usetheseoperationstofindout aboutexistingstorageconfiguredonanESX/ESXisystembeforecreatingnewstorageormodifyingexistingstorage. ThequeryoperationsforHostDatastoreSystemarespecifictothetypeofstorage,butmostworkinthesame generalway,typicallyrequiringthemanagedobjectreferencetotheHostDatastoreSystemandoneormore specificdataobjectsspecifyingtheconfigurationdetails. Table 11-5. HostDatastoreSystem Query Operations
Operation QueryAvailableDisks ForVmfs Parameter _this datastore _this devicePath Type MOR>HostDatastoreSystem MOR>Datastore MOR>HostDatastoreSystem string Description ReferencetotheHostDatastoreSystem. Referencetoanexistingdatastoreon whichtocreateoraddVMFSextents. ReferencetotheHostDatastoreSystem usedfortheinvocation. ThedevicePathofthediskonwhich datastorecreationoptionsaregenerated. Thedevicepathisafilepaththatcanbe openedtocreatepartitionsonthedisk.

QueryVmfsDatastore CreateOptions

VMware, Inc.

107

vSphere Web Services SDK Programming Guide

Table 11-5. HostDatastoreSystem Query Operations (Continued)


Operation QueryVmfsDatastore ExtendOptions Parameter _this datastore devicePath suppress Expand Candidates Type MOR>HostDatastoreSystem MOR>Datastore string boolean Description ReferencetotheHostDatastoreSystem usedtomakethemethodcall. Referencetothedatastoretoextend. ThedevicePathofthediskonwhich datastorecreationoptionsaregenerated. Indicateswhethertoexcludeoptionsthat canbeusedforeitherextendingor expandingextent. Settotruetoexcludefreespaceavailable forexpansion.

Freespacecanbeusedforaddinganextentorexpandinganexistingextent.Expandinganexistingextentis sometimesreferredtoasgrowingtheextent.

Creating New Datastores


TheHostDatastoreSystemprovidesseveraloperationsforcreatingnewdatastores(Table 116).Allofthe operationsrequireamanagedobjectreferencetoHostDatastoreSystem,andreturnareferencetothe Datastoreobjectafteritiscreated. Table 11-6. HostDatastoreSystem Creation Operations
Operation CreateLocalDatastore Parameter _this name path Type MOR>HostDatastoreSystem string string Description ReferencetotheHostDatastoreSystem ofthehostsystem. Hostwideuniquenameforthedatastore. Filepathtothedirectoryinwhichvirtual machinedata(specifically,VMXand otherfiles)willbelocated. ReferencetotheHostDatastoreSystem ofthehostsystem. Dataobjectthatdefinesthelocalpath, remotehost,andremotepathforthe datastore.SeeTable 117fordetails. ReferencetotheHostDatastoreSystem. Specificationforcreatingadatastore backedbyVMFS.Thedataobjectdefines theextent(ifappropriate,toappendtoan existingVMFSdatastore),thepartition, andtheVMFSpropertiesforthe datastore.

CreateNasDatastore

_this spec

MOR>HostDatastoreSystem HostNasVolumeSpec

CreateVmfsDatastore

_this spec

MOR>HostDatastoreSystem VmfsDatastoreCreateSpec

Table 117liststhepropertiesanddatatypesoftheHostNasVolumeSpecdataobject.Youcreateaninstanceof thisdataobjecttodefineanetworkattachedstoragebaseddatastoreonthesystem.

108

VMware, Inc.

Chapter 11 Managing Storage

Table 11-7. HostNasVolumeSpec Data Object


Property accessMode localPath Type string string Description and Usage Accessmodeforthemountpoint.AccessmodesincludestandardNFSfilepermissions. NameoftheNASdatastorethatwillbecreatedusingthisspecification. ESX/ESXisystems:Datastorenameisacomponentinthefilesystempathatwhichthe NASvolumecanbefound.Forexample,iflocalPathissettonas_volumethecreated NASdatastoreisnamed"nas_volume"anditcanbeaccessedusingthefilesystempath /vmfs/volumes/nas_volume. vCenterServersystem:DatastorenameislocalPath,butthedatastorenamemaynot beshowninthefilesystempathwheretheNASvolumeisaccessed. password remoteHost remotePath type userName string string string string string SettoCIFSifthepasswordfortheCIFSservershouldbeused.IftypeisNFS,thisfieldis ignored. FullyqualifiednameofthehostsupportingtheNFSserver. RemotepathtotheNFSmountpoint. Typeofnetworkattachedstoragevolume.DefaultisNFS.ValidtypesincludeCIFSand NFS. IftypeisCIFS,theusernametousewhenconnectingtotheCIFSserver.IftypeisNFS,this fieldisignored.

TocreateaVMFSbaseddatastore,youusetheCreateVmfsDatastoreoperation.Thisoperationtakesa VmfsDatastoreCreateSpecdataobjectthatconsistsofanextent,apartition,andavmfsproperty,allof whicharecomplexdataobjects.Forexample,thevmfspropertyisdefinedasaninstanceoftheHostVmfsSpec dataobject.Table 118liststhepropertiesanddatatypesoftheHostVmfsSpecdataobject. Table 11-8. HostVmfsSpec Data Object
Property blockSizeMb Type int Description and Usage Optional.VMFSblocksize,inmegabytes(MB).Controlsmaximumfilesize. ValidblocksizevariesbyVMFSversion: VMFS31MB VMFS21,2,4,8,16,32,64,128,256MB extent HostScsiDiskParti tion PrimaryextentthatidentifiestheVMFSinvmhbaI:T:Lformat.Thedatais notguaranteedtobestableacrossreboots,sodonottrytoidentifyVMFS usingthisdata.Instead,defineauniquevolumenameonthehostanduseit torefertotheVMFS.Or,usetheVMFSUUID(whichisimmutableafteritis created). VMFSversionnumber,suchas2or3.Versionnumbercanbeoptionally changedduringanupgrade.Upgradedfilesystemscannotbedowngraded. NameoftheVMFSvolume.

majorVersion volumeName

int string

Table 119liststhepropertiesanddatatypesfortheHostScsiDiskPartitiondataobject. Table 11-9. HostScsiDiskPartition Data Object


Property diskName Type string Description and Usage NameoftheSCSIdiskdeviceonwhichtheVMFSextentresides.Thename canbeathenameoftheHostScsiDiskdataobjectorthecanonicalName (propertyofScsiLundataobject). NumberoftheHostScsiDiskpartition.

partition

int

Definingthespecificationforadatastoretakesafairnumberofcomplexdataobjects,suchasthese.Seethe vSphereAPIReferenceformoreinformation.

VMware, Inc.

109

vSphere Web Services SDK Programming Guide

Modifying Datastore Configuration


Table 1110liststheoperationsavailabletochangetheHostDatastoreSystemconfiguration. Table 11-10. HostDatastoreSystem Modification Operations
Operation ConfigureDatastorePrincipal Parameter _this Type MOR>HostDatastoreSystem Description Referencetothe HostDatastoreSystem serviceinterface. Principal(user)nameforthe datastore. Optional.Passwordfor storagesystemsthatsupport userimpersonationand requirepassword. Referencetothe HostDatastoreSystem serviceinterface. ReferencetotheDatastoreto expand.Increasesthesizeof anexistingextent. Dataobjectdefiningthe extentsoftheDatastoreto expand. Referencetothe HostDatastoreSystem serviceinterface. ReferencetotheDatastoreto extendbyaddingnew extents. Dataobjectdefiningthe extentstoaddtothe Datastore. Referencetothe HostDatastoreSystem serviceinterface. ReferencetotheDatastoreto remove. Referencetothe HostDatastoreSystem serviceinterface. TheHUVRSdataobject containsastringarray comprisingthelistofdevice paths,eachofwhichspecifies aVMFSextent.

userName password

string string

ExpandVmfsDatastore

_this

MOR>HostDatastoreSystem

datastore

MOR>Datastore

spec

VmfsDatastoreExpandSpec

ExtendVmfsDatastore

_this

MOR > HostDatastoreSystem MOR>Datastore

datastore

spec

VmfsDatastoreExtendSpec

RemoveDatastore

_this

MOR>HostDatastoreSystem

datastore ResignatureUnresolvedVmfs Volume_Task _this

MOR>Datastore MOR>HostDatastoreSystem

resolutionSpec

HostUnresolvedVmfs ResignatureSpec

110

VMware, Inc.

12

Monitoring Performance

12

VMwarevSphereservershavebeeninstrumentedusingacomprehensivesystemthattracksutilizationof resourcesbyvariousobjects.Atruntime,statisticaldataisgeneratedbythevSphereserversperformance providers.Aperformanceproviderisanyentityonthesystemthatgeneratesutilizationorconsumption information.PerformanceprovidersincludeallthemanagedentitiessuchasHostSystemand VirtualMachineobjects,andthedevicesassociatedwiththem,suchasvirtualdisks. IMPORTANTSeveraldataobjects,includingHostListSummaryQuickStats,VirtualMachineQuickStats, andResourcePoolQuickStats,providenearrealtimesummaryinformationaboutperformanceor utilizationwithoutgoingthroughthePerformanceManager.Thesedataobjectsdonotsupportmonitoring. Thischapterincludesthesetopics: SampleCodeReferenceonpage 111 IntroductiontoPerformanceManageronpage 112 ObtainingStatisticsonpage 115 vCenterServerandPerformanceManageronpage 117

Sample Code Reference


Table 121liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 12-1. Sample Applications that Demonstrate Using PerformanceManager Operations
Java SDK\samples\Axis\java\com\vmware\samples\performance Basics.java History.java PrintCounters.java Realtime.java VITop.java VIUsage.java C# SDK\samples\DotNet\cs Basics History PrintCounters QueryMemoryOverhead RealTime

VMware, Inc.

111

vSphere Web Services SDK Programming Guide

Introduction to PerformanceManager
ThePerformanceManageristheserviceinterfaceforobtainingstatisticaldataaboutvariousaspectsofsystem performance,asgeneratedandmaintainedbyvariousperformanceproviders. Table 12-2. PerformanceManager Properties
Property description Type PerformanceDescript ion PerfInterval[ ] Description Thedescriptionpropertyisacompositeobjectthatincludes informationaboutthetypesofcounters(counterType)and statistics(statsType)availableonthesystem. AnarrayofPerfIntervaldataobjectsthatdefinesthe performanceintervalsconfiguredforthesystem. ForanESX/ESXisystem,thearraycontainsasingleobjectthat definesthebaselinesamplingperiodfortheserver. ForavCenterServer,thisarraycontainsfourobjects.See HistoricalIntervalsonpage 117formoreinformation. perfCounter PerfCounterInfo[ ] AnarrayofPerfCounterInfodataobjectsthatcontainsallthe metadataassociatedwiththeperformancemetricsgeneratedon thesystem.

historicalInterval

InadditiontothepropertieslistedinTable 122,PerformanceManagerprovidesseveralqueryoperationsfor obtainingmetadatathatdefinesthestatistics,andforobtainingstatisticalvaluesaboutperformance. Table 12-3. PerformanceManager Operations


Operation QueryAvailablePerfMetric QueryPerf QueryPerfComposite Description ObtainsmetricscollectedforspecifictimeframesorhavingaspecificintervalId. Obtainsmetricsforaspecificlistofmanagedentities.Monitorspecificentitiesthat provideperformancedata. Obtainsmetricsforthespecifiedinventoryentityanditsfirstgenerationchild entities,suchasforahostanditsvirtualmachines.Thisoperationacceptsthe refreshRateforcurrentstatisticsortheintervalIdofoneofthehistorical intervals.SupportedforHostSystemmanagedentityonly. ObtainsPerfCounterInfodataobjectsforthespecifiedlistofcounterIDs. ObtainsPerfCounterInfodataobjectsforthespecifiedcollectionlevel. ObtainsthePerfProviderSummarydataobjectforthespecifiedmanagedobject.

QueryPerfCounter QueryPerfCounterByLevel QueryPerfProviderSummary

SeethevSphereAPIReferenceforVMwareWebServicesSDK4.0forcompletePerformanceManager documentation.

Overview of Counter Groups and the PerfCounterInfo Data Object


Theperformancemonitoringsystemwasdesignedformaximumflexibility.Eachperformanceproviderhas itsownsetofcountersthatprovidesmetadataabouttheperformancedataitmightgenerate.Countersare organizedbygroupsoffinitesystemresources,suchasmemory,CPU,disk,andsoon.ThevSphereAPI Referenceincludesdocumentationforthefollowingcountergroups: CPU DiskI/OCounters ManagementAgent Memory Network StorageUtilizationCounters VirtualMachineOperations

112

VMware, Inc.

Chapter 12 Monitoring Performance

Someofthesecountergroups,suchasstorageutilization,arenewinvSphere4.0.Thecountergroupsand specificcountersusedonanysystemdependonthespecificconfiguration.Notallcountergroupsareused, andyoumightfindavailablecountersthatarealsonotused.Disregardanyextraneouscounters. ThecountersaremodeledinthesystemusingthePerfCounterInfodataobject.Instancesofthisdataobject providethemetadatafortheruntimestatisticalvalues. Figure 12-1. PerfCounterInfo Data Object

ThePerfCounterInfodataobjectincludesadescription,theunitofmeasurethatthecounterrepresents,and theotherattributeslistedinTable 124. Table 12-4. PerfCounterInfo Data Object Properties


Property associatedCounterId Type int [ ] Description AnarrayofintegersthatlistscounterIDs (PerfCounterInfo.keyproperty)forothercountersrelatedto thisone.Thispropertyisnotusedincurrentreleases. Containsthenameoftheresourcegrouptowhichthiscounter belongs,suchasdisk,cpu,ormemory. Auniqueintegerthatidentifiesthecounter.Alsocalledthe counterID.Thevalueisnotstatic.Thecounterkeyonan ESX/ESXisystemmightnotbethesameasthecounterkeyforthe samecounteronthevCenterServersystemmanagingthe ESX/ESXihost.However,thesystemmapsthekeysfrom ESX/ESXitovCenterServersystemstransparently. Anumberfrom1to4thatidentifiesthelevelatwhichthis counterwillbeaggregatedwithothersofitskindintovCenter Serversystems. Adescriptivenameforthecounterthatcomprisesseveralnested properties. Identifiesthefunctionthatcontrolshowdataisconvertedasitis consolidatedfromoneintervalintothenextinterval.Some countersspecifyabsolutevalues,suchasthetotalnumberof secondsthatthesystemhasbeenrunningcontinuouslysince startup,andsonoconversionofvaluesoccurs.The PerfSummaryTypeisanenumerationcontainingvalidconstants forthisproperty.

groupInfo key

ElementDescription int

level

int

nameInfo rollupType

ElementDescription PerfSummaryType

VMware, Inc.

113

vSphere Web Services SDK Programming Guide

Table 12-4. PerfCounterInfo Data Object Properties (Continued)


Property statsType Type PerfStatsType Description Identifiesthetypeofstatisticaldatathatthevaluerepresents overthecourseoftheinterval,suchasanaverage,arate,the minimumvalue,themaximumvalue,summation,latest,or absolute.ThePerfStatsTypeisanenumerationcontaining validconstantsforthisproperty. Unitofmeasure,suchasmegahertz,kilobytes,kilobytesper second,andsoon.The ElementDescriptionskeypropertyis populatedusingoneoftheconstantsavailableinthe PerformanceManagerUnitenumeration.

unitInfo

ElementDescription

Eachcounterhaskeypropertythatidentifiesthemetricgeneratedbythesystem.Thevalueofkeyisunique andisnotstaticitmightchangebetweensystemreboots,forexample.Atruntime,thekeypropertyofa PerfCounterInfoinstanceisusedtopopulatethevalueofthecounterIdpropertyofaspecific PerfMetricIdinstance(Figure 122). Figure 12-2. PerfCounterInfo Key Matches a PerfMetricId CounterId

TheinstancevalueofPerfMetricIdassociatestheinstanceofthemetricwithitssource.Thestringforthe instancevalueisderivedfromconfigurationnamesforthedevice,butthisvaluemaybeempty.Forexample, formemoryandaggregatedmetricvalues,thispropertyisempty.ForaCPU,thispropertyidentifiesthe numericpositionwithintheCPUcore,suchas0,1,2,3.

Sampling Periods and Intervals


UnmanagedESX/ESXisystemsproviderealtimestatisticsforthecurrentdayonly.Managedhostssend statisticstothevCenterServersystemthatmanagesthem.ThevCenterServerconsolidatesthestatistical performancedatafromalltheESX/ESXisystemsthatitmanagesandstorestheinformationinitsdatabase. Table 12-5. Default Sampling Periods and Retention
Sampling Period 20seconds 5minutes 1hour 6hour 24hour Retention Period 1day 24hours 7days 30days 365days ESX, ESXi vCenter Server

114

VMware, Inc.

Chapter 12 Monitoring Performance

ThehistoricalIntervalisdefinedasanarrayofPerfIntervaldataobjects.ForanESX/ESXisystem,the arraycontainsasinglePerfIntervalobjectwiththepropertieslistedinTable 126. Table 12-6. Values of PerfInterval Data Object from an ESX/ESXi System
Property key name samplingPeriod length enabled level Value 1 PastDay 300 129600 true null Description NumericidentifierforthePerfInterval. NameofthePerfInterval. Numberofsecondsduringwhichthesystemsamplesperformance datatoproduceametric. Numberofsecondsthatstatisticsassociatedwiththeintervalarekept bythesystem. DenotesthatthisPerfIntervalisenabledonthesystem. Statisticscollectionlevel.ForanESX/ESXisystem,thispropertyis null.ThePerfIntervalobjectonanESX/ESXisystemdefinesthe baselineinterval.

SeeHistoricalIntervalsonpage 117forinformationaboutintervalsonmanagedhostsusingvCenterServer.

Obtaining Statistics
YouusetheQueryPerfandtheQueryPerfCompositeoperationsofPerformanceManagertoobtain statisticaldataaboutperformance.Theseoperationsbehavedifferently,inthefollowingways: TheQueryPerfoperationretrievesperformancestatisticsforoneormoreinventoryentities.Withoutan intervalIdaspartofthequery,theQueryPerfoperationsummarizesacrossallintervals.Youdefine oneoremorePerfQuerySpecobjectsforthequerySpecparameterforthisoperation,andtheserver returnsanarrayofoneormorePerfEntityMetricBaseobjects. TheQueryPerfCompositeoperationretrievesperformancestatisticsforanentityanditsfirstgeneration childentities. Forbothoperations,youmustdefinethestatisticsyouwanttoretrieveusingaPerfQuerySpecdataobject. ForQueryPerf,yousubmitanarrayofPerfQuerySpecobjects. ForQueryPerfComposite,yousubmitasinglePerfQuerySpecobject. Figure 12-3. Define a PerfQuerySpec to Obtain Statistics

TheQueryPerfCompositeoperationworksatthehostlevelonly.Youcanobtainstatisticsforahostandits associatedvirtualmachinesforthespecifiedinterval.Theclientcanlimitthereturnedinformationby specifyingalistofmetrics,andasampleintervalID.TheserveracceptstherefreshRatepropertyoroneof thehistoricalintervalsasinputinterval.


VMware, Inc. 115

vSphere Web Services SDK Programming Guide

QueryPerfCompositeisdesignedforefficientclientservercommunications.Intheory,itgeneratesless networktraffic(thanQueryPerf)becauseitreturnsalargegrainedobject,aPerfCompositeMetricdata objectthatcontainsallthedata(seeFigure 124,PerfEntityMetricBaseDataObject,onpage 116). Figure 12-4. PerfEntityMetricBase Data Object

BeforeusingQueryPerforQueryPerfComposite,youusetheQueryAvailablePerfMetricoperation beforeeitheroftheseoperations,toretrieveinformationaboutthemetricsthatareavailableforaspecified managedentitywithinagiventimeframe,soyoucanspecifythemetricsyouwanttoobtain. Table 127liststheparametersfortheQueryAvailablePerfMetricoperation. Table 12-7. QueryAvailablePerfMetric Operation


Parameter _this entity beginTime Type MOR>PerformanceManager MOR>ManagedEntity dateTime Description ReferencetothePerformanceManager. Referencetothemanagedentityforwhichavailablemetrics shouldbeobtained. Optional.Servertimefromwhichtostartgatheringavailable metrics.Ifnotspecified,firstavailablemetricsinthesystem arereturned. Optional.Servertimeatwhichtostopgatheringavailable metrics.Ifnotspecified,returnedmetricsincludesall metrics,uptothemostrecent. Optional.Identifieroftheintervalforwhichtoreturn availablemetrics.Validintervalsinclude: TherefreshratereturnedbyQueryProviderSummary operation OneoftheHistoricalIntervals Ifnotspecified,systemreturnsavailablehistoricalmetrics.

endTime

dateTime

intervalId

int

Usetheoptionalbeginandendtime,orspecifyanintervaltoobtaininformationaboutthemetricsavailable fortheinterval.ForunmanagedESX/ESXisystems,usetherefreshRate,whichyoucanobtainfromthe serviceprovider.

116

VMware, Inc.

Chapter 12 Monitoring Performance

vCenter Server and PerformanceManager


AvCenterServersystemaggregatesperformancedatafromalltheESX/ESXisystemsthatitmanages. The amountofdataaggregateddependsonthelevelsettingconfiguredforthevCenterServer.Thelevel settingsarereflectedinthehistoricalIntervalpropertyofthePerformanceManagerofthevCenter Serversystem.historicalIntervalisanarrayofPerfIntervaldataobjectsthatdefinefourdifferentlevel settings,1through4. Bydefault,thecollectionlevelissetto1foreachofthefourintervals.Bydefault,vCenterServersystemsretain thefollowinginformation: 5minutesamplesforthepastday 30minutesamplesforthepastweek 2hoursamplesforthepastmonth 1daysamplesforthepastyear DataolderthanayearispurgedfromthevCenterServerdatabase.

Historical Intervals
Table 128liststhedefaultvaluesofthehistoricalIntervalpropertyfromavCenterServersystem. Table 12-8. Values of PerfInterval Data Objects from a vCenter Server System
key 1 2 3 4 name PastDay PastWeek PastMonth PastYear sampling period 300 1800 7200 86400 length 86400 604800 2592000 31536000 enabled TRUE TRUE TRUE TRUE level 1 1 1 1

Table 129listssomeexamplesofthetypesofstatisticsthatcanbecollectedatvariouslevels.Theactual counterscanvaryfromversiontoversionoftheproduct. Table 12-9. Statistics Level Settings


Level 1 Description CountersdefinedwithaveragerolluptypeforCPU,Memory,Disk,andNetwork;pluscountersforSystem Uptime,SystemHeartbeat,andDRS(DistributedResourceScheduler,trackedintheclusterServices group).Doesnotincludecountersfordevices. Countersdefinedwithaverage,summation,andlatestrolluptypesforCPU,memory,disk,andnetwork; pluscountersforsystemuptime,systemheartbeat,andDRS(clusterServices).Doesnotincludecounters fordevices. Countersdefinedwithaverage,summation,andlatestrolluptypesforCPU,memory,disk,network,andall devices;pluscountersforsystemuptime,systemheartbeat,andDRS(clusterServices). Allcountersdefinedforallentitiesanddevices,foreveryrolluptype,includingminimumandmaximum.

3 4

TherollupTypeidentifiesthefunctionthatcontrolshowdataisconvertedasitisconsolidatedfromone intervaltothenext.

Modifying Historical Intervals


VMwarerecommendsthatyoudonotmodifythedefaulthistoricalintervals.ThePerfIntervaldataobjects inthehistoricalIntervalarraybuildincrementallyoneachobjectinthearray.Modifyingthespecificsof anygivenobjectinthearraycanresultinproblems.Also,changestoanintervalareglobalandapplytoall entitiesinthesystem.

VMware, Inc.

117

vSphere Web Services SDK Programming Guide

Ifyoumustmodifyanintervaltomeetaspecialrequirement,usetheUpdatePerfIntervaloperationof PerformanceManagerandfollowtheseguidelines. Theretentiontime(thelengthpropertyofPerfInterval)mustbeamultipleofthesamplingPeriod propertyvalue. Theretentionlengthofeachsuccessiveperiodmustbegreaterthantheretentionlengthoftheprevious intervalinthearray. ThevalueofthesamplingPeriodpropertyforanyPerfIntervalinstancecannotbechanged.

Optimizing Query Response Time


TheQueryPerfoperationofPerformanceManageronvCenterServerhasbeenoptimizedtoreturnresults fasterwhenthequeryissubmittedwithincertainparameters.Specifically,ifyoudefinethePerfQuerySpec dataobjectwiththefollowingparametersettings,thequerycircumventsvCenterServerandobtainsresults directlyfromeachoftheESX/ESXisystems: SetthevalueoftheintervalIdto300(thedefaultsamplinginterval). SetthevalueofstartTimeandendTimesothatthetimespanfallswithinthelast30minutesofthe currenttime. ThisoptimizationensuresthatvCenterServersystemisnotoverloaded.Considerusingthistechniquefor reportingoranyotherclientapplicationthatmightsubjectthesystemtorepeatedqueries. TheoptimizationisavailableinVirtualCenterServer2.5andsubsequentsystems.

118

VMware, Inc.

13

Using vCenter Server for Virtual Machine Operations

13

VMwarevCenterServersupportscomprehensivedeployment,management,monitoring,andotherservices formultipleESX/ESXisystems.vCenterServerrunsasadatabasebackedserviceonavarietyofWindows operatingsystems.ThesoftwarelicensingandinstallationprocessincludesaninstanceofMicrosoftSQL Server.vCenterServeralsosupportsintegrationwithOracleDatabaseServer. AvCenterServerpersistsstatus,configuration,performance,andotherinformationabouteachvirtual machine,host,cluster,virtualapplication,andotherentitiesthatitmanagestoitsdatabase.Historical performance,event,task,andotherdataisalsopreservedinthevCenterServerdatabase. TheAPIavailableonthevCenterServerincludesseveralserviceinterfacesthatarenotsupportedon unmanagedESX/ESXisystems,includingAlarmManagerandScheduledTaskManager.Theseservice interfaceshavebeenavailableinpriorreleasesofvCenterServer,butwithvCenterServer4.0andvSphereAPI 4.0,theysupportmanynewcapabilities. Forexample,controloverAlarmsettingismoregranularthanin priorreleases,falsealarmsorunnecessaryrepeatedtriggeringofanalarmhasbeenresolved.SeeUsingthe AlarmInfrastructureonpage 137. ManynewfeaturesofvSphere4.0areavailableonlythroughtheAPIavailableonthevCenterServerWeb service,includingClusterProfileManager,ProfileComplianceManager,HostProfileManager, IpPoolManager,HostSnmpManager,VirtualMachineCompatibilityChecker,and VirtualMachineProvisioningChecker,amongothers. vCenterServerprovidesarangeofoptionsfordeployingandconfiguringvirtualmachines,andfor organizingvirtualassets.vCenterServerprovidescontainerobjects,suchasfoldersanddatacenters,for organizingvirtualassetsinaninventorycomprisingmultipleESX/ESXisystems.vCenterServersupports deployingmultiplevirtualmachinesbyusingatemplatethatcodifiesastandardconfiguration.Thischapter providesinformationabouttheseapproaches.Itincludesthesetopics: SampleCodeReferenceonpage 120 OverviewoftheVirtualMachineManagedObjectTypeonpage 120 UsingTemplatestoDeployStandardVirtualMachinesonpage 124 MigratingVirtualMachinesUsingVMotiononpage 125 MovingStorageDynamicallyUsingStorageVMotiononpage 127

VMware, Inc.

119

vSphere Web Services SDK Programming Guide

Sample Code Reference


Table 131liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 13-1. Sample Applications Demonstrating VirtualMachine Deployment Using vCenter Server Systems
Java SDK\samples\Axis\java\com\vmware\samples\vm VMClone.java VMDeltaDisk.java VMLinkedClone.java VMPromoteDisks.java VMRelocate.java VMotion.java VMotion25.java C# SDK\samples\DotNet\cs VMClone RecordSession VMPowerOps VMotion

Overview of the VirtualMachine Managed Object Type


AVirtualMachinemanagedobjectprovidesoperationsformanagingvirtualmachines,suchascreating snapshotsofitsstate,creatingnewinstancesofitselfbycloning,andparticipatingwithothervirtualmachine instancesinfaulttolerantdeployments. Figure 13-1. VirtualMachine Extends ManagedEntity Type

120

VMware, Inc.

Chapter 13 Using vCenter Server for Virtual Machine Operations

AVirtualMachinemanagedentityhasclosetofiftyoperations,manyofwhicharenewinvSphereAPI4.0 Figure 131showsonlysomeofthedetails.SeethevSphereAPIReferenceforcompleteinformation. Table 13-2. VirtualMachineConfigSpec Data Object


Property alternateGuestName annotation Type string string Description and Usage Fullnameforguest.UsedonlyifguestIdisspecifiedasother orother-64. Userprovideddescriptionofthevirtualmachine.Becausethis propertyisoptionalinthevirtualmachineconfiguration,itis necessarytopassanexplicitemptystringinaConfigSpec objecttoremoveanannotationthatisalreadypresentinthe VirtualMachineConfigInfoforavirtualmachine. Settingsthatcontrolthebootbehaviorofthevirtualmachine. Thesesettingstakeeffectduringthenextpoweronofthe virtualmachine. Settingtocontrolenabling/disablingchangedblocktracking forthevirtualdisksofthisVM.Thismayonlybesetifthe changeTrackingSupportedcapabilityistrueforthisvirtual machine.Anychangetothispropertywilltakeeffectthenext timethevirtualmachinepowerson,resumesfroma suspendedstate,performsasnapshotcreate/delete/revert operationormigrateswhilepoweredon. Ifspecified,thechangesareonlyappliedifthecurrent changeVersionmatchesthespecifiedchangeVersion.This fieldcanbeusedtoguardagainstupdatesthathavehappened betweenwhenconfigInfoisreadandwhenitisapplied. Legacyconsoleviewerpreferencesthatareusedwithpower operations.Forexample,poweron. AffinitysettingsforCPU. ResourcelimitsforCPU. SpecifiestheCPUfeaturecompatibilitymasks. Indicateswhethervirtualprocessorscanbeaddedtothe virtualmachinewhileitisrunning,ornot.Thisattributecan onlybesetwhenthevirtualmachineispoweredoff. Indicateswhethervirtualprocessorscanberemovedfromthe virtualmachinewhileitisrunning,ornot.Thisattributecan onlybesetwhenthevirtualmachineispoweredoff. Setofvirtualdevicesbeingmodifiedbytheconfiguration operation. Additionalconfigurationinformationforthevirtualmachine. Thisdescribesasetofmodificationstotheadditionaloptions. Anoptionisremovedifthekeyispresentbutthevalueisnot setorthevalueisanemptystring.Otherwise,thekeyissetto thenewvalue.Configurationkeysthatwouldconflictwith parametersthatareexplicitlyconfigurablethroughotherfields intheConfigSpecobjectaresilentlyignored. Informationaboutvirtualmachinefiles. Additionalflagsforavirtualmachine. Faulttolerancesettingsforthisvirtualmachine. Shortguestoperatingsystemidentifier.

bootOptions

VirtualMachineBoot Options boolean

changeTracking Enabled

changeVersion

string

consolePreferences cpuAffinity cpuAllocation cpuFeatureMask cpuHotAddEnabled

VirtualMachine ConsolePreferences VirtualMachine AffinityInfo ResourceAllocation Info VirtualMachine CpuIdInfoSpec[] boolean

cpuHotRemove Enabled deviceChange extraConfig

boolean

VirtualDevice ConfigSpec[] OptionValue[]

files flags ftInfo guestId

VirtualMachine FileInfo VirtualMachine FlagInfo FaultTolerance ConfigInfo string

VMware, Inc.

121

vSphere Web Services SDK Programming Guide

Table 13-2. VirtualMachineConfigSpec Data Object (Continued)


Property instanceUuid Type string Description and Usage 128bitUUIDofavirtualmachine,representedasa hexadecimalstring.ThisidentifierisusedbythevCenter Serversystemtouniquelyidentifyallvirtualmachine instancesinthevSphereenvironment,includingthosethat maysharethesameSMBIOSUUID.Normally,thispropertyis notsetbyaclient,allowingthevSphereenvironmenttoassign orchangeitwhenvCenterServerdetectsanidentifierconflict betweenvirtualmachines.Thisidentifiercanbemodifiedeven whenavirtualmachineispoweredon. 128bithashbasedonthevirtualmachinesconfigurationfile locationandtheUUIDofthehostassignedtorunthevirtual machine.Normally,thispropertyisnotsetbyaclient,allowing theVirtualInfrastructureenvironmenttoassignalocationID whenthevirtualmachineiscreated.However,ifthevirtual machinesconfigurationfilehasbeenmanuallymoved,itmay bedesirabletoclearthisproperty,settingittoanemptystring, sothepropertyisregenerated. Affinitysettingsformemory. Resourcelimitsformemory. Indicateswhethermemorycanbeaddedtothevirtualmachine whileitisrunning,ornot.Thisattributecanonlybesetwhen thevirtualmachineispoweredoff. Sizeofavirtualmachinesmemory,inMB. Displaynameofthevirtualmachine.Any%(percent) characterusedinthisnameparametermustbeescaped,unless itisusedtostartanescapesequence.Clientsmayalsoescape anyothercharactersinthisnameparameter.Snapshotsof virtualmachinesthathavespacesintheirnamesandare associatedwithESXServer2.xsystemsarenotsupported. Therefore,ifyouwanttheoptiontotakesnapshotsofthis virtualmachineandyouareassociatingitwithanESXServer 2.xsystems,donotusespacesinthename. Resourcelimitsfornetwork. TheNPIVnodeWWNstobeextendedfromtheoriginallistof WWNnumbers.Thispropertyshouldbesettotheaggregate ofexistingnumbersplusnewnumbers.DesiredNodeWWNs shouldalwaysbegreaterthantheexistingnumberofnode WWNs TheNPIVportWWNstobeextendedfromtheoriginallistof WWNnumbers.Thispropertyshouldbesettotheaggregate ofexistingplusnewnumbers.DesiredNodeWWNsshould alwaysbegreaterthantheexistingnumberofportWWNs TheNPIVnodeWWNtobeassignedtoavirtualmachine.This propertyshouldonlybeusedorsetwhenthevalueof npivWorldWideNameOppropertyisset.Otherwise,an InvalidVmConfigfaultisthrown.IfthespecifiednodeWWN iscurrentlybeingusedbyanothervirtualmachine,a VmWwnConflictfaultisthrown.Formoreinformationabout WWN,seenpivNodeWorldWideName. ThispropertyisusedtocheckwhethertheNPIVcanbe enabledontheVirtualmachinewithnonRDMdisksinthe configuration,sothisispotentiallynotenablingNPIVon VMFSdisks.ThispropertyisalsousedtocheckwhetherRDM isrequiredtogenerateWWNsforavirtualmachine.

locationId

string

memoryAffinity memoryAllocation memoryHotAddEnabled

VirtualMachine AffinityInfo ResourceAllocation Info boolean

memoryMB name

long string

networkShaper npivDesiredNodeWwns

VirtualMachine NetworkShaperInfo short

npivDesiredPortWwns

short

npivNodeWorldWideName

long[]

npivOnNonRdmDisks

boolean

122

VMware, Inc.

Chapter 13 Using vCenter Server for Virtual Machine Operations

Table 13-2. VirtualMachineConfigSpec Data Object (Continued)


Property npivPortWorldWideName Type long[] Description and Usage TheNPIVportWWNtobeassignedtoavirtualmachine.This propertyshouldonlybeusedorsetwhenthevalueof npivWorldWideNameOppropertyisset.Otherwise,an InvalidVmConfigfaultisthrown.IfthespecifiedportWWN iscurrentlybeingusedbyanothervirtualmachine,a VmWwnConflictfaultisthrown.Fordetaildescriptionon WWN,seenpivPortWorldWideName. ThispropertyisusedtoenableordisabletheNPIVcapability onaspecificvirtualmachineonatemporarybasis.Whenthis propertyissetNPIVVportwillnotbeinstantiatedbytheVMX processofthevirtualmachine.Whenthispropertyissetport WWNsandnodeWWNsintheVMconfigurationare preserved. TheflagtoindicatewhattypeofNPIVWWNoperationis goingtobeperformedonthevirtualmachine.Ifunset,it indicatesnochangetoexistingNPIVWWNassignment(ornot assigned)inthevirtualmachine. Thispropertyisusedinternallyinthecommunicationbetween thevCenterServerandESX/ESXisystemtoindicatethesource fornpivNodeWorldWideNameandnpivPortWorldWideName whennpivWorldWideNameOpisset.Thispropertyshouldonly besetbythevCenterServer.Ifthispropertyissetinacalltoa vCenterServer,anInvalidVmConfigfaultwillalwaysbe thrown.InacalltoanESX/ESXisystem,anInvalidVmConfig faultisthrownifthevalueofnpivWorldWideNameOpisnotset toset. Numberofvirtualprocessorsinavirtualmachine. Configurationfordefaultpoweroperations. Whethertokeepthevirtualmachinesswapfilewhenitis poweredoff.Thismayonlybesettotrueifthe swapPreservationSupportedcapabilityistrueforthis virtualmachine. Adatastorepathtoadirectorythatmaybeusedtostorethe swapfileforthisvirtualmachine.Thismayonlybesetifthe swapPlacementSupportedcapabilityistrueforthisvirtual machine.Anychangetothispropertywilltakeeffectthenext timethevirtualmachinepowerson,resumesfroma suspendedstate,ormigrateswhilepoweredon. Virtualmachineswapfileplacementpolicy.Thismayonlybe setiftheswapPlacementSupportedcapabilityistrueforthis virtualmachine.Anychangetothispolicywilltakeeffectthe nexttimethevirtualmachinepowerson,resumesfroma suspendedstate,ormigrateswhilepoweredon. ConfigurationofVMwareToolsrunningintheguestoperating system. 128bitSMBIOSUUIDofavirtualmachinerepresentedasa hexadecimalstringin 12345678-abcd-1234-cdef-123456789abcformat. Normally,thispropertyisnotsetbyaclient,allowingthe vSphereenvironmenttoassignaUUIDwhenthevirtual machineiscreated.However,insomerarecases,suchasa manualcopyofavirtualmachine,itmaybenecessarytoset thisproperty.

npivTemporaryDisabled

boolean

npivWorldWideNameOp

string

npivWorldWideNameType

string

numCPUs powerOpInfo preserveSwapOnPowerOff

int VirtualMachine DefaultPowerOpInfo boolean

swapDirectory

string

swapPlacement

string

tools uuid

ToolsConfigInfo string

VMware, Inc.

123

vSphere Web Services SDK Programming Guide

Table 13-2. VirtualMachineConfigSpec Data Object (Continued)


Property vAssertsEnabled Type boolean Description and Usage Indicateswhetheruserconfiguredvirtualassertsaretriggered duringvirtualmachinereplay.Thissettingtakeseffectduring thenextreplayofthevirtualmachine.Enablingthis functionalitycanpotentiallycausesomeperformance overheadduringvirtualmachineexecution. Theversionstringforthisvirtualmachine.Thisisusedonly whilecreatinganewvirtualmachine,andcanbeupdatedby invokingUpgradeVM_Taskforthisvirtualmachine. ConfigurationofVServicemetadataforavirtualmachine Settotrue,iftheVServiceconfigurationshouldberemoved

version

string

vServiceConfig vServiceConfigRemoved

VmConfigSpec boolean

Using Templates to Deploy Standard Virtual Machines


AtemplateisinstanceofaVirtualMachinemanagedobjectthathasitstemplatepropertysettotrue. Templatesdonotconsumeresourcesandtheirpermissionsderivefromtheircontainingfolderonly,notfrom theirassociatedresourcepoolasdoVirtualMachineobjects. Table 133listsadvancedoperationsavailablethroughtheVirtualMachinemanagedobject. Table 13-3. Advanced VirtualMachine Operations Summary
Operation CloneVM_Task Description Createsacloneofthisvirtualmachine.Ifthevirtualmachineisusedasatemplate,this methodcorrespondstothedeploycommand.Any%(percent)characterusedinthis nameparametermustbeescaped,unlessitisusedtostartanescapesequence.Clients mayalsoescapeanyothercharactersinthisnameparameter. Obtainsanexportleaseonthisvirtualmachine.TheexportleasecontainsalistofURLs forthevirtualdisksforthisvirtualmachine,andaticketgivingaccesstotheURLs. ReturnstheOVFenvironmentforavirtualmachine.Ifthevirtualmachinehasno VServiceconfiguration,anemptystringisreturned.Also,sensitiveinformationis omitted,sothismethodisnotguaranteedtoreturnthecompleteOVFenvironment. MarksaVirtualMachineobjectasbeingusedasatemplate.Note:AVirtualMachine markedasatemplatecannotbepoweredon. ClearstheisTemplateflagandreassociatesthevirtualmachinewitharesourcepooland host. Removesthespecifiedsecondaryvirtualmachinefromthisfaulttolerantgroup.

ExportVm ExtractOvfEnvironment

MarkAsTemplate MarkAsVirtualMachine RemoveSecondaryVM_Task

Creating Templates
Youuseatemplatetocreatemultiplevirtualmachineshavingthesamecharacteristics,suchasamountof resourcesallocatedtoCPUandmemoryandtypeofvirtualhardwareattributessupported. Theonlypropertythatdistinguishesatemplatefromavirtualmachineisthetemplatepropertyofthe VirtualMachineConfigInfodataobjectthatcomprisestheconfigpropertyofaVirtualMachineinstance: AtemplateisaninstanceofaVirtualMachineobjectthathasitstemplatepropertysettotrue. Youuseoneofthesetwogeneralwaystocreateatemplate: Ifyounolongerneedaspecificinstanceofavirtualmachine,butyouwanttousethevirtualmachines configurationasatemplate,usetheMarkAsTemplateoperationonthevirtualmachineinstance.Youuse themanagedobjectreferenceofthevirtualmachinetoinvokethisoperation.Invokingthisoperationsets theconfig.templatepropertytotrue,andthevirtualmachineisdisabled. Ifyouwanttouseanexistingvirtualmachineasatemplate,yetalsokeepthevirtualmachine,usethe CloneVM_Taskoperationofthevirtualmachinefirst,tocreateaduplicateofthevirtualmachine Example 131demonstratesthecloningapproach,whichmakesthevirtualmachineinoperative.

124

VMware, Inc.

Chapter 13 Using vCenter Server for Virtual Machine Operations

Example 13-1. Cloning a Virtual Machine to Use as a Template


... VirtualMachineRelocateSpec vmRelocSpec = new VirtualMachineRelocateSpec(); vmRelocSpec.setTransform(VirtualMachineRelocateTransformation.sparse); VirtualMachineCloneSpec vmCSpec = new VirtualMachineCloneSpec(); vmCSpec.setLocation(vmRelocSpec); vmCSpec.setTemplate(Boolean=TRUE); vmCSpec.setPowerOn(Boolean=FALSE); ManagedObjectReference taskMoRef = my_conn.cloneVM_Task(vmMoRef, folderMoRef, new String("Templ_1"), vmCSpec); ...

Example 131usestheVirtualMachineCloneSpec,whosepropertiesprovideinformationaboutwherethe datastoreinformationislocated,thetargethost,theresourcepool,andthekindoftransformation(flator sparse)toperformonthedisks.Ifdatastoreinformationisnotprovided,defaultsareprovided.Seethe VirtualMachineRelocateSpecinthevSphereAPIReferenceformoreinformation.

Reverting a Template to Its Active Virtual Machine Status


Youchangeatemplatebacktoanoperationalvirtualmachinebyusingtheappropriateoperation: InvoketheMarkAsVirtualMachineoperationonthetemplate.Thisclearsthebooleanpropertythat definesthevirtualmachineasatemplateandreassociatesthevirtualmachinewiththeresourcepooland hosttowhichithadoriginallybeenassociated.However,thetemplatenolongerexists. Toretainthetemplate,clonethetemplatebyinvokingtheCloneVM_Taskoperationonthetemplate.In theVirtualMachineCloneSpec(thespecparameter)fortheoperation,setthetemplatepropertyto false.

Migrating Virtual Machines Using VMotion


VMotionhasbeenacapabilityofVMwareserversforseveralreleasesoftheproduct,buthasmanynew featuresandcapabilitiessupportedinvSphere4.0,includingsupportfordistributedvirtualswitches. VMotionhasdependenciesonbothnetworkinginfrastructureandthehostsystemhardware. Migratingavirtualmachinefromonehosttoanotherrequiresproperlyconfigurednetworkingofallvirtual machinesandsourceandtargethosts.Thevirtualmachinecanbeinanystate,includingpoweredon,powered off,orsuspended. Table 133listsoperationsavailablethroughtheVirtualMachinemanagedobjectformigratingorrelocating virtualmachines. Table 13-4. VirtualMachine Operations for VMotion
Operation MigrateVM_Task Description MigratesavirtualmachinetoaspecificResourcePoolorHostSystem.Theprincipalassociated withthesessioninvokingtheoperationmusthavetheappropriateprivilegesforthestateofthe virtualmachine: Migratingavirtualmachinethatisrunning(stateispoweredOn)requiresthe Resource.HotMigrateprivilege. Migratingavirtualmachinethatisshutdownorsuspended(stateispoweredOffor suspended)requirestheResource.ColdMigrateprivilege. RelocateVM_Task Relocatesthevirtualdisksassociatedwiththespecifiedvirtualmachinetoanewlocation. Optionally,alsomovesthevirtualmachinetoadifferenthost. ForStorageVMotionwhenthevirtualmachineispoweredon,theprincipalinvokingthis operationrequirestheResource.HotMigrateprivilegeandtheDatastore.AllocateSpace privilegeonthetargetdatastore.

VMware, Inc.

125

vSphere Web Services SDK Programming Guide

Checking the Validity of a Migration In Advance


AsofvSphere4.0,youusetheVirtualMachineProvisioningCheckertodetermineifaproposedmigration isviableornot. Figure 13-2. VirtualMachineProvisioningChecker Service Interface

TheCheckMigrate_TaskoperationdetermineswhetheraproposedMigrateVM_Taskoperationispossible. SeethevSphereAPIReferenceformoreinformation.

Using the MigrateVM_Task Operation


TheMigrateVM_Taskoperationmovesalltheconfigurationfilesthatmakeupavirtualmachine.Thedisk filesthatmakeupthevirtualmachineremainintheiroriginallocation. Table 135liststheparametersfortheMigrateVM_Taskoperations.Youcanusethisoperationwithvirtual machinesthatarerunningornot.Youusethestateparametertoensurethatthevirtualmachineismovedonly ifitisinthestateyouspecify. Table 13-5. MigrateVM_Task Operation
Parameter _this pool Type MOR MOR>ResourcePool Description Managedobjectreferenceofthevirtualmachinethatyouwantto migratetoanewlocation. ManagedobjectreferencetothetargetResourcePoolforthevirtual machine.Ifthisparameterisnotset,thevirtualmachinestays assignedtoitscurrentResourcePool.Youmustspecifyahost withinthesamecomputeresource. ManagedobjectreferencetothetargetHostSystemforthevirtual machine.TheHostSystemmustbeassociatedwiththe object.Thetargethosttorunthevirtualmachine.Thismustspecify ahostthatisamemberoftheComputeResourceobjectindirectly specifiedbythepool.Forastandalonehostoraclusterwith VMwareDRS,thepropertycanbeunspecifiedandthesystem selectsadefaultfromthesameComputeResourceobjectasthe ResourcePoolspecifiedbythepoolparameter. priority VirtualMachineMovePriority Priorityofthemigration.Thepriorityvalueisoneofthe VirtualMachineMovePriorityenumeratedtypevalues, specifically,defaultPriority,highPriority,orlowPriority. Optional.Ifspecified,thevirtualmachineismovedtothetarget locationonlyifitsstatematchesthespecifiedstate.Thevalueof stateisoneoftheVirtualMachinePowerStateenumeratedtype values,specifically,poweredOff,poweredOn,orsuspended.

host

MOR>HostSystem

state

VirtualMachinePowerState

126

VMware, Inc.

Chapter 13 Using vCenter Server for Virtual Machine Operations

Moving Storage Dynamically Using Storage VMotion


StorageVMotionallowsyoutomovearunningvirtualmachinefromoneVMFSvolumetoanother.Storage VMotionwasintroducedinVMwareInfrastructure3.5,andhasfullsupportinvSphere4.0. Neitherthevirtualmachinenoritsassociatedstorageneedtobetakenoffline.Alldatastoretypesare supported,includinglocalstorage,VMFS,andNAS(networkattachedstorage).StorageVMotionusesthe RelocateVM_Taskoperation(ofVirtualMachine).RelocateVM_Taskoperationmovesvirtualdiskstoa newstoragelocation,specifiedintheVirtualMachineRelocateSpecdataobject. Table 13-6. RelocateVM_Task Operation
Parameter _this spec priority Type ManagedObjectReference VirtualMachineRelocateSpec VirtualMachineMovePriority Description and Usage ReferencetotheVirtualMachineusedtomakethemethodcall. Thespecificationofwheretorelocatethevirtualmachine. Thepriorityoftheoperation,specifiedasoneofthethreepossible VirtualMachineMovePriorityenumerations: defaultPriority,highPriority,lowPriority.

Figure 133showsapartialUMLdiagramofVirtualMachineandsomeofthedataobjectsthatareusedwith RelocateVM_Task. Figure 13-3. VirtualMachine RelocateVM_Task Operation

ThedataobjectsandenumerationtotheleftoftheVirtualMachinemanagedobjecttyperepresentinputsto theoperation.Table 137liststhepropertiesoftheVirtualMachineRelocateSpecdataobject. Table 13-7. VirtualMachineRelocateSpec Data Object


Property datastore disk diskMove Type Type MOR>Datastore VirtualMachine RelocateSpecDiskLocator[] string Description and Usage Optional.Targetdatastoreforthevirtualmachine.Defaultsto currentdatastoreifthisparameterisnotspecified. Optional.Listthatspecifiesdatastorelocationforeachvirtualdisk. Optional.Specifiesthemannerinwhichtomovethevirtualdiskto thetargetdatastoreusingoneofthe VirtualMachineRelocateDiskMoveOptionsenumerations: createNewChildDiskBacking moveAllDiskBackingsAndAllowSharing moveAllDiskBackingsAndDisallowSharing moveChildMostDiskBacking Settingthispropertyrequiresthatthe deltaDiskBackingsSupportedpropertyofHostCapability be settotrue.Ifnotspecified,themovetypedefaultsto moveAllDiskBackingsAndDisallowSharing. Appliestoallthedisksassociatedwiththevirtualmachine.To overrideandspecifythemovetypeonaperdiskbasis,usethe diskMoveTypepropertyof VirtualMachineRelocateSpecDiskLocator.

VMware, Inc.

127

vSphere Web Services SDK Programming Guide

Table 13-7. VirtualMachineRelocateSpec Data Object (Continued)


Property host Type MOR>HostSystem Description and Usage Optional.Targethostforthevirtualmachine.Ifneitherhostnor resourcepoolisspecified,thecurrenthostisused.ifresourcepoolis specified,andthetargetpoolrepresentsastandalonehost,thehost isused.ifresourcepoolisspecified,andthetargetpoolrepresentsa DRSenabledcluster,ahostselectedbyDRSisused.ifresourcepool isspecifiedandthetargetpoolrepresentsaclusterwithoutDRS enabled,anInvalidArgumentexceptionbethrown. Targetresourcepoolforthevirtualmachine. Optionalforrelocatingorcloningtoavirtualmachine.Defaults tocurrentresourcepoolofvirtualmachineunlessspecified. Ignoredforcloningtoatemplate. Requiredtoclonefromatemplatetoavirtualmachine. transform VirtualMachine Relocate Transformation Optional.Specifieshowtotransformvirtualdisksduringcopy. (VirtualMachineRelocateTransformationisanenumerated datatypeconsistingofflatandsparseoptions.)Anyinvalid transformationsareignoredbythestoragesubsystem.

pool

MOR>ResourcePool

Tomovethediskfiles,usetheRelocateVM_Taskoperation.SeethesampleslistedinSampleCode Referenceonpage 120forexamplesofusingtheseoperations.

128

VMware, Inc.

14

Event and Task Management Using vCenter Server

14

AnEventisamessagegeneratedbymanagedentitiesduringoraftervariousoperations.TheEventManager istheserviceinterfacethatyoucanusetodefineyourownevents.Thischapterincludesthesetopics: SampleCodeReferenceonpage 129 UnderstandingEventManagerandtheEventDataObjectonpage 129 CreatingCustomEventsonpage 132 ObtainingInformationaboutEventsUsingaHistoryCollectoronpage 133

Sample Code Reference


Table 141liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 14-1. Sample Applications that Demonstrate Event and EventManager
Java SDK\samples\Axis\java\com\vmware\samples\events EventFormat.java EventHistoryCollectorMonitor.java VMEventHistoryCollectorMonitor.java C# SDK\samples\DotNet\cs\ EventFormat EventHistoryCollectorMonitor VMEventHistoryCollectorMonitor

Understanding EventManager and the Event Data Object


AnEventisadataobjecttypethatcontainsinformationaboutstatechangesofmanagedentitiesandother objectsontheserver.Eventsincludeuseractionsandsystemactionsthatoccurondatacenters,datastores, clusters,hosts,resourcepools,virtualmachines,networks,anddistributedvirtualswitches.Forexample, thesecommonsystemactivitiesgenerateoneormoreEventdataobjects: Poweringavirtualmachineonoroff Creatingavirtualmachine InstallingVMwareToolsontheguestOSofavirtualmachine Reconfiguringacomputeresource AddinganewlyconfiguredESX/ESXisystemtoavCenterServer InformationfromEventobjectsgeneratedonanunmanagedESX/ESXisystemdisplayintheEventstabofthe vSphereClient.Formanagedhosts,informationfromEventobjectsdisplaysintheTasks&Eventstabof vSphereClient.Fordevelopers,theEventManagerprovidesaccesstoEventdataobjects.

VMware, Inc.

129

vSphere Web Services SDK Programming Guide

EventManager Managed Object


TheEventManageristheserviceinterfaceforworkingwiththeeventinfrastructure.Figure 141shows EventManagerandsomeofitsrelatedobjects.AnEventManagerhastheseproperties: AdescriptionpropertydefinedasaninstanceofaEventDescriptiondataobject,whichcontainsan eventcategoryandotherinformation. AlatestEventpropertythatcontainsthemostrecentEventdataobjectinmemory. AmaxCollectorpropertythatspecifiesthenumberofEventHistoryCollectorobjectsperclient sessionthatcanbecreated.Thisvalueissetbytheserver. Figure 14-1. EventManager Managed Object and Event Data Object

InvSphereAPI4.0,theeventinfrastructureincludesmanynewpropertiesanddataobjectstosupportnew capabilitiesofvSphere4.0. Forexample,changeTag,ds,dvs,andnetareallnewpropertiesdesignedtosupportenhancementstothe AlarmandEventinfrastructure,ortosupportnewcapabilities,suchasDistributedVirtualSwitch managedobject. SeethevSphereAPIReferenceformoreinformation.

Event Data Objects


TheEventdataobjecthasmanysubtypesthatdefinethespecifickindsofeventsthatthesystemgenerates. Figure 142,EventDataObjectisaBaseTypeUsedbyManyGenerationsofSubtypes,onpage 131,shows onlyafewofthesubtypesthatextendtheEventdataobject.Inmanycases,thesubtypecontainsnoadditional propertiesbeyondthoseoftheEventbasetype,butinothercases,thesubtypeprovidesadditional information. Forexample,theTaskEventisasubtypeofEvent.InadditiontocontainingallthepropertiesoftheEvent typethatareappropriateforthesystem,aTaskEventalsoincludesaninfopropertythatisdefinedasan instanceofaTaskInfoobject.TheTaskEventcontainsinformationsuchastheentityNameoftheobjectthat generatedtheevent.SeeUnderstandingtheTaskInfoDataObjectonpage 85formoreinformationaboutthe TaskInfodataobject. Thesearesomeexamplesofcommoneventobjectsoutputbyaconsolestyleclientapplication:
com.vmware.vim.VmPoweredOnEvent com.vmware.vim.VmStartingEvent com.vmware.vim.VmReconfiguredEvent com.vmware.vim.VmCreatedEvent com.vmware.vim.VmBeingCreatedEvent

130

VMware, Inc.

Chapter 14 Event and Task Management Using vCenter Server

TheVmPoweredOnEventisalsoshowninFigure 142.Asshownattheconsole,theeventdataobjectsarenot formattedanddonotprovideanycontextinformation. Figure 14-2. Event Data Object is a Base Type Used by Many Generations of Subtypes

Formatting Event Message Content


Toformataneventmessage,youcanusethepredefinedstringcontainedinthefullFormattedMessage propertyoftheEventobject. YoucanalsoformatanEventmessagebasedonthecontextualinformation.Atruntime,theeventsgenerated bythesystemarepopulatedwiththeappropriatevaluesfortheirsource,suchasthemanagedobjectreference ofthecomputeresourceassociatedwiththeevent.Thepropertiescontainingargumentsassociatedwiththe sourceofaneventincludethecomputeResource,datacenter,ds,dvs,host,net,andvmpropertiesofthe Eventdataobject(seeFigure 141,EventManagerManagedObjectandEventDataObject,onpage 130). YouusethepropertiesofanEventobjectinconjunctionwiththeEventDescriptionEventDetaildata objecttoformateventmessagecontentappropriateasoutputforyourapplication.Table 142liststhe propertiesofEventDescriptionEventDetaildataobject. Table 14-2. EventDescriptionEventDetail Data Object Type
Property category description Type string string Description CategoryoftheEvent,suchasinfo,error,user,orwarning. AlocalizeddescriptionoftheEventdesignedforpresentationtoendusers. Forexample,theEnglishdescriptionoftheVmPoweredOnEventmight readVM Powered On.Usewhencreatingeventbasedalarmstowhich endusersmustrespond. Descriptionpatternthatisappropriateinthecontextofaspecificcluster. Forexample,anEventgeneratedbypoweringonavirtualmachineina clusterusingthisformatthefollowingtextpattern: {vm.name} on {host.name} is powered on formatOnDatacenter string Descriptionpatternthatisappropriateinthecontextofaspecific datacenter.Forexample,arenamingeventthatusesthisformatusesthe followingpattern: Renamed {vm.name} from {oldName} to {newName} The{oldName}and{newName}arepropertiesofthesource VmRenamedEventobject.

formatOnComputeResource

string

VMware, Inc.

131

vSphere Web Services SDK Programming Guide

Table 14-2. EventDescriptionEventDetail Data Object Type (Continued)


Property formatOnHost Type string Description Descriptionpatternthatisappropriateinthecontextofaspecifichost.For example,anEventgeneratedbypoweringonavirtualmachineusesthe followingpattern: {vm.name} is powered on formatOnVm string Descriptionpatternthatisappropriateinthecontextofaspecificvirtual machine.Forexample,anEventgeneratedbypoweringonavirtual machineusesthefollowingpattern: Virtual machine on {host.name} is powered on fullFormat string Completedescriptionpatternthatincludesallcontextualinformationabout thesourceoftheEvent,includingdatacenter,hostname,andvirtual machinename.Forexample,thefollowingisafullyformattedtextpattern foraneventgeneratedbystartingavirtualmachine: {vm.name} on key string {host.name} in {datacenter.name} is powered on Typeofeventbeingdescribed.

ThenamepropertyinanyoftheformattedoutputisderivedfromcomputeResource,datacenter,ds,dvs, host,net,andvmpropertiesoftheEventobject. Forexamplesofdefininganeventmessagebasedoncontext,seetheEventFormat.javaorEventFormat.cs samplesinthevSphereWebServicesSDKpackage.

Creating Custom Events


TheEventManagerLogUserEventoperationenablesyoutocreatecustomEventobjectstoaugmentthe predefinedeventsorprovidingmarkersthatfacilitatebrowsingEventhistory.Youcanassociateyourcustom Eventwithanymanagedentity. To define a custom Event 1 ObtainthemanagedobjectreferencetotheEventManager.
.. ManagedObjectReference _svcRef = new ManagedObjectReference(); ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef); ManagedObjectReference eMgrRef = _sic.getEventManager(); ...

2 3

ObtainthemanagedobjectreferencetotheentitywithwhichyouareassociatingtheEvent. InvoketheLogUserEventoperationusingboththesereferencesandastringconsistingoftheEvent messageforthemsgparameteroftheoperation.

UserdefinedEventobjectsdisplayinthevSphereClientamongtheothereventsonthesystem,withthe prefixUser logged event:followedbythetextsubmittedinyourmsgparameter.Inotherclient applications,suchasintheconsolebasedEventsampleapplications,customeventsdisplayas com.vmware.vim.GeneralUserEventobjects.

132

VMware, Inc.

Chapter 14 Event and Task Management Using vCenter Server

Obtaining Information about Events Using a HistoryCollector


AnEventHistoryCollectorletsyougatherinformationabouttheeventsthathavebeengeneratedbythe server.YoucreateanEventHistoryCollectorusingtheCreateCollectorForEventsoperationof EventManager. To create an EventHistoryCollector 1 IdentifythetypeofEventobjectsthatyouwanttocollect,andcreateaninstanceofanEventFilterSpec dataobjectthatspecifiesyourfiltercriteria.TheEventFilterSpecincludesproperties,suchas eventTypeId,thatyouusetolimitthesetofcollectedeventobjectstospecifictypes.Youcanalsoprovide atimerangeintheEventFilterSpec,bydefininganEventFilterSpecByTimedataobjectforitstime property.SeethevSphereAPIReferencefordetails. ObtainthemanagedobjectreferencetotheEventManageronyourserverinstance. SubmitthefilterandthereferencetotheserverintheCreateEventHistoryCollectoroperation. The serverreturnsareferencetoaEventHistoryCollectorobject.

2 3

TheEventHistoryCollectorreturnedconsistsofthecollectionofobjectsfromthevCenterServerdatabase. TheEventHistoryCollectorconsistsofanarrayofoneormoreEventdataobjectsthatmeetthecriteria specified.ThelatestPagepropertyoftheEventHistoryCollectorobjecthasapropertythatconsistsofthe 1000mostrecentobjectsinthecollection.

Overview of HistoryCollector Managed Objects


AnEventHistoryCollectorisoneofthespecificsubtypesoftheHistoryCollectormanagedobjecttype. TheTaskHistoryCollectorisanother.Youdefinethespecificationtouseasthefilterandpassittothe CreateTaskHistoryCollectoroperationoftheTaskManager.Figure 143showstherelationshipof HistoryCollectortoitstwosubtypes. Figure 14-3. TaskHistoryCollector and EventHistoryCollector Descend from HistoryCollector

InadditiontothefilterpropertythattheyinheritfromtheHistoryCollectorbasetype,the EventHistoryCollectorandTaskHistoryCollectoreachhasalatestPagepropertyfortheirrespective objecttypes.TheHistoryCollectormanagedobjecttypeprovidesoperationsformanagingthelifecycle andscrollableviewofacollection. Table 14-3. Operations Common to HistoryCollector and Its Descendents
Operation DestroyCollector ResetCollector Description AHistoryCollectorexistsonlyforthecurrentsession.InvoketheDestroyCollector operationtoexplicitlydestroythecollectorbeforethesessionends. Adjuststhestartingpositionforthesubsetofobjectsfromthecollectortotheobject immediatelyprecedingthecurrentlatestPage.

VMware, Inc.

133

vSphere Web Services SDK Programming Guide

Table 14-3. Operations Common to HistoryCollector and Its Descendents (Continued)


Operation RewindCollector SetCollectorPageSize Description PositionsthelatestPagetotheoldestiteminthearray.WhenaHistoryCollectoris created,thisisthedefaultlocation. AcceptsanintegerparametertosetthesizeofthelatestPagepropertyofa HistoryCollector.ThedefaultsizeofaHistoryCollectorisanarraycomprisinga maximumof1000objectsoftheappropriatetype(Task,Event).Thearrayissortedby creationdateandtimeoftheobjects.

Table 144liststhepropertiesofTaskFilterSpec.TocreateaTaskHistoryCollector,youuseoneormore propertiesofTaskFilterSpecdataobjecttodefinefilterthatmeetsyourrequirements.Forexample,rather thanreturningallTaskobjectsassociatedwithvirtualmachines,youmightcreateafiltertocollectonlythose Taskobjectsassociatedwithvirtualmachinesthatwereexecutedbythebackupadministratorbetween2:00 and4:00a.m.onaspecificdate. Table 14-4. TaskFilterSpec Data Object
Property alarm entity eventChainId parentTaskKey rootTaskKey scheduledTask state Type MOR >Alarm TaskFilterSpecByEntity int[] string[] string[] MOR >ScheduledTask TaskInfoState[] Description and Usage Optional.Usetocreateafilterbasedonspecificinstanceofan Alarm. Optional.Usetocreateafilterbasedonspecificmanagedentity types.Defaultreturnsvaluesforallmanagedentities. Optional.UsetocreateafilterthatreturnsonlyTaskobjects associatedbyaspecificchainofevents. Optional.UsetocreateafilterthatreturnsonlythoseTaskobjects thathavethespecifiedparentTaskKey. Optional.UsetocreateafilterthatreturnsonlythoseTaskobjects thatcontainthespecifiedrootTaskKey. Optional.Usetocreateafilterthatreturnsareferenceonlytothe specifiedScheduledTask.DefaultreturnsallTaskobjects. Optional.UsetocreateafilterthatreturnsonlythoseTaskobjects inthespecifiedstate: error queued running success tag string[] Optional.UsetocreateafilterthatreturnsTaskobjectswiththe specifiedtag.Includeanemptystring()inthearraytoreturn Taskobjectswithoutatag. Optional.UsetocreateafilterthatreturnsTaskobjectswiththe specifiedtime.Ifnotspecified,thecollectorincludesallTask objects. Optional.UsetocreateafilterthatreturnsTaskobjectsfora specifieduseraccount.Ifnotprovided,thenthetasksbelongingto anyuserarecollected.

time

TaskFilterSpecByTime

userName

TaskFilterSpecByUsername

BeforeyoucancreateaTaskHistoryCollector,youmustcreateaninstanceofthefilterthatdefinesthe specificationsoftheTaskobjectsthatyouwanttocollect.Mostofthepropertiesareoptionalandcanbe submittedasnullvalues.TheTaskFilterSpecletsyoucollecttasksbasedonusername,entitytype,time, stateoftheTask,oranyoftheotherpropertieslistedinTable 144. Bydefault,whenaHistoryCollectorisinstantiated,theobjectsinthecollectionareretrievedinorderof oldesttonewest.ToaccessthecontentofaHistoryCollector,youuseaPropertyCollectortoobtainthe itemsfromthelatestPageproperty.

134

VMware, Inc.

Chapter 14 Event and Task Management Using vCenter Server

New Objects Appended to a HistoryCollector


OnceaHistoryCollectorexists,theserverappendsnewobjectsthatmeetthefiltercriteriatothecollection astheyoccur.Thesystemappendsthenewobjecttothecollectionbyplacingitinthefirstpositionofthe latestPageanditremovestheoldestobjectfromthecollection.

Deleting a HistoryCollector
AHistoryCollectorexistsonlyforthedurationofthesessionthatinstantiatedit.Youinvokethe DestroyCollectoroperationtoexplicitlyeliminatethecollectorbeforethesessionends. SeethevSphereAPIReferenceforcompleteinformationaboutHistoryCollector,EventHistoryCollector, andTaskHistoryCollector.

VMware, Inc.

135

vSphere Web Services SDK Programming Guide

136

VMware, Inc.

15

Using the Alarm Infrastructure

15

VMwarevCenterServerprovidesacomprehensivealarminfrastructureforautomatingactionsandsending varioustypesofnotificationinresponsetospecifiedserverconditions.Youcancreatealarmsthatrespondto specificconditions,serverstate,oraspecifiedevent.Analarmmusthaveanexpressionthatevaluatestoa truefalsevalue.ThealarminfrastructureincludestheAlarmManagerserviceinterface,theAlarmmanaged objecttype,andmanyassociatedobjectsthatmakeupthedatastructuresrequiredtosupportdefiningthe serverconditionsthatmustexistforanalarmtobecomeactive.Thealarminfrastructureintegrateswithother servercomponents,suchaseventsandperformancecounters.WiththereleaseofvSphere4.0,thealarm infrastructureprovidesfinergrainedcontroloveralarmthresholdsettingsthaninpriorreleases.Many AlarmsexistbydefaultonvCenterServer. Thischapterincludesthesetopics: SampleCodeReferenceonpage 137 OverviewofAlarmManagerandAlarmManagedObjectsonpage 137

Sample Code Reference


Table 151liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 15-1. Sample Applications that Use Alarm
Java SDK\samples\Axis\java\com\vmware\samples\alarms VMPowerStateAlarm.java C# SDK\samples\DotNet\cs\ VMPowerStateAlarm

Overview of AlarmManager and Alarm Managed Objects


TheAlarmManageristheserviceinterfaceforcreating,setting,andmanagingalarms.TheAlarmManager instantiatesanAlarmpopulatedwiththepropertiesyouspecifyandreturnsamanagedobjectreferencetothe Alarm. Figure 15-1. Alarm Managed Object

VMware, Inc.

137

vSphere Web Services SDK Programming Guide

Obtaining a List of Alarms


TheAlarmManagerprovidesoperationsforobtaininginformationaboutexistingalarms.Youusethe GetAlarmoperationtoobtainanarrayofreferencestoalltheAlarmmanagedobjectsdefinedforaspecific managedentity.TheparametersfortheoperationareareferencetotheAlarmManagerobjectandanoptional referencetoaspecificmanagedentity.Withoutareferencetoamanagedentity,theGetAlarmoperation returnsallAlarmobjectsforallentitiesthatarevisibletotheprincipalassociatedwiththesessioninvokingthe operation. AsshowninFigure 151,anAlarmisamanagedobjectwithoperationsforitsownreconfigurationand removal.ItalsohasaninfopropertythatconsistsofanAlarmInfodataobject.AswiththeTaskmanaged objectandTaskInfodataobject,youcanobtaininformationabouttheAlarmsthatareactiveonthesystemby collectingthepropertiesoftheAlarmInfodataobject. WhenyoucreatetheAlarm,youassociateitwithoneormorespecificmanagedentities,suchasvirtual machines,hosts,distributedvirtualswitches,datastores,andsoon.WhentheconditionsdefinedfortheAlarm occuronthesystem,theActionspecifiedforthealarmstarts.Theactionmightbesendinganemail,running ascript,orinvokinganoperationofoneoftheserviceinterfaces.

Defining an Alarm
Severaldifferentdataobjectsprovidethecomponentsneededtospecifythesettingsforanalarm.Thealarm infrastructureintegrateswithotherinfrastructureservices,suchastheperformancemonitoringsystemand theeventinfrastructure. Forexample,youcandefineanalarmthatmonitorsthevaluesofaspecificmetricgeneratedbyoneofthe performanceprovidersonthesystem,byspecifyingthemetricintheexpressionyoudefine.Youmightwant tocreateanAlarmthatsendsanalertemailmessagewhenCPUusageonaspecificvirtualmachineexceeds 99%formorethan30minutes. Figure 15-2. CreateAlarm Operation Returns a Reference to an Alarm Managed Object

To create an Alarm on a specific managed entity 1 2 ObtainamanagedobjectreferencetotheAlarmManagerofthevCenterServer. ObtainamanagedobjectreferenceoftheentityonwhichyouwanttosettheAlarm.

138

VMware, Inc.

Chapter 15 Using the Alarm Infrastructure

PopulatetheAlarmSpecdataobjectwiththedetailsfortheAlarm.Manyofthesepropertiesarenested dataobjectsthatyoumustcreateinyourcodebeforeyoucaninstantiatetheAlarmSpecdataobject.See Table 152,AlarmSpecProperties,onpage 139formoreinformationaboutthisdataobjecttype. PassthereferencesandthedataobjecttotheCreateAlarmoperation,asitsparameters.Thesystem returnsamanagedobjectreferencetotheAlarm,asshowninFigure 152.

Table 15-2. AlarmSpec Properties


Property action Type AlarmAction Description ActiontoinitiatewhentheAlarmbecomesactive.Specifyoneofthe Actionsubtypes,including: CreateTaskAction MethodAction RunScriptAction SendEmailAction SendSNMPAction SeeOverviewoftheAlarmActionDataObjectonpage 141. actionFrequency description enabled expression int string boolean AlarmExpression NumberofsecondsthattheAlarmremainsinthestaterequiredtoinitiate thespecifiedAction. Required.DescriptionoftheAlarm. Required.SettotruetoenabletheAlarm.Settofalsetodisablethe Alarm. Required.OneormoreoftheAlarmExpressiondataobjectscombined inawaythatevaluatestoatruefalseexpression. AndAlarmExpression OrAlarmExpression EventAlarmExpression MetricAlarmExpression StateAlarmExpression. SeeOverviewoftheAlarmExpressionDataObjectonpage 139. name setting string AlarmSetting Required.NameoftheAlarm. ToleranceandfrequencylimitsfortheAlarmdefinedinthe AlarmSettingdataobject.AlarmSettingcontainstwointeger properties: reportingFrequency,whichspecifiesthenumberofseconds betweenactivationofanalarm.Use0tospecifythatthealarmcan activateasfrequentlyasrequired. toleranceRange,whichspecifiestheacceptablerange(measuredin hundredthpercentage)aboveandbelowthespecifiedvaluedefined inaMetricAlarmExpression.

Overview of the AlarmSpec Data Object


YousetanAlarmonanentitybycreatingtheAlarmSpecdataobject.TheAlarmSpecdataobjectincludes propertiesforallaspectsofanAlarm,includingitsexpressionandtheactiontotakewhentheexpression evaluatestotrue.AsshowninTable 152,theexpressionandtheactionpropertiesaredefinedasinstances oftwoothercomplexdataobjecttypes,AlarmExpressionandAlarmAction,bothofwhichareabstractdata objecttypes.

Overview of the AlarmExpression Data Object


YouspecifytheconditionsthattriggertheactiondefinedforanAlarmbyprovidinganAlarmExpression dataobjectfortheexpressionpropertyoftheAlarmSpecdataobject.TheAlarmExpressiondataobjectis anabstracttype.Ithasseveralsubtypes(seeFigure 153,AlarmExpressionAbstractDataTypeandIts Subtypes,onpage 140).

VMware, Inc.

139

vSphere Web Services SDK Programming Guide

TheAlarmExpressionsubtypesallowyoutospecifythresholdsonobjects,stateofobjects,orspecifyspecific eventstomonitor.YouusetheAlarmExpressiondataobjecttypetospecifytheconditionsunderwhichyou wanttheAlarmtobecomeactive. Figure 15-3. AlarmExpression Abstract Data Type and Its Subtypes

ByusingtheappropriatesubtypeofAlarmExpression,youmightsetalarmsforavarietyofconditions, states,orevents,suchastheseexamples: Powerstateofavirtualmachineorthestateofadistributedvirtualswitch,byusinga StateAlarmExpressiondataobject Resourceutilizationmetricsthatexceedaspecifiedlimit,byusingaMetricAlarmExpression Eventssuchaspoweronorpoweroffofprimaryorsecondaryvirtualmachinesinafaulttolerantcluster, byusingtheEventAlarmExpression YoucreateinstancesoftheStateAlarmExpression,EventAlarmExpression,orMetricAlarmExpression dataobjectsspecifythresholdsthattriggerthealarm.Touseaspecifictypeofeventasthebasisforanalarm configuration,youusetheEventAlarmExpression.TheEventAlarmComparisondataobjectletsyouspecify thepropertyoftheEventthatshouldtriggerthealarmandtheoperatortouseasthebasisforcomparison. Figure 15-4. EventAlarmExpression

YoucansetanalarmtomonitorspecificperformancemetricsbyusingtheMetricAlarmExpressiondata object.YousetthemetricpropertytothePerfMetricIdofaspecificperformancemetricthatyouwantto monitoronthesystem. Settheredoryellowpropertiestoidentitythelevelatwhichthemetricvaluemovesfromgreen,toyellow, toredstatus.

140

VMware, Inc.

Chapter 15 Using the Alarm Infrastructure

Figure 15-5. MetricAlarmExpression Data Object

YoumustdefineeithertheredoryellowpropertyintheMetricAlarmExpressiondataobjectthatyou create.Youcanalsospecifybothproperties,ifappropriateforyourapplication.Forexample,usetheyellow propertytospecifyathresholdvaluethatsignifiesawarningcondition,andusetheredpropertytospecifya thresholdvaluethatsignifiesamoreseriouscondition.Useeachofthesepropertiesinconjunctionwiththe isAboveorisBelowMetricAlarmOperatorenumerationstocompletethedefinitionofthethreshold. Inconjunctionwithredandyellowproperties,youuseeitherredIntervaloryellowIntervalproperties. TheredIntervalandyellowIntervalpropertiesarebothnewinvSphereAPI4.0.Thesepropertiesenable youtosetthenumberofsecondsthattheperformancemetricmustbeinredoryellow,respectively,before theexpressionbecomestrue,thustriggeringthedefinedaction. UsingoneormoreinstancesoftheAndAlarmExpressionandtheOrAlarmExpressiondataobjects,you combinetheobjectsintoacompleteexpressionthatevaluatestoatruefalsevalue.

Overview of the AlarmAction Data Object


Thesystemcanrespondtothealarmssetonanyobjectinmanydifferentways: Byinvokingoperationsofotherserviceinterfaces Byrunningascript Bysendinganemailmessagetoaspecificemailaccount BygeneratinganSNMPtrap Toinvokeanoperationofoneoftheserviceinterfaces,youcreateaMethodActiondataobject.Torunascript, youcreateaninstanceoftheRunScriptActiondataobjectthatspecifiesthefullyqualifiedpathtotheshell scriptonthevCenterServer.Tosendanemailmessagetoasystemadministrator,youusethe SendEmailActiondataobject.Andsoon. YouspecifytheactionsthatthesystemshouldtakebysettingtheactionpropertyoftheAlarmSpecdata objecttotheAlarmActiondataobjectdefinedforthepurpose.YouusetheAlarmActiondataobjectin conjunctionwithoneormoreAlarmTriggeringActionTransitionSpecdataobjects. TheAlarmActiondataobjectisanabstracttypethathastwodescendentobjects,AlarmTriggeringAction andGroupAlarmAction.TheGroupAlarmActiondataobjectisanarrayversionoftheAlarmActionbase type,meaningthatyoucancreateasingleAlarmActioninstanceoranarrayofAlarmActioninstancestotake effectwhentheconditionsspecifiedforyouralarmaremetonthesystem. TheAlarmTriggeringActionhasanactionpropertyandatransitionSpecsproperty. The transitionSpecspropertyisnewinvSphereAPI4.0.ThetransitionSpecspropertyconsistsofan instanceofanAlarmTriggeringActionTransitionSpec,alsonewinvSphereAPI4.0. TheactionpropertyoftheScheduledTaskSpecisdefinedasaninstanceoftheActiondataobject. The Actiondataobjectisanabstracttypethathasseveraldescendentobjectsthatmodelspecificbehaviors.

VMware, Inc.

141

vSphere Web Services SDK Programming Guide

Figure 15-6. AlarmAction and Action Abstract Data Object Types and Subtypes

InvSphereAPI4.0,theAlarmTriggeringActiondataobjecthasanewproperty,transitionSpecs,that providesdiscretecontroloverthetiming,thresholds,andfrequencyofanAlarm.Ratherthanusing green2yellow,red2yellow,yellow2green,andyellow2redpropertiestotriggeralarms,usethe AlarmTriggeringActionTransitionSpectodefinestatechangeswithcompletecontrol. AlarmTriggeringActionTransitionSpechaspropertiesthatenableyoutodefineastartingstatusanda finalstatusforthestateoftheAlarm.ThestateofanalarmiscontainedinanAlarmStatedataobject.Youcan alsolimitthenumberofAlarmobjectsactuallytriggeredtoasingleAlarm,byspecifyingfalseforthe repeatspropertyoftheAlarmTriggeringActionTransitionSpec. Forexample,youcanusetheMethodActiondataobjecttypetoinvokeanoperationontheserver. The MethodActiondataobjectcontainstheseproperties: nameUsethenamepropertyofMethodArgumenttospecifythenameoftheoperationthatyouwantto invokeatthescheduledtime. argumentUsetheargumentpropertytopasstheparametersrequiredbytheoperation,ifany. The argumentpropertyisdefinedasanarrayofMethodArgumentActiondataobjects. Dependingontheentityassociatedwiththealarm,theargumentpropertyofMethodActionmightnotbe needed.Forexample,thePowerOffVM_Taskoperationnormallyrequiresthemanagedobjectreferenceofthe virtualmachineyouwanttoshutdown.Ifyouralarmactionisassociatedwithacontainerobject,suchasa FolderorDatacenter,aparameterspecifyingaspecificvirtualmachinereferenceisnotneeded. Whenanalarmisactivated,itgeneratesanEventthatgetspostedtotheEventhistorydatabase.The action initiatedbytheAlarmmightalsopostitsownEventtothedatabase,dependingontheActiontype. SeethevSphereAPIReferenceforcompleteinformation.

Deleting or Disabling an Alarm


AnAlarmremainsactiveuntilyoudeleteitordisableit.Todeletethealarm,obtainamanagedobjectreference totheAlarmandinvokeitsRemoveAlarmoperation. YoucandisabletheAlarmratherthandeletingit.ObtainamanagedobjectreferencetotheAlarmManagerand theentityonwhichtheAlarmisset,andinvoketheEnableAlarmActionsoperation,passingthevaluefalse fortheenabledparameter.TheEnableAlarmActionsoperationisnewinvSphereAPI4.0.

142

VMware, Inc.

16

Scheduling vCenter Server Operations

16

TheScheduledTaskManagerenablesyoutoscheduleoperationsonvCenterServer.Theoperationmightbe scheduledforaonetimerunorforaregularrepeatingschedule.TheScheduledTaskManagerissupported onvCenterServer.Thischapterincludesthesetopics: SampleCodeReferenceonpage 143 ScheduledTaskManagerManagedObjectonpage 143 CreatingaScheduledTaskObjectonpage 144 DefiningtheScheduleforthevCenterServerOperationonpage 145 Visibilityofmanyoftheobjectsandreturntypesdiscussedinthischapterdependsonthepermissions associatedwithuseraccountusingtheclientapplication.Avisibleentityisoneforwhichtheprincipal associatedwiththesessionhasviewprivileges.Formoreinformationaboutpermissions,seeOverviewof UserModelsandServerAccessControlConceptsonpage 33.

Sample Code Reference


Table 161liststhesampleapplicationsincludedwiththevSphereWebServicesSDKthatdemonstratesome ofthetopicsdiscussedinthischapter. Table 16-1. Sample Applications that Demonstrate Using ScheduledTaskManager
Java SDK\samples\Axis\java\com\vmware\samples\scheduling DeleteOneTimeScheduledTask.java OneTimeScheduledTask.java WeeklyRecurrenceScheduledTask.java C# SDK\samples\DotNet\cs\ DeleteOneTimeScheduledTask OneTimeScheduledTask WeeklyRecurrenceScheduledTask

ScheduledTaskManager Managed Object


YoucanuseScheduledTaskManagertodefineactionstooccuronvCenterServeratmanydifferenttimes: WhenthevCenterServersystemstartsupoperations,suchasafterareboot Ataspecifictimeandday Athourly,daily,weekly,ormonthlyintervals Thetypeofactionsyouspecifytooccuratthescheduledtimeincluderunningscriptsontheserverorinvoking operationsusingoneoftheotherserviceinterfacesonthevCenterServersystem.Youapplythescheduled actiontoanentityintheinventory,suchasaspecificvirtualmachineorahostinadatacenter.ScheduledTask objectsdisplayinthevSphereClientTask&Eventstab. WithvSphere4.0,youcanapplyscheduledtaskstoanymanagedobject,notjustmanagedentities,byusing theCreateObjectScheduledTaskoperation.SeethevSphereAPIReferencefordetails.
VMware, Inc. 143

vSphere Web Services SDK Programming Guide

Figure 161showstheScheduledTaskManagerserviceinterfaceandassociateddataobjectsforitsproperties. Figure 16-1. ScheduleTaskManager and ScheduledTask Managed Object Types

ThescheduledTaskpropertycontainsanarrayoftheScheduledTaskobjectsconfiguredfortheserver.Ifyou havenoactionsscheduled,thispropertyisempty.ForanyScheduledTaskobjectsinthisarray,youcanuse theinfopropertyoftheScheduledTaskobjecttoobtaininformationaboutthestatusofthescheduledaction, includingitsprogress,state,previousandnextruntimes,andtheotherdetailscontainedinthe ScheduledTaskInfodataobject. IftheactionspecifiedforaScheduledTaskcreatesitsownTask(suchaswithanyoftheasynchronous operations(*_Task)operations),themanagedobjectreferencetotheTaskpopulatestheactiveTaskproperty ofScheduledTaskInfo.

Retrieving ScheduledTasks for a Specific Managed Entity


YoucanusetheRetrieveEntityScheduledTaskoperationobtainanarrayofallactionsscheduledfora specificmanagedentity. Table 16-2. RetrieveEntityScheduledTask Operation
Parameter ScheduledTaskManager entity Type MOR>ScheduledTaskManager MOR>managed entity Description ReferencetotheScheduledTaskManager. Optional.EntitywhoseScheduledTasksyouwantto obtain.Ifnoentityisspecified,thisoperationreturnsall ScheduledTasksthatarevisibletotheprincipal associatedwiththesession.

Creating a ScheduledTask Object


AScheduledTaskisamanagedobjecttype.ItiscreatedbytheScheduledTaskManagerbasedonthe specificationsyouprovideinaScheduledTaskSpecdataobject(seeFigure 162,Using ScheduledTaskManagertoCreateaScheduledTask,onpage 145). YoucreateaScheduledTaskbyinvokingtheCreateScheduledTaskoperationwiththemanagedobject referenceoftheScheduledTaskManager,themanagedobjectreferenceofthemanagedentityonwhichto applytheschedule,andaninstanceoftheScheduledTaskSpecobjectthatdefinesthescheduleandspecifies theactiontotakeatthespecifiedtime. Youcanscheduleactionsonanyentityintheinventory.TheScheduledTaskobjectisassociatedwiththe entityyouspecify,takingintoaccounttherelativelocationoftheentityintheinventoryhierarchy.Ascheduled actionappliestoanobjectbasedontheserules: Ifyouspecifyacontainerobjectastheentityforthescheduledaction,thescheduleappliestoallentities thataredirectdescendentsofthecontainer. Ifyouspecifyanodeobjectintheinventory,suchasavirtualmachine,thescheduleappliesonlytothe virtualmachine.

144

VMware, Inc.

Chapter 16 Scheduling vCenter Server Operations

YoucansetaScheduledTaskattheFolder,Datacenter,orVirtualApplevelandhavethescheduledaction applytoallentitiesassociatedwiththeFolder,Datacenter,orVirtualApp.SeeUnderstandingContainer ObjectsandtheInventoryonpage 26. Figure 16-2. Using ScheduledTaskManager to Create a ScheduledTask

Defining the Schedule for the vCenter Server Operation


TheScheduledTaskSpecdataobjectcontainsalltheinformationtocreateaScheduledTask. Table 16-3. ScheduledTaskSpec Data Object Properties
Property action Type Action Description SpecifiestheactiontotakewhentheScheduledTaskruns.TheAction dataobjectisanabstracttypethatisextendedbyseveralspecificaction types.SeeDefiningtheActionsonpage 146formoreinformation abouttheActiondataobject. DescriptionoftheScheduledTask. SettotruetoenabletheScheduledTask.Settofalsetodisablethe ScheduledTask. NameoftheScheduledTask. Optional.Usetospecifytheemailaddressforsendingnotification messagesabouttheScheduledTask.Tousenotifications,thevCenter ServermusthaveanSNMPemailgatewayconfigured.Bydefault,this propertyissettoanemptystring. Specifiesthetime,frequency,andotherdetailsoftheschedule.The TaskSchedulerdataobjectisthebasetypeforanumberofspecific scheduleobjects.SeeSchedulingRecurringOperationsonpage 146.

description enabled name notification

string boolean string string

scheduler

TaskScheduler

BothactionandschedulepropertiesofaScheduledTaskSpecobjectconsistoftwootherdataobjects,an ActionandTaskSchedulerdataobjects,respectively.SeeSchedulingRecurringOperationsonpage 146 foranoverviewoftheTaskSchedulerdataobjectanditssubtypes.

VMware, Inc.

145

vSphere Web Services SDK Programming Guide

Defining the Actions


TheActiondataobjectisanabstracttype.Youdefinethespecificactiontooccurontheserveraccordingto yourschedulebyusingofthespecificsubtypesofActiondataobject(seeFigure 163). Figure 16-3. Action Data Object and Its Subtypes

TheActiondataobjectsarealsousedbytheAlarminfrastructure.SeeOverviewoftheAlarmActionData Objectonpage 141formoreinformationaboutusingActionsubtypes. SeethevSphereAPIReferenceformoreinformation.

Scheduling Recurring Operations


TheTaskSchedulerdataobjectisabasetypethathasmanysubtypes.Tospecifythetimes,days,orfrequency ofscheduledtasks,createtheappropriateinstancesofTaskSchedulersubtypesthatyouneedandsetthe schedulerpropertyoftheScheduledTaskSpec. Figure 16-4. TaskScheduler Data Object Type and Subtypes

TheTaskSchedulerbasetypehastwoproperties: activeTimeisthetimeatwhichtheactionshouldoccur.Ifyouleavethispropertyunset,itdefaultsto thetimethatspecificationforthescheduledtaskwassubmittedtotheserver. expireTimeisthetimeafterwhichthescheduledactionshouldnotoccur.Bydefault,thispropertyis Unset,sothescheduledtaskdoesnotexpire.


146 VMware, Inc.

Chapter 16 Scheduling vCenter Server Operations

Table 164providessomeusageinformationabouttheTaskSchedulersubtypesshowninFigure 164.The examplesinthetableareJavacodesnippets. Table 16-4. TaskScheduler Data Object Subtypes
TaskScheduler subtype AfterStartupTaskScheduler Usage ScheduleatasktostartassoonasthevCenterServersystemisstarted,orata definedtimeafterstartup.Usetheminutepropertytospecifythenumberof minutes.Thevaluemustbezero(tasktriggeredatstartup)orhigher. AfterStartupTaskScheduler asts = new AfterStartupTaskScheduler(); asts.setMinute(10); OnceTaskScheduler Example:Scheduleatasktorun thirtyminutesafterthescheduleis submittedtotheserver. Scheduleanactiontorunonceonlyatthespecifieddateandtime. Calendar runTime= Calendar.getInstance(); runtime.add(Calendar.MINUTE, 30); OnceTaskScheduler ots = new OnceTaskScheduler (); ots.setRunAt(runTime); RecurrentTaskScheduler BasetypeforHourlyTaskScheduler,DailyTaskScheduler, WeeklyTaskScheduler,andMonthlyTaskSchedulerobjects.Settheinterval propertytodefinehowfrequentlyataskshouldrun.Forexample,settingthe intervalpropertyofanhourlytaskto4causesthetasktorunevery4hours. Scheduleatasktorunonceeveryhour(oreveryspecifiednumberofhours)ata specifiedtime.Settheintervalpropertytorunthetaskafteraspecifiednumber ofhours. HourlyTaskScheduler hts = new HourlyTaskScheduler(); hts.setMinute(30); hts.setInterval(4); DailyTaskScheduler Scheduleatasktorundailyoraspecifiednumberofdaysataspecifiedtime (hourandminutes).Useinconjunctionwiththeintervalpropertytorunthetask afteraspecifiednumberofdays. DailyTaskScheduler dts = new DailyTaskScheduler(); dts.setMinute(30); dts.setHour(14); WeeklyTaskScheduler Scheduleatasktoruneveryweek(oreveryspecifiednumberofweeks)ona specifiedday(ordays)ataspecifictime.ThehoursandminutesaresetasUTC values.Atleastoneofthebooleanvaluesmustbesettotrue.Youcanalsosetthe intervalpropertytorunthetaskafteraspecifiednumberofweeks. WeeklyTaskScheduler wts = new WeeklyTaskScheduler(); wts.setMonday(true); wts.setTuesday(true); wts.setWednesday(false); wts.setThursday(false); wts.setFriday(false); wts.setSaturday(false); wts.setSunday(true); dts.setMinute(30); dts.setHour(4); MonthlyByDayTaskScheduler Scheduleatasktoruneverymonth(oreveryspecifiednumberofmonths)ona specifieddayataspecifiedtime(hourandminutes).Youcanalsosettheinterval propertytorunthetaskafteraspecifiednumberofmonths. MonthlyByDayTaskScheduler mbdts = new MonthlyByDayTaskScheduler(); mbdts.setDay(31); mbdts.setInterval(3); mbdts.setMinute(30); mbdts.setHour(14);

Example:Scheduleatasktorun10 minutesaftervCenterServerstartup.

HourlyTaskScheduler

Example:Scheduleatasktorun every4hoursathalfpastthehour.

Example:Scheduleatasktorun dailyat9:30am(EST).

Example:Scheduleatasktorun everyTuesdayandSundayat30 minutespastmidnight.

Example:Scheduleatasktorun every3months(onthelastdayofthe month)at30minutespastnoon

VMware, Inc.

147

vSphere Web Services SDK Programming Guide

Table 16-4. TaskScheduler Data Object Subtypes (Continued)


TaskScheduler subtype MonthlyByWeekdayTaskScheduler Usage Scheduleatasktoruneverymonth(oreveryspecifiednumberofmonths)ona specifiedweek,weekday,andtime(hour:minutes).Youcanalsosettheinterval propertytorunthetaskafteraspecifiednumberofmonths. MonthlyByWeekdayTaskScheduler mbwts = new MonthlyByWeekdayTaskScheduler(); mbwts.setOffset(WeekOfMonth.last); mbwts.setWeekday(DayOfWeek.wednesday); mbwts.setHour(4); mbwts.setMinute(30);

Example:Scheduleatasktorunon thelastWednesdayofeachmonthat 30minutespastmidnight:

AsofvSphereAPI4.0,thehourandminutepropertiesofallobjectsthatextendtheRecurrentTaskSchedule dataobjectarespecifiedinCoordinatedUniversalTime(UTC)valuesratherthanthelocaltimeoftheserver. Whenyoudefinetheschedule,convertyourlocaltimetoaUTCvalue. Forexample,thecodeinExample 161definesaScheduledTaskthatpowersonvirtualmachinesdailyat4:15 a.m.,iftheserverlocaltimeisinthePacificStandardTime(PST)timezone.ForaserverintheEastern EuropeanSummerTime(EEST)zone,thesettingisreadbythesystemas3:15pm. Example 16-1. ScheduledTask for Powering-on Virtual Machines
... / Set the schedule using the DailyTaskScheduler subtype. DailyTaskScheduler dTScheduler = new DailyTaskScheduler(); dTScheduler.setHour(12); dTScheduler.setMinute(15); ScheduledTaskSpec tSpec = new ScheduledTaskSpec(); tSpec.setDescription("Start virtual machine as per schedule."); tSpec.setEnabled(Boolean=TRUE); tSpec.setName("Power On Virtual Machine"); tSpec.setAction(ma); tSpec.setScheduler(dTScheduler); tSpec.setNotification("admin@vmware.com"); my_conn.createScheduledTask(_sic.getScheduledTaskManager, vmRef, tSpec); ...

Deleting a Scheduled Task


TodeleteaScheduledTaskobjectyouneeditsmanagedobjectreferencetopasstothe RemoveScheduledTaskoperationoftheScheduledTask.TheRemoveScheduledTaskoperationcancelsonly thecurrentrunoftheScheduledTask.ItdoesnotcancelsubsequentrunsoftheScheduledTask. TocancelanupcomingrunofaScheduledTask,youusetheReconfigureScheduledTaskwithanew ScheduledTaskSpecdataobjectcontainingthenewspecificationsfortheschedule. TocancelaScheduledTaskthatspawnsitsownTaskandcanceltheTaskasitruns,youcreatea PropertyCollectortoobtainthereferencetotheTaskandinvokeitsCancelTaskoperation.TheTaskmust becancellable.SeeOverviewoftheTaskInfrastructureonpage 83.

148

VMware, Inc.

Managed Object Privileges Reference

VMwarevSpherecomponentsaresecuredthroughasystemofprivileges,roles,andpermissions(see Chapter 4,OverviewofUserModelsandServerAccessControlConcepts,onpage 33formoreinformation). Thissectionlistsprivilegesrequiredtoperformvariousoperations,andprivilegesrequiredtoreadproperties. Itincludesthesetopics: PrivilegesRequiredtoInvokeOperationsonpage 149 PrivilegesRequiredtoReadPropertiesonpage 156 PrivilegesDefinedfortheAdministratorRoleonpage 158

Privileges Required to Invoke Operations


Table A1liststheprivilegesrequiredtoperformvariousoperations.(Forprivilegesidentifiedasdynamic,see thevSphereAPIReference.)OperationscanbesupportedbyvCenterServer,ESX/ESXi,orboth,asshownin Table A1. Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations
Operation Privilege VS ESX/ESXi

AcquireLocalTicket AcquireMksTicket AddAuthorizationRole AddCustomFieldDef AddHost_Task AddInternetScsiSendTargets AddInternetScsiStaticTargets AddPortGroup AddServiceConsoleVirtualNic AddStandaloneHost_Task AddVirtualNic AddVirtualSwitch AnswerVM ApplyRecommendation AssignUserToGroup AttachVmfsExtent AutoStartPowerOff

System.Anonymous VirtualMachine.Interact.ConsoleInteract Authorization.ModifyRoles Global.ManageCustomFields Host.Inventory.AddHostToCluster Host.Config.Storage Host.Config.Storage Host.Config.Network Host.Config.Network Host.Inventory.AddStandaloneHost Host.Config.Network Host.Config.Network VirtualMachine.Interact.AnswerQuestion Resource.ApplyRecommendation Host.Local.ManageUserGroups Host.Config.Storage Host.Config.AutoStart

X X X X X X X X X X X X X X X X X

X X X

X X X X

X X X

X X X

VMware, Inc.

149

vSphere Web Services SDK Programming Guide

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation AutoStartPowerOn BrowseDiagnosticLog CancelTask CancelWaitForUpdates CheckCustomizationResources CheckCustomizationSpec CheckForUpdates CheckIfMasterSnmpAgentRunning CheckLicenseFeature CloneVM_Task Privilege Host.Config.AutoStart Global.Diagnostics Global.CancelTask System.View System.View VirtualMachine.Provisioning.Customize System.View Host.Config.Snmp Global.Licenses NONE. Privilegesarerequiredonthevirtualmachinebeing clonedanddependonwhetherthevirtualmachineisa template.SeeCloneVM_TaskinthevSphereAPI Referenceforspecificprivileges. YouneedtheVirtualMachine.Inventory.Create privilegeonthefolderwherethenewvirtualmachine islocated. ComputeDiskPartitionInfo ConfigureDatastorePrincipal ConfigureLicenseSource CreateAlarm Host.Config.Storage Host.Config.Maintenance Global.Licenses NONE. Createprivilegerequiredontheentityassociatedwith thealarm. CreateCluster CreateCollectorForEvents CreateCollectorForTasks CreateCustomizationSpec CreateDatacenter CreateDiagnosticPartition CreateFilter CreateFolder CreateGroup CreateLocalDatastore CreateNasDatastore CreatePerfInterval CreateResourcePool CreateScheduledTask Host.Inventory.CreateCluster System.View System.View VirtualMachine.Provisioning.ModifyCustSpecs Datacenter.Create Host.Config.Storage System.View Folder.Create Host.Local.ManageUserGroups Host.Config.Storage Host.Config.Storage Performance.ModifyIntervals Resource.CreatePool NONE. ScheduledTask.Createrequiredontheentity associatedwiththescheduledtask. CreateSnapshot_Task CreateUser CreateVM_Task VirtualMachine.State.CreateSnapshot Host.Local.ManageUserGroups VirtualMachine.Inventory.Create Also,Resource.AssignVMToPoolprivilegerequired ontheresourcepoolwithwhichthevirtualmachine willbeassociated. X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X VS X X X X X X X X X X X X X X ESX/ESXi X X

150

VMware, Inc.

Appendix A Managed Object Privileges Reference

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation CreateVmfsDatastore CurrentTime CustomizationSpecItemToXml CustomizeVM_Task DeleteCustomizationSpec DeleteFile DeselectVnic Destroy_Task DestroyChildren DestroyCollector DestroyDatastore DestroyNetwork DestroyPropertyFilter DisableFeature DisableHyperThreading DisableMultipathPath DisableRuleSet DisconnectHost_Task DoesCustomizationSpecExist DuplicateCustomizationSpec EnableFeature EnableHyperThreading EnableMultipathPath EnableRuleset EnterMaintenanceMode_Task ExitMaintenanceMode_Task ExtendVmfsDatastore FindByDatastorePath FindByDnsName FindByInventoryPath FindByIp FindByUuid FindChild FormatVmfs GenerateLogBundles_Task GetAlarm GetAlarmState Privilege Host.Config.Storage System.View System.View VirtualMachine.Provisioning.Customize VirtualMachine.Provisioning.ModifyCustSpecs Datastore.DeleteFile Host.Config.Network SeeDestroy_TaskinthevSphereAPIReference. SeeDestroyChildreninthevSphereAPIReference. NONE Datastore.Delete Network.Delete NONE Global.Licenses Host.Config.HyperThreading Host.Config.Storage Host.Config.NetService Host.Config.Connection VirtualMachine.Provisioning.ReadCustSpecs VirtualMachine.Provisioning.ModifyCustSpecs Global.Licenses Host.Config.HyperThreading Host.Config.Storage Host.Config.NetService Host.Config.Maintenance Host.Config.Maintenance Host.Config.Storage System.View System.View System.View System.View System.View System.View Host.Config.Storage Global.Diagnostics System.View NONE System.Readprivilegeisrequiredontheentity associatedwiththealarm. GetCustomizationSpec Login VirtualMachine.Provisioning.ReadCustSpecs System.Anonymous X X X VS X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ESX/ESXi X X

VMware, Inc.

151

vSphere Web Services SDK Programming Guide

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation Logout LogUserEvent Privilege System.View NONE Global.LogEventrequiredontheentityassociated withtheevent. MarkAsTemplate MarkAsVirtualMachine VirtualMachine.Provisioning.MarkAsTemplate VirtualMachine.Provisioning.MarkAsVM Resource.AssignVMToPoolrequiredontheresource pooltoassociatewiththevirtualmachine. MergePermissions MigrateVM_Task MountToolsInstaller MoveHostInto_Task Authorization.ReassignRolePermissions SeeMigrateVM_TaskinthevSphereAPIReference. VirtualMachine.Interact.ToolsInstall Host.Inventory.EditCluster Host.Inventory.MoveHostrequiredonthehost beingmoved. MoveInto_Task Host.Inventory.EditCluster Host.Inventory.MoveHostrequiredonthehost beingmoved. MoveIntoFolder_Task MoveIntoResourcePool OverwriteCustomizationSpec PowerOffVM_Task PowerOnVM_Task QueryAvailableDisksForVmfs QueryAvailablePartition QueryAvailablePerfMetric SeeMoveIntoFolder_TaskinthevSphereAPIReference. SeeMoveIntoFolder_TaskinthevSphereAPIReference. VirtualMachine.Provisioning.ModifyCustSpecs VirtualMachine.Interact.PowerOff VirtualMachine.Interact.PowerOn Host.Config.Storage Host.Config.Storage NONE System.Readisrequiredontheentityforwhich availableperformancemetricsarequeried. QueryConfigOption QueryConfigOptionDescriptor QueryConfigTarget QueryConnectionInfo QueryDescriptions QueryEvents QueryHostConnectionInfo QueryLicenseSourceAvailability QueryLicenseUsage QueryMemoryOverhead QueryNetworkHint QueryOptions QueryPartitionCreateDesc QueryPartitionCreateOptions QueryPerf System.Read System.Read System.Read Host.Inventory.AddStandaloneHost Global.Diagnostics System.View System.Read Global.Licenses Global.Licenses System.Read Host.Config.Network System.Read Host.Config.Storage Host.Config.Storage NONE System.Readprivilegeisrequiredontheentitywhose performancestatisticsarebeingqueried. X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X VS X X ESX/ESXi X X

152

VMware, Inc.

Appendix A Managed Object Privileges Reference

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation QueryPerfComposite Privilege NONE System.Readprivilegeisrequiredontheentitywhose performancestatisticsarebeingqueried. QueryPerfCounter QueryPerfProviderSummary System.View NONE System.Readprivilegeisrequiredontheentitywhose performancestatisticsarebeingqueried. QueryVmfsDatastoreCreateOptions QueryVmfsDatastoreExtendOptions QueryVMotionCompatibility ReadNextEvents ReadNextTasks ReadPreviousEvents ReadPreviousTasks RebootGuest RebootHost_Task RecommendHostsForVm ReconfigureAlarm ReconfigureAutostart ReconfigureCluster_Task ReconfigureHostForDAS_Task ReconfigureScheduledTask ReconfigureServiceConsoleReservation ReconfigVM_Task ReconnectHost_Task RefreshDatastore RefreshFirewall RefreshNetworkSystem RefreshServices RefreshStorageSystem RegisterVM_Task Host.Config.Storage Host.Config.Storage Resource.QueryVMotion NONE NONE NONE NONE VirtualMachine.Interact.Reset Host.Config.Maintenance System.Read Alarm.Edit Host.Config.AutoStart Host.Inventory.EditCluster Host.Config.Connection ScheduledTask.Edit Host.Config.Memory dynamic Host.Config.Connection System.Read Host.Config.NetService Host.Config.Network Host.Config.NetService Host.Config.Storage VirtualMachine.Inventory.Create Resource.AssignVMToPoolprivilegeisrequiredon theresourcepooltowhichthevirtualmachineshould beattached. ReleaseLease Reload RelocateVM_Task RemoveAlarm RemoveAllSnapshots_Task RemoveAuthorizationRole RemoveCustomFieldDef RemoveDatastore NONE. System.Read Resource.ColdMigrate Alarm.Delete VirtualMachine.State.RemoveSnapshot Authorization.ModifyRoles Global.ManageCustomFields Host.Config.Storage X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X VS X ESX/ESXi X

VMware, Inc.

153

vSphere Web Services SDK Programming Guide

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation RemoveEntityPermission Privilege NONE Authorization.ModifyPermissionsprivilegeis requiredontheentityassociatedwiththepermission. RemoveGroup RemoveInternetScsiSendTargets RemoveInternetScsiStaticTargets RemovePerfInterval RemovePortGroup RemoveScheduledTask RemoveServiceConsoleVirtualNic RemoveSnapshot_Task RemoveUser RemoveVirtualNic RemoveVirtualSwitch Rename_Task RenameCustomFieldDef RenameCustomizationSpec RenameDatastore RenameSnapshot RenewLease RescanAllHba RescanHba RescanVmfs ResetCollector ResetEntityPermissions Host.Local.ManageUserGroups Host.Config.Storage Host.Config.Storage Performance.ModifyIntervals Host.Config.Network ScheduledTask.Delete Host.Config.Network VirtualMachine.State.RemoveSnapshot Host.Local.ManageUserGroups Host.Config.Network Host.Config.Network SeeRename_TaskinthevSphereAPIReference. Global.ManageCustomFields VirtualMachine.Provisioning.ModifyCustSpecs Datacenter.RenameDatastore VirtualMachine.State.RenameSnapshot NONE Host.Config.Storage Host.Config.Storage Host.Config.Storage NONE NONE Authorization.ModifyPermissionsprivilegeis requiredontheentityassociatedwiththepermission andtheentitysparent. ResetGuestInformation ResetVM_Task RestartMasterSnmpAgent RestartService RestartServiceConsoleVirtualNic RetrieveAllPermissions RetrieveDiskPartitionInfo RetrieveEntityPermissions VirtualMachine.Config.ResetGuestInfo VirtualMachine.Interact.Reset Host.Config.Snmp Host.Config.NetService Host.Config.Network System.View Host.Config.Storage NONE System.Readprivilegeisrequiredontheentitywhose performancestatisticsarebeingqueried. RetrieveEntityScheduledTask RetrieveProperties RetrieveRolePermissions RetrieveServiceContent System.View System.View System.View System.Anonymous X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X Allbut ESX2.x X X X X X X X X X X X X X X X X X VS X ESX/ESXi X

154

VMware, Inc.

Appendix A Managed Object Privileges Reference

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation RetrieveUserGroups RevertToCurrentSnapshot_Task RevertToSnapshot_Task RewindCollector RunScheduledTask SearchDatastore_Task SearchDatastoreSubFolders_Task SelectActivePartition SelectVnic SetCollectorPageSize SetEntityPermissions Privilege System.View VirtualMachine.State.RevertToSnapshot VirtualMachine.State.RevertToSnapshot NONE ScheduledTask.Run Datastore.Browse Datastore.Browse Host.Config.Storage Host.Config.Network NONE NONE Authorization.ModifyPermissionsrequiredon entityassociatedwiththepermissionsanditsparent. SetField NONE Global.SetCustomFieldrequiredontheentity associatedwiththecustomfield. SetLicenseEdition SetLocale SetMultipathLunPolicy SetScreenResolution ShutdownGuest ShutdownHost_Task StandbyGuest StartService StopMasterSnmpAgent StopServiceq SuspendVM_Task TerminateSession UnassignUserFromGroup UninstallService UnmountToolsInstaller UnregisterAndDestroy_Task UnregisterVM UpdateAuthorizationRole UpdateChildResourceConfiguration UpdateConfig UpdateConsoleIpRouteConfig UpdateDefaultPolicy UpdateDiskPartitions UpdateDnsConfig UpdateInternetScsiAlias Global.Licenses System.View Host.Config.Storage VirtualMachine.Interact.ConsoleInteract VirtualMachine.Interact.PowerOff Host.Config.Maintenance VirtualMachine.Interact.Suspend Host.Config.NetService Host.Config.Snmp Host.Config.NetService VirtualMachine.Interact.Suspend Sessions.TerminateSession Host.Local.ManageUserGroups Host.Config.NetService VirtualMachine.Interact.ToolsInstall Folder.Delete
1

VS X X

ESX/ESXi X Onallbut ESX2.x X

X X X X X X X X

X X X X X X

X X X X X X X X X X X X X X X X X X X X X X X X X

X X X X X X X X X X X X X X X X X X X X X X X X X

VirtualMachine.Inventory.Delete Authorization.ModifyRoles SeeUpdateChildResourceConfigurationinthe vSphereAPIReference. SeeUpdateConfiginthevSphereAPIReference. Host.Config.Network Host.Config.Network Host.Config.Storage Host.Config.Network Host.Config.Storage

VMware, Inc.

155

vSphere Web Services SDK Programming Guide

Table A-1. Privileges Required for vCenter Server and ESX/ESXi Operations (Continued)
Operation UpdateInternetScsiAuthenticationProperties UpdateInternetScsiDiscoveryProperties UpdateInternetScsiIPProperties UpdateInternetScsiName UpdateIpConfig UpdateIpRouteConfig UpdateNetworkConfig UpdateOptions UpdatePerfInterval UpdatePhysicalNicLinkSpeed UpdatePortGroup UpdateServiceConsoleVirtualNic UpdateServiceMessage UpdateServicePolicy UpdateSnmpConfig UpdateSoftwareInternetScsiEnabled UpdateSystemResources UpdateUser UpdateVirtualNic UpdateVirtualSwitch UpgradeTools_Task UpgradeVM_Task UpgradeVmfs UpgradeVmLayout ValidateMigration Privilege Host.Config.Storage Host.Config.Storage Host.Config.Storage Host.Config.Storage Host.Config.Network Host.Config.Network Host.Config.Network SeeUpdateOptionsinthevSphereAPIReference. Performance.ModifyIntervals Host.Config.Network Host.Config.Network Host.Config.Network Sessions.GlobalMessage Host.Config.NetService Host.Config.Snmp Host.Config.Storage Host.Config.Resources Host.Local.ManageUserGroups Host.Config.Network Host.Config.Network VirtualMachine.Interact.ToolsInstall VirtualMachine.Config.UpgradeVirtualHardware Host.Config.Storage Host.Config.Storage SeeValidateMigrationinthevSphereAPIReference. Resource.AssignVMToPoolrequiredonthetarget resourcepoolforthevirtualmachines. WaitForUpdates XmlToCustomizationSpecItem System.View System.View X X X VS X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X ESX/ESXi X X X X X X X

1. Theprivilegeisalsorequiredontheparentmanagedentity.

Privileges Required to Read Properties


Figure A2liststheprivilegesrequiredtoreadspecificmanagedobjectproperties. Table A-2. Privileges Required for Reading Object Properties
Object AlarmManager Property defaultExpression description AuthorizationManager privilegeList roleList description Privilege System.View System.View System.View System.View System.View

156

VMware, Inc.

Appendix A Managed Object Privileges Reference

Table A-2. Privileges Required for Reading Object Properties (Continued)


Object ComputeResource Property resourcePool host CustomFieldsManager CustomizationSpecManager field info encryptionKey Datacenter vmFolder hostFolder EventManager description latestEvent maxCollector Folder childType childEntity HostCpuSchedulerSystem HostDiagnosticSystem HostFirewallSystem HostMemoryManagerSystem HostNetworkSystem hyperThread activePartition firewallInfo consoleReservationInfo capabilities networkConfig networkInfo offloadCapabilities HostServiceSystem HostSnmpSystem HostStorageSystem serviceInfo snmpConfig fileSystemVolumeInfo storageDeviceInfo HostVMotionSystem netConfig ipConfig LicenseManager source sourceAvailable featureInfo ManagedEntity parent effectiveRole name PerformanceManager description historicalInterval perfCounter PropertyCollector ResourcePool ScheduledTaskManager filter owner scheduledTask description ServiceInstance serverClock capability Privilege System.View System.View System.View VirtualMachine.Provisioning.ReadCustSpecs System.View System.View System.View System.View System.View System.View System.View System.View Host.Config.HyperThreading Host.Config.Storage Host.Config.NetService Host.Config.Memory Host.Config.Network Host.Config.Network Host.Config.Network Host.Config.Network Host.Config.NetService Host.Config.Snmp Host.Config.Storage Host.Config.Storage Host.Config.Network Host.Config.Network Global.Licenses Global.Licenses Global.Licenses System.View System.View System.View System.View System.View System.View System.View System.View System.View System.View System.View System.View

VMware, Inc.

157

vSphere Web Services SDK Programming Guide

Table A-2. Privileges Required for Reading Object Properties (Continued)


Object SessionManager Property sessions currentSession message messageLocaleList supportedLocaleList defaultLocale TaskManager recentTask description maxCollector UserDirectory domainList Privilege Sessions.TerminateSession System.Anonymous System.View System.Anonymous System.Anonymous System.Anonymous System.View System.View System.View System.View

Privileges Defined for the Administrator Role


TheAdministratorroleasdefinedonavCenterServer4.0systemcontainsalltheprivilegeslistedinTable A3. Table A-3. Privileges Granted to the Administrator Role
Privilege Alarm.Acknowledge Alarm.Create Alarm.Delete Alarm.DisableActions Alarm.Edit Alarm.SetStatus Authorization.ModifyPermissions Authorization.ModifyRoles Authorization.ReassignRolePermissions Datacenter.Create Datacenter.Delete Datacenter.IpPoolConfig Datacenter.Move Datacenter.Rename Datastore.AllocateSpace Datastore.Browse Datastore.Delete Datastore.DeleteFile Datastore.FileManagement Datastore.Move Datastore.Rename DVPortgroup.Create DVPortgroup.Delete DVPortgroup.Modify DVPortgroup.PolicyOp Privilege Resource.AssignVAppToPool Resource.AssignVMToPool Resource.ColdMigrate Resource.CreatePool Resource.DeletePool Resource.EditPool Resource.HotMigrate Resource.MovePool Resource.QueryVMotion Resource.RenamePool ScheduledTask.Create ScheduledTask.Delete ScheduledTask.Edit ScheduledTask.Run Sessions.GlobalMessage Sessions.ImpersonateUser Sessions.TerminateSession Sessions.ValidateSession StorageViews.ConfigureService StorageViews.View System.Anonymous System.Read System.View Task.Create VApp.ApplicationConfig

158

VMware, Inc.

Appendix A Managed Object Privileges Reference

Table A-3. Privileges Granted to the Administrator Role (Continued)


Privilege DVPortgroup.ScopeOp DVSwitch.Create DVSwitch.Delete DVSwitch.HostOp DVSwitch.Modify DVSwitch.Move DVSwitch.PolicyOp DVSwitch.PortConfig DVSwitch.PortSetting DVSwitch.Vspan Extension.Register Extension.Unregister Extension.Update Folder.Create Folder.Delete Folder.Move Folder.Rename Global.CancelTask Global.CapacityPlanning Global.Diagnostics Global.DisableMethods Global.EnableMethods Global.GlobalTag Global.Health Global.Licenses Global.LogEvent Global.ManageCustomFields Global.Proxy Global.ScriptAction Global.ServiceManagers Global.SetCustomField Global.Settings Global.SystemTag Global.VCServer Host.Cim.CimInteraction Host.Config.AdvancedConfig Host.Config.AutoStart Host.Config.Connection Host.Config.DateTime Host.Config.Firmware Host.Config.HyperThreading
VMware, Inc.

Privilege VApp.AssignResourcePool VApp.AssignVApp VApp.AssignVM VApp.Clone VApp.Create VApp.Delete VApp.Export VApp.ExtractOvfEnvironment VApp.Import VApp.InstanceConfig VApp.Move VApp.PowerOff VApp.PowerOn VApp.Rename VApp.ResourceConfig VirtualMachine.Config.AddExistingDisk VirtualMachine.Config.AddNewDisk VirtualMachine.Config.AddRemoveDevice VirtualMachine.Config.AdvancedConfig VirtualMachine.Config.ChangeTracking VirtualMachine.Config.CPUCount VirtualMachine.Config.DiskExtend VirtualMachine.Config.DiskLease VirtualMachine.Config.EditDevice VirtualMachine.Config.HostUSBDevice VirtualMachine.Config.Memory VirtualMachine.Config.QueryUnownedFiles VirtualMachine.Config.RawDevice VirtualMachine.Config.RemoveDisk VirtualMachine.Config.Rename VirtualMachine.Config.ResetGuestInfo VirtualMachine.Config.Resource VirtualMachine.Config.Settings VirtualMachine.Config.SwapPlacement VirtualMachine.Config.UpgradeVirtualHardware VirtualMachine.Interact.AnswerQuestion VirtualMachine.Interact.Backup VirtualMachine.Interact.ConsoleInteract VirtualMachine.Interact.CreateScreenshot VirtualMachine.Interact.CreateSecondary VirtualMachine.Interact.DefragmentAllDisks
159

vSphere Web Services SDK Programming Guide

Table A-3. Privileges Granted to the Administrator Role (Continued)


Privilege Host.Config.Maintenance Host.Config.Memory Host.Config.NetService Host.Config.Network Host.Config.Patch Host.Config.PciPassthru Host.Config.Resources Host.Config.Settings Host.Config.Snmp Host.Config.Storage Host.Config.SystemManagement Host.Inventory.AddHostToCluster Host.Inventory.AddStandaloneHost Host.Inventory.CreateCluster Host.Inventory.DeleteCluster Host.Inventory.EditCluster Host.Inventory.MoveCluster Host.Inventory.MoveHost Host.Inventory.RemoveHostFromCluster Host.Inventory.RenameCluster Host.Local.CreateVM Host.Local.DeleteVM Host.Local.InstallAgent Host.Local.ManageUserGroups Host.Local.ReconfigVM Network.Assign Network.Config Network.Delete Network.Move Performance.ModifyIntervals Profile.Clear Profile.Create Profile.Delete Profile.Edit Profile.View Resource.ApplyRecommendation Privilege VirtualMachine.Interact.DeviceConnection VirtualMachine.Interact.DisableSecondary VirtualMachine.Interact.EnableSecondary VirtualMachine.Interact.MakePrimary VirtualMachine.Interact.PowerOff VirtualMachine.Interact.PowerOn VirtualMachine.Interact.Record VirtualMachine.Interact.Replay VirtualMachine.Interact.Reset VirtualMachine.Interact.SetCDMedia VirtualMachine.Interact.SetFloppyMedia VirtualMachine.Interact.Suspend VirtualMachine.Interact.TerminateFaultTolerantVM VirtualMachine.Interact.ToolsInstall VirtualMachine.Interact.TurnOffFaultTolerance VirtualMachine.Inventory.Create VirtualMachine.Inventory.Delete VirtualMachine.Inventory.Move VirtualMachine.Provisioning.Clone VirtualMachine.Provisioning.CloneTemplate VirtualMachine.Provisioning.CreateTemplateFromVM VirtualMachine.Provisioning.Customize VirtualMachine.Provisioning.DeployTemplate VirtualMachine.Provisioning.DiskRandomAccess VirtualMachine.Provisioning.DiskRandomRead VirtualMachine.Provisioning.GetVmFiles VirtualMachine.Provisioning.MarkAsTemplate VirtualMachine.Provisioning.MarkAsVM VirtualMachine.Provisioning.ModifyCustSpecs VirtualMachine.Provisioning.PromoteDisks VirtualMachine.Provisioning.PutVmFiles VirtualMachine.Provisioning.ReadCustSpecs VirtualMachine.State.CreateSnapshot VirtualMachine.State.RemoveSnapshot VirtualMachine.State.RenameSnapshot VirtualMachine.State.RevertToSnapshot

160

VMware, Inc.

Diagnostics and Troubleshooting

ThissectionprovidesinformationaboutusingtheDiagnosticManagerserviceinterfacetofacilitate troubleshooting.Thisappendixincludesthesetopics: BestPracticesforTroubleshootingonpage 161 OverviewofConfigurationFilesandLogFilesonpage 162 ModifyingtheLogLeveltoObtainDetailedInformationonpage 164 UnderstandingandUsingtheDiagnosticManageronpage 167

Best Practices for Troubleshooting


Approachtroubleshootingandproblemsolvingsystematically,andtakenotessoyoucantraceyoursteps. Followtheseindustrystandardguidelineswheneveryouneedtoresolveanissuewithyourclientapplication. Dontchangemorethanonethingatatime,anddocumenteachchangeanditsresult.Trytoisolatethe problem:Doesitseemtobelocal,totheclient?Anerrormessagegeneratedfromtheserver?Anetwork probleminbetweenclientandserver? Usetheappropriateloggingfacilitiesforyourprogramminglanguagetocaptureruntimeinformationfor theclientapplication.SeetheLog.csandLog.javafilesforC#andJavalogclassimplementations,as usedbythevariousSDKsampleapplications.Thesefilesarelocatedinthe\samplessubdirectoryofthe vSphereWebServicesSDK: C#clientloggingexample:\SDK\samples\DotNet\cs\ClientUtils\Log.cs Javaclientloggingexample:\SDK\samples\Axix\java\com\vmware\apputils\Log.java UsethetoolsprovidedbyVMwareforanalysisandtofacilitatedebugging.Thefollowingtoolsprovide accesstologginginformation.TheyrequireESXorvCenterServeradministratorprivileges. UsetheVMwarevSphereClient.ThevSphereClientprovidesagraphicaluserinterfacethatenables administratorstoexamineallESXandvCenterServerlogfile,includinglogfilesforvirtualmachines, changetheloglevelsettingsifnecessary.ThevSphereClientprovidesmenuselectionsforcreating reportsthatsummarizeconfigurationinformation,performance,andotherdetails,andforexporting diagnosticbundles.ThevSphereClientapplicationmaintainsitsownlocallogfiles. UsetheMOB.TheMOBprovidesdirectaccesstoliveruntimeserversideobjects.Youcanusethe MOBtodrilldownintothevariousobjectsandobtainpropertyvalues.SeeChapter 2,Usingthe ManagedObjectBrowsertoExploretheObjectModel,onpage 16foranoverviewoftheMOB. UsetheAPI.ThevSphereobjectmodelprovidesaDiagnosticManagerserviceinterfacethatenables youtoobtaininformationfromtheserverlogfiles,andtocreateadiagnosticbundlethatcontainsall systemlogfilesandallserverconfigurationinformation.ThevSphereClientandtheMOBprovide graphicalandwebbasedaccesstotheDiagnosticManager.

VMware, Inc.

161

vSphere Web Services SDK Programming Guide

Overview of Configuration Files and Log Files


ESXandvCenterServerbothhavevariousconfigurationfilesthatcontrolthebehaviorofthesystem.Most configurationfilesettingsaresetduringinstallationbutcanbemodifiedafterinstallation.Thelogfilescapture messagesgeneratedbythekernelandvarioussubsystemsandservices.BothESXandvCenterServerservices maintaintheirownlogfiles.Table B1listsvariouslogfilesorreports,theirlocationsandassociated configurationfiles. Table B-1. Server and System Logs Reference
Description ESXservicelog VirtualCenter Agentlog VirtualMachine KernelCorefile syslogdlog Log location /var/log/vmware/ /var/log/vmware/vpx/ /root/ Filename or names hostd.log [hostd-0.log, ...hostd-9.log] vpxa.log vmkernel-core.<date> vmkernel-log.<date> /var/log/ messages [messages.1,... messages.4] ServiceConsole Availabilityreport VMkernel Messages VMkernelAlerts andAvailability report VMkernelWarning /var/log/ /var/log/vmkernel /var/log/vmkernel vmkernel [vmkernel.1, ... vmkernel.8] syslog.conf, logrotate.conf syslog.conf, logrotate.conf syslog.conf, logrotate.conf vmkwarning [vmkwarning.1 ... 4 for history] vmware.log syslog.conf, logrotate.conf <vm_name>/<vm_name>.vmx syslog.conf, logrotate.conf, various other syslog.conf, logrotate.conf Configuration file config.xml

/var/log/

VirtualMachine logfile

vmfs/volume/<vm_name>

Fordevelopers,thefollowingarethemostrelevantlogfiles: hostd.log,whichcanbeusedassomethingofaSOAPmonitor(whensettotrivialoglevelasGenerating Logsonpage 166) vpxa.log(filelocatedonamanagedESXhostsystem,placedbythevCenterServer) vmware.log Inadditiontoviewinglogfilesinrealtime,usingthevSphereClient(Administration>SystemLogstab),you canalsogeneratereportsandcompletediagnosticbundles. TogenerateadiagnosticbundleusingthevSphereClient,selectFile>Export>ExportDiagnosticData. ForcompleteinformationaboutESXandvCenterServerconfigurationandsystemsadministration,seethe vSpheredocumentationlibrary,inparticular,thevSphereBasicSystemAdministrationmanual.

162

VMware, Inc.

Appendix B Diagnostics and Troubleshooting

ESX Log File


TheESXlog(hostd.log)capturesinformationofvaryingspecificityanddetail,dependingontheloglevel. Eachrequesttotheserverislogged. Figure B-1. ESX Log (hostd.log) Displayed using vSphere Client

TherawtextformofanESX(hostd)logfileisshowninExample B1. Example B-1. Sample ESX Log (hostd.log) File Data
... [2008-05-07 09:50:04.857 'SOAP' 2260 trivia] Received soap response from [TCP:myservername.vmware.com:443]: GetInterfaceVersion [2008-05-07 09:50:04.857 'ClientConnection' 2260 info] UFAD interface version is vmware-converter-4.0.0 [2008-05-07 09:50:04.857 'SOAP' 2260 trivia] Sending soap request to [TCP:myservername.eng.vmware.com:443]: logout [2008-05-07 09:50:04.857 'ProxySvc Req00588' 3136 trivia] Client HTTP stream read error [2008-05-07 09:50:04.872 'ProxySvc Req00612' 3136 trivia] Request header: POST /vmc/sdk HTTP/1.1 User-Agent: VMware-client Content-Length: 435 Content-Type: text/xml; charset=utf-8 Cookie: vmware_soap_session="F127B435-56C7-4580-BAC4-3034DA1E67B6"; $Path=/ Host: myservername.vmware.com

[2008-05-07 [2008-05-07 [2008-05-07 [2008-05-07

09:50:04.872 'ProxySvc Req00588' 3816 trivia] Closed 09:50:08.450 'App' 3560 verbose] [VpxdHeartbeat] Invalid heartbeat from 10.17.218.46 09:50:10.013 'App' 3560 verbose] [VpxdHeartbeat] Queuing 10.17.218.45:829 (host-55) 09:50:10.013 'App' 1928 verbose] [HeartbeatHandler] 50208862-2752-d94c-2a73-fa2ec9e38ecc:829 (host-55)

Virtual Machine Log Files


Eachvirtualmachinerunningonahostsystemhasitsownlogfile,vmware.log,storedontheVMFSvolume. Bydefault,thelogfileisrotatedwheneverthevirtualmachineispoweredon,butfilerotationisconfigurable. Herearesomepointstonoteaboutvirtualmachinelogs: ESXmaintainssixlogfilesthatrotateateachpowercycle(thedefault)orataconfiguredfilesize. ESXcanbeconfiguredtomaintainaspecificnumberoflogfiles.Whenthelimitisreached,theoldestfile isautomaticallydeleted. VMwarerecommendsalogfilesizeof500KB. MessagesgeneratedbyVMwareToolsmessagesareloggedseparately.

VMware, Inc.

163

vSphere Web Services SDK Programming Guide

Example B-2. VMkernel Availability Report


Availability Report for <servername> Feb 27, 2008 - May 7, 2008 Availability: 99.949% Total time: 69 days, 15 hours Uptime: 69 days, 14 hours Downtime: 51 minutes Note: Downtime is any time the system isn't capable of running Virtual Machines. This includes reboots, crashes, configuration and running linux Downtime Analysis: 0.1% (51 minutes) downtime caused by: 13.1% (6 minutes) scheduled downtime 86.9% (44 minutes) unscheduled downtime Reasons for scheduled downtime: 84.9% server rebooting (1 instance) 9.4% VMkernel unloaded (1 instance) 5.7% server booting (3 instances) Reasons for unscheduled downtime: 100.0% unknown (powerfail / reset?) (1 instance) Stats: Current uptime: 8 days, 11 hours Longest uptime: 61 days, 2 hours Shortest uptime: 38 minutes Average uptime: 23 days, 4 hours Longest downtime: 44 minutes Shortest downtime: 7 seconds Average downtime: 8 minutes Maximum VMs Sampled: 1 Average VMs Sampled: 0.94 Server Information: Number of CPUs: 4 logical 4 cores 2 packages, Intel(R) Xeon(R) CPU 5150 @ 2.66GHz Installed Memory: 2096416 kB Current Build: 78591 Report generated Wed May 7 04:02:04 PDT 2008

vCenter Server Log Files


vCenterServerlogfilesarelocatedbydefaultintheDocumentsandSettingssubdirectoryoftheWindows accountusedtoinstallthesoftware.Forexample:
C:\Documents and Settings\Administrator\Local Settings\Application Data\VMware\

IMPORTANTVMwarerecommendscreatingauseraccountespeciallyforvCenterServersystems. Bydefault,systemfilesandfoldersarenotvisibleintheWindowsExplorerofFileManager.TolocateVMware logfiles,youmightneedtochangethesetting.FromtheWindowsExplorer,selectTools>FolderOptions> ViewpropertiespageandselecttheShowhiddenfilesandfoldersoption.

Modifying the Log Level to Obtain Detailed Information


TheservicerunningonESXsystemsthatgeneratesloginformationiscalledhostd(hostdaemon).Thedefault loglevelsettingforhostdinfo(Table B2).ThevCenterServerlogsarecontrolledbysettingsthroughthe vSphereClient.Thissectionprovidesinformationaboutchangingloglevelsfromthedefaults.

164

VMware, Inc.

Appendix B Diagnostics and Troubleshooting

Log Level Settings


Theamountofinformationcapturedinthelogfilesvaries,dependingonthelevelsetting. Table B-2. Log Level Settings
Log Level Setting None Error Warning Info Verbose Trivia Description Disableslogging. Logginglimitedtoerrormessagesonly. Errormessagespluswarningmessagesarelogged. DefaultsettingforloggingonESXandvCenterServersystems.Errors,warnings,plusinformational messagesaboutnormaloperationsarelogged.Acceptableforproductionenvironments. Canfacilitatetroubleshootinganddebugging.Notrecommendedforproductionenvironments. Extendedverboselogging.Providescompletedetail,includingcontentofallSOAPmessages betweenclientandserver.SeeExample B5,SOAPMessageContainedinGeneratedESXLog,on page 167.Usefordebuggingandtofacilitateclientapplicationdevelopmentonly.Not recommendedforproductionenvironments.

Setting the Log Level on ESX Systems


TheESXlogsarecontrolledbyasettingintheconfig.xmlfile,locatedinthe/etc/vmware/hostdsubdirectory ofanESXsystem(Example B3). Example B-3. ESX Config.xml File Excerpt Showing Default Log Level Setting
<config> <vmacore> <threadPool> <MaxFdsPerThread>2048</MaxFdsPerThread> </threadPool> <ssl> <doVersionCheck> false </doVersionCheck> </ssl> <vmdb> <maxConnectionCount>8</maxConnectionCount> </vmdb> <loadPlugins> true </loadPlugins> </vmacore> <workingDir> /var/log/vmware/ </workingDir> <log> <directory>/var/log/vmware/</directory> <name>hostd</name> <outputToConsole>false</outputToConsole> <level>info</level> </log> ,,, </config>

Bydefault,theloglevelsettingisinfo.Ifyourunintoissuesduringdevelopment,youcansettheloglevelto triviatoobtainSOAPmessagecontenttouseindebugging. YoucanalsousethistechniquetoanalyzeanoperationinvokedusingthehevSphereClientandthenread throughtheextensivelogfilestoextrapolatehowyoumightaccomplishthesametasksinyourowncode. NOTETheprocessdescribedbelowrequiresasystemrestart. To change the log level in config.xml for hostd 1 2 ConnecttoESXusingputtyorothersecureshell. Navigatetothelocationoftheconfig.xmlfile:
cd /etc/vmware/hostd

VMware, Inc.

165

vSphere Web Services SDK Programming Guide

Usevioreditorofyourchoicetoopentheconfig.xmlfile:
vi config.xml

Theconfig.xmlfileopensforediting(Example B3). 4 Scrollthroughthefiletothe<log>element.Forexample:


<log> <directory>/var/log/vmware/</directory> <name>hostd</name> <outputToConsole>false</outputToConsole> <level>info</level> </log>

5 6 7

Change<level>info</level>to<level>trivia</level>. Saveandclosethefile. Navigatetotheinit.ddirectory:


cd /etc/init.d

Restartthehostagent:
./mgmt-vmware restart

Aftertheservicerestarts,thenewloglevelisineffect.Example B4showstheentireprocess. Example B-4. Editing the ESX Configuration File and Restarting the Server
login as: root root@sdkpubslab-01.eng.vmware.com's password: Last login: Tue May 6 03:40:58 2008 from 10.16.250.244 [root@sdkpubslab-01 root]# cd /etc/vmware/hostd [root@sdkpubslab-01 hostd]# vi config.xml ... [root@sdkpubslab-01 hostd]# cd /etc/init.d [root@sdkpubslab-01 init.d]# ./mgmt-vmware restart Stopping VMware ESX Management services: VMware ESX Host Agent Watchdog [ OK VMware ESX Host Agent [ OK Starting VMware ESX Management services: VMware ESX Host Agent (background) [ OK Availability report startup (background) [root@sdkpubslab-01 init.d]#

] ] ] [

OK

Generating Logs
IfyouareconnectedtoESX,youcanusethetailcommandtoexplicitlycreatealogfilethatcapturesthe completedetailofanyactionsthatfollow.Forexample,youcanusethevSphereClienttocreateanewvirtual machineandthenusethecontentfromthelogasamodelforhowtocreateyourowncode. To start the logging process and capture content to a file 1 Navigatetothelocationofthehostd.logfile:
cd /var/log/vmware

Runthetailcommand(startscapturingnewlogdatafromtheendofthefile),passingafilenameinwhich tocaptureoutput:
tail -f hostd.log > yourfilenamehere

UsethevSphereClienttoperformwhateveractionyouarehavingdifficultymodelinginyourowncode. Forexample,createanewvirtualmachine.Aftertheoperationcompletes,stopthetailprocessby entering:


<ctrl><c>

166

VMware, Inc.

Appendix B Diagnostics and Troubleshooting

ThefilecontainstheSOAPmessagecontentandotherlogmessagessentandreceivedbyhostdduringthe execution.Example B5showsanexcerptofaSOAPmessage(hostd)associatedwithcreatinganewvirtual machine. Example B-5. SOAP Message Contained in Generated ESX Log
<soap:Body> <CreateVM_Task xmlns="urn:internalvim25"> <_this type="Folder">ha-folder-vm</_this> <config> <name>TestVM_06</name> <version>vmx-04</version> <guestId>rhel3_64Guest</guestId> <alternateGuestName>Red Hat Enterprise Linux 3 (64-bit)</alternateGuestName> <files> <vmPathName>[sdkpubslab-01:storage1]</vmPathName> </files> <tools> <afterPowerOn>true</afterPowerOn> <afterResume>true</afterResume> <beforeGuestStandby>true</beforeGuestStandby> <beforeGuestShutdown>true</beforeGuestShutdown> <beforeGuestReboot>true</beforeGuestReboot> </tools> <numCPUs>1</numCPUs> <memoryMB>384</memoryMB> ... </config> <pool type="ResourcePool">ha-root-pool</pool> </CreateVM_Task> ...

Besuretochangetheloglevelbacktoinfoafterobtainingtheinformationyouneedfromthelogfile.

Setting the Log Level on vCenter Server System


TochangeloglevelsettingsonvCenterServer,youmustusethevSphereClient.ConnecttothevCenterServer instance. To set logging level for vCenter Server using the VMware vSphere Client 1 2 ChooseAdministrationandclickServerSettings>LoggingOptions. ChooseTriviafromthepopupmenuandclickOK.

Understanding and Using the DiagnosticManager


ThevSphereAPIprovidesaccesstotheDiagnosticManager,theserviceinterfaceforobtaininginformation fromthelogfilesandforgeneratingdiagnosticbundles.Thelogsarepopulatedbasedonconfiguration settings,suchasinfo,trivia,andsoon.SeeLogLevelSettingsonpage 165fordetails. TheDiagnosticManagerisasingletonmanagedobjectthatworksservicewide,ratherthanonapersession basis.TheDiagnosticManagerhasnoproperties,butprovidesoperationsforobtaininginformationabout thelogsandhowtheyhavebeendefined,andforinitiatingtheprocessofgeneratingadiagnosticbundlethat canbesenttoVMwaresupportforanalysis.

VMware, Inc.

167

vSphere Web Services SDK Programming Guide

Figure B2showsaUMLclassdiagramforDiagnosticManager.TheDiagnosticManagerisavailableon bothESXandvCenterServersystems. Figure B-2. DiagnosticManager Managed Object and Associated Data Objects

AsshowninFigure B2,thethreeoperationsavailablethroughDiagnosticManagerare: BrowseDiagnosticLog GenerateLogBundleTask QueryDescriptions SeethevSphereAPIReferenceforcompletedocumentation. Thecreatorofthelogisthesystemorsubsystemthatcontrolsthespecificlog.Forexample,hostdandvpxa aretwoexamplesoflogcreators. ThecreatorvalueispopulatedfromtheDiagnosticManagerLogCreatorenumeration.Table B3listsall stringvaluescurrentlyavailablefromtheDiagnosticManagerLogCreatorenumerationthatcanpopulate thecreatorpropertyoftheDiagnosticManagerLogDescriptordataobject. Table B-3. DiagnosticManagerLogCreator Enumeration
Name hostd install recordLog serverd vpxa vpxClient vpxd Description Hostagent Installation SystemRecordLog Hostserveragent VirtualCenteragent Virtualinfrastructureclient VirtualCenterservice

Table B-4. ESX Sample DiagnosticManager Log Descriptor Values


creator hostd hostd hostd hostd file name /var/log/vmware/hostd.log /var/log/messages /var/log/vmkernel /var/log/vmksummary.txt format plain plain plain plain info.label ESXLog ESXLog ESXLog ESXLog info.summary ESXloginplain format ESXloginplain format ESXloginplain format ESXloginplain format key hostd messages vmkernel vmksummary mime type text/plain text/plain text/plain text/plain

168

VMware, Inc.

Appendix B Diagnostics and Troubleshooting

Table B-4. ESX Sample DiagnosticManager Log Descriptor Values (Continued)


creator hostd vpxa file name /var/log/vmkwarning /var/log/vmware/vpx/vpxa .log format plain plain info.label ESXLog VirtualCenter AgentLog info.summary ESXloginplain format VirtualCenter agentlogin plainformat key vmkwarning vpxa mime type text/plain text/plain

Using the MOB to Explore the DiagnosticManager


YoucanaccesstheDiagnosticManagerdirectlyfromtheESXorvCenterServerinstanceusingtheMOB.See NavigatingtheObjectModelintheMOBonpage 17forinformationaboutusingtheMOBtonavigateto theServiceContentdataobject,ifnecessary. IntheServiceContentdataobject,clickthelink(ha-diagnosticmanagerorDiagMgr)intheValuecolumn forthediagnosticManagerproperty,tonavigatetotheDiagnosticManagerforthesystem. ThelinknameisthemanagedobjectIDforthemanagedobjectreference.ThemanagedobjectIDnamevaries dependingonwhetheryouareaccessingavCenterServerorESXsystem: ForESX,ha-diagnosticsmanageristhemanagedobjectID. ForvCenterServer,DiagMgristypicallythemanagedobjectID. ClickthelinktothereferencetodisplaythemanagedobjectreferencetotheDiagnosticManagerintheMOB (Figure B3).DiagnosticManagerprovidesthreeoperationsthatenableyoutoobtaininformationaboutthe descriptionscurrentlyavailableinthelogfileandlogfilecontent. Figure B-3. Managed Object Reference to DiagnosticManager

Figure B3showstheDiagnosticManagerforavCenterServerinstance. ThevCenterServerDiagnosticManagertracksmultipleESXhostsystems,soyoucanusethe QueryDescriptionsoperationtoreturnthenamesofkeysusedforallhosts.Fromthisarray,selectthekey forthehostfromwhichyouwanttoobtainthelogfile(Figure B4).

VMware, Inc.

169

vSphere Web Services SDK Programming Guide

Figure B-4. Using the MOB to Invoke DiagnosticManager Operations

WhenyouclicktheInvokeMethodlink,thecontentsofthelogfilefortheselectedhostarereturnedbythe vCenterServersystem(Figure B5).ThecontentsarereturnedasastringarrayforthelineTextpropertyof DiagnosticManagerLogHeader. ThestringarrayreturnedthroughtheMOBinthiswayisthecontentofthelogfile.Thecontentcontainedin thelogfileisthesamecontentthatisavailablethroughthefollowingothermechanisms: DisplayedinthevSphereClient IncludedintheadiagnosticbundlecreatedthroughtheGenerateLogBundles_Task Availableinthehostd.log Returnedtoaclientapplicationthatyouwrite Figure B-5. DiagnosticManager Operations Available Through the MOB

170

VMware, Inc.

Appendix B Diagnostics and Troubleshooting

ThevSphereClientprovidesgraphicaluserinterfaceaccesstothesesameoperations.Example B6showsthe contentofalogfilewhentheloglevelissettoverbose. Example B-6. Sample Verbose Log File Data
...[2008-05-06 09:44:42.005 'TaskManager' 15227824 info] Task Created : haTask-ha-folder-vm-vim.Folder.createVm-755 [2008-05-06 09:44:42.005 'PropertyJournal' 19266480 verbose] PropertyJournalImpl::HasChanged: Overflow [N5Vmomi19PropertyJournalImplE:0xbb3cac0] recentTask ...'vm:/vmfs/volumes/47c5b0d6-16d11128-a260-0019b9c4369f/TestVM_05/TestVM_05.vmx' 15227824 verbose] Adding task: haTask-ha-folder-vm-vim.Folder.createVm-755 [2008-05-06 09:44:42.196 'ha-host' 15227824 verbose] ModeMgr::Begin: op = normal, current = normal, count = 1 [2008-05-06 09:44:42.201 'ha-eventmgr' 15227824 info] Event 17 : Creating TestVM_05 on host sdkpubslab-01.eng.vmware.com in ha-datacenter [2008-05-06 09:44:42.218 'HostsvcPlugin' 15227824 verbose] CreateEntry '112' [2008-05-06 09:44:42.222 'ResourcePool ha-root-pool' 15227824 verbose] Added child 112 to pool [2008-05-06 09:44:42.222 'Vmsvc' 15227824 verbose] Create VM initiated [112]: /vmfs/volumes/47c5b0d6-16d11128-a260-0019b9c4369f/TestVM_05/TestVM_05.vmx...

Table B5liststheDiagnosticManagerLogDescriptorobjectpropertiesandvalues.AllfilesareVCenter Serverlogsinplainformat. Table B-5. vCenter Server DiagnosticManagerLogDescriptor Values


creator vpxd vpxd vpxd vpxd vpxd vpxd vpxd vpxd vpxd vpxd vpxd file name vpxd-0.log vpxd-1.log vpxd-2.log vpxd-3.log vpxd-4.log vpxd-5.log vpxd-6.log vpxd-7.log vpxd-8.log vpxd-9.log vpxd-index format plain plain plain plain plain plain plain plain plain plain plain info.label VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog VirtualCenter ServerLog key vpxd:vpxd-0.log vpxd:vpxd-1.log vpxd:vpxd-2.log vpxd:vpxd-3.log vpxd:vpxd-4.log vpxd:vpxd-5.log vpxd:vpxd-6.log vpxd:vpxd-7.log vpxd:vpxd-8.log vpxd:vpxd-9.log vpxd:vpxd-index mime type text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain

Generating Diagnostic Bundles


Typically,diagnosticbundlesaregeneratedattherequestofVMwaretechnicalsupport,bycustomershaving problems.However,thesediagnosticbundlescanalsoprovideaquickwayfordeveloperstoobtainall configurationfilesandlogfilesinacompletepackage. Thegeneratedcompressedfilesarepackagedinafilehavingthefollowingpattern:
<fqdn-hostname>-esxsupport-yyyy-mm-dd@hh-mm-ss.tgz

VMware, Inc.

171

vSphere Web Services SDK Programming Guide

To export diagnostic data using the vSphere Client 1 2 LaunchthevSphereClientandconnecttotheESXorvCenterServersystem. SelectAdministration>ExportDiagnosticData. ForvCenterServer,youcanfilterforspecifichostswhoselogsyouwanttoexportandthelocation forstoringthelogfiles. ForESXhostsystems,youcanspecifythelocationforthebundle. 3 ClickOK.

To collect ESX VMkernel files IftheVMkernelfails,errormessagestypicallydisplaybriefly,andthenthevirtualmachinereboots. IfyouspecifiedVMwarecoredumppartitionaspartofyourvirtualmachineconfiguration,theVMkernelalso generatesacoredumpanderrorlog. Inrarecircumstances,veryseriousVMkernelproblemscanfreezetheserverwithoutraisingerrormessages ordumpingthesystemcore. To use the command line to collect ESX log files 1 2 3 UseputtyorotherSSHtooltoconnecttotheserviceconsole. Navigatetothe/usr/binsubdirectory. Runthe vm-supportscript: /usr/bin/vm-support 4 ThisscriptcollectsallrelevantESX3systemlogfiles,configurationfiles,andotherserverdetailsintoa compressedfile(thediagnosticbundle)whosenameincludesthedateandtime.

ToobtainamanagedobjectreferencetotheDiagnosticManager,firstobtainamanagedobjectreferenceto ServiceContent.EachServiceContentdataobjecthasadiagnosticManagerproperty,whichisdefined asamanagedobjectreferencetoaninstanceofDiagnosticManagerspecificforthesession.

172

VMware, Inc.

Deploying Client Applications

Thisappendixexplainshowtodeployclientapplications.Itincludesthesetopics: UnderstandingtheClientApplicationDeploymentModelonpage 173 CredentialStoreAdministrationToolforNonInteractiveClientsonpage 173

Understanding the Client Application Deployment Model


ThevSphereWebServicesSDKincludesWSDLfilesandothersoftwareartifactsthatyoucanusetodevelop clientapplications.IncludedwiththeSDKareprecompiledclientsidelibrariescontainingtheproxycode neededtointeractwiththeWebservicesAPI. TheVMwarevSphereservers(ESX/ESXi,vCenterServer,forexample)targetedbyanyclientapplicationsyou developmustbeappropriatelylicensed.However,youdonotneedanyspeciallicensefromVMwaretocreate softwareusingtheVMwarevSphereWebServicesSDKforsuchenvironments. DeployyourapplicationsasyouwouldanyWebservicesbasedclient.

Credential Store Administration Tool for Non-Interactive Clients


ThevSphereWebServicesSDKincludesaJavaadministrationtool(commandlineinterface)thatcanbeused byVMwarevSphereadministratorstomanagethecredentialstoreforanyclientapplicationsoragents.Ifyou haveanapplicationthatstartsup,automaticallyaWindowsorotherservice,forexample,oracronjobthat launchesanapplicationthatmustconnecttoESX/ESXiorvCenterServer,youcanusetheCredentialStore AdministrationTooltostoretheuseraccountanditspasswordlocally. Forexample,sayyouareusingVCB(VMwareCentralBackup)inyourenvironment,andyouwantto configureacronjobtoinitiatethebackupprocesseachnightat3:00a.m.tolauncheachnight ThetooliscontainedintheunpackedvSphereWebServicesSDKdownloadfileatthislocation:
%SDKHOME%\samples\Axis\java\com\vmware\security\credstore\CredentialStoreAdmin.java

Guidelines for Using the CredentialStoreAdmin Tool


TheCredentialStoreAdmintoolprovidescompleteaccesstothecredentialstorebackingfileonthelocal machine.ThisistheactualtextbasedXMLfilethatiscreated,opened,manipulated,andclosedbythe interfacesandimplementationsprovidedinthevariouscredstoreclassesinthevSphereWebServicesSDK. IMPORTANTNeverusetheCredentialStoreAdmintooltostoretherootorAdministratoruseraccountand passwordinthecredentialstore.Createspecialuseraccountsforanyautomatedoragentsoftwareandcreate specialroles(oruseappropriatelyprivileged,nonAdministratorroles)toapplytotheseuseraccounts. Accountscreatedexpresslyforthepurposeofrunningautomatedapplicationsoragentsaretheonlytypeof accountthatshouldgenerallybestoredinthecredentialstore.

VMware, Inc.

173

vSphere Web Services SDK Programming Guide

BeforeusingtheCredentialStoreAdmintool,besureyoufullyunderstanditsbehavior. CAUTIONTheCredentialStoreAdmintoolcandisplayuseraccountsandpasswordsstoredinthecredential storeincleartext,attheconsoleprompt.Donotallowthistooltobeusedbynonadministratorusers.Keep thistoolinapasswordprotectedsubdirectorythatonlyyouorappropriateadministratorcanaccess.

CredentialStoreAdmin Tool and the Backing File


TheCredentialStoreAdmintoolletsyouaccessthelocalcredentialstorebackingfile.Thebackingfileisan XMLformattedtextfilecontaininghosts(targetservers)andassociatedusernames,withtheirrespective passwords(Example C1). Example C-1. Populated Credential Store Backing File
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> - <viCredentials> <version>1.0</version> - <passwordEntry> <host>myTestServer</host> <username>root</username> <password>8Ofo8/bh8IPLnlD/YpB+mYV/jhIYm4V4+ulVwSVgK2BGPPV3U65i5IC2xxOYVYVnQ+2sgbzdvnT4brs +pu+HhqkYdrXuyCs3NceT5mrrTPP5m0XEo1ZsZEup6t1PSVcO53ddrN+dnZqEUqNA8FFDhV4B OKTkBAGQhCnRb0GBA0c=</password> </passwordEntry> - <passwordEntry> <host>192.168.25.14></host> <username>user94</username> <password>ChsJCQ0eS0pIeqB+6K6uv/gvaxqmzJJvL0ltudLnqBOz+2WQGvAadQ9ZS6gdGg6jWGTTOuoS+OE1Zsx A37dv1MqRpvabWzAK0YQIPwysKLijkF9Nc7yP8/GQCQBL1nBXOSZLk4HTemZMOHzZE7ojMqu4 l/GUI1PfS9zNs4m44dY=</password> </passwordEntry> </viCredentials>

ThehostsinthefilecanbespecifiedbyservernameorbyIPaddressbothIPv4andIPv6aresupported.At runtime,whenyoureaccessingthecredentialstoreandtryingtoobtainthepasswordfortheusername associatedwiththehost,youmustspecifythehostinthesameformasitisstoredinthebacking filehostnameorIPaddress. Forexample,ifyoustorebyhostname,youmustenterthehostnameintheapplication.OrifyouuseIP address,youmustusethesamestyleofIPaddressasisinthefile(IPv6,IPv4). Table C-1. Specify the Server by Hostname or by IP Address
Host prodserver.mycompany.com prodserver IPv4 192.168.28.124 IPv6 2001:0db8:3c4d:0015:0000:0000:abcd:ef12

Youdonotneedtousefullyqualifieddomainnames(FQDN)ifyourlocalsystemcanfindtheserver.Ifyou douseFQDNtospecifyservernames,youmustusethesamenameswithyourapplicationcodeaswiththe CredentialStoreAdmintool. Passwordsareobfuscated(Example C1)butnotencrypted,soitsimportantthatuserskeeptheircredential storefilesprotectedontheirlocalfilesystems. CAUTIONNeveremailthecredentialstorebackingfileunlessyouencryptthefile.Thecredentialstoreclient APIsdonotencryptthecontentsofthisfile. Furthermore,theCredentialStoreAdmintooldisplaysthepasswordincleartext,notinitsobfuscatedform, sobecarefulwhenusingthetooltodisplaypasswords. TheJavaruntime(JRE)mustbeinlocalpathtorunthetool.

174

VMware, Inc.

Appendix C Deploying Client Applications

PerlandPowerShellversionsofthiscommandlinetoolarealsoavailablewiththeVMwarevSphereSDKfor PerlandwiththeVMwarevSpherePowerCLI. To run the Java Credential Store Administration Tool on a client machine 1 InstalltheCredentialStoreAdmintoolfromthevSphereWebServicesSDKintoadirectoryontheclient machinethatwillruntheagentsoftware. Installingthetoolmeanstocopythecontentsofthe\credstoresubdirectorytoadirectoryonthelocal machineandsetthepathsothattheJavaruntimecanloadtheclassandrunit. 2 3 4 Ontheclientmachine,openacommandprompt. NavigatetothesubdirectorycontainingtheCredentialStoreadministrationtool. LaunchtheCredentialStoreAdmintoolfromacommandpromptasfollows:
java com.vmware.security.credstore.CredentialStoreAdmin add -h <servername> -u <username> -p <password>

Table C2listsallthecommandsavailabletotheCredentialStoreAdmintool. Inadditiontotheargumentslistedinthetable,eachofthesecommandscantakethefargument,tospecify thenameofthebackingfile.UsethefoptiontocreateaCredentialStorebackingfileusinganameofyour choice,includingdirectorypath. Ifyoucreateacredentialstoreusingacustomfilename,youmustpassthefilenametothecommandwhen youinvokeit. Table C-2. CredentialStoreAdmin Command Summary
Command clear add ~ -h -u -p get -h -u help <command> Arguments ~ host username password host username Forthespecifiedhostnameandusername,obtainsthepasswordfromthe credentialstore. Displaysatthecommandpromptthesamebasictextascapturedinthis table.Currently,enteringacommandnamewiththehelpcommandhasno effectontheoutputofthehelpcommand. Displaysatthecommandpromptthecontentsofthecredentialstore. Withoutanyarguments,displaysallhostnameswitheachuseraccount. Usethe--showpwargumenttodisplaythepasswordsincleartext.(Be mindfulofthesecurityissuesassociatedwithdoingthis.)Theshowpw argumentusestwodashes. Usethe-hargumentwiththespecifichostnametoobtaintheuser namestoredinthecredentialstoreforthathost.Enterthehostnamein thesame remove -h -u host username Forthespecifiedhostnameandusername,deletestheusernameand passwordfromthecredentialstore. Forthespecifiedhostname,addstothelocalcredentialstorethespecified useraccountandpassword. Description

list

--showpw -h host

EachtimeaclientapplicationortheCredentialStoreAdmintoolitselfaccessesthecredentialstorewhether toreaditscontentsorwritenewdatatoitthebackingfileislocked.Afterthereadorwritecompletes,the fileisstoredagaintodisk.Thisensuresthatreadersandwritersbothhaveacompletefiletoworkwithand donotstartreadingfromamidpoint,orcorruptthedatainthefilebywritingtoafilethatsopenforaread.

VMware, Inc.

175

vSphere Web Services SDK Programming Guide

176

VMware, Inc.

Index

A
access, limiting 70 accessing property values 49 accessor methods 52 accounts 70 Action object 142, 146 Active Directory 37 AddAuthorizationRole operation 42 Administrator role 158 Alarm managed object 137, 138 AlarmAction object 141, 142 AlarmExpression object 139, 140 AlarmManager object 137 alarms 137, 138 actions 146 deleting 142 disabling 142 list 138 samples 137 AlarmSpec object 139 properties 139 API version supported 64 applying permission to an entity 71 asynchronous applications 46 authenticating users 39 authentication 33 authorization 33 AuthorizationManager limiting access 70 managed object 40 operations 41, 43 overview 39 automating client application login 67

B
backing file 174

C
C# datatypes,map to XML 53 helper classes 65 cancelling tasks 88 changing permissions 43 CheckForUpdates operation 79 checking migration validity 126

client applications characteristics 46 deploying 173 pattern 59 patterns 59 client data, synchronizing 78 client library 51 client-side proxy code 51 cloning virtual machines 125 closing server connection 60 collection performance 79 complex content 55 config.xml file 165 configuration files 162, 166 configured storage 107 connection object 59 container object 26 cookie 63 counter groups 112 CreateAlarm operation 138 CreateFilter 57, 77 CreateUser sample 69 creating a VirtualMachineConfigSpec 94 creating custom events 132 creating datastores 108 creating new user accounts 70 creating roles 41 creating ScheduledTask object 144 creating snapshots 97 creating templates 124 creating UserAccount objects 71 creating virtual machines 93 credential store 69 administration tool 173 backing file 68, 174 backing file structure 68 client API libraries 67 client API methods 68 CreateUser sample 69 default locations 70 file format 68 introduction 67 least privilege 69 SimpleAgent sample 69

VMware, Inc.

177

vSphere Web Services SDK Programming Guide

CredentialStoreAdmin commands 175 tool 70

D
Datacenter managed object type 26 Datastore managed object 102 datastores configuration 110 creating 108 datatypes for MOB usage 58 default log level setting 165 deleting alarms 142 deleting HistoryCollector 135 deleting permissions 43 deleting roles 41 deleting scheduled tasks 148 deploying client applications 173 deploying virtual machines 124 deployment model 173 deployment sample 120 deprecated items 51 diagnostic bundles 171 DiagnosticManager 167 log descriptor values 168 managed object 168 operations 170 operations available through the MOB 170 DiagnosticManagerLogCreator enumeration 168 diagnostics 161 disabling alarms 142 distributed virtual switch 12

EventDescriptionEventDetail data object type 131 EventHistoryCollector 133 EventManager object 129, 130 samples 129 events creating 132 exported from ESX/ESXi system 92 formatting messages 130 management 129 message content 131 examples generated accessor and mutator methods 52 returned object displayed in MOB 54

F
file access 34 file format, credential store 68 Folder object 27, 30 folder object 26 format for iSCSI names 105

G
generated accessor and mutator methods 52 generating logs 166 granting privileges 42 group permissions 44 groups 37 management 36 membership 44 permissions 44

H
helper classes 65 C#

E
enabling single sign-on support 37 Escape characters 53 ESX/ESXi config.xml file 165 configuration file 166 events 92 inventory 30 log 163 log file 163 log level 165 PerfInterval 115 sample log 163 user model 35 Event object 129, 130 objects 92, 130, 131 samples 129 EventAlarmExpression 140

sample applications
java

65 65

sample applications
sample applications 64 historical intervals 117 HistoryCollector 133 appending objects 135 deleting 135 operations 133 overview 133 host name 174 host provisioning 12 hostd.log 163 HostDatastoreSystem creation operations 108 modification operations 110 query operations 107

178

VMware, Inc.

Index

HostDatastoreSystem object 106 HostDatastoreSystem operations 106 HostHostBusAdapter data object 102, 106 HostLocalAccountManager object 35 operations 36 HostNasVolumeSpec data object 109 HostScsiDiskPartition data object 109 HostStorageSystem object 102 operations 103 HostSystem object 106 HostVmfsSpec data object 109 HTTP-based file access 34

settings 165 vCenter Server system 167 login 67 logs 163 generating 166 server 162 system 162

M
managed object browser 17 managed object references 24 managed objects 101 handling local user accounts 38 ManagedEntity 26 descendents 13 ManagedEntity subtypes 25 permission objects 29 ManagedObjectReference default methods 52 diagram 46 Type property 46 valid string values 52 XML schema 55 managing storage 99 mapping WSDL to client-side proxy code 51 mapping XML datatypes to java and C# datatypes 53 maximum allowed resource usage 94 messages (event), formatting 130 MetricAlarmExpression data object 141 Microsoft Active Directory 37 MigrateVM_Task operation 126 migrating virtual machines 125, 126 minimum available resources 94 mo_ref 22 MOB 17, 54, 58 invoking DiagnosticManager operations 170 invoking operations 53 navigating object model 17 passing complex datatypes to operations 55 passing primitive datatypes to operations 54 monitoring performance 111 MOR (managed object reference, abbreviation for) 22 MOR>ManagedObject 22 MoRef 22 multiple API versions 63 mutator methods 52

I
Import statements 51 includes 51 intervals 117 inventory 25, 26, 30 introduction 30 permissions 29 privileges 28 root folders 27 invoking operations through MOB 53 IP address 174 iSCSI names 105 overview 101

J
java datatypes, map to XML 53 helper classes 65 TaskList application 90

L
limit 94 limiting access 70 local storage 100 local user accounts 38 locale, setting 60 localization 60 log descriptor values 168 log files overview 162 sample 171 vCenter Server 164 virtual machines 163 log level default settings 165 ESX system 165 modifying 164
VMware, Inc.

N
NAS storage overview 100 nested data objects 57 nested properties 50, 52 nested TraversalSpec 76 new features 12
179

vSphere Web Services SDK Programming Guide

O
ObjectContent data object 76, 77 ObjectSpec definition as XML Schema 57 obtaining statistics 115 operations HistoryCollector 133 passing complex datatypes 55 passing primitive datatypes 54 privileges required 149 required privileges for 149 optimizing query response time 118

P
passing complex datatypes to operations 55 passing primitive datatypes to operations 54 PerfCounterInfo data object 113 matching PerfMetricId CounterId 114 overview 112 properties 113 PerfEntityMetricBase data object 116 PerfInterval data objects ESX/ESXi system 115 vCenter Server system 117 PerfMetricId CounterId 114 performance 79, 111 performance counter groups 112 PerformanceManager operations 112 overview 117 properties 112 samples 111 PerfQuerySpec 115 permissions 29, 42, 43, 44, 71 changing 43 deleting 43 group membership 44 setting 43 users and groups 44 physical storage 99 powering on VM 148 predefined user roles 41 privileges 28, 40, 42 Administrator role 158 and security management 28 definition format 28 ESX/ESXi

properties, required for 156 reading object properties 156 vCenter Server operations 149 profiles 12 property values 49 PropertyCollector 77, 89 managed object type 74, 81 operations 74 operations 74 operations, compared 78 performance 79 samples 73 PropertyFilter managed object type 74 PropertyFilterSpec 56, 75, 89 introduction 75 XML schema definition 56 PropertySpec XML schema 56 provisioning 12

Q
QueryAvailablePerfMetric operation 116

R
recent tasks 89 recentTask Array 90 recurring operations 146 recursion 76 RelocateVM_Task operation 127 removing permissions 43 reservation 94 ResourceAllocationInfo, properties 94 restarting server 166 RetrieveEntityScheduledTask operation 144 RetrieveProperties operation 76 return datatypes 50 revert to snapshot 97 roles 40, 41 and security management 40 creating 42 modifying 42 root folders 27

S
sample applications 64 sample ESX log 163 samples Alarm 137 datastore operations 99 Event 129 EventManager 129 multiple API versions 64 overview 83 PerformanceManager 111
VMware, Inc.

operations

149

examples 28 format 28, 34 invoking operations 149 operations, required for 149

180

Index

PropertyCollector 73 ScheduledTaskManager 143 SearchIndex 73 storage operations 99 verbose log file 171 virtual machine deployment 120 VirtualMachine 93 sampling intervals 114 sampling periods 114 ScheduledTask 144, 145 cancelling 88 deleting 148 power on VM 148 retrieving 144 ScheduledTaskManager creating ScheduledTask 145 samples 143 ScheduledTaskSpec object 145 ScheduleTaskManager 144 scheduling recurring operations 146 scheduling vCenter Server operations 145 SDK 2.5 client applications 14 SDK 2.5 clients and vSphere 4.0 servers 13 SearchIndex 80 object 81 operations 81 samples 73 security 69 server access control 33 server connection, closing 60 server logs 162 ServiceContent data object 18, 19 property names 20 return types 20 values 20 ServiceInstance object 23 properties 18 session token 63 session tokens 59, 60, 63 SessionManager managed object 39 setting permissions 43 shares 94 simple client application 62 SimpleAgent sample 69 single sign-on support 37 snapshots 97 special characters 53 specifying server 174 statistics 115 statistics level settings 117

storage 101, 107 requirements 100 storage VMotion 127 supported version 64 synchronizing client data 78 system logs 162 system privileges 34 system roles 40, 41

T
target server, specifying 174 task infrastructure 83 task management 129 Task object 84, 85 TaskFilterSpec data object 134 TaskHistoryCollector 133 TaskInfo object 85 properties 88 properties 85 TaskInfoState values 90 TaskList java application 90 TaskManager 88 object 84, 85 properties 84 tasks, cancelling 88 TaskScheduler subtypes 147 templates 124, 125 retrieving 125 tokens 60, 63 TraversalSpec 76 troubleshooting 161

U
Unified Modeling Language 21 Update operation 77 UpdateAuthorizationRole operation 42 updating roles 41 user accounts 38, 70 user management 36 user models 33 User permissions 44 UserAccount object 71 UserDirectory 37 UserDirectory managed object 37 UserManager operations 38 server source data 37 users overview 37 permissions 44

VMware, Inc.

181

vSphere Web Services SDK Programming Guide

V
vCenter Server DiagnosticManagerLogDescriptor values 171 inventory 30 log files 164 scheduling operations 145 user model, overview 36 virtual machine operations 119 version information 64 versions 51, 64 sample using multiple versions 64 VI SDK 2.5-based clients 14 View object 80 View objects 79 ViewManager object 80 ViewManager objects 79 vimServiceVersions.xml 63 virtual machines cloning 125 creating 93 deployment using vCenter Server 120 log files 163 managing 93 migrating 126 migration 125 operations 119 powering on 148 templates 124 virtual storage 99 VirtualMachine ConfigSpec data object 121 nested properties 50 operations 95 operations 124 operations for VMotion 125 overview 50 RelocateVM_Task operation 127 samples 93 VirtualMachine managed object overview 120 VirtualMachineConfigSpec 94 VirtualMachineProvisioningChecker service interface 126 VirtualMachineRelocateSpec data object 127 VMkernel availability report 164 VMotion 125 vNetwork Distributed Switch See distributed virtual switch 12 vSphere 4.0 servers and SDK 2.5 clients 13

vSphere Client connected to ESX/ESXi 16 Connected to vCenter Server 16 vSphere components 11 vSphere object model 15

W
WaitForUpdates operation 79 Web Server, reusing session token 63 web service connecting 59 overview 45, 50 WSDL file 45 map to client-side proxy code 51

X
XML schema 55 ManagedObjectReference 55 PropertyFilterSpec 56 PropertySpec 56 XML Schema Primitives to .NET mapping 53 XML Schema Primitives to java mapping 53

182

VMware, Inc.

Vous aimerez peut-être aussi