Java 类com.vmware.vim25.ManagedObjectReference 实例源码

项目:oscm    文件:NetworkManager.java   
public static String getNetworkName(VMwareClient vmw,
        ManagedObjectReference vmwInstance, int numNic) throws Exception {
    logger.debug("");

    List<ManagedObjectReference> networkList = (List<ManagedObjectReference>) vmw
            .getServiceUtil().getDynamicProperty(vmwInstance, "network");

    String name = null;
    if (networkList != null && networkList.size() >= numNic) {
        name = (String) vmw.getServiceUtil()
                .getDynamicProperty(networkList.get(numNic - 1), "name");
        NetworkSummary summary = (NetworkSummary) vmw.getServiceUtil()
                .getDynamicProperty(networkList.get(numNic - 1), "summary");

        logger.debug(
                "name: " + name + " ipPoolId: " + summary.getIpPoolName()
                        + " ipPoolName: " + summary.getName());
    }

    if (name == null) {
        throw new Exception(
                "Failed to retrieve network name from template.");
    }
    return name;
}
项目:oscm    文件:NetworkManager.java   
private static void replaceNetworkAdapter(
        VirtualMachineConfigSpec vmConfigSpec, VirtualDevice oldNIC,
        ManagedObjectReference newNetworkRef, String newNetworkName)
        throws Exception {
    logger.debug("new network: " + newNetworkName);
    VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
    nicBacking.setDeviceName(newNetworkName);
    nicBacking.setNetwork(newNetworkRef);
    nicBacking.setUseAutoDetect(true);
    oldNIC.setBacking(nicBacking);

    VirtualDeviceConnectInfo info = new VirtualDeviceConnectInfo();
    info.setConnected(true);
    info.setStartConnected(true);
    info.setAllowGuestControl(true);
    oldNIC.setConnectable(info);
    // oldNIC.getConnectable().setConnected(true);
    // oldNIC.getConnectable().setStartConnected(true);
    VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
    vmDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
    vmDeviceSpec.setDevice(oldNIC);
    vmConfigSpec.getDeviceChange().add(vmDeviceSpec);
}
项目:oscm    文件:DiskManager.java   
/**
 * Reconfigures VMware system disks and data disks.
 */
public void reconfigureDisks(VirtualMachineConfigSpec vmConfigSpec,
        ManagedObjectReference vmwInstance) throws Exception {

    logger.debug("");

    long systemDiskMB = (long) paramHandler.getConfigDiskSpaceMB();
    VirtualMachineConfigInfo configSpec = (VirtualMachineConfigInfo) vmw
            .getServiceUtil().getDynamicProperty(vmwInstance, "config");
    List<VirtualDevice> devices = configSpec.getHardware().getDevice();
    VirtualDisk vdSystemDisk = getVMSystemDisk(devices,
            configSpec.getName());

    configureSystemDisk(vmConfigSpec, systemDiskMB, vdSystemDisk);
    configureDataDisks(vmConfigSpec, devices, vdSystemDisk);
}
项目:oscm    文件:VM.java   
public VM(VMwareClient vmw, String instanceName) throws Exception {
    this.vmw = vmw;
    this.instanceName = instanceName;

    vmInstance = vmw.getServiceUtil().getDecendentMoRef(null,
            "VirtualMachine", instanceName);
    configSpec = (VirtualMachineConfigInfo) vmw.getServiceUtil()
            .getDynamicProperty(vmInstance, "config");
    folder = (ManagedObjectReference) vmw.getServiceUtil()
            .getDynamicProperty(vmInstance, "parent");
    guestInfo = (GuestInfo) vmw.getServiceUtil()
            .getDynamicProperty(vmInstance, "guest");

    if (vmInstance == null || configSpec == null || folder == null
            || guestInfo == null) {
        LOG.warn("failed to retrieve VM");
        throw new Exception(
                "Failed to retrieve information of VM " + instanceName);
    }
}
项目:oscm    文件:VM.java   
public String getCPUModel(VMPropertyHandler paramHandler) throws Exception {
    String datacenter = paramHandler.getTargetDatacenter();
    ManagedObjectReference dataCenterRef = vmw.getServiceUtil()
            .getDecendentMoRef(null, "Datacenter", datacenter);
    if (dataCenterRef == null) {
        LOG.error("Datacenter not found. dataCenter: " + datacenter);
        throw new APPlatformException(Messages.get(paramHandler.getLocale(),
                "error_invalid_datacenter", new Object[] { datacenter }));
    }

    String hostName = paramHandler
            .getServiceSetting(VMPropertyHandler.TS_TARGET_HOST);
    ManagedObjectReference hostRef = vmw.getServiceUtil()
            .getDecendentMoRef(dataCenterRef, "HostSystem", hostName);
    if (hostRef == null) {
        LOG.error("Target host " + hostName + " not found");
        throw new APPlatformException(Messages.getAll("error_invalid_host",
                new Object[] { hostName }));
    }

    return (String) vmw.getServiceUtil().getDynamicProperty(hostRef,
            "summary.hardware.cpuModel");

}
项目:oscm    文件:ManagedObjectAccessor.java   
/**
 * Retrieve contents for a single object based on the property collector
 * registered with the service.
 *
 * @param collector
 *            Property collector registered with service
 * @param mobj
 *            Managed Object Reference to get contents for
 * @param properties
 *            names of properties of object to retrieve
 *
 * @return retrieved object contents
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 */
private ObjectContent[] getObjectProperties(ManagedObjectReference mobj,
        String[] properties)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    if (mobj == null) {
        return null;
    }

    PropertyFilterSpec spec = new PropertyFilterSpec();
    spec.getPropSet().add(new PropertySpec());
    if ((properties == null || properties.length == 0)) {
        spec.getPropSet().get(0).setAll(Boolean.TRUE);
    } else {
        spec.getPropSet().get(0).setAll(Boolean.FALSE);
    }
    spec.getPropSet().get(0).setType(mobj.getType());
    spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(properties));
    spec.getObjectSet().add(new ObjectSpec());
    spec.getObjectSet().get(0).setObj(mobj);
    spec.getObjectSet().get(0).setSkip(Boolean.FALSE);
    List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
    listpfs.add(spec);
    List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);
    return listobjcont.toArray(new ObjectContent[listobjcont.size()]);
}
项目:oscm    文件:VMwareClient.java   
private static ManagedObjectReference searchSnapshot(
        List<VirtualMachineSnapshotTree> tree, String id) {

    if (tree == null) {
        return null;
    }

    for (VirtualMachineSnapshotTree snapshot : tree) {
        if (snapshot.getSnapshot().getValue().equals(id)) {
            return snapshot.getSnapshot();
        }
        ManagedObjectReference mor = searchSnapshot(
                snapshot.getChildSnapshotList(), id);
        if (mor != null) {
            return mor;
        }
    }

    return null;
}
项目:oscm    文件:VMwareDatacenterInventoryTest.java   
@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());
}
项目:oscm    文件:VMwareDatacenterInventoryTest.java   
@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());
}
项目:photon-model    文件:EnumerationClient.java   
public EnumerationClient(Connection connection, ComputeStateWithDescription parent,
                         ManagedObjectReference datacenter) {
    super(connection);

    if (datacenter == null) {
        // / the regionId is used as a ref to a vSphere datacenter name
        this.datacenter = VimUtils.convertStringToMoRef(parent.description.regionId);
    } else {
        this.datacenter = datacenter;
    }

    if (this.datacenter == null) {
        throw new IllegalStateException("Datacenter cannot be extracted from compute resources"
                + " and is not explicitly provided");
    }
    this.getMoRef = new GetMoRef(connection);
    this.finder = new Finder(connection, datacenter);
}
项目:photon-model    文件:VSphereAdapterResourceEnumerationService.java   
/**
 * Retreives all tags for a MoRef from an endpoint.
 *
 * @param endpoint
 * @param ref
 * @param tenantLinks
 * @return empty list if no tags found, never null
 */
private List<TagState> retrieveAttachedTags(VapiConnection endpoint,
        ManagedObjectReference ref, List<String> tenantLinks) throws IOException, RpcException {
    TaggingClient taggingClient = endpoint.newTaggingClient();
    List<String> tagIds = taggingClient.getAttachedTags(ref);

    List<TagState> res = new ArrayList<>();
    for (String id : tagIds) {
        TagState cached = this.tagCache.get(id, newTagRetriever(taggingClient));
        if (cached != null) {
            TagState tag = TagsUtil.newTagState(cached.key, cached.value, true, tenantLinks);
            res.add(tag);
        }
    }

    return res;
}
项目:photon-model    文件:DeletePortgroupFlow.java   
private DeferredResult<Void> deletePortgroup(Operation stateOp) {
    this.networkState = stateOp.getBody(NetworkState.class);

    DeferredResult<Void> res = new DeferredResult<>();

    ManagedObjectReference pgRef = CustomProperties.of(this.subnetState)
            .getMoRef(CustomProperties.MOREF);

    if (pgRef == null) {
        // a provisioning has failed mid-flight, just proceed, skipping actual vc call
        res.complete(null);
        return res;
    }

    getVsphereIoPool().submit(getService(),
            this.networkState.adapterManagementReference,
            this.networkState.authCredentialsLink,
            deletePortgroupInVsphere(res));

    return res;
}
项目:photon-model    文件:InstanceClient.java   
public ComputeState createInstanceFromTemplate(ManagedObjectReference template)
        throws Exception {
    ManagedObjectReference vm = cloneVm(template);

    if (vm == null) {
        // vm was created by someone else
        return null;
    }
    // store reference to created vm for further processing
    this.vm = vm;

    customizeAfterClone();

    ComputeState state = new ComputeState();
    state.resourcePoolLink = VimUtils
            .firstNonNull(this.ctx.child.resourcePoolLink, this.ctx.parent.resourcePoolLink);

    return state;
}
项目:photon-model    文件:InstanceClient.java   
private boolean isSameDatastore(ManagedObjectReference datastore, ManagedObjectReference vm,
        GetMoRef get) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    if (datastore == null) {
        return false;
    }
    ArrayOfManagedObjectReference datastores = get.entityProp(vm,
            VimPath.vm_datastore);
    if (null != datastores) {
        for (ManagedObjectReference p : datastores.getManagedObjectReference()) {
            if (p.getValue().equals(datastore.getValue())) {
                return true;
            }
        }
    }
    return false;
}
项目:photon-model    文件:WaitForValues.java   
private PropertyFilterSpec propertyFilterSpec(ManagedObjectReference objmor,
        String[] filterProps, String[] propsToMatch) {
    PropertyFilterSpec spec = new PropertyFilterSpec();
    ObjectSpec oSpec = new ObjectSpec();
    oSpec.setObj(objmor);
    oSpec.setSkip(Boolean.FALSE);
    spec.getObjectSet().add(oSpec);

    Set<String> uniqPropSet = new HashSet<>(Arrays.asList(filterProps));
    uniqPropSet.addAll(Arrays.asList(propsToMatch));

    PropertySpec pSpec = new PropertySpec();
    pSpec.getPathSet().addAll(new ArrayList<>(uniqPropSet));
    pSpec.setType(objmor.getType());
    spec.getPropSet().add(pSpec);
    return spec;
}
项目:photon-model    文件:VimUtilsTest.java   
@Test
public void convertStringToMoRef() {
    ManagedObjectReference ref = new ManagedObjectReference();
    String type = "Datastore";
    String value = "ds-123";

    ref.setType(type);
    ref.setValue(value);
    String s = VimUtils.convertMoRefToString(ref);

    assertEquals(type + ":" + value, s);

    ManagedObjectReference conv = VimUtils.convertStringToMoRef(s);
    assertEquals(type, conv.getType());
    assertEquals(value, conv.getValue());
}
项目:photon-model    文件:InstanceClient.java   
/**
 * Finds the datastore to use for the VM from the ComputeState.description.datastoreId.
 */
private ManagedObjectReference getDatastore()
        throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg, FinderException {
    if (this.datastore != null) {
        return this.datastore;
    }

    String datastorePath = this.ctx.child.description.dataStoreId;

    if (datastorePath == null) {
        ArrayOfManagedObjectReference datastores = findDatastoresForPlacement(
                this.ctx.computeMoRef);
        if (datastores == null || datastores.getManagedObjectReference().isEmpty()) {
            this.datastore = this.finder.defaultDatastore().object;
        } else {
            this.datastore = datastores.getManagedObjectReference().get(0);
        }
    } else {
        this.datastore = this.finder.datastore(datastorePath).object;
    }

    return this.datastore;
}
项目:photon-model    文件:GetMoRef.java   
public static String populate(final RetrieveResult rslts,
        final Map<String, ManagedObjectReference> tgtMoref) {
    String token = null;
    if (rslts != null) {
        token = rslts.getToken();
        for (ObjectContent oc : rslts.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;
}
项目:vsphere-automation-sdk-java    文件:VimUtil.java   
public static boolean createSnapshot(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference vmMor,
        String snapshotname, String description) {
    WaitForValues waitForValues = new WaitForValues(vimPort,
            serviceContent);
    System.out.println("Taking snapshot : [" + snapshotname + "]");
    try {
        ManagedObjectReference taskMor = vimPort.createSnapshotTask(vmMor,
                snapshotname, description, false, false);
        if (waitForValues.getTaskResultAfterDone(taskMor)) {
            System.out.println("Snapshot - [" + snapshotname
                    + "] Creation Successful");
            return true;
        } else {
            System.out.println(
                    "Snapshot - [" + snapshotname + "] Creation Failed");
            return false;
        }
    } catch (Exception e) {
        System.out.println(
                "Snapshot - [" + snapshotname + "] Creation Failed");
        System.out.println("Reason :" + e.getLocalizedMessage());
        return false;
    }
}
项目:photon-model    文件:LibraryClient.java   
private ObjectNode makeSpec(ManagedObjectReference datastore,
        VirtualMachineDefinedProfileSpec pbmSpec, String vmName,
        Map<String, String> networkMappings,
        VirtualDiskType diskType) {
    ObjectNode res = newNode();
    ObjectNode t = res.putObject(K_STRUCTURE)
            .putObject("com.vmware.vcenter.ovf.library_item.resource_pool_deployment_spec");
    t.put("accept_all_EULA", true);

    // Only one of datastore / policy can be set. Not both. If datastore is present that will
    // be given preference
    if (datastore != null) {
        t.putObject("default_datastore_id").put(K_OPTIONAL, datastore.getValue());
    } else if (pbmSpec != null) {
        t.putObject("storage_profile_id").put(K_OPTIONAL, pbmSpec.getProfileId());
    }

    if (diskType != null) {
        t.putObject("storage_provisioning").put(K_OPTIONAL, diskType.value());
    }

    t.putObject("name").put(K_OPTIONAL, vmName);
    return res;
}
项目:oscm    文件:NetworkManager.java   
public static int getNumberOfNICs(VMwareClient vmw,
        ManagedObjectReference vmwInstance) throws Exception {
    logger.debug("");

    VirtualMachineConfigInfo configInfo = (VirtualMachineConfigInfo) vmw
            .getServiceUtil().getDynamicProperty(vmwInstance, "config");
    List<VirtualEthernetCard> vmNics = getNetworkAdapter(configInfo);
    return vmNics.size();
}
项目:oscm    文件:NetworkManager.java   
/**
 * Replaces the NICs in the given VM.
 *
 * @param vmw
 *            connected VMware client entity
 * @param paramHandler
 *            entity which holds all properties of the instance
 * @param vmwInstance
 *            the virtual machine that gets reconfigured
 */
public static void configureNetworkAdapter(VMwareClient vmw,
        VirtualMachineConfigSpec vmConfigSpec,
        VMPropertyHandler paramHandler, ManagedObjectReference vmwInstance)
        throws Exception {
    logger.debug("");

    VirtualMachineConfigInfo configInfo = (VirtualMachineConfigInfo) vmw
            .getServiceUtil().getDynamicProperty(vmwInstance, "config");
    List<VirtualEthernetCard> vmNics = getNetworkAdapter(configInfo);

    int numberOfNICs = Integer.parseInt(paramHandler
            .getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS));

    if (numberOfNICs != vmNics.size()) {
        throw new Exception(
                "the number of NICs in virtual machine does not match the service parameter. VM: "
                        + configInfo.getName() + " NICs: " + vmNics.size()
                        + " " + VMPropertyHandler.TS_NUMBER_OF_NICS + ": "
                        + numberOfNICs);
    }

    for (int i = 1; i <= numberOfNICs; i++) {
        String newNetworkName = paramHandler.getNetworkAdapter(i);
        VirtualEthernetCard vmNic = vmNics.get(i - 1);
        String vmNetworkName = getNetworkName(vmw, vmwInstance, i);
        if (newNetworkName != null && newNetworkName.length() > 0
                && !newNetworkName.equals(vmNetworkName)) {
            ManagedObjectReference newNetworkRef = getNetworkFromHost(vmw,
                    vmwInstance, newNetworkName);

            replaceNetworkAdapter(vmConfigSpec, vmNic, newNetworkRef,
                    newNetworkName);
        } else {
            connectNIC(vmConfigSpec, vmNic, vmNetworkName);
        }
    }
}
项目:oscm    文件:NetworkManager.java   
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;
}
项目:oscm    文件:SnapshotActions.java   
@StateMachineAction
public String deleteSnapshots(String instanceId,
        ProvisioningSettings settings,
        @SuppressWarnings("unused") InstanceStatus result) {

    VMPropertyHandler ph = new VMPropertyHandler(settings);
    try (VMwareClient client = new VMwareClientFactory("en")
            .getInstance(ph);) {

        ManagedObjectReference snapshot = client.findSnapshot(
                ph.getInstanceName(),
                ph.getServiceSetting(VMPropertyHandler.SNAPSHOT_ID));
        if (snapshot == null) {
            logger.info("Found no old snapshot to delete for instance "
                    + instanceId + ", virtual system '"
                    + ph.getInstanceName() + "' and snapshot id "
                    + ph.getServiceSetting(VMPropertyHandler.SNAPSHOT_ID));
            return EVENT_SUCCESS;
        }

        boolean removeChildren = false;
        boolean consolidate = true;
        ManagedObjectReference removeTask = client.getService()
                .removeSnapshotTask(snapshot, removeChildren, consolidate);

        ph.setTask(client.retrieveTaskInfo(removeTask));
        return EVENT_RUN;
    } catch (Exception e) {
        String message = "Failed to delete old snapshot for instance "
                + instanceId + " and snapshot id "
                + ph.getServiceSetting(VMPropertyHandler.SNAPSHOT_ID);
        logger.error(message, e);
        ph.setSetting(VMPropertyHandler.SM_ERROR_MESSAGE, message);
        return EVENT_FAILED;
    }
}
项目:oscm    文件:SnapshotActions.java   
@StateMachineAction
@Override
protected String successfulTask(TaskInfo taskInfo, VMPropertyHandler ph) {
    ph.setSetting(VMPropertyHandler.GUEST_READY_TIMEOUT_REF,
            String.valueOf(System.currentTimeMillis()));
    if (TASK_NAME_CREATE_SNAPSHOT.equals(taskInfo.getName())) {
        ManagedObjectReference mor = (ManagedObjectReference) taskInfo
                .getResult();
        ph.setSetting(VMPropertyHandler.SNAPSHOT_ID, mor.getValue());
    }
    return EVENT_SUCCESS;
}
项目:oscm    文件:Actions.java   
protected TaskInfo getTaskInfo(VMwareClient vmw,
        VMPropertyHandler paramHandler) throws Exception {

    String instanceId = paramHandler.getInstanceName();
    String taskKey = paramHandler
            .getServiceSetting(VMPropertyHandler.TASK_KEY);
    logger.debug("VM: " + instanceId + " taskId: " + taskKey);
    if (taskKey == null || "".equals(taskKey)) {
        return null;
    }

    VimPortType service = vmw.getConnection().getService();
    ManagedObjectReference taskManager = vmw.getConnection()
            .getServiceContent().getTaskManager();
    ManagedObjectReference taskHistoryCollector = service
            .createCollectorForTasks(taskManager, new TaskFilterSpec());
    try {
        service.resetCollector(taskHistoryCollector);
        service.readNextTasks(taskHistoryCollector, 100);
        List<TaskInfo> taskList = vmw.getConnection().getService()
                .readPreviousTasks(taskHistoryCollector, 100);

        if (taskList != null) {
            for (TaskInfo taskInfo : taskList) {
                if (taskInfo != null && taskKey.equals(taskInfo.getKey())) {
                    logTaskInfo(taskInfo);
                    return taskInfo;
                }
            }
        }

        logger.error("Task not found. VM: " + instanceId + " taskId: "
                + taskKey);
        return null;
    } finally {
        service.destroyCollector(taskHistoryCollector);
    }
}
项目:oscm    文件:DiskManager.java   
private VirtualDeviceConfigSpec createNewDataDisk(VirtualDisk vdSystemDisk,
        long newDiskSpace, int deviceKey, int unitNumber) throws Exception {

    logger.info("reconfigureDisks() create data disk space with "
            + newDiskSpace + " KB");

    ManagedObjectReference vmDatastore = ((VirtualDeviceFileBackingInfo) vdSystemDisk
            .getBacking()).getDatastore();
    String vmDatastoreName = (String) vmw.getServiceUtil()
            .getDynamicProperty(vmDatastore, "summary.name");

    VirtualDisk vdDataDisk = new VirtualDisk();
    VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo();
    diskfileBacking.setFileName("[" + vmDatastoreName + "]");
    diskfileBacking.setDiskMode("persistent");

    vdDataDisk.setKey(deviceKey);
    vdDataDisk.setControllerKey(vdSystemDisk.getControllerKey());
    vdDataDisk.setUnitNumber(new Integer(unitNumber));
    vdDataDisk.setBacking(diskfileBacking);
    vdDataDisk.setCapacityInKB(newDiskSpace);

    VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
    vmDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
    vmDeviceSpec
            .setFileOperation(VirtualDeviceConfigSpecFileOperation.CREATE);
    vmDeviceSpec.setDevice(vdDataDisk);

    return vmDeviceSpec;
}
项目:oscm    文件:VM.java   
public TaskInfo start() throws Exception {
    LOG.debug("instanceName: " + instanceName);
    ManagedObjectReference startTask = vmw.getConnection().getService()
            .powerOnVMTask(vmInstance, null);

    TaskInfo tInfo = (TaskInfo) vmw.getServiceUtil()
            .getDynamicProperty(startTask, "info");
    return tInfo;
}
项目:oscm    文件:VM.java   
/**
 * Reconfigures VMware instance. Memory, CPU, disk space and network
 * adapter. The VM has been created and must be stopped to reconfigure the
 * hardware.
 */
public TaskInfo reconfigureVirtualMachine(VMPropertyHandler paramHandler)
        throws Exception {
    LOG.debug("instanceName: " + instanceName);

    VimPortType service = vmw.getConnection().getService();
    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();

    vmConfigSpec
            .setMemoryMB(Long.valueOf(paramHandler.getConfigMemoryMB()));
    vmConfigSpec.setNumCPUs(Integer.valueOf(paramHandler.getConfigCPUs()));

    String reqUser = paramHandler
            .getServiceSetting(VMPropertyHandler.REQUESTING_USER);

    String comment = Messages.get(paramHandler.getLocale(), "vm_comment",
            new Object[] { paramHandler.getSettings().getOrganizationName(),
                    paramHandler.getSettings().getSubscriptionId(),
                    reqUser });
    String annotation = vmConfigSpec.getAnnotation();
    comment = updateComment(comment, annotation);
    vmConfigSpec.setAnnotation(comment);

    DiskManager diskManager = new DiskManager(vmw, paramHandler);
    diskManager.reconfigureDisks(vmConfigSpec, vmInstance);

    NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler,
            vmInstance);

    LOG.debug("Call vSphere API: reconfigVMTask()");
    ManagedObjectReference reconfigureTask = service
            .reconfigVMTask(vmInstance, vmConfigSpec);

    return (TaskInfo) vmw.getServiceUtil()
            .getDynamicProperty(reconfigureTask, "info");
}
项目:oscm    文件:VM.java   
public TaskInfo updateCommentField(String comment) throws Exception {
    LOG.debug("instanceName: " + instanceName + " comment: " + comment);
    VimPortType service = vmw.getConnection().getService();
    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
    String annotation = vmConfigSpec.getAnnotation();
    comment = updateComment(comment, annotation);
    vmConfigSpec.setAnnotation(comment);
    LOG.debug("Call vSphere API: reconfigVMTask()");
    ManagedObjectReference reconfigureTask = service
            .reconfigVMTask(vmInstance, vmConfigSpec);

    return (TaskInfo) vmw.getServiceUtil()
            .getDynamicProperty(reconfigureTask, "info");
}
项目:oscm    文件:VM.java   
/**
 * Delete VMware instance on vSphere server.
 * 
 * @param vmw
 *            connected VMware client entity
 * @param instanceId
 *            id of the instance
 */
public TaskInfo delete() throws Exception {
    LOG.debug("Call vSphere API: destroyTask() instanceName: "
            + instanceName);
    ManagedObjectReference startTask = vmw.getConnection().getService()
            .destroyTask(vmInstance);

    return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(startTask,
            "info");
}
项目:oscm    文件:ManagedObjectAccessor.java   
public List<DynamicProperty> getDynamicProperty(ManagedObjectReference mor,
        String[] propertyNames) throws Exception {
    ObjectContent[] objContent = getObjectProperties(mor, propertyNames);
    if (objContent != null) {
        return objContent[0].getPropSet();
    }
    return null;
}
项目:oscm    文件:ManagedObjectAccessor.java   
/**
 * Uses the new RetrievePropertiesEx method to emulate the now deprecated
 * RetrieveProperties method
 *
 * @param filterSpecs
 * @return list of object content
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 * @throws Exception
 */
private List<ObjectContent> retrievePropertiesAllObjects(
        List<PropertyFilterSpec> filterSpecs)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {

    RetrieveOptions retrieveOptions = new RetrieveOptions();
    ManagedObjectReference collector = serviceContent
            .getPropertyCollector();

    List<ObjectContent> contents = new ArrayList<ObjectContent>();

    RetrieveResult results = vimPort.retrievePropertiesEx(collector,
            filterSpecs, retrieveOptions);
    if (results != null && results.getObjects() != null
            && !results.getObjects().isEmpty()) {
        contents.addAll(results.getObjects());
    }
    String token = null;
    if (results != null && results.getToken() != null) {
        token = results.getToken();
    }
    while (token != null && token.length() > 0) {
        results = vimPort.continueRetrievePropertiesEx(collector, token);
        token = null;
        if (results != null) {
            token = results.getToken();
            if (results.getObjects() != null
                    && !results.getObjects().isEmpty()) {
                contents.addAll(results.getObjects());
            }
        }
    }

    return contents;
}
项目:oscm    文件:VMwareClient.java   
public ManagedObjectReference getVirtualMachine(String vmName)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {

    ManagedObjectReference vm = getServiceUtil().getDecendentMoRef(null,
            MO_TYPE_VIRTUAL_MACHINE, vmName);
    return vm;
}
项目:oscm    文件:VMwareClient.java   
public ManagedObjectReference findSnapshot(String vmName, String snapshotId)
        throws Exception {

    ManagedObjectReference vm = getVirtualMachine(vmName);
    VirtualMachineSnapshotInfo info = (VirtualMachineSnapshotInfo) getServiceUtil()
            .getDynamicProperty(vm, PROPERTY_SNAPSHOT);
    if (info == null) {
        return null;
    }
    return searchSnapshot(info.getRootSnapshotList(), snapshotId);
}
项目:oscm    文件:VMwareDatacenterInventoryTest.java   
@Before
public void setup() throws Exception {
    inventory = new VMwareDatacenterInventory();
    serviceUtil = Mockito.mock(ManagedObjectAccessor.class);
    Mockito.when(serviceUtil.getDynamicProperty(
            Matchers.any(ManagedObjectReference.class),
            Matchers.anyString())).thenReturn("hostname");
}
项目:oscm    文件:VMwareDatacenterInventoryTest.java   
@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());
}
项目:oscm    文件:VMwareDatacenterInventoryTest.java   
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);
}
项目:photon-model    文件:ComputeResourceOverlay.java   
public Collection<ManagedObjectReference> getHosts() {
    ArrayOfManagedObjectReference hosts = (ArrayOfManagedObjectReference) getOrDefault(
            VimPath.res_host, null);
    if (hosts != null) {
        return hosts.getManagedObjectReference();
    } else {
        return Collections.emptyList();
    }
}
项目:photon-model    文件:ComputeResourceOverlay.java   
public List<ManagedObjectReference> getDatastore() {
    ArrayOfManagedObjectReference res = (ArrayOfManagedObjectReference) getOrDefault(VimPath.res_datastore, null);
    if (res == null) {
        return Collections.emptyList();
    } else {
        return res.getManagedObjectReference();
    }
}