/** * Establishes session with the virtual center server. * * @throws Exception the exception */ private static void connect() throws Exception { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); SVC_INST_REF.setType(SVC_INST_NAME); SVC_INST_REF.setValue(SVC_INST_NAME); vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); vimPort.login(serviceContent.getSessionManager(), userName, password, null); isConnected = true; propCollectorRef = serviceContent.getPropertyCollector(); rootRef = serviceContent.getRootFolder(); perfManager = serviceContent.getPerfManager(); }
private static void reconfigVirtualMachine() throws Exception { System.out.println("ReConfigure The Virtual Machine .........."); VirtualMachineFileInfo vmFileInfo = new VirtualMachineFileInfo(); vmFileInfo.setLogDirectory("[" + datastore + "] " + vmName); vmFileInfo.setSnapshotDirectory("[" + datastore + "] " + vmName); vmFileInfo.setSuspendDirectory("[" + datastore + "] " + vmName); vmFileInfo.setVmPathName("[" + datastore + "] " + vmName + "/" + vmName + ".vmx"); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec.setFiles(vmFileInfo); ManagedObjectReference taskmor = vimPort.reconfigVMTask(getVmByVMname(vmName), vmConfigSpec); Object[] result = waitForValues( taskmor, new String[] {"info.state", "info.error"}, new String[] {"state"}, new Object[][] {new Object[] {TaskInfoState.SUCCESS, TaskInfoState.ERROR}}); if (result[0].equals(TaskInfoState.SUCCESS)) { System.out.println("ReConfigure The Virtual Machine .......... Done"); } else { System.out.println("Some Exception While Reconfiguring The VM " + result[0]); } }
private static void initServiceContent() { if (SERVICE_CONTENT == null) { try { SERVICE_CONTENT = VIM_PORT.retrieveServiceContent(SIMO_REF); } catch (Exception e) { e.printStackTrace(); } } }
private static void refreshStats() { try { PerfCompositeMetric metric = vimPort.queryPerfComposite(perfManager, querySpec); XMLGregorianCalendar latestTs = displayStats(querySpec.getMetricId(), metric); if (latestTs != null) { querySpec.setStartTime(latestTs); } } catch (SOAPFaultException sfe) { printSoapFaultException(sfe); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Demonstrate how to use the PropertyCollector to retrieve properties of a managed object. * * <p>Prints Virtual machine name and powerstate of all the VMs in the datacenter (Either VC or * ESX host). */ public static void getVMInfo() { try { TraversalSpec tSpec = getVMTraversalSpec(); // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(Boolean.FALSE); propertySpec.setPathSet(new String[] {"name", "runtime.powerState"}); propertySpec.setType("VirtualMachine"); PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec}; // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.setObj(ROOT_FOLDER); objectSpec.setSkip(Boolean.TRUE); objectSpec.setSelectSet(new SelectionSpec[] {tSpec}); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs); if (oCont != null) { // System.out.println("ObjectContent Length : " + oCont.length); StringBuilder sb = new StringBuilder(); for (ObjectContent oc : oCont) { DynamicProperty[] dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { if (dp.getName().equalsIgnoreCase("name")) { sb.append(dp.getVal()); sb.append(" : "); } else { sb.append(dp.getVal()); sb.append("\n"); } // System.out.println(dp.getName() + " : " + // dp.getVal()); } } } System.out.println(sb.toString()); } } catch (Exception e) { e.printStackTrace(); } }
/** * Uses the new RetrievePropertiesEx method to emulate the now deprecated RetrieveProperties * method. * * @param listpfs * @return list of object content * @throws Exception */ private static List<ObjectContent> retrievePropertiesAllObjects(List<PropertyFilterSpec> listpfs) throws Exception { RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions(); List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>(); try { RetrieveResult rslts = vimPort.retrievePropertiesEx(propCollectorRef, listpfs, propObjectRetrieveOpts); if (rslts != null && rslts.getObjects() != null && !rslts.getObjects().isEmpty()) { listobjcontent.addAll(rslts.getObjects()); } String token = null; if (rslts != null && rslts.getToken() != null) { token = rslts.getToken(); } while (token != null && !token.isEmpty()) { rslts = vimPort.continueRetrievePropertiesEx(propCollectorRef, token); token = null; if (rslts != null) { token = rslts.getToken(); if (rslts.getObjects() != null && !rslts.getObjects().isEmpty()) { listobjcontent.addAll(rslts.getObjects()); } } } } catch (SOAPFaultException sfe) { printSoapFaultException(sfe); } catch (Exception e) { System.out.println(" : Failed Getting Contents"); e.printStackTrace(); } return listobjcontent; }
/** * Establishes session with the virtual center server. * * @throws Exception the exception */ private static void connect() throws Exception { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); SVC_INST_REF.setType(SVC_INST_NAME); SVC_INST_REF.setValue(SVC_INST_NAME); vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); boolean isVCApi = checkApiType(serviceContent); if (!isVCApi) { System.out.println("Virtual Center is not supported"); System.exit(0); } headers = (Map) ((BindingProvider) vimPort) .getResponseContext() .get(MessageContext.HTTP_RESPONSE_HEADERS); vimPort.login(serviceContent.getSessionManager(), userName, password, null); isConnected = true; rootRef = serviceContent.getRootFolder(); propCollectorRef = serviceContent.getPropertyCollector(); }
/** * Demonstrate how to use the PropertyCollector to retrieve properties of a managed object when * the managed object reference is known. * * <p>Retrieves the Virtual machine property. * * @return String property of the VirtualMachine. */ public static Object getVMProperty(ManagedObjectReference mor, String prop) { Object retVal = null; try { // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(Boolean.FALSE); // propertySpec.setPathSet(new String[]{"name"}); propertySpec.setPathSet(new String[] {prop}); propertySpec.setType("VirtualMachine"); PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec}; // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.setObj(mor); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs); if (oCont != null) { // System.out.println("ObjectContent Length : " + oCont.length); for (ObjectContent oc : oCont) { // DynamicProperty[] dps = oc.getPropSet(); DynamicProperty[] dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { // System.out.println(dp.getName() + " : " + // dp.getVal()); retVal = dp.getVal(); } } } } } catch (Exception e) { e.printStackTrace(); } return retVal; }
/** * Demonstrate how to use the PropertyCollector to retrieve managed object reference. * * <p>Initializes the VM_MOR_LIST with the MOREFs to all the VMs. */ public static void initVMMorList() { try { TraversalSpec tSpec = getVMTraversalSpec(); // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(Boolean.FALSE); propertySpec.setType("VirtualMachine"); PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec}; // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.setObj(ROOT_FOLDER); objectSpec.setSkip(Boolean.TRUE); objectSpec.setSelectSet(new SelectionSpec[] {tSpec}); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; ObjectContent[] oCont = VIM_PORT.retrieveProperties(PROP_COLLECTOR, propertyFilterSpecs); if (oCont != null) { // System.out.println("ObjectContent Length : " + oCont.length); for (ObjectContent oc : oCont) { ManagedObjectReference mr = oc.getObj(); // System.out.println("MOR Type : " + mr.getType()); VM_MOR_LIST.add(mr); } } } catch (Exception e) { e.printStackTrace(); } }
/** * Disconnects the user session. * * @throws Exception */ private static void disconnect() throws Exception { if (isConnected) { vimPort.logout(serviceContent.getSessionManager()); } isConnected = false; }
private static boolean registerVirtualMachine() throws Exception { boolean registered = false; ManagedObjectReference resourcePoolRef = new ManagedObjectReference(); System.out.println("Registering The Virtual Machine .........."); ManagedObjectReference host = null; // Get The Data Center ManagedObjectReference dcmor = getDatacenterByName(datacenter); List<DynamicProperty> vmFolderList = getDynamicProarray(dcmor, "Datacenter", "vmFolder"); ManagedObjectReference vmFolderMor = (ManagedObjectReference) (vmFolderList.get(0)).getVal(); List<DynamicProperty> hostFolderList = getDynamicProarray(dcmor, "Datacenter", "hostFolder"); ManagedObjectReference hostFolderMor = (ManagedObjectReference) hostFolderList.get(0).getVal(); List<DynamicProperty> computeResourceList = getDynamicProarray(hostFolderMor, "Folder", "childEntity"); List<ManagedObjectReference> csMoRefList = new ArrayList<ManagedObjectReference>(); List<ManagedObjectReference> cSList = new ArrayList<ManagedObjectReference>(); for (int i = 0; i < computeResourceList.size(); i++) { ArrayOfManagedObjectReference moArray = (ArrayOfManagedObjectReference) (computeResourceList.get(0)).getVal(); csMoRefList.addAll(moArray.getManagedObjectReference()); for (int j = 0; j < csMoRefList.size(); j++) { if (csMoRefList.get(j).getType().toString().contains("ComputeResource")) { cSList.add(csMoRefList.get(j)); } } } List<ManagedObjectReference> hosts = new ArrayList<ManagedObjectReference>(); for (int k = 0; k < cSList.size(); k++) { List<DynamicProperty> hostSystemList = getDynamicProarray(cSList.get(k), "ComputeResource", "host"); ArrayOfManagedObjectReference hostsArray = (ArrayOfManagedObjectReference) (hostSystemList.get(0)).getVal(); ManagedObjectReference hostSystem = hostsArray.getManagedObjectReference().get(0); hosts.add(hostSystem); } if (hosts.size() < 1) { System.out.println("No host found in datacenter to" + " register the Virtual Machine"); return registered; } else { boolean hostFound = false; for (int i = 0; i < hosts.size(); i++) { ManagedObjectReference hostMor = (ManagedObjectReference) hosts.get(i); List<DynamicProperty> datastoresList = getDynamicProarray(hostMor, "HostSystem", "datastore"); ArrayOfManagedObjectReference hostSystemArray = ((ArrayOfManagedObjectReference) (datastoresList.get(0)).getVal()); List<ManagedObjectReference> datastores = hostSystemArray.getManagedObjectReference(); long dirSize = getDirSize(localPath); for (int j = 0; j < datastores.size(); j++) { DatastoreSummary dataStoreSummary = getDataStoreSummary(datastores.get(j)); if (dataStoreSummary.getName().equalsIgnoreCase(datastore)) { DatastoreInfo datastoreInfo = getDataStoreInfo(datastores.get(j)); if (datastoreInfo.getFreeSpace() > dirSize) { host = hostMor; hostFound = true; i = hosts.size() + 1; j = datastores.size() + 1; } } } } if (hostFound) { // Get The vmx path String vmxPath = "[" + datastore + "] " + vmName + "/" + vmName + ".vmx"; ManagedObjectReference vmRef = new ManagedObjectReference(); List<DynamicProperty> vmsPropList = getDynamicProarray(host, "HostSystem", "vm"); ArrayOfManagedObjectReference vmsPropArray = (ArrayOfManagedObjectReference) (vmsPropList.get(0)).getVal(); List<ManagedObjectReference> vmsList = vmsPropArray.getManagedObjectReference(); for (int i = 0; i < vmsList.size(); i++) { if (vmsList.get(i).getType().equalsIgnoreCase("VirtualMachine")) { vmRef = vmsList.get(i); break; } } List<DynamicProperty> rpRef = getDynamicProarray(vmRef, "VirtualMachine", "resourcePool"); resourcePoolRef = (ManagedObjectReference) rpRef.get(0).getVal(); // Registering The Virtual machine ManagedObjectReference taskmor = vimPort.registerVMTask(vmFolderMor, vmxPath, vmName, false, resourcePoolRef, host); String result = waitForTask(taskmor); if (result != null) { if (result.equalsIgnoreCase("sucess")) { System.out.println("Registering The Virtual Machine ..........Done"); registered = true; } else { System.out.println("Some Exception While Registering The VM"); registered = false; } } else { System.out.println("Some Exception While Registering The VM"); registered = false; } return registered; } else { System.out.println( "No host in datacenter has got the" + " specified datastore and free space"); return registered; } } }
/** * Wait for values. * * @param objmor the object mor * @param filterProps the filter props * @param endWaitProps the end wait props * @param expectedVals the expected vals * @return the object[] * @throws RemoteException the remote exception * @throws Exception the exception */ private static Object[] waitForValues( ManagedObjectReference objmor, String[] filterProps, String[] endWaitProps, Object[][] expectedVals) throws RemoteException, Exception { // version string is initially null String version = ""; Object[] endVals = new Object[endWaitProps.length]; Object[] filterVals = new Object[filterProps.length]; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.getObjectSet().add(new ObjectSpec()); spec.getObjectSet().get(0).setObj(objmor); spec.getPropSet().addAll(Arrays.asList(new PropertySpec[] {new PropertySpec()})); spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(filterProps)); spec.getPropSet().get(0).setType(objmor.getType()); spec.getObjectSet().get(0).setSkip(Boolean.FALSE); ManagedObjectReference filterSpecRef = vimPort.createFilter(propCollectorRef, spec, true); boolean reached = false; UpdateSet updateset = null; PropertyFilterUpdate[] filtupary = null; PropertyFilterUpdate filtup = null; ObjectUpdate[] objupary = null; ObjectUpdate objup = null; PropertyChange[] propchgary = null; PropertyChange propchg = null; while (!reached) { boolean retry = true; while (retry) { try { updateset = vimPort.waitForUpdates(propCollectorRef, version); retry = false; } catch (SOAPFaultException sfe) { printSoapFaultException(sfe); } catch (Exception e) { e.printStackTrace(); } } if (updateset != null) { version = updateset.getVersion(); } if (updateset == null || updateset.getFilterSet() == null) { continue; } List<PropertyFilterUpdate> listprfup = updateset.getFilterSet(); filtupary = listprfup.toArray(new PropertyFilterUpdate[listprfup.size()]); filtup = null; for (int fi = 0; fi < filtupary.length; fi++) { filtup = filtupary[fi]; List<ObjectUpdate> listobjup = filtup.getObjectSet(); objupary = listobjup.toArray(new ObjectUpdate[listobjup.size()]); objup = null; propchgary = null; for (int oi = 0; oi < objupary.length; oi++) { objup = objupary[oi]; if (objup.getKind() == ObjectUpdateKind.MODIFY || objup.getKind() == ObjectUpdateKind.ENTER || objup.getKind() == ObjectUpdateKind.LEAVE) { List<PropertyChange> listchset = objup.getChangeSet(); propchgary = listchset.toArray(new PropertyChange[listchset.size()]); for (int ci = 0; ci < propchgary.length; ci++) { propchg = propchgary[ci]; updateValues(endWaitProps, endVals, propchg); updateValues(filterProps, filterVals, propchg); } } } } Object expctdval = null; // Check if the expected values have been reached and exit the loop if done. // Also exit the WaitForUpdates loop if this is the case. for (int chgi = 0; chgi < endVals.length && !reached; chgi++) { for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++) { expctdval = expectedVals[chgi][vali]; reached = expctdval.equals(endVals[chgi]) || reached; } } } // Destroy the filter when we are done. vimPort.destroyPropertyFilter(filterSpecRef); return filterVals; }
/** * Disconnects the user session * * @throws Exception */ private static void disconnect() throws Exception { VIM_PORT.logout(SERVICE_CONTENT.getSessionManager()); }
/** * @param url The URL of the server * @param uname The user name for the session * @param pword The password for the user * <p>Establishes session with the virtual center / ESX server * @throws Exception */ private static void connect(String url, String uname, String pword) throws Exception { VIM_PORT.login(SERVICE_CONTENT.getSessionManager(), uname, pword, null); }