com.vmware.vim25.ManagedObjectReference Java Examples

The following examples show how to use com.vmware.vim25.ManagedObjectReference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClusterMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception {
    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName +
                ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption);

    ManagedObjectReference morRp = getHyperHostOwnerResourcePool();
    assert (morRp != null);

    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.getValue());

    HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, null);

    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - importVmFromOVF() done");
}
 
Example #2
Source File: ClusterComputeResourceServiceTest.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
private void commonVmMockInitializations() throws Exception {
    commonMockInitializations();
    when(morObjectHandlerMock.getMorById(eq(connectionResourcesMock), eq("VirtualMachine"), anyString())).thenReturn(vmMorMock);
    when(vmMorMock.getValue()).thenReturn(VM_ID_VALUE);
    when(vmMorMock.getType()).thenReturn("VirtualMachine");
    List<ClusterDasVmConfigInfo> dasVmConfig = new ArrayList<>();
    ClusterDasVmConfigInfo clusterDasVmConfigInfo = new ClusterDasVmConfigInfo();
    ManagedObjectReference vmMor = new ManagedObjectReference();
    vmMor.setValue(VM_ID_VALUE);
    clusterDasVmConfigInfo.setKey(vmMor);
    ClusterDasVmSettings clusterDasVmSettings = new ClusterDasVmSettings();
    clusterDasVmSettings.setRestartPriority(DAS_RESTART_PRIORITY);
    clusterDasVmConfigInfo.setDasSettings(clusterDasVmSettings);
    dasVmConfig.add(clusterDasVmConfigInfo);
    doReturn(dasVmConfig).when(clusterConfigInfoExSpy, GET_DAS_VM_CONFIG);
    doReturn(clusterConfigInfoExSpy).when(clusterComputeResourceServiceSpy, GET_CLUSTER_CONFIGURATION,
            any(ConnectionResources.class), any(ManagedObjectReference.class), any(String.class));
}
 
Example #3
Source File: CreateLunTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
@Override
public void rollBack() throws Exception {
    if (volumeMO == null) {
        logger.info("Could not create the volume...");
        return;
    }
    logger.info("---------CreateLun/VolumeTask, rolling back and deleted created volume...");
    List<TaskInfo> rollBackTaskInfoList = new ArrayList<>();
    try {
        createTaskList(rollBackTaskInfoList, TaskInfoConst.Type.TASK_DELETE_LUN);
        storage.deleteVolume(volumeMO.id);
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.SUCCESS, "Delete volume finished.");
        for (ManagedObjectReference hostMo : hostMos) {
            hostServiceImpl.rescanAllHba(hostMo, serverInfo);
        }
    } catch (NullPointerException ex) {
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.ERROR,
                String.format(Locale.ROOT, "Delete volume failed: %s", ex.getMessage()));
        throw ex;
    }
}
 
Example #4
Source File: VmVappPowerOps.java    From vsphere-automation-sdk-java with MIT License 6 votes vote down vote up
/**
 * Powers on VM and wait for power on operation to complete
 *
 * @param vmName name of the vm (for logging)
 * @param vmMor vm MoRef
 */
public boolean powerOnVM(String vmName, ManagedObjectReference vmMor) {
    System.out.println("Powering on virtual machine : " + vmName + "["
                       + vmMor.getValue() + "]");
    try {
        ManagedObjectReference taskmor = vimPort.powerOnVMTask(vmMor, null);
        if (waitForValues.getTaskResultAfterDone(taskmor)) {
            System.out.println(vmName + "[" + vmMor.getValue()
                               + "] powered on successfully");
            return true;
        } else {
            System.out.println("Unable to poweron vm : " + vmName + "["
                               + vmMor.getValue() + "]");
            return false;
        }
    } catch (Exception e) {
        System.out.println("Unable to poweron vm : " + vmName + "[" + vmMor
            .getValue() + "]");
        System.out.println("Reason :" + e.getLocalizedMessage());
        return false;
    }
}
 
Example #5
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public boolean removeSnapshot(String snapshotName, boolean removeChildren) throws Exception {
    ManagedObjectReference morSnapshot = getSnapshotMor(snapshotName);
    if (morSnapshot == null) {
        s_logger.warn("Unable to find snapshot: " + snapshotName);
        return false;
    }

    ManagedObjectReference morTask = _context.getService().removeSnapshotTask(morSnapshot, removeChildren, true);
    boolean result = _context.getVimClient().waitForTask(morTask);
    if (result) {
        _context.waitForTaskProgressDone(morTask);
        return true;
    } else {
        s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    }

    return false;
}
 
Example #6
Source File: VmVappPowerOps.java    From vsphere-automation-sdk-java with MIT License 6 votes vote down vote up
/**
 * Powers off VM and waits for power off operation to complete
 *
 * @param vmName name of the vm (for logging)
 * @param vmMor vm MoRef
 */
public boolean powerOffVM(String vmName, ManagedObjectReference vmMor) {
    System.out.println("Powering off virtual machine : " + vmName + "["
                       + vmMor.getValue() + "]");
    try {
        ManagedObjectReference taskmor = vimPort.powerOffVMTask(vmMor);
        if (waitForValues.getTaskResultAfterDone(taskmor)) {
            System.out.println(vmName + "[" + vmMor.getValue()
                               + "] powered off successfully");
            return true;
        } else {
            System.out.println("Unable to poweroff vm : " + vmName + "["
                               + vmMor.getValue() + "]");
            return false;
        }
    } catch (Exception e) {
        System.out.println("Unable to poweroff vm : " + vmName + "[" + vmMor
            .getValue() + "]");
        System.out.println("Reason :" + e.getLocalizedMessage());
        return false;
    }
}
 
Example #7
Source File: ClusterMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception {
    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.getValue() + ", vm: " + vmMo.getName());

    List<ClusterHostRecommendation> candidates = recommendHostsForVm(vmMo);
    if (candidates != null && candidates.size() > 0) {
        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - findMigrationTarget() done(successfully)");
        return candidates.get(0).getHost();
    }

    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - findMigrationTarget() done(failed)");
    return null;
}
 
Example #8
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public List<Pair<Integer, ManagedObjectReference>> getAllDiskDatastores() throws Exception {
    List<Pair<Integer, ManagedObjectReference>> disks = new ArrayList<Pair<Integer, ManagedObjectReference>>();

    List<VirtualDevice> devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device");
    if (devices != null && devices.size() > 0) {
        for (VirtualDevice device : devices) {
            if (device instanceof VirtualDisk) {
                VirtualDeviceBackingInfo backingInfo = ((VirtualDisk)device).getBacking();
                if (backingInfo instanceof VirtualDiskFlatVer2BackingInfo) {
                    VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)backingInfo;
                    disks.add(new Pair<Integer, ManagedObjectReference>(new Integer(device.getKey()), diskBackingInfo.getDatastore()));
                }
            }
        }
    }

    return disks;
}
 
Example #9
Source File: HostMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception {
    assert (vmSpec != null);
    DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter());
    ManagedObjectReference morPool = getHyperHostOwnerResourcePool();

    ManagedObjectReference morTask = _context.getService().createVMTask(dcMo.getVmFolder(), vmSpec, morPool, _mor);
    boolean result = _context.getVimClient().waitForTask(morTask);

    if (result) {
        _context.waitForTaskProgressDone(morTask);
        return true;
    } else {
        s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    }
    return false;
}
 
Example #10
Source File: HostDatastoreSystemMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
    assert (exportPath != null);

    List<ManagedObjectReference> datastores = getDatastores();
    if (datastores != null && datastores.size() > 0) {
        for (ManagedObjectReference morDatastore : datastores) {
            DatastoreMO dsMo = new DatastoreMO(_context, morDatastore);
            if (dsMo.getInventoryPath().equals(exportPath))
                return morDatastore;

            NasDatastoreInfo info = getNasDatastoreInfo(morDatastore);
            if (info != null) {
                String vmwareUrl = info.getUrl();
                if (vmwareUrl.charAt(vmwareUrl.length() - 1) == '/')
                    vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1);

                URI uri = new URI(vmwareUrl);
                if (uri.getPath().equals("/" + exportPath))
                    return morDatastore;
            }
        }
    }

    return null;
}
 
Example #11
Source File: VmTemplateCapture.java    From vsphere-automation-sdk-java with MIT License 6 votes vote down vote up
/**
 * Capture the VM to the local library provided.
 *
 * @param libId
 *            identifier of the library on which vm will be captured
 */
private void captureVM(String libraryId) throws Exception {
    String entityType = "VirtualMachine"; // Substitute 'VirtualApp' for
                                          // vApp
    ManagedObjectReference entityId = VimUtil.getVM(
            this.vimAuthHelper.getVimPort(),
            this.vimAuthHelper.getServiceContent(), this.vmName);
    DeployableIdentity deployable = new DeployableIdentity();
    deployable.setType(entityType);
    deployable.setId(entityId.getValue());

    CreateTarget target = new CreateTarget();
    target.setLibraryId(libraryId);
    CreateSpec spec = new CreateSpec();
    spec.setName(this.libItemName);
    spec.setDescription("VM template created from a VM capture");

    // Create OVF library item
    CreateResult result = client.ovfLibraryItemService().create(null,
            deployable, target, spec);
    if (result.getSucceeded()) {
        System.out.println("The vm capture to content library succeeded");
    } else {
        System.out.println("The vm capture to content library failed");
    }
}
 
Example #12
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public boolean relocate(ManagedObjectReference morTargetHost) throws Exception {
    VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec();
    relocateSpec.setHost(morTargetHost);

    ManagedObjectReference morTask = _context.getService().relocateVMTask(_mor, relocateSpec, null);

    boolean result = _context.getVimClient().waitForTask(morTask);
    if (result) {
        _context.waitForTaskProgressDone(morTask);
        return true;
    } else {
        s_logger.error("VMware relocateVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    }

    return false;
}
 
Example #13
Source File: LicenseAssignmentManagerMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public boolean isFeatureSupported(String featureKey, ManagedObjectReference hostMor) throws Exception {
    boolean featureSupported = false;

    // Retrieve host license properties
    List<KeyAnyValue> props = getHostLicenseProperties(hostMor);

    // Check host license properties to see if specified feature is supported by the license.
    for (KeyAnyValue prop : props) {
        String key = prop.getKey();
        if (key.equalsIgnoreCase(LICENSE_INFO_FEATURE)) {
            KeyValue propValue = (KeyValue)prop.getValue();
            if (propValue.getKey().equalsIgnoreCase(featureKey)) {
                featureSupported = true;
                break;
            }
        }
    }

    return featureSupported;
}
 
Example #14
Source File: ClusterComputeResourceServiceTest.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@Test
public void listHostGroupsSuccess() throws Exception {
    commonMockInitializations();
    List<ClusterGroupInfo> clusterGroupInfoList = new ArrayList<>();
    clusterGroupInfoList.add(new ClusterVmGroup());
    clusterGroupInfoList.add(new ClusterVmGroup());
    ClusterConfigInfoEx clusterConfigInfoEx = new ClusterConfigInfoEx();
    clusterConfigInfoEx.getGroup().addAll(clusterGroupInfoList);
    doReturn(clusterConfigInfoEx).when(clusterComputeResourceServiceSpy, GET_CLUSTER_CONFIGURATION,
            any(ConnectionResources.class), any(ManagedObjectReference.class), any(String.class));
    whenNew(ArrayList.class).withNoArguments().thenReturn(hostGroupNameListSpy);

    String result = clusterComputeResourceServiceSpy.listGroups(httpInputsMock, "Cluster1", ",", ClusterHostGroup.class);

    verify(hostGroupNameListSpy, never()).add(any(String.class));
    assertNotNull(result);
    assertTrue(StringUtilities.isEmpty(result));
}
 
Example #15
Source File: VmwareStorageProcessor.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private String getDatastoreUuid(DatastoreMO dsMO, HostMO hostToMatchMO) throws Exception {
    List<DatastoreHostMount> datastoreHostMounts = dsMO.getHostMounts();

    for (DatastoreHostMount datastoreHostMount : datastoreHostMounts) {
        ManagedObjectReference morHost = datastoreHostMount.getKey();
        HostMO hostMO = new HostMO(dsMO.getContext(), morHost);

        if (hostMO.getHostName().equals(hostToMatchMO.getHostName())) {
            String path = datastoreHostMount.getMountInfo().getPath();

            String searchStr = "/vmfs/volumes/";
            int index = path.indexOf(searchStr);

            if (index == -1) {
                throw new CloudRuntimeException("Unable to find the following search string: " + searchStr);
            }

            return path.substring(index + searchStr.length());
        }
    }

    throw new CloudRuntimeException("Unable to locate the UUID of the datastore");
}
 
Example #16
Source File: VmUtils.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public ManagedObjectReference getMorFolder(String folderName, ConnectionResources connectionResources)
        throws Exception {
    if (StringUtils.contains(folderName, "/")) {
        return getSpecificMorFolder(connectionResources, folderName);
    } else {
        // perform a search based on name
        ManagedObjectReference folder;
        if (isNotBlank(folderName)) {
            ManagedObjectReference morRootFolder = connectionResources.getMorRootFolder();
            folder = new MorObjectHandler().getSpecificMor(connectionResources, morRootFolder,
                    FOLDER.getValue(), escapeSpecialCharacters(folderName));
            if (folder == null) {
                throw new RuntimeException(ErrorMessages.FOLDER_NOT_FOUND);
            }
        } else {
            folder = connectionResources.getVmFolderMor();
        }
        return folder;
    }
}
 
Example #17
Source File: HostMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public HostFirewallSystemMO getHostFirewallSystemMO() throws Exception {
    HostConfigManager configMgr = getHostConfigManager();
    ManagedObjectReference morFirewall = configMgr.getFirewallSystem();

    // only ESX hosts have firewall manager
    if (morFirewall != null)
        return new HostFirewallSystemMO(_context, morFirewall);
    return null;
}
 
Example #18
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 5 votes vote down vote up
public static List<DynamicProperty> createVMProperties(String name,
        String memory, String cpu, String host) {
    ManagedObjectReference mor = new ManagedObjectReference();
    mor.setValue(host);
    return createProperties("name", name, "summary.config.memorySizeMB",
            memory, "summary.config.numCpu", cpu, "runtime.host", mor);
}
 
Example #19
Source File: VmwareHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static void updateDvNicDevice(VirtualDevice nic, ManagedObjectReference morNetwork, String dvSwitchUuid) throws Exception {
    final VirtualEthernetCardDistributedVirtualPortBackingInfo dvPortBacking = new VirtualEthernetCardDistributedVirtualPortBackingInfo();
    final DistributedVirtualSwitchPortConnection dvPortConnection = new DistributedVirtualSwitchPortConnection();

    dvPortConnection.setSwitchUuid(dvSwitchUuid);
    dvPortConnection.setPortgroupKey(morNetwork.getValue());
    dvPortBacking.setPort(dvPortConnection);
    nic.setBacking(dvPortBacking);
}
 
Example #20
Source File: NetworkManager.java    From development with Apache License 2.0 5 votes vote down vote up
private static ManagedObjectReference getNetworkFromHost(VMwareClient vmw,
        ManagedObjectReference vmwInstance, String networkName)
        throws Exception {
    logger.debug("networkName: " + networkName);

    VirtualMachineRuntimeInfo vmRuntimeInfo = (VirtualMachineRuntimeInfo) vmw
            .getServiceUtil().getDynamicProperty(vmwInstance, "runtime");
    ManagedObjectReference hostRef = vmRuntimeInfo.getHost();
    List<ManagedObjectReference> networkRefList = (List<ManagedObjectReference>) vmw
            .getServiceUtil().getDynamicProperty(hostRef, "network");
    ManagedObjectReference netCard = null;
    StringBuffer networks = new StringBuffer();
    for (ManagedObjectReference networkRef : networkRefList) {
        String netCardName = (String) vmw.getServiceUtil()
                .getDynamicProperty(networkRef, "name");
        networks.append(netCardName + " ");
        if (netCardName.equalsIgnoreCase(networkName)) {
            netCard = networkRef;
            break;
        }
    }

    if (netCard == null) {
        String hostName = (String) vmw.getServiceUtil()
                .getDynamicProperty(hostRef, "name");
        logger.error("Network " + networkName + " not found on host "
                + hostName);
        logger.debug("available networks are: " + networks.toString());
        throw new Exception("Network card " + networkName
                + " not found on host " + hostName);
    }

    return netCard;
}
 
Example #21
Source File: VmService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to connect to data center to update existing devices of a virtual machine identified by the inputs
 * provided.
 *
 * @param httpInputs Object that has all the inputs necessary to made a connection to data center
 * @param vmInputs   Object that has all the specific inputs necessary to identify the targeted device
 * @return Map with String as key and value that contains returnCode of the operation, success message with task id
 *         of the execution or failure message and the exception if there is one
 * @throws Exception
 */
public Map<String, String> updateVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
    ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
    try {
        ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
                ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
        if (vmMor != null) {
            VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
            String device = Device.getValue(vmInputs.getDevice()).toLowerCase();
            if (Constants.CPU.equalsIgnoreCase(device) || Constants.MEMORY.equalsIgnoreCase(device)) {
                vmConfigSpec = new VmUtils().getUpdateConfigSpec(vmInputs, vmConfigSpec, device);
            } else {
                vmConfigSpec = new VmUtils().getAddOrRemoveSpecs(connectionResources, vmMor, vmInputs, vmConfigSpec, device);
            }

            ManagedObjectReference task = connectionResources.getVimPortType().reconfigVMTask(vmMor, vmConfigSpec);

            return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" +
                    vmInputs.getVirtualMachineName() + "] VM was successfully reconfigured. The taskId is: " +
                    task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be reconfigured.");
        } else {
            return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
        }
    } catch (Exception ex) {
        return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
    } finally {
        if (httpInputs.isCloseSession()) {
            connectionResources.getConnection().disconnect();
            clearConnectionFromContext(httpInputs.getGlobalSessionObject());
        }
    }
}
 
Example #22
Source File: VmService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to connect to data center and clone a virtual machine identified by the inputs provided.
 *
 * @param httpInputs Object that has all the inputs necessary to made a connection to data center
 * @param vmInputs   Object that has all the specific inputs necessary to identify the virtual machine that will be
 *                   cloned
 * @return Map with String as key and value that contains returnCode of the operation, success message with task id
 *         of the execution or failure message and the exception if there is one
 * @throws Exception
 */
public Map<String, String> cloneVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
    ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
    try {
        ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
                ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());

        if (vmMor != null) {
            VmUtils utils = new VmUtils();
            ManagedObjectReference folder = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
            ManagedObjectReference resourcePool = utils.getMorResourcePool(vmInputs.getCloneResourcePool(), connectionResources);
            ManagedObjectReference host = utils.getMorHost(vmInputs.getCloneHost(), connectionResources, vmMor);
            ManagedObjectReference dataStore = utils.getMorDataStore(vmInputs.getCloneDataStore(), connectionResources,
                    vmMor, vmInputs);

            VirtualMachineRelocateSpec vmRelocateSpec = utils.getVirtualMachineRelocateSpec(resourcePool, host, dataStore, vmInputs);

            VirtualMachineCloneSpec cloneSpec = new VmConfigSpecs().getCloneSpec(vmInputs, vmRelocateSpec);

            ManagedObjectReference taskMor = connectionResources.getVimPortType()
                    .cloneVMTask(vmMor, folder, vmInputs.getCloneName(), cloneSpec);

            return new ResponseHelper(connectionResources, taskMor).getResultsMap("Success: The [" +
                    vmInputs.getVirtualMachineName() + "] VM was successfully cloned. The taskId is: " +
                    taskMor.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be cloned.");
        } else {
            return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
        }
    } catch (Exception ex) {
        return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
    } finally {
        if (httpInputs.isCloseSession()) {
            connectionResources.getConnection().disconnect();
            clearConnectionFromContext(httpInputs.getGlobalSessionObject());
        }
    }
}
 
Example #23
Source File: VmUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public ManagedObjectReference getMorResourcePoolFromCluster(final ConnectionResources connectionResources, final ManagedObjectReference clusterMor,
                                                            final String resourcePoolName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    if (isNotBlank(resourcePoolName)) {
        return new MorObjectHandler().getSpecificMor(connectionResources, clusterMor,
                ManagedObjectType.RESOURCE_POOL.getValue(), resourcePoolName);
    } else {
        return new MorObjectHandler().getSpecificMor(connectionResources, clusterMor,
                ManagedObjectType.RESOURCE_POOL.getValue(), ManagedObjectType.RESOURCES.getValue());
    }
}
 
Example #24
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public boolean hasSnapshot() throws Exception {
    VirtualMachineSnapshotInfo info = getSnapshotInfo();
    if (info != null) {
        ManagedObjectReference currentSnapshot = info.getCurrentSnapshot();
        if (currentSnapshot != null) {
            return true;
        }
        List<VirtualMachineSnapshotTree> rootSnapshotList = info.getRootSnapshotList();
        if (rootSnapshotList != null && rootSnapshotList.size() > 0) {
            return true;
        }
    }
    return false;
}
 
Example #25
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void detachAllDisks() throws Exception {
    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.getValue());

    VirtualDisk[] disks = getAllDiskDevice();
    if (disks.length > 0) {
        VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[disks.length];

        for (int i = 0; i < disks.length; i++) {
            deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
            deviceConfigSpecArray[i].setDevice(disks[i]);
            deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
        }
        reConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray));

        ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
        boolean result = _context.getVimClient().waitForTask(morTask);

        if (!result) {
            if (s_logger.isTraceEnabled())
                s_logger.trace("vCenter API trace - detachAllDisk() done(failed)");
            throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
        }

        _context.waitForTaskProgressDone(morTask);
    }

    if (s_logger.isTraceEnabled())
        s_logger.trace("vCenter API trace - detachAllDisk() done(successfully)");
}
 
Example #26
Source File: VmwareStorageManagerImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private long getVMSnapshotChainSize(VmwareContext context, VmwareHypervisorHost hyperHost, String fileName, ManagedObjectReference morDs, String exceptFileName)
        throws Exception {
    long size = 0;
    DatastoreMO dsMo = new DatastoreMO(context, morDs);
    HostDatastoreBrowserMO browserMo = dsMo.getHostDatastoreBrowserMO();
    String datastorePath = "[" + dsMo.getName() + "]";
    HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();
    FileQueryFlags fqf = new FileQueryFlags();
    fqf.setFileSize(true);
    fqf.setFileOwner(true);
    fqf.setModification(true);
    searchSpec.setDetails(fqf);
    searchSpec.setSearchCaseInsensitive(false);
    searchSpec.getMatchPattern().add(fileName);
    ArrayList<HostDatastoreBrowserSearchResults> results = browserMo.searchDatastoreSubFolders(datastorePath, searchSpec);
    for (HostDatastoreBrowserSearchResults result : results) {
        if (result != null) {
            List<FileInfo> info = result.getFile();
            for (FileInfo fi : info) {
                if (exceptFileName != null && fi.getPath().contains(exceptFileName)) {
                    continue;
                } else {
                    size = size + fi.getFileSize();
                }
            }
        }
    }
    return size;
}
 
Example #27
Source File: VmUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
ManagedObjectReference getDataStoreRef(String dataStoreName, List<VirtualMachineDatastoreInfo> dataStoresList) {
    for (VirtualMachineDatastoreInfo dataStore : dataStoresList) {
        DatastoreSummary dsSummary = dataStore.getDatastore();
        if (dataStoreName.equals(dsSummary.getName())) {
            if (!dsSummary.isAccessible()) {
                throw new RuntimeException(ErrorMessages.DATA_STORE_NOT_ACCESSIBLE);
            }
            return dsSummary.getDatastore();
        }
    }
    throw new RuntimeException(ErrorMessages.DATA_STORE_NOT_FOUND);
}
 
Example #28
Source File: DeployOvfTemplateServiceTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateLeaseSetupWithClusterName() throws Exception {
    prepareMocksForCreateLeaseSetupTest(true);

    ImmutablePair<ManagedObjectReference, OvfCreateImportSpecResult> result
            = serviceSpy.createLeaseSetup(connectionResourcesMock, vmInputsMock, PATH, ovfNetworkMapMock, ovfPropertyMapMock);

    verifyMockInvocationsForCreateLeaseSetupTest(result, true);
}
 
Example #29
Source File: HostMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHAEnabled() throws Exception {
    ManagedObjectReference morParent = getParentMor();
    if (morParent.getType().equals("ClusterComputeResource")) {
        ClusterMO clusterMo = new ClusterMO(_context, morParent);
        return clusterMo.isHAEnabled();
    }

    return false;
}
 
Example #30
Source File: OvfUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static String getHttpNfcLeaseErrorState(final ConnectionResources connectionResources, final ManagedObjectReference httpNfcLease) throws Exception {
    final ObjectContent objectContent = GetObjectProperties.getObjectProperty(connectionResources, httpNfcLease, "error");
    final List<DynamicProperty> dynamicProperties = objectContent.getPropSet();
    if (firstElementIsOfClass(dynamicProperties, LocalizedMethodFault.class)) {
        return ((LocalizedMethodFault) dynamicProperties.get(0).getVal()).getLocalizedMessage();
    }
    throw new Exception(LEASE_ERROR_STATE_COULD_NOT_BE_OBTAINED);
}