com.vmware.vim25.DynamicProperty Java Examples

The following examples show how to use com.vmware.vim25.DynamicProperty. 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: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddVM() throws Exception {

    List<DynamicProperty> properties = createVMProperties("vm1", "512", "2",
            "host1");
    VMwareVirtualMachine vm = inventory.addVirtualMachine(properties,
            serviceUtil);
    assertNotNull(vm);
    assertEquals("vm1", vm.getName());
    assertTrue(vm.getMemorySizeMB() == 512);
    assertTrue(vm.getNumCpu() == 2);

    inventory.addVirtualMachine(properties, serviceUtil);
    Mockito.verify(serviceUtil, Mockito.times(1)).getDynamicProperty(
            Matchers.any(ManagedObjectReference.class),
            Matchers.anyString());
}
 
Example #2
Source File: VmUtils.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public ManagedObjectReference getMorHost(String hostname, ConnectionResources connectionResources,
                                         ManagedObjectReference vmMor) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    ManagedObjectReference host = null;
    if (isNotBlank(hostname)) {
        host = getManagedObjectReference(hostname, connectionResources,
                ManagedObjectType.HOST_SYSTEM.getValue(), ErrorMessages.HOST_NOT_FOUND);
    } else if (StringUtils.isBlank(hostname) && vmMor != null) {
        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();
                host = virtualMachineSummary.getRuntime().getHost();
                break;
            }
            break;
        }
    } else {
        host = connectionResources.getHostMor();
    }
    return host;
}
 
Example #3
Source File: VMwareDatacenterInventory.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a host instance to the inventory based on given properties.
 *
 * @return the created host instance
 */
public VMwareHost addHostSystem(List<DynamicProperty> properties) {

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

    VMwareHost result = new VMwareHost(this);
    for (DynamicProperty dp : properties) {
        String key = dp.getName();
        if ("name".equals(key) && dp.getVal() != null) {
            result.setName(dp.getVal().toString());
        } else if ("summary.hardware.memorySize".equals(key)
                && dp.getVal() != null) {
            result.setMemorySizeMB(VMwareValue
                    .fromBytes(Long.parseLong(dp.getVal().toString()))
                    .getValue(Unit.MB));
        } else if ("summary.hardware.numCpuCores".equals(key)
                && dp.getVal() != null) {
            result.setCpuCores(Integer.parseInt(dp.getVal().toString()));
        }
    }
    hostsSystems.put(result.getName(), result);
    return result;
}
 
Example #4
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 #5
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitialize() throws Exception {

    Mockito.when(serviceUtil.getDynamicProperty(
            Matchers.any(ManagedObjectReference.class),
            Matchers.anyString())).thenReturn("hostname")
            .thenReturn("other");

    List<DynamicProperty> properties = createVMProperties("vm1", "512", "2",
            "hostname");
    inventory.addVirtualMachine(properties, serviceUtil);
    properties = createVMProperties("vm2", "4096", "4", "hostname");
    inventory.addVirtualMachine(properties, serviceUtil);
    properties = createVMProperties("vm3", "2048", "1", "otherhost");
    inventory.addVirtualMachine(properties, serviceUtil);
    properties = createHostSystemProperties("hostname", "8192", "8");
    VMwareHost host = inventory.addHostSystem(properties);
    inventory.initialize();
    assertNotNull(host);
    assertEquals(6, host.getAllocatedCPUs());
}
 
Example #6
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddHostSystem() {
    // given
    List<DynamicProperty> properties = createHostSystemProperties("host1",
            "512", "2");

    // when
    VMwareHost host = inventory.addHostSystem(properties);

    // then
    assertEquals("host1", host.getName());
    assertTrue(512 == host.getMemorySizeMB());
    assertTrue(2 == host.getCpuCores());

    host = inventory.getHost("host1");
    assertEquals("host1", host.getName());
    assertTrue(512 == host.getMemorySizeMB());
    assertTrue(2 == host.getCpuCores());
    assertTrue(host
            .getBalancer() instanceof DynamicEquipartitionStorageBalancer);
}
 
Example #7
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 #8
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDatastore() {

    List<DynamicProperty> properties = createDataStoreProperties("ds1",
            "100", "50");
    VMwareStorage storage = inventory.addStorage("host", properties);
    assertNotNull(storage);
    assertEquals("ds1", storage.getName());
    assertTrue(0.5 == storage.getLevel());

    storage = inventory.getStorage("ds1");
    assertNotNull(storage);
    assertEquals("ds1", storage.getName());
    assertTrue(0.5 == storage.getLevel());

    assertNull(inventory.getStorage("ds2"));
}
 
Example #9
Source File: HostDatastoreSystemMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public ManagedObjectReference findDatastore(String name) throws Exception {
    // added Apache CloudStack specific name convention, we will use custom field "cloud.uuid" as datastore name as well
    CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager());
    int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID);
    assert (key != 0);

    List<ObjectContent> ocs = getDatastorePropertiesOnHostDatastoreSystem(new String[] {"name", String.format("value[%d]", key)});
    if (ocs != null) {
        for (ObjectContent oc : ocs) {
            if (oc.getPropSet().get(0).getVal().equals(name))
                return oc.getObj();

            if (oc.getPropSet().size() > 1) {
                DynamicProperty prop = oc.getPropSet().get(1);
                if (prop != null && prop.getVal() != null) {
                    if (prop.getVal() instanceof CustomFieldStringValue) {
                        String val = ((CustomFieldStringValue)prop.getVal()).getValue();
                        if (val.equalsIgnoreCase(name))
                            return oc.getObj();
                    }
                }
            }
        }
    }
    return null;
}
 
Example #10
Source File: MoRefHandler.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
private static String populate(final RetrieveResult results, final Map<String, ManagedObjectReference> tgtMoref) {
    String token = null;
    if (results != null) {
        token = results.getToken();
        for (ObjectContent oc : results.getObjects()) {
            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 token;
}
 
Example #11
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public Pair<DatastoreMO, String> getOwnerDatastore(String dsFullPath) throws Exception {
    String dsName = DatastoreFile.getDatastoreNameFromPath(dsFullPath);

    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("Datastore");
    pSpec.getPathSet().add("name");

    TraversalSpec vmDatastoreTraversal = new TraversalSpec();
    vmDatastoreTraversal.setType("VirtualMachine");
    vmDatastoreTraversal.setPath("datastore");
    vmDatastoreTraversal.setName("vmDatastoreTraversal");

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

    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) {
            DynamicProperty prop = oc.getPropSet().get(0);
            if (prop.getVal().toString().equals(dsName)) {
                return new Pair<DatastoreMO, String>(new DatastoreMO(_context, oc.getObj()), dsName);
            }
        }
    }

    return null;
}
 
Example #12
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 #13
Source File: Utils.java    From GraphiteReceiver with Apache License 2.0 5 votes vote down vote up
/**
 * initClusterHostMap is a self recursive method for generating VM/ESX to Cluster Hash Map.
 * In the first iteration it gathers all clusters and in consecutive calls for each cluster it updates Hash Map.
 * The logic here is use ComputeResource Entity as a base for gathering all virtual machines and ESX Hosts.
 * As part of configurations, GraphiteReceiver invokes this method at regular intervals (configured) and during runtime
 * if VM/ESX does not exist in the hash map.
 */
public static boolean initClusterHostMap(String clusterName, ManagedObjectReference rootFolder, ExecutionContext context, Map<String,String> clusterMap){
    try {
        if(clusterName == null){
            clusterMap.clear();
        }
        VimConnection connection = context.getConnection();
        RetrieveResult retrieveResult = getRetrieveResult(clusterName, connection, rootFolder);

        while((retrieveResult != null) && (retrieveResult.getObjects() != null) && (retrieveResult.getObjects().size() > 0)){

            String token = retrieveResult.getToken();

            for(ObjectContent objectContent : retrieveResult.getObjects()){
                List<DynamicProperty> dynamicProperties = objectContent.getPropSet();
                if(clusterName != null){
                    String dpsGet = String.valueOf(dynamicProperties.get(0).getVal());
                    clusterMap.put(dpsGet.replace(" ", "_"), clusterName.replace(" ", "_"));
                } else {
                    initClusterHostMap((String) (dynamicProperties.get(0).getVal()), objectContent.getObj(), context, clusterMap);
                }
            }

            if (token == null) {
                return true;
            }
            retrieveResult = connection.getVimPort().continueRetrievePropertiesEx(connection.getPropertyCollector(), token);
        }
        return true;
    } catch(Exception e){
        logger.fatal("Critical Error Detected.");
        logger.fatal(e.getLocalizedMessage());
        return false;
    }
}
 
Example #14
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 #15
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 #16
Source File: OvfUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static HttpNfcLeaseInfo getHttpNfcLeaseInfo(final ConnectionResources connectionResources, final ManagedObjectReference httpNfcLease) throws Exception {
    final ObjectContent objectContent = GetObjectProperties.getObjectProperty(connectionResources, httpNfcLease, "info");
    final List<DynamicProperty> dynamicProperties = objectContent.getPropSet();
    if (firstElementIsOfClass(dynamicProperties, HttpNfcLeaseInfo.class)) {
        return (HttpNfcLeaseInfo) dynamicProperties.get(0).getVal();
    }
    throw new RuntimeException(LEASE_COULD_NOT_BE_OBTAINED);
}
 
Example #17
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 5 votes vote down vote up
private static List<DynamicProperty> createNullValueProperties(
        String... properties) {
    List<DynamicProperty> result = new ArrayList<DynamicProperty>();
    for (int i = 0; i < properties.length; i++) {
        DynamicProperty p = new DynamicProperty();
        p.setName(properties[i]);
        result.add(p);
    }
    return result;
}
 
Example #18
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 retrieve details 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 virtual machine
 * @return Map with String as key and value that contains returnCode of the operation, a JSON formatted string that
 *         contains details of the virtual machine or failure message and the exception if there is one
 * @throws Exception
 */
public Map<String, String> getVMDetails(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());
        ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, vmMor,
                new String[]{ManagedObjectType.SUMMARY.getValue()});

        if (objectContents != null) {
            Map<String, String> vmDetails = new HashMap<>();
            for (ObjectContent objectItem : objectContents) {
                List<DynamicProperty> vmProperties = objectItem.getPropSet();
                for (DynamicProperty propertyItem : vmProperties) {
                    VirtualMachineSummary virtualMachineSummary = (VirtualMachineSummary) propertyItem.getVal();
                    VirtualMachineConfigSummary virtualMachineConfigSummary = virtualMachineSummary.getConfig();

                    ResponseUtils.addDataToVmDetailsMap(vmDetails, virtualMachineSummary, virtualMachineConfigSummary);
                }
            }
            String responseJson = ResponseUtils.getJsonString(vmDetails);
            return ResponseUtils.getResultsMap(responseJson, Outputs.RETURN_CODE_SUCCESS);
        } else {
            return ResponseUtils.getResultsMap("Could not retrieve the details for: [" +
                    vmInputs.getVirtualMachineName() + "] VM.", Outputs.RETURN_CODE_FAILURE);
        }
    } catch (Exception ex) {
        return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
    } finally {
        if (httpInputs.isCloseSession()) {
            connectionResources.getConnection().disconnect();
            clearConnectionFromContext(httpInputs.getGlobalSessionObject());
        }
    }
}
 
Example #19
Source File: HostMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private DatastoreMO getHostDatastoreMO(String datastoreName) throws Exception {
    ObjectContent[] ocs = 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(_context, oc.getObj());
                }
            }
        }
    }
    return null;
}
 
Example #20
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 #21
Source File: DatacenterMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ManagedObjectReference getDvPortGroupMor(String dvPortGroupName) throws Exception {
    PropertySpec pSpec = new PropertySpec();
    pSpec.setType("DistributedVirtualPortgroup");
    pSpec.getPathSet().add("name");

    TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec();
    datacenter2DvPortGroupTraversal.setType("Datacenter");
    datacenter2DvPortGroupTraversal.setPath("network");
    datacenter2DvPortGroupTraversal.setName("datacenter2DvPortgroupTraversal");

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

    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(dvPortGroupName))
                        return oc.getObj();
                }
            }
        }
    }
    return null;
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 5 votes vote down vote up
/**
 * Get the required properties of the specified object.
 *
 * @param vimPort
 * @param serviceContent
 * @param moRef
 * @param type
 * @param properties
 * @return
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 */
public static List<DynamicProperty> getProperties(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference moRef,
        String type, List<String> properties)
        throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
    // Create Property Spec
    PropertySpec propertySpec = new PropertySpec();
    propertySpec.setAll(false);
    propertySpec.setType(type);
    propertySpec.getPathSet().addAll(properties);

    // Now create Object Spec
    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(moRef);
    objectSpec.setSkip(false);

    // Create PropertyFilterSpec using the PropertySpec and ObjectPec
    // created above.
    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
    listpfs.add(propertyFilterSpec);
    List<ObjectContent> listobjcontent = VimUtil
            .retrievePropertiesAllObjects(vimPort,
                    serviceContent.getPropertyCollector(), listpfs);
    assert listobjcontent != null && listobjcontent.size() > 0;
    ObjectContent contentObj = listobjcontent.get(0);
    List<DynamicProperty> objList = contentObj.getPropSet();
    return objList;
}
 
Example #28
Source File: VMwareDatacenterInventory.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a storage instance to the inventory based on given properties.
 *
 * @return the created storage instance
 */
public VMwareStorage addStorage(String host,
        List<DynamicProperty> properties) {

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

    VMwareStorage result = new VMwareStorage();
    for (DynamicProperty dp : properties) {
        String key = dp.getName();
        if ("summary.name".equals(key) && dp.getVal() != null) {
            result.setName(dp.getVal().toString());
        } else if ("summary.capacity".equals(key) && dp.getVal() != null) {
            result.setCapacity(VMwareValue
                    .fromBytes(Long.parseLong(dp.getVal().toString())));
        } else if ("summary.freeSpace".equals(key) && dp.getVal() != null) {
            result.setFreeStorage(VMwareValue
                    .fromBytes(Long.parseLong(dp.getVal().toString())));
        }
    }
    storages.put(result.getName(), result);

    if (storageByHost.containsKey(host)) {
        storageByHost.get(host).add(result);
    } else {
        List<VMwareStorage> storage = new ArrayList<VMwareStorage>();
        storage.add(result);
        storageByHost.put(host, storage);
    }
    return result;
}
 
Example #29
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddVM_nullHostSystem() throws Exception {
    Mockito.when(serviceUtil.getDynamicProperty(
            Matchers.any(ManagedObjectReference.class),
            Matchers.anyString())).thenReturn(null);
    List<DynamicProperty> properties = createVMProperties("vm", "512", "4",
            "host1");
    VMwareVirtualMachine vm = inventory.addVirtualMachine(properties,
            serviceUtil);
    assertNotNull(vm);
    assertNull(vm.getHostName());
}
 
Example #30
Source File: VMwareDatacenterInventoryTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddVM_nullValueProps() throws Exception {
    List<DynamicProperty> properties = createNullValueProperties("name",
            "summary.config.memorySizeMB", "summary.config.numCpu",
            "runtime.host");
    VMwareVirtualMachine vm = inventory.addVirtualMachine(properties,
            serviceUtil);
    assertNotNull(vm);
    assertNull(vm.getName());
}