/** * Retrieve contents for a single object based on the property collector * registered with the service. * * @param collector * Property collector registered with service * @param mobj * Managed Object Reference to get contents for * @param properties * names of properties of object to retrieve * * @return retrieved object contents * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ private ObjectContent[] getObjectProperties(ManagedObjectReference mobj, String[] properties) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (mobj == null) { return null; } PropertyFilterSpec spec = new PropertyFilterSpec(); spec.getPropSet().add(new PropertySpec()); if ((properties == null || properties.length == 0)) { spec.getPropSet().get(0).setAll(Boolean.TRUE); } else { spec.getPropSet().get(0).setAll(Boolean.FALSE); } spec.getPropSet().get(0).setType(mobj.getType()); spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(properties)); spec.getObjectSet().add(new ObjectSpec()); spec.getObjectSet().get(0).setObj(mobj); spec.getObjectSet().get(0).setSkip(Boolean.FALSE); List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1); listpfs.add(spec); List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs); return listobjcont.toArray(new ObjectContent[listobjcont.size()]); }
/** * Get one of the datastore compatible with storage policy */ public static ManagedObjectReference getDatastoreFromStoragePolicy(final Connection connection, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (pbmSpec != null) { for (VirtualMachineDefinedProfileSpec sp : pbmSpec) { try { PbmProfileId pbmProfileId = new PbmProfileId(); pbmProfileId.setUniqueId(sp.getProfileId()); List<String> datastoreNames = ClientUtils.getDatastores(connection, pbmProfileId); String dsName = datastoreNames.stream().findFirst().orElse(null); if (dsName != null) { ManagedObjectReference dsFromSp = new ManagedObjectReference(); dsFromSp.setType(VimNames.TYPE_DATASTORE); dsFromSp.setValue(dsName); return dsFromSp; } } catch (Exception runtimeFaultFaultMsg) { // Just ignore. No need to log, as there are alternative paths. } } } return null; }
/** * Get customization config spec for all the image disks if any */ private List<VirtualDeviceConfigSpec> getCustomizationConfigSpecs(ArrayOfVirtualDevice devices, List<DiskStateExpanded> diskStates) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<VirtualDeviceConfigSpec> specs = new ArrayList<>(); List<VirtualDisk> virtualDisks = devices.getVirtualDevice().stream() .filter(d -> d instanceof VirtualDisk) .map(d -> (VirtualDisk) d) .collect(Collectors.toList()); for (VirtualDisk vd : virtualDisks) { VirtualDeviceConfigSpec diskSpec = getBootDiskCustomizeConfigSpec( findMatchingImageDiskState(vd, diskStates), vd); if (diskSpec != null) { specs.add(diskSpec); } } return specs; }
private boolean isSameDatastore(ManagedObjectReference datastore, ManagedObjectReference vm, GetMoRef get) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (datastore == null) { return false; } ArrayOfManagedObjectReference datastores = get.entityProp(vm, VimPath.vm_datastore); if (null != datastores) { for (ManagedObjectReference p : datastores.getManagedObjectReference()) { if (p.getValue().equals(datastore.getValue())) { return true; } } } return false; }
/** * Decides in which folder to put the newly created vm. * * @return * @throws InvalidPropertyFaultMsg * @throws RuntimeFaultFaultMsg * @throws FinderException */ private ManagedObjectReference getVmFolder() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException { // look for a configured folder in compute state String folderPath = CustomProperties.of(this.ctx.child) .getString(RESOURCE_GROUP_NAME); if (folderPath == null) { // look for a configured folder in parent folderPath = CustomProperties.of(this.ctx.parent) .getString(RESOURCE_GROUP_NAME); } Element vmFolderElement = this.finder.vmFolder(); if (folderPath == null) { return vmFolderElement.object; } else { return getExistingOrCreateNewFolder(vmFolderElement, folderPath); } }
/** * Finds the datastore to use for the VM from the ComputeState.description.datastoreId. */ private ManagedObjectReference getDatastore() throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg, FinderException { if (this.datastore != null) { return this.datastore; } String datastorePath = this.ctx.child.description.dataStoreId; if (datastorePath == null) { ArrayOfManagedObjectReference datastores = findDatastoresForPlacement( this.ctx.computeMoRef); if (datastores == null || datastores.getManagedObjectReference().isEmpty()) { this.datastore = this.finder.defaultDatastore().object; } else { this.datastore = datastores.getManagedObjectReference().get(0); } } else { this.datastore = this.finder.datastore(datastorePath).object; } return this.datastore; }
private List<ServiceStat> getStats(StatsClient client, String type, ManagedObjectReference obj) throws RuntimeFaultFaultMsg { List<ServiceStat> metrics = null; switch (type) { case VimNames.TYPE_VM: metrics = client.retrieveMetricsForVm(obj); break; case VimNames.TYPE_COMPUTE_RESOURCE: case VimNames.TYPE_CLUSTER_COMPUTE_RESOURCE: metrics = client.retrieveMetricsForCluster(obj); break; case VimNames.TYPE_HOST: metrics = client.retrieveMetricsForHost(obj); break; default: logInfo(() -> String.format("Cannot retrieve metrics for type %s", type)); } return metrics; }
public void start(ScheduledExecutorService executorService) { Runnable task = new Runnable() { @Override public void run() { if (LeaseProgressUpdater.this.done.get()) { return; } try { updateLease(); } catch (RuntimeFaultFaultMsg | TimedoutFaultMsg e) { logger.warn("Lease timed out", e); return; } executorService.schedule(this, LEASE_UPDATE_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } }; executorService.submit(task); }
private void updateLease() throws TimedoutFaultMsg, RuntimeFaultFaultMsg { long reported = this.reported.get(); int pct = (int) Math.floor((double) reported / this.total * 100); // normalize pct if (pct > 100) { pct = 100; } else if (pct < 0) { pct = 0; } if (pct >= 100 && reported != this.total) { // rounding got to 100 but still not done pct = 99; } logger.info("Updating nfcLease {}: {} %", VimUtils.convertMoRefToString(this.nfcLease), pct); getVimPort().httpNfcLeaseProgress(this.nfcLease, pct); }
/** * This method returns a boolean value specifying whether the Task is * succeeded or failed. * * @param task * ManagedObjectReference representing the Task. * @return boolean value representing the Task result. * @throws InvalidCollectorVersionFaultMsg * * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ public boolean getTaskResultAfterDone(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { boolean retVal = false; // info has a property - state for state of the task Object[] result = wait(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); if (result[0].equals(TaskInfoState.SUCCESS)) { retVal = true; } if (result[1] instanceof LocalizedMethodFault) { throw new RuntimeException( ((LocalizedMethodFault) result[1]).getLocalizedMessage()); } return retVal; }
private List<Element> list(Element pivot, boolean traverseLeafs, String arg) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<String> parts = toParts(arg); Element root = rootElement(); if (parts.size() > 0) { switch (parts.get(0)) { case "..": // Not supported; many edge case, little value throw new FinderException("cannot traverse up a tree"); case ".": // Relative to whatever root = fullPath(pivot.object); parts = parts.subList(1, parts.size()); break; default: } } this.traverseLeafs = traverseLeafs; return this.recurse(root, parts.toArray(new String[] {})); }
public List<Element> list() throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { switch (this.start.getType()) { case "Folder": return listFolder(); case "Datacenter": return listDatacenter(); case "ComputeResource": case "ClusterComputeResource": // Treat ComputeResource and ClusterComputeResource as one and the same. // It doesn't matter from the perspective of the lister. return listComputeResource(); case "ResourcePool": return listResourcePool(); default: throw new FinderException("Unlistable type: " + this.start.getType()); } }
/** * Returns all the MOREFs of the specified type that are present under the * container * * @param container {@link ManagedObjectReference} of the container to begin the * search from * @param morefType Type of the managed entity that needs to be searched * @param morefProperties Array of properties to be fetched for the moref * @return Map of MOREF and Map of name value pair of properties requested of * the managed objects present. If none exist then empty Map is * returned * @throws InvalidPropertyFaultMsg * @throws RuntimeFaultFaultMsg */ public Map<ManagedObjectReference, Map<String, Object>> inContainerByType( ManagedObjectReference container, String morefType, String[] morefProperties, RetrieveOptions retrieveOptions) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<ObjectContent> oCont = containerViewByType(container, morefType, retrieveOptions, morefProperties).getObjects(); Map<ManagedObjectReference, Map<String, Object>> tgtMoref = new HashMap<ManagedObjectReference, Map<String, Object>>(); if (oCont != null) { for (ObjectContent oc : oCont) { Map<String, Object> propMap = new HashMap<String, Object>(); List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { propMap.put(dp.getName(), dp.getVal()); } } tgtMoref.put(oc.getObj(), propMap); } } return tgtMoref; }
public Map<String, ManagedObjectReference> toMap(RetrieveResult rslts) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { final Map<String, ManagedObjectReference> tgtMoref = new HashMap<String, ManagedObjectReference>(); String token = null; token = populate(rslts, tgtMoref); while (token != null && !token.isEmpty()) { // fetch results based on new token rslts = this.vimPort.continueRetrievePropertiesEx( this.serviceContent.getPropertyCollector(), token); token = populate(rslts, tgtMoref); } return tgtMoref; }
/** * Uses the new RetrievePropertiesEx method to emulate the now deprecated * RetrieveProperties method * * @param filterSpecs * @return list of object content * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg * @throws Exception */ private List<ObjectContent> retrievePropertiesAllObjects( List<PropertyFilterSpec> filterSpecs) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { RetrieveOptions retrieveOptions = new RetrieveOptions(); ManagedObjectReference collector = serviceContent .getPropertyCollector(); List<ObjectContent> contents = new ArrayList<ObjectContent>(); RetrieveResult results = vimPort.retrievePropertiesEx(collector, filterSpecs, retrieveOptions); if (results != null && results.getObjects() != null && !results.getObjects().isEmpty()) { contents.addAll(results.getObjects()); } String token = null; if (results != null && results.getToken() != null) { token = results.getToken(); } while (token != null && token.length() > 0) { results = vimPort.continueRetrievePropertiesEx(collector, token); token = null; if (results != null) { token = results.getToken(); if (results.getObjects() != null && !results.getObjects().isEmpty()) { contents.addAll(results.getObjects()); } } } return contents; }
public ManagedObjectReference getVirtualMachine(String vmName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { ManagedObjectReference vm = getServiceUtil().getDecendentMoRef(null, MO_TYPE_VIRTUAL_MACHINE, vmName); return vm; }
/** * Uses the new RetrievePropertiesEx method to emulate the now deprecated * RetrieveProperties method. * * @param listpfs * @return list of object content * @throws Exception */ public static List<ObjectContent> retrievePropertiesAllObjects( VimPortType vimPort, ManagedObjectReference propCollectorRef, List<PropertyFilterSpec> listpfs) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions(); List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>(); 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()); } } } return listobjcontent; }
/** * Creates HDD virtual disk */ public static VirtualDeviceConfigSpec createHdd(Integer controllerKey, int unitNumber, DiskService.DiskStateExpanded ds, String diskName, ManagedObjectReference datastore, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { return createHdd(controllerKey, unitNumber, ds, diskName, datastore, pbmSpec, true); }
/** * Creates HDD virtual disk */ public static VirtualDeviceConfigSpec createHdd(Integer controllerKey, int unitNumber, DiskService.DiskStateExpanded ds, String diskName, ManagedObjectReference datastore, List<VirtualMachineDefinedProfileSpec> pbmSpec, boolean isCreateFile) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { VirtualDiskFlatVer2BackingInfo backing = new VirtualDiskFlatVer2BackingInfo(); backing.setDiskMode(getDiskMode(ds)); VirtualDiskType provisionType = getDiskProvisioningType(ds); if (provisionType != null) { backing.setThinProvisioned(provisionType == VirtualDiskType.THIN); backing.setEagerlyScrub(provisionType == VirtualDiskType.EAGER_ZEROED_THICK); } backing.setFileName(diskName); backing.setDatastore(datastore); VirtualDisk disk = new VirtualDisk(); disk.setCapacityInKB(toKb(ds.capacityMBytes)); disk.setBacking(backing); disk.setStorageIOAllocation(getStorageIOAllocationInfo(ds)); disk.setControllerKey(controllerKey); disk.setUnitNumber(unitNumber); fillInControllerUnitNumber(ds, unitNumber); disk.setKey(-1); VirtualDeviceConfigSpec change = new VirtualDeviceConfigSpec(); change.setDevice(disk); if (pbmSpec != null) { // Add storage policy spec pbmSpec.stream().forEach(sp -> { change.getProfile().add(sp); }); } change.setOperation(VirtualDeviceConfigSpecOperation.ADD); if (isCreateFile) { change.setFileOperation(VirtualDeviceConfigSpecFileOperation.CREATE); } return change; }
/** * Create a directory at the specified path. */ public static void createFolder(Connection connection, ManagedObjectReference datacenterMoRef, String path) throws FileFaultFaultMsg, InvalidDatastoreFaultMsg, RuntimeFaultFaultMsg { ManagedObjectReference fileManager = connection.getServiceContent().getFileManager(); connection.getVimPort().makeDirectory(fileManager, path, datacenterMoRef, true); }
/** * Delete a directory at the specified path. */ public static void deleteFolder(Connection connection, ManagedObjectReference datacenterMoRef, String path) throws FileFaultFaultMsg, InvalidDatastoreFaultMsg, RuntimeFaultFaultMsg, FileNotFoundFaultMsg, InvalidDatastorePathFaultMsg { ManagedObjectReference fileManager = connection.getServiceContent().getFileManager(); connection.getVimPort().deleteDatastoreFileTask(fileManager, path, datacenterMoRef); }
public static String getDefaultDatastore(Finder finder) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<Element> datastoreList = finder.datastoreList("*"); String defaultDatastore = datastoreList.stream().map(o -> o.path.substring(o.path .lastIndexOf("/") + 1)) .findFirst() .orElse(null); return defaultDatastore; }
private List<OvfNetworkMapping> mapNetworks(List<String> ovfNetworkNames, Document ovfDoc, List<NetworkInterfaceStateWithDetails> nics) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<OvfNetworkMapping> networks = new ArrayList<>(); if (ovfNetworkNames.isEmpty() || nics.isEmpty()) { return networks; } CustomProperties custProp; ManagedObjectReference moRef; NetworkInterfaceStateWithDetails nic = nics.iterator().next(); if (nic.subnet != null) { custProp = CustomProperties.of(nic.subnet); } else { custProp = CustomProperties.of(nic.network); } moRef = custProp.getMoRef(CustomProperties.MOREF); if (moRef == null) { moRef = this.finder.networkList("*").iterator().next().object; } final ManagedObjectReference finalMoRef = moRef; ovfNetworkNames.forEach(n -> { OvfNetworkMapping nm = new OvfNetworkMapping(); nm.setName(n); nm.setNetwork(finalMoRef); networks.add(nm); }); return networks; }
private ManagedObjectReference findTemplateByName(String vmName, GetMoRef get) { try { return get.vmByVMname(vmName, this.connection.getServiceContent().getPropertyCollector()); } catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) { logger.debug("Error finding template vm[" + vmName + "]", e); return null; } }
/** * Construct VM config spec for boot disk size customization, if the user defined value is * greater then the existing size of the disk */ private VirtualDeviceConfigSpec getBootDiskCustomizeConfigSpec(DiskStateExpanded disk, VirtualDisk virtualDisk) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException { if (disk != null && virtualDisk != null) { // Resize happens if the new size is more than the existing disk size, other storage // related attributes will be applied the disk. VirtualDeviceConfigSpec hdd = resizeHdd(virtualDisk, disk); return hdd; } return null; }
@Test public void recurse() throws InvalidPropertyFaultMsg, FinderException, RuntimeFaultFaultMsg { Recurser recurser = new Recurser(this.connection); recurser.setTraverseLeafs(true); Element root = Element.asRoot(this.connection.getServiceContent().getRootFolder()); List<Element> all = recurser.recurse(root, "New Folder", "My*"); for (Element element : all) { System.out.println(element); } }
private VirtualDeviceConfigSpec resizeHdd(VirtualDisk sysdisk, DiskStateExpanded ds) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { VirtualDiskFlatVer2BackingInfo oldbacking = (VirtualDiskFlatVer2BackingInfo) sysdisk .getBacking(); VirtualDiskFlatVer2BackingInfo backing = new VirtualDiskFlatVer2BackingInfo(); backing.setDiskMode(getDiskMode(ds)); backing.setThinProvisioned(oldbacking.isThinProvisioned()); backing.setEagerlyScrub(oldbacking.isEagerlyScrub()); backing.setFileName(oldbacking.getFileName()); VirtualDisk disk = new VirtualDisk(); if (toKb(ds.capacityMBytes) > sysdisk.getCapacityInKB()) { disk.setCapacityInKB(toKb(ds.capacityMBytes)); } else { disk.setCapacityInKB(sysdisk.getCapacityInKB()); } disk.setBacking(backing); disk.setStorageIOAllocation(getStorageIOAllocationInfo(ds)); disk.setControllerKey(sysdisk.getControllerKey()); disk.setUnitNumber(sysdisk.getUnitNumber()); fillInControllerUnitNumber(ds, sysdisk.getUnitNumber()); disk.setKey(sysdisk.getKey()); VirtualDeviceConfigSpec change = new VirtualDeviceConfigSpec(); change.setDevice(disk); change.setOperation(VirtualDeviceConfigSpecOperation.EDIT); return change; }
/** * Once a vm is provisioned this method collects vsphere-assigned properties and stores them in * the {@link ComputeState#customProperties} * * @param state * @throws InvalidPropertyFaultMsg * @throws RuntimeFaultFaultMsg */ public VmOverlay enrichStateFromVm(ComputeState state) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { Map<String, Object> props = this.get.entityProps(this.vm, VimPath.vm_config_instanceUuid, VimPath.vm_config_name, VimPath.vm_config_hardware_device, VimPath.vm_runtime_powerState, VimPath.vm_runtime_host, VimPath.vm_config_guestId, VimPath.vm_guest_net, VimPath.vm_summary_guest_ipAddress, VimPath.vm_summary_guest_hostName, VimPath.vm_datastore); VmOverlay overlay = new VmOverlay(this.vm, props); state.id = overlay.getInstanceUuid(); state.primaryMAC = overlay.getPrimaryMac(); state.powerState = overlay.getPowerState(); state.address = overlay.guessPublicIpV4Address(); state.name = overlay.getName(); CustomProperties.of(state) .put(CustomProperties.MOREF, this.vm) .put(CustomProperties.TYPE, VimNames.TYPE_VM) .put(STORAGE_REFERENCE, overlay.getDatastoreMorefsAsString()); return overlay; }
/** * Creates a spec used to create the VM. * * @param datastoreName * @return * @throws InvalidPropertyFaultMsg * @throws FinderException * @throws RuntimeFaultFaultMsg */ private VirtualMachineConfigSpec buildVirtualMachineConfigSpec(String datastoreName) throws InvalidPropertyFaultMsg, FinderException, RuntimeFaultFaultMsg { String displayName = this.ctx.child.name; VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec(); spec.setName(displayName); spec.setNumCPUs((int) this.ctx.child.description.cpuCount); spec.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST_64.value()); spec.setMemoryMB(toMemoryMb(this.ctx.child.description.totalMemoryBytes)); VirtualMachineFileInfo files = new VirtualMachineFileInfo(); // Use a full path to the config file to avoid creating a VM with the same name String path = String.format("[%s] %s/%s.vmx", datastoreName, displayName, displayName); files.setVmPathName(path); spec.setFiles(files); for (NetworkInterfaceStateWithDetails ni : this.ctx.nics) { VirtualDevice nic = createNic(ni, null); addDeviceToVm(spec, nic); } VirtualDevice scsi = createScsiController(); addDeviceToVm(spec, scsi); return spec; }
private VirtualEthernetCard createNic(NetworkInterfaceStateWithDetails nicWithDetails, Integer controllerKey) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { VirtualEthernetCard nic = new VirtualE1000(); nic.setAddressType(VirtualEthernetCardMacType.GENERATED.value()); nic.setKey(-1); nic.setControllerKey(controllerKey); // Currently the network backing information is stored in both places subnet and network // If it were to exist at one state object, then it would reduce complexity further. // Question: Is it acceptable for querying subnet first and network later? Or the order // should be reversed? QueryConfigTargetRequest queryConfigTargetRequest = new QueryConfigTargetRequest(this.get, getVimPort(), this.ctx.computeMoRef); VirtualDeviceBackingInfo deviceBackingInfo = NetworkDeviceBackingFactory .getNetworkDeviceBackingInfo(nicWithDetails.subnet, queryConfigTargetRequest); if (deviceBackingInfo == null) { deviceBackingInfo = NetworkDeviceBackingFactory .getNetworkDeviceBackingInfo(nicWithDetails.network, queryConfigTargetRequest); } nic.setBacking(deviceBackingInfo); return nic; }
/** * If there is a datastore that is specified for the disk in custom properties, then it will * be used, otherwise fall back to default datastore selection if there is no storage policy * specified for this disk. If storage policy is specified for this disk, then that will be * honored. */ private ManagedObjectReference getDataStoreForDisk(DiskStateExpanded diskState, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { ManagedObjectReference datastore = null; if (diskState.storageDescription != null) { datastore = this.finder.datastore(diskState.storageDescription.id).object; } return datastore != null ? datastore : (pbmSpec == null ? getDatastore() : null); }
private ArrayOfManagedObjectReference findDatastoresForPlacement(ManagedObjectReference target) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (VimNames.TYPE_RESOURCE_POOL.equals(target.getType())) { ManagedObjectReference owner = this.get.entityProp(target, VimNames.PROPERTY_OWNER); return findDatastoresForPlacement(owner); } // at this point a target is either host or ComputeResource: both have a property // "datastore" return this.get.entityProp(target, VimPath.res_datastore); }
private ManagedObjectReference getResourcePool() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (this.resourcePool != null) { return this.resourcePool; } if (VimNames.TYPE_HOST.equals(this.ctx.computeMoRef.getType())) { // find the ComputeResource representing this host and use its root resource pool ManagedObjectReference parentCompute = this.get.entityProp(this.ctx.computeMoRef, VimPath.host_parent); this.resourcePool = this.get.entityProp(parentCompute, VimPath.res_resourcePool); } else if ( VimNames.TYPE_CLUSTER_COMPUTE_RESOURCE.equals(this.ctx.computeMoRef.getType()) || VimNames.TYPE_COMPUTE_RESOURCE .equals(this.ctx.computeMoRef.getType())) { // place in the root resource pool of a cluster this.resourcePool = this.get .entityProp(this.ctx.computeMoRef, VimPath.res_resourcePool); } else if (VimNames.TYPE_RESOURCE_POOL.equals(this.ctx.computeMoRef.getType())) { // place in the resource pool itself this.resourcePool = this.ctx.computeMoRef; } else { throw new IllegalArgumentException("Cannot place instance on " + VimUtils.convertMoRefToString(this.ctx.computeMoRef)); } return this.resourcePool; }
private ManagedObjectReference getHost() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { if (this.host != null) { return this.host; } if (VimNames.TYPE_HOST.equals(this.ctx.computeMoRef.getType())) { this.host = this.ctx.computeMoRef; } return this.host; }
/** * Create parent directory for the disk file to be created. */ private void createParentFolder(String path) throws FileFaultFaultMsg, InvalidDatastoreFaultMsg, RuntimeFaultFaultMsg { ManagedObjectReference fileManager = this.connection.getServiceContent().getFileManager(); getVimPort().makeDirectory(fileManager, path, this.diskContext.datacenterMoRef, true); }
/** * See <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.PerformanceManager.html#queryStats">queryStats method</a> * @param ctx * @return * @throws RuntimeFaultFaultMsg */ private List<ServiceStat> querySingleEntity(StatCollectionContext ctx) throws RuntimeFaultFaultMsg { List<PerfEntityMetricBase> metrics = getVimPort().queryPerf(PERF_MGR_MOREF, Collections.singletonList(ctx.getSpec())); List<ServiceStat> res = new ArrayList<>(); if (metrics.isEmpty()) { // nothing fetched return Collections.emptyList(); } // the metrics for the single entity PerfEntityMetric m = (PerfEntityMetric) metrics.get(0); for (PerfMetricSeries pms : m.getValue()) { PerfMetricId metricId = pms.getId(); PerfMetricIntSeries series = (PerfMetricIntSeries) pms; SamplesAggregator factory = ctx.getFactory(metricId.getCounterId()); PerfCounterInfo counter = this.perfCounterLookup .getCounterByKey(metricId.getCounterId()); ServiceStat stat = factory.createStat(counter, m.getSampleInfo(), series.getValue()); if (stat != null) { res.add(stat); } } return res; }
public void complete() { this.done.set(true); try { getVimPort().httpNfcLeaseProgress(this.nfcLease, 100); getVimPort().httpNfcLeaseComplete(this.nfcLease); } catch (RuntimeFaultFaultMsg | TimedoutFaultMsg | InvalidStateFaultMsg e) { logger.warn("Cannot complete nfcLease, continuing", e); } }
public void abort(LocalizedMethodFault e) { this.done.set(true); try { getVimPort().httpNfcLeaseAbort(this.nfcLease, e); } catch (RuntimeFaultFaultMsg | TimedoutFaultMsg | InvalidStateFaultMsg ex) { logger.warn("Error aborting nfcLease {}", VimUtils.convertMoRefToString(this.nfcLease), e); } }
/** * For some reason getting the state of a nfcLease returns a element instead of HttpNfcLeaseState. * This method parses the dom element to a state. * * @return * @throws InvalidPropertyFaultMsg * @throws RuntimeFaultFaultMsg */ private HttpNfcLeaseState getState() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { Object state = this.get.entityProp(this.nfcLease, PROP_STATE); if (state instanceof HttpNfcLeaseState) { return (HttpNfcLeaseState) state; } if (state instanceof org.w3c.dom.Element) { org.w3c.dom.Element e = (org.w3c.dom.Element) state; return HttpNfcLeaseState.fromValue(e.getTextContent()); } throw new IllegalStateException("Cannot get state of nfcLease"); }
/** * Method to retrieve properties of a {@link ManagedObjectReference} * * @param entityMor {@link ManagedObjectReference} of the entity * @param props Array of properties to be looked up * @return Map of the property name and its corresponding value * @throws InvalidPropertyFaultMsg If a property does not exist * @throws RuntimeFaultFaultMsg */ public Map<String, Object> entityProps( ManagedObjectReference entityMor, String... props) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { init(); final HashMap<String, Object> retVal = new HashMap<>(); // Create PropertyFilterSpec using the PropertySpec and ObjectPec PropertyFilterSpec[] propertyFilterSpecs = { new PropertyFilterSpecBuilder() .propSet( // Create Property Spec new PropertySpecBuilder() .all(Boolean.FALSE) .type(entityMor.getType()) .pathSet(props) ) .objectSet( // Now create Object Spec new ObjectSpecBuilder() .obj(entityMor) ) }; List<ObjectContent> oCont = this.vimPort.retrievePropertiesEx(this.serviceContent.getPropertyCollector(), Arrays.asList(propertyFilterSpecs), new RetrieveOptions()).getObjects(); if (oCont != null) { for (ObjectContent oc : oCont) { List<DynamicProperty> dps = oc.getPropSet(); for (DynamicProperty dp : dps) { retVal.put(dp.getName(), dp.getVal()); } } } return retVal; }