Java Code Examples for com.vmware.vim25.ObjectContent#getPropSet()

The following examples show how to use com.vmware.vim25.ObjectContent#getPropSet() . 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: HypervisorHostHelper.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static VirtualMachineMO findVmFromObjectContent(VmwareContext context, ObjectContent[] ocs, String name, String instanceNameCustomField) {

        if (ocs != null && ocs.length > 0) {
            for (ObjectContent oc : ocs) {
                String vmNameInvCenter = null;
                String vmInternalCSName = null;
                List<DynamicProperty> objProps = oc.getPropSet();
                if (objProps != null) {
                    for (DynamicProperty objProp : objProps) {
                        if (objProp.getName().equals("name")) {
                            vmNameInvCenter = (String)objProp.getVal();
                        } else if (objProp.getName().contains(instanceNameCustomField)) {
                            if (objProp.getVal() != null)
                                vmInternalCSName = ((CustomFieldStringValue)objProp.getVal()).getValue();
                        }

                        if ((vmNameInvCenter != null && name.equalsIgnoreCase(vmNameInvCenter)) || (vmInternalCSName != null && name.equalsIgnoreCase(vmInternalCSName))) {
                            VirtualMachineMO vmMo = new VirtualMachineMO(context, oc.getObj());
                            return vmMo;
                        }
                    }
                }
            }
        }
        return null;
    }
 
Example 2
Source File: MoRefHandler.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
/**
 * 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 {
    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(false).type(entityMor.getType()).pathSet(props))
            .objectSet(
            // Now create Object Spec
            new ObjectSpecBuilder().obj(entityMor))};

    List<ObjectContent> objCont = vimPort.retrievePropertiesEx(serviceContent.getPropertyCollector(),
            Arrays.asList(propertyFilterSpecs), new RetrieveOptions()).getObjects();

    if (objCont != null) {
        for (ObjectContent oc : objCont) {
            List<DynamicProperty> dps = oc.getPropSet();
            for (DynamicProperty dp : dps) {
                retVal.put(dp.getName(), dp.getVal());
            }
        }
    }

    return retVal;
}
 
Example 3
Source File: DatacenterMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public VirtualMachineMO checkIfVmAlreadyExistsInVcenter(String vmNameOnVcenter, String vmNameInCS) throws Exception {
    int key = getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_VM_INTERNAL_NAME);
    if (key == 0) {
        s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
    }

    List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name", String.format("value[%d]", key)});
    if (ocs != null && ocs.size() > 0) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> props = oc.getPropSet();
            if (props != null) {
                String vmVcenterName = null;
                String vmInternalCSName = null;
                for (DynamicProperty prop : props) {
                    if (prop.getName().equals("name")) {
                        vmVcenterName = prop.getVal().toString();
                    }
                    if (prop.getName().startsWith("value[") && prop.getVal() != null) {
                        vmInternalCSName = ((CustomFieldStringValue)prop.getVal()).getValue();
                    }
                }
                if (vmNameOnVcenter.equals(vmVcenterName)) {
                    if (vmInternalCSName != null && !vmInternalCSName.isEmpty() && !vmNameInCS.equals(vmInternalCSName)) {
                        return (new VirtualMachineMO(_context, oc.getObj()));
                    }
                }
            }
        }
    }
    return null;
}
 
Example 4
Source File: DatacenterMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public List<VirtualMachineMO> findVmByNameAndLabel(String vmLabel) throws Exception {
    CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager());
    int key = cfmMo.getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_UUID);
    assert (key != 0);

    List<VirtualMachineMO> list = new ArrayList<VirtualMachineMO>();

    List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name", String.format("value[%d]", key)});
    if (ocs != null && ocs.size() > 0) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> props = oc.getPropSet();
            if (props != null) {
                for (DynamicProperty prop : props) {
                    if (prop.getVal() != null) {
                        if (prop.getName().equalsIgnoreCase("name")) {
                            if (prop.getVal().toString().equals(vmLabel)) {
                                list.add(new VirtualMachineMO(_context, oc.getObj()));
                                break;        // break out inner loop
                            }
                        } else if (prop.getVal() instanceof CustomFieldStringValue) {
                            String val = ((CustomFieldStringValue)prop.getVal()).getValue();
                            if (val.equals(vmLabel)) {
                                list.add(new VirtualMachineMO(_context, oc.getObj()));
                                break;        // break out inner loop
                            }
                        }
                    }
                }
            }
        }
    }
    return list;
}
 
Example 5
Source File: HypervisorHostHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static DatastoreMO getHyperHostDatastoreMO(VmwareHypervisorHost hyperHost, String datastoreName) throws Exception {
    ObjectContent[] ocs = hyperHost.getDatastorePropertiesOnHyperHost(new String[] {"name"});
    if (ocs != null && ocs.length > 0) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> objProps = oc.getPropSet();
            if (objProps != null) {
                for (DynamicProperty objProp : objProps) {
                    if (objProp.getVal().toString().equals(datastoreName))
                        return new DatastoreMO(hyperHost.getContext(), oc.getObj());
                }
            }
        }
    }
    return null;
}
 
Example 6
Source File: HostMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ManagedObjectReference getNetworkMor(String portGroupName) throws Exception {
    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("Network");
    pSpec.getPathSet().add("summary.name");

    TraversalSpec host2NetworkTraversal = new TraversalSpec();
    host2NetworkTraversal.setType("HostSystem");
    host2NetworkTraversal.setPath("network");
    host2NetworkTraversal.setName("host2NetworkTraversal");

    ObjectSpec oSpec = new ObjectSpec();
    oSpec.setObj(_mor);
    oSpec.setSkip(Boolean.TRUE);
    oSpec.getSelectSet().add(host2NetworkTraversal);

    PropertyFilterSpec pfSpec = new PropertyFilterSpec();
    pfSpec.getPropSet().add(pSpec);
    pfSpec.getObjectSet().add(oSpec);
    List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
    pfSpecArr.add(pfSpec);

    List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);

    if (ocs != null) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> props = oc.getPropSet();
            if (props != null) {
                for (DynamicProperty prop : props) {
                    if (prop.getVal().equals(portGroupName))
                        return oc.getObj();
                }
            }
        }
    }
    return null;
}
 
Example 7
Source File: VmUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public ManagedObjectReference getMorDataStore(String dataStoreName, ConnectionResources connectionResources,
                                              ManagedObjectReference vmMor, VmInputs vmInputs)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    ManagedObjectReference dataStore = null;
    if (isNotBlank(dataStoreName)) {
        ManagedObjectReference cloneHostMor = getMorHost(vmInputs.getCloneHost(), connectionResources, vmMor);
        ConfigTarget configTarget = getHostConfigTarget(connectionResources, cloneHostMor);
        List<VirtualMachineDatastoreInfo> dataStoreInfoList = configTarget.getDatastore();
        for (VirtualMachineDatastoreInfo dataStoreInfo : dataStoreInfoList) {
            if (vmInputs.getCloneDataStore().equals(dataStoreInfo.getDatastore().getName())) {
                dataStore = getDataStoreRef(vmInputs.getCloneDataStore(), dataStoreInfoList);
                break;
            }
        }

        if (dataStore == null) {
            throw new RuntimeException(ErrorMessages.DATA_STORE_NOT_FOUND);
        }
    } else {
        ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, vmMor,
                new String[]{ManagedObjectType.SUMMARY.getValue()});

        for (ObjectContent objectItem : objectContents) {
            List<DynamicProperty> vmProperties = objectItem.getPropSet();
            for (DynamicProperty propertyItem : vmProperties) {
                VirtualMachineSummary virtualMachineSummary = (VirtualMachineSummary) propertyItem.getVal();
                String vmPathName = virtualMachineSummary.getConfig().getVmPathName();
                dataStoreName = vmPathName.substring(1, vmPathName.indexOf(Constants.RIGHT_SQUARE_BRACKET));
                dataStore = getDataStore(dataStoreName, connectionResources, vmMor);
                break;
            }
            break;
        }
    }
    return dataStore;
}
 
Example 8
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);
}
 
Example 9
Source File: OvfUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static String getHttpNfcLeaseState(final ConnectionResources connectionResources, final ManagedObjectReference httpNfcLease) throws Exception {
    final ObjectContent objectContent = GetObjectProperties.getObjectProperty(connectionResources, httpNfcLease, "state");
    final List<DynamicProperty> dynamicProperties = objectContent.getPropSet();
    if (dynamicProperties.size() != 0) {
        return ((TextImpl) ((ElementNSImpl) dynamicProperties.get(0).getVal()).getFirstChild()).getData();
    }
    throw new Exception(LEASE_STATE_COULD_NOT_BE_OBTAINED);
}
 
Example 10
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public VirtualMachineFileLayoutEx getFileLayout() throws Exception {
    VirtualMachineFileLayoutEx fileLayout = null;
    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("VirtualMachine");
    pSpec.getPathSet().add("layoutEx");

    ObjectSpec oSpec = new ObjectSpec();
    oSpec.setObj(_mor);
    oSpec.setSkip(Boolean.FALSE);

    PropertyFilterSpec pfSpec = new PropertyFilterSpec();
    pfSpec.getPropSet().add(pSpec);
    pfSpec.getObjectSet().add(oSpec);
    List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
    pfSpecArr.add(pfSpec);

    List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);

    if (ocs != null) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> props = oc.getPropSet();
            if (props != null) {
                for (DynamicProperty prop : props) {
                    if (prop.getName().equals("layoutEx")) {
                        fileLayout = (VirtualMachineFileLayoutEx)prop.getVal();
                        break;
                    }
                }
            }
        }
    }

    return fileLayout;
}
 
Example 11
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public String getSnapshotDescriptorDatastorePath() throws Exception {
    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("VirtualMachine");
    pSpec.getPathSet().add("name");
    pSpec.getPathSet().add("config.files");

    ObjectSpec oSpec = new ObjectSpec();
    oSpec.setObj(_mor);
    oSpec.setSkip(Boolean.FALSE);

    PropertyFilterSpec pfSpec = new PropertyFilterSpec();
    pfSpec.getPropSet().add(pSpec);
    pfSpec.getObjectSet().add(oSpec);
    List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
    pfSpecArr.add(pfSpec);

    List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
    assert (ocs != null);

    String vmName = null;
    VirtualMachineFileInfo fileInfo = null;

    assert (ocs.size() == 1);
    for (ObjectContent oc : ocs) {
        List<DynamicProperty> props = oc.getPropSet();
        if (props != null) {
            assert (props.size() == 2);

            for (DynamicProperty prop : props) {
                if (prop.getName().equals("name")) {
                    vmName = prop.getVal().toString();
                } else {
                    fileInfo = (VirtualMachineFileInfo)prop.getVal();
                }
            }
        }
    }
    assert (vmName != null);
    assert (fileInfo != null);

    // .vmsd file exists at the same directory of .vmx file
    DatastoreFile vmxFile = new DatastoreFile(fileInfo.getVmPathName());
    return vmxFile.getCompanionPath(vmName + ".vmsd");
}
 
Example 12
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Map<String, ManagedObjectReference> getVms(VMwareConnection connection) throws Exception {
    Map<String, ManagedObjectReference> nameToVm = new HashMap<>();

    ManagedObjectReference rootFolder = connection.getServiceContent().getRootFolder();

    TraversalSpec tSpec = getVMTraversalSpec();

    PropertySpec propertySpec = new PropertySpec();

    propertySpec.setAll(Boolean.FALSE);
    propertySpec.getPathSet().add("name");
    propertySpec.setType("VirtualMachine");

    ObjectSpec objectSpec = new ObjectSpec();

    objectSpec.setObj(rootFolder);
    objectSpec.setSkip(Boolean.TRUE);
    objectSpec.getSelectSet().add(tSpec);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();

    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> lstPfs = new ArrayList<>(1);

    lstPfs.add(propertyFilterSpec);

    VimPortType vimPortType = connection.getVimPortType();
    ManagedObjectReference propertyCollector = connection.getServiceContent().getPropertyCollector();

    List<ObjectContent> lstObjectContent = retrievePropertiesAllObjects(lstPfs, vimPortType, propertyCollector);

    if (lstObjectContent != null) {
        for (ObjectContent oc : lstObjectContent) {
            ManagedObjectReference mor = oc.getObj();
            List<DynamicProperty> dps = oc.getPropSet();
            String vmName = null;

            if (dps != null) {
                for (DynamicProperty dp : dps) {
                    vmName = (String)dp.getVal();
                }
            }

            if (vmName != null) {
                nameToVm.put(vmName, mor);
            }
        }
    }

    return nameToVm;
}
 
Example 13
Source File: VmwareClient.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
/**
 * Get the ManagedObjectReference for an item under the
 * specified root folder that has the type and name specified.
 *
 * @param root a root folder if available, or null for default
 * @param type type of the managed object
 * @param name name to match
 *
 * @return First ManagedObjectReference of the type / name pair found
 */
public ManagedObjectReference getDecendentMoRef(ManagedObjectReference root, String type, String name) throws Exception {
    if (name == null || name.length() == 0) {
        return null;
    }

    try {
        // Create PropertySpecs
        PropertySpec pSpec = new PropertySpec();
        pSpec.setType(type);
        pSpec.setAll(false);
        pSpec.getPathSet().add("name");

        ObjectSpec oSpec = new ObjectSpec();
        oSpec.setObj(root);
        oSpec.setSkip(false);
        oSpec.getSelectSet().addAll(constructCompleteTraversalSpec());

        PropertyFilterSpec spec = new PropertyFilterSpec();
        spec.getPropSet().add(pSpec);
        spec.getObjectSet().add(oSpec);
        List<PropertyFilterSpec> specArr = new ArrayList<PropertyFilterSpec>();
        specArr.add(spec);

        ManagedObjectReference propCollector = getPropCol();
        List<ObjectContent> ocary = vimPort.retrieveProperties(propCollector, specArr);

        if (ocary == null || ocary.size() == 0) {
            return null;
        }

        // filter through retrieved objects to get the first match.
        for (ObjectContent oc : ocary) {
            ManagedObjectReference mor = oc.getObj();
            List<DynamicProperty> propary = oc.getPropSet();
            if (type == null || type.equals(mor.getType())) {
                if (propary.size() > 0) {
                    String propval = (String)propary.get(0).getVal();
                    if (propval != null && name.equalsIgnoreCase(propval))
                        return mor;
                }
            }
        }
    } catch (InvalidPropertyFaultMsg invalidPropertyException) {
        s_logger.debug("Failed to get Vmware ManagedObjectReference for name: " + name + " and type: " + type + " due to " + invalidPropertyException.getMessage());
        throw invalidPropertyException;
    } catch (RuntimeFaultFaultMsg runtimeFaultException) {
        s_logger.debug("Failed to get Vmware ManagedObjectReference for name: " + name + " and type: " + type + " due to " + runtimeFaultException.getMessage());
        throw runtimeFaultException;
    }

    return null;
}
 
Example 14
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> getEntityProps(VMwareConnection connection, ManagedObjectReference entityMor, String[] props)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    Map<String, Object> retVal = new HashMap<>();

    PropertySpec propertySpec = new PropertySpec();

    propertySpec.setAll(Boolean.FALSE);
    propertySpec.setType(entityMor.getType());
    propertySpec.getPathSet().addAll(Arrays.asList(props));

    ObjectSpec objectSpec = new ObjectSpec();

    objectSpec.setObj(entityMor);

    // Create PropertyFilterSpec using the PropertySpec and ObjectPec created above.
    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();

    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<>();

    propertyFilterSpecs.add(propertyFilterSpec);

    RetrieveResult rslts = connection.getVimPortType().retrievePropertiesEx(connection.getServiceContent().getPropertyCollector(),
            propertyFilterSpecs, new RetrieveOptions());
    List<ObjectContent> listobjcontent = new ArrayList<>();

    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 = connection.getVimPortType().continueRetrievePropertiesEx(connection.getServiceContent().getPropertyCollector(),
                token);

        token = null;

        if (rslts != null) {
            token = rslts.getToken();

            if (rslts.getObjects() != null && !rslts.getObjects().isEmpty()) {
                listobjcontent.addAll(rslts.getObjects());
            }
        }
    }

    for (ObjectContent oc : listobjcontent) {
        List<DynamicProperty> dps = oc.getPropSet();

        if (dps != null) {
            for (DynamicProperty dp : dps) {
                retVal.put(dp.getName(), dp.getVal());
            }
        }
    }

    return retVal;
}
 
Example 15
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public List<NetworkDetails> getNetworksWithDetails() throws Exception {
    List<NetworkDetails> networks = new ArrayList<NetworkDetails>();

    int gcTagKey = getCustomFieldKey("Network", CustomFieldConstants.CLOUD_GC);

    if (gcTagKey == 0) {
        gcTagKey = getCustomFieldKey("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP);
        s_logger.debug("The custom key for dvPortGroup is : " + gcTagKey);
    }

    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("Network");
    pSpec.getPathSet().add("name");
    pSpec.getPathSet().add("vm");
    pSpec.getPathSet().add(String.format("value[%d]", gcTagKey));

    TraversalSpec vm2NetworkTraversal = new TraversalSpec();
    vm2NetworkTraversal.setType("VirtualMachine");
    vm2NetworkTraversal.setPath("network");
    vm2NetworkTraversal.setName("vm2NetworkTraversal");

    ObjectSpec oSpec = new ObjectSpec();
    oSpec.setObj(_mor);
    oSpec.setSkip(Boolean.TRUE);
    oSpec.getSelectSet().add(vm2NetworkTraversal);

    PropertyFilterSpec pfSpec = new PropertyFilterSpec();
    pfSpec.getPropSet().add(pSpec);
    pfSpec.getObjectSet().add(oSpec);
    List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
    pfSpecArr.add(pfSpec);

    List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);

    if (ocs != null && ocs.size() > 0) {
        for (ObjectContent oc : ocs) {
            ArrayOfManagedObjectReference morVms = null;
            String gcTagValue = null;
            String name = null;

            for (DynamicProperty prop : oc.getPropSet()) {
                if (prop.getName().equals("name"))
                    name = prop.getVal().toString();
                else if (prop.getName().equals("vm"))
                    morVms = (ArrayOfManagedObjectReference)prop.getVal();
                else if (prop.getName().startsWith("value[")) {
                    CustomFieldStringValue val = (CustomFieldStringValue)prop.getVal();
                    if (val != null)
                        gcTagValue = val.getValue();
                }
            }

            NetworkDetails details =
                    new NetworkDetails(name, oc.getObj(), (morVms != null ? morVms.getManagedObjectReference().toArray(
                            new ManagedObjectReference[morVms.getManagedObjectReference().size()]) : null), gcTagValue);

            networks.add(details);
        }
        s_logger.debug("Retrieved " + networks.size() + " networks with key : " + gcTagKey);
    }

    return networks;
}
 
Example 16
Source File: HostMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private void loadVmCache() throws Exception {
    if (s_logger.isDebugEnabled())
        s_logger.debug("load VM cache on host");

    _vmCache.clear();

    int key = getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_VM_INTERNAL_NAME);
    if (key == 0) {
        s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
    }

    // name is the name of the VM as it appears in vCenter. The CLOUD_VM_INTERNAL_NAME custom
    // field value contains the name of the VM as it is maintained internally by cloudstack (i-x-y).
    ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] {"name", "value[" + key + "]"});
    if (ocs != null && ocs.length > 0) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> props = oc.getPropSet();
            if (props != null) {
                String vmVcenterName = null;
                String vmInternalCSName = null;
                for (DynamicProperty prop : props) {
                    if (prop.getName().equals("name")) {
                        vmVcenterName = prop.getVal().toString();
                    } else if (prop.getName().startsWith("value[")) {
                        if (prop.getVal() != null)
                            vmInternalCSName = ((CustomFieldStringValue)prop.getVal()).getValue();
                    }
                }
                String vmName = null;
                if (vmInternalCSName != null && isUserVMInternalCSName(vmInternalCSName)) {
                    vmName = vmInternalCSName;
                } else {
                    vmName = vmVcenterName;
                }

                if (s_logger.isTraceEnabled())
                    s_logger.trace("put " + vmName + " into host cache");

                _vmCache.put(vmName, new VirtualMachineMO(_context, oc.getObj()));
            }
        }
    }
}
 
Example 17
Source File: HostMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public HashMap<String, Integer> getVmVncPortsOnHost() throws Exception {

        int key = getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_VM_INTERNAL_NAME);
        if (key == 0) {
            s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
        }

        ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] {"name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]", "value[" + key + "]"});

        HashMap<String, Integer> portInfo = new HashMap<String, Integer>();
        if (ocs != null && ocs.length > 0) {
            for (ObjectContent oc : ocs) {
                List<DynamicProperty> objProps = oc.getPropSet();
                if (objProps != null) {
                    String vmName = null;
                    String value = null;
                    String vmInternalCSName = null;
                    for (DynamicProperty objProp : objProps) {
                        if (objProp.getName().equals("name")) {
                            vmName = (String)objProp.getVal();
                        } else if (objProp.getName().startsWith("value[")) {
                            if (objProp.getVal() != null)
                                vmInternalCSName = ((CustomFieldStringValue)objProp.getVal()).getValue();
                        } else {
                            OptionValue optValue = (OptionValue)objProp.getVal();
                            value = (String)optValue.getValue();
                        }
                    }

                    if (vmInternalCSName != null && isUserVMInternalCSName(vmInternalCSName))
                        vmName = vmInternalCSName;

                    if (vmName != null && value != null) {
                        portInfo.put(vmName, Integer.parseInt(value));
                    }
                }
            }
        }

        return portInfo;
    }
 
Example 18
Source File: ManagedObjectAccessor.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all the managed object references of the specified type that are
 * present under the container.
 *
 * @param folder
 *            {@link ManagedObjectReference} of the container to begin the
 *            search from
 * @param morefType
 *            type of the managed entity that needs to be searched
 *
 * @return map of name and MoRef of the managed objects present. May be
 *         empty but not <code>null</code>
 *
 * @throws InvalidPropertyFaultMsg
 * @throws RuntimeFaultFaultMsg
 */
public Map<String, ManagedObjectReference> getMoRefsInContainerByType(
        ManagedObjectReference folder, String morefType)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {

    String PROP_ME_NAME = "name";
    ManagedObjectReference viewManager = serviceContent.getViewManager();
    ManagedObjectReference containerView = vimPort.createContainerView(
            viewManager, folder, Arrays.asList(morefType), true);

    Map<String, ManagedObjectReference> tgtMoref = new HashMap<String, ManagedObjectReference>();

    PropertySpec propertySpec = new PropertySpec();
    propertySpec.setAll(Boolean.FALSE);
    propertySpec.setType(morefType);
    propertySpec.getPathSet().add(PROP_ME_NAME);

    TraversalSpec ts = new TraversalSpec();
    ts.setName("view");
    ts.setPath("view");
    ts.setSkip(Boolean.FALSE);
    ts.setType("ContainerView");

    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(containerView);
    objectSpec.setSkip(Boolean.TRUE);
    objectSpec.getSelectSet().add(ts);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<PropertyFilterSpec>();
    propertyFilterSpecs.add(propertyFilterSpec);

    RetrieveResult rslts = vimPort.retrievePropertiesEx(
            serviceContent.getPropertyCollector(), propertyFilterSpecs,
            new RetrieveOptions());

    List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>();
    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.length() > 0) {
        rslts = vimPort.continueRetrievePropertiesEx(
                serviceContent.getPropertyCollector(), token);
        token = null;
        if (rslts != null) {
            token = rslts.getToken();
            if (rslts.getObjects() != null
                    && !rslts.getObjects().isEmpty()) {
                listobjcontent.addAll(rslts.getObjects());
            }
        }
    }
    for (ObjectContent oc : listobjcontent) {
        ManagedObjectReference mr = oc.getObj();
        String entityNm = null;
        List<DynamicProperty> dps = oc.getPropSet();
        if (dps != null) {
            for (DynamicProperty dp : dps) {
                entityNm = (String) dp.getVal();
            }
        }
        tgtMoref.put(entityNm, mr);
    }
    return tgtMoref;
}
 
Example 19
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Retrieves the vm managed object reference for the specified vm name using
 * the vim port type.
 *
 * @param vimPortType
 * @param serviceContent
 * @param vmname
 * @return
 * @throws NotFoundFaultMsg
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 */
public static ManagedObjectReference getVM(VimPortType vimPortType,
        ServiceContent serviceContent, String vmname)
        throws NotFoundFaultMsg, InvalidPropertyFaultMsg,
        RuntimeFaultFaultMsg {
    ManagedObjectReference propCollectorRef = serviceContent
            .getPropertyCollector();
    ManagedObjectReference rootFolderRef = serviceContent.getRootFolder();

    ManagedObjectReference retVmRef = null;
    TraversalSpec tSpec = getVMTraversalSpec();

    PropertySpec propertySpec = new PropertySpec();
    propertySpec.setAll(Boolean.FALSE);
    propertySpec.getPathSet().add("name");
    propertySpec.setType("VirtualMachine");

    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(rootFolderRef);
    objectSpec.setSkip(Boolean.TRUE);
    objectSpec.getSelectSet().add(tSpec);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
    listpfs.add(propertyFilterSpec);
    List<ObjectContent> listobjcont = retrievePropertiesAllObjects(
            vimPortType, propCollectorRef, listpfs);

    if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
            ManagedObjectReference mr = oc.getObj();
            String vmnm = null;
            List<DynamicProperty> dps = oc.getPropSet();
            if (dps != null) {
                for (DynamicProperty dp : dps) {
                    vmnm = (String) dp.getVal();
                }
            }
            if (vmnm != null && vmnm.equals(vmname)) {
                retVmRef = mr;
                break;
            }
        }
    }
    if (retVmRef == null) {
        throw new NotFoundFaultMsg("VM Not Found - " + vmname,
                new NotFound());
    }
    return retVmRef;
}
 
Example 20
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Retrieves the cluster managed object reference for the specified cluster
 * name using the vim port type.
 *
 * @param vimPortType
 *
 * @param serviceContent
 *            {@link ServiceContent}
 * @param clusterName
 *            name of the cluster to be searched for.
 * @return {@link ManagedObjectReference}
 * @throws InvalidPropertyFaultMsg
 * @throws RuntimeFaultFaultMsg
 * @throws NotFoundFaultMsg
 */
public static ManagedObjectReference getCluster(VimPortType vimPortType,
        ServiceContent serviceContent, String clusterName)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg,
        NotFoundFaultMsg {

    // Spec to allow recursion on the Folder to Folder traversal
    SelectionSpec folderToFolderSelection = new SelectionSpec();
    folderToFolderSelection.setName("folderToFolder");

    SelectionSpec dcToHostFolderSelection = new SelectionSpec();
    dcToHostFolderSelection.setName("dcToHostFolder");

    // spec to traverse from Datacenter to hostFolder
    TraversalSpec dcToHostFolderTraversal = new TraversalSpec();
    dcToHostFolderTraversal.setName("dcToHostFolder");
    dcToHostFolderTraversal.setPath("hostFolder");
    dcToHostFolderTraversal.setType("Datacenter");
    dcToHostFolderTraversal.getSelectSet().addAll(
            Arrays.asList(new SelectionSpec[] { folderToFolderSelection }));
    dcToHostFolderTraversal.setSkip(false);

    // spec to traverse from Folder to a child folder
    TraversalSpec folderToFolderTraversal = new TraversalSpec();
    folderToFolderTraversal.setName("folderToFolder");
    folderToFolderTraversal.setPath("childEntity");
    folderToFolderTraversal.setType("Folder");
    folderToFolderTraversal.getSelectSet()
            .addAll(Arrays.asList(new SelectionSpec[] {
                folderToFolderSelection, dcToHostFolderSelection }));
    folderToFolderTraversal.setSkip(false);

    PropertySpec propertySpec = new PropertySpec();
    propertySpec.getPathSet()
            .addAll(Arrays.asList(new String[] { "name" }));
    propertySpec.setType("ClusterComputeResource");

    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(serviceContent.getRootFolder());
    objectSpec.getSelectSet().addAll(Arrays.asList(new SelectionSpec[] {
        folderToFolderTraversal, dcToHostFolderTraversal }));
    objectSpec.setSkip(false);

    // Create PropertyFilterSpec using the PropertySpec and ObjectPec
    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet()
            .addAll(Arrays.asList(new PropertySpec[] { propertySpec }));
    propertyFilterSpec.getObjectSet()
            .addAll(Arrays.asList(new ObjectSpec[] { objectSpec }));

    ManagedObjectReference morPropertyCollector = serviceContent
            .getPropertyCollector();
    List<ObjectContent> objectContents = vimPortType.retrieveProperties(
            morPropertyCollector,
            Arrays.asList(new PropertyFilterSpec[] { propertyFilterSpec }));

    for (ObjectContent objectContent : objectContents) {
        ManagedObjectReference clusterManagedObjectReference = objectContent
                .getObj();
        List<DynamicProperty> dynamicProperties = objectContent
                .getPropSet();
        for (DynamicProperty dynamicProperty : dynamicProperties) {
            if (dynamicProperty.getName().equalsIgnoreCase("name")) {
                if (dynamicProperty.getVal().toString()
                        .equalsIgnoreCase(clusterName)) {
                    return clusterManagedObjectReference;
                }
            }
        }
    }
    throw new NotFoundFaultMsg("Cluster Not Found - " + clusterName,
            new NotFound());
}