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

项目:cloudstack    文件:VirtualMachineMO.java   
public String getVmxHttpAccessUrl() throws Exception {
    Pair<DatacenterMO, String> dcInfo = getOwnerDatacenter();

    VirtualMachineFileInfo fileInfo = getFileInfo();
    String vmxFilePath = fileInfo.getVmPathName();
    String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/");

    StringBuffer sb = new StringBuffer("https://" + _context.getServerAddress() + "/folder/");
    sb.append(URLEncoder.encode(vmxPathTokens[2].trim(), "UTF-8"));
    sb.append("/");
    sb.append(URLEncoder.encode(vmxPathTokens[3].trim(), "UTF-8"));
    sb.append("?dcPath=");
    sb.append(URLEncoder.encode(dcInfo.second(), "UTF-8"));
    sb.append("&dsName=");
    sb.append(URLEncoder.encode(vmxPathTokens[1].trim(), "UTF-8"));

    return sb.toString();
}
项目:cloudstack    文件:VirtualMachineMO.java   
public String[] getCurrentSnapshotDiskChainDatastorePaths(String diskDevice) throws Exception {
    HostMO hostMo = getRunningHost();
    List<Pair<ManagedObjectReference, String>> mounts = hostMo.getDatastoreMountsOnHost();
    VirtualMachineFileInfo vmFileInfo = getFileInfo();

    SnapshotDescriptor descriptor = getSnapshotDescriptor();
    SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain();

    List<String> diskDsFullPaths = new ArrayList<String>();
    for (int i = 0; i < snapshotInfo.length; i++) {
        SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks();
        if (disks != null) {
            for (SnapshotDescriptor.DiskInfo disk : disks) {
                String deviceNameInDisk = disk.getDeviceName();
                if (diskDevice == null || diskDevice.equalsIgnoreCase(deviceNameInDisk)) {
                    String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, mounts, disk.getDiskFileName());
                    diskDsFullPaths.add(vmdkFullDsPath);
                }
            }
        }
    }
    return diskDsFullPaths.toArray(new String[0]);
}
项目:photon-model    文件:InstanceClient.java   
/**
 * Creates a spec used to create the VM.
 *
 * @param datastoreName
 * @return
 * @throws InvalidPropertyFaultMsg
 * @throws FinderException
 * @throws RuntimeFaultFaultMsg
 */
private VirtualMachineConfigSpec buildVirtualMachineConfigSpec(String datastoreName)
        throws InvalidPropertyFaultMsg, FinderException, RuntimeFaultFaultMsg {
    String displayName = this.ctx.child.name;

    VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec();
    spec.setName(displayName);
    spec.setNumCPUs((int) this.ctx.child.description.cpuCount);
    spec.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST_64.value());
    spec.setMemoryMB(toMemoryMb(this.ctx.child.description.totalMemoryBytes));

    VirtualMachineFileInfo files = new VirtualMachineFileInfo();
    // Use a full path to the config file to avoid creating a VM with the same name
    String path = String.format("[%s] %s/%s.vmx", datastoreName, displayName, displayName);
    files.setVmPathName(path);
    spec.setFiles(files);

    for (NetworkInterfaceStateWithDetails ni : this.ctx.nics) {
        VirtualDevice nic = createNic(ni, null);
        addDeviceToVm(spec, nic);
    }

    VirtualDevice scsi = createScsiController();
    addDeviceToVm(spec, scsi);

    return spec;
}
项目:cloudstack    文件:VirtualMachineMO.java   
/**
 * Retrieve path info to access VM files via vSphere web interface
 * @return [0] vm-name, [1] data-center-name, [2] datastore-name
 * @throws Exception
 */
public String[] getHttpAccessPathInfo() throws Exception {
    String[] pathInfo = new String[3];

    Pair<DatacenterMO, String> dcInfo = getOwnerDatacenter();

    VirtualMachineFileInfo fileInfo = getFileInfo();
    String vmxFilePath = fileInfo.getVmPathName();
    String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/");
    assert (vmxPathTokens.length == 4);
    pathInfo[1] = vmxPathTokens[1].trim();                            // vSphere vm name
    pathInfo[2] = dcInfo.second();                                    // vSphere datacenter name
    pathInfo[3] = vmxPathTokens[0].trim();                            // vSphere datastore name
    return pathInfo;
}
项目:cloudstack    文件:VirtualMachineMO.java   
public void redoRegistration(ManagedObjectReference morHost) throws Exception {
    String vmName = getVmName();
    VirtualMachineFileInfo vmFileInfo = getFileInfo();
    boolean isTemplate = isTemplate();

    HostMO hostMo;
    if (morHost != null)
        hostMo = new HostMO(getContext(), morHost);
    else
        hostMo = getRunningHost();

    ManagedObjectReference morFolder = getParentMor();
    ManagedObjectReference morPool = hostMo.getHyperHostOwnerResourcePool();

    _context.getService().unregisterVM(_mor);

    ManagedObjectReference morTask = _context.getService().registerVMTask(morFolder, vmFileInfo.getVmPathName(), vmName, false, morPool, hostMo.getMor());

    boolean result = _context.getVimClient().waitForTask(morTask);
    if (!result) {
        throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    } else {
        _context.waitForTaskProgressDone(morTask);
        if (isTemplate) {
            VirtualMachineMO vmNewRegistration = hostMo.findVmOnHyperHost(vmName);
            assert (vmNewRegistration != null);
            vmNewRegistration.markAsTemplate();
        }
    }
}
项目:vijava    文件:CreateVM.java   
public static void main(String[] args) throws Exception 
{  
  if(args.length!=3)
  {
    System.out.println("Usage: java CreateVM <url> " +
          "<username> <password>");
    System.exit(0);
  }

  String dcName = "ha-datacenter";
  String vmName = "vimasterVM";
  long memorySizeMB = 500;
  int cupCount = 1;
  String guestOsId = "sles10Guest";
  long diskSizeKB = 1000000;
  // mode: persistent|independent_persistent,
  // independent_nonpersistent
  String diskMode = "persistent";
  String datastoreName = "storage1 (2)";
  String netName = "VM Network";
  String nicName = "Network Adapter 1";

  ServiceInstance si = new ServiceInstance(
      new URL(args[0]), args[1], args[2], true);

  Folder rootFolder = si.getRootFolder();

  Datacenter dc = (Datacenter) new InventoryNavigator(
      rootFolder).searchManagedEntity("Datacenter", dcName);
  ResourcePool rp = (ResourcePool) new InventoryNavigator(
      dc).searchManagedEntities("ResourcePool")[0];

  Folder vmFolder = dc.getVmFolder();

  // create vm config spec
  VirtualMachineConfigSpec vmSpec = 
    new VirtualMachineConfigSpec();
  vmSpec.setName(vmName);
  vmSpec.setAnnotation("VirtualMachine Annotation");
  vmSpec.setMemoryMB(memorySizeMB);
  vmSpec.setNumCPUs(cupCount);
  vmSpec.setGuestId(guestOsId);

  // create virtual devices
  int cKey = 1000;
  VirtualDeviceConfigSpec scsiSpec = createScsiSpec(cKey);
  VirtualDeviceConfigSpec diskSpec = createDiskSpec(
      datastoreName, cKey, diskSizeKB, diskMode);
  VirtualDeviceConfigSpec nicSpec = createNicSpec(
      netName, nicName);

  vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[] 
      {scsiSpec, diskSpec, nicSpec});

  // create vm file info for the vmx file
  VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();
  vmfi.setVmPathName("["+ datastoreName +"]");
  vmSpec.setFiles(vmfi);

  // call the createVM_Task method on the vm folder
  Task task = vmFolder.createVM_Task(vmSpec, rp, null);
  String result = task.waitForMe();       
  if(result == Task.SUCCESS) 
  {
    System.out.println("VM Created Sucessfully");
  }
  else 
  {
    System.out.println("VM could not be created. ");
  }
}
项目:cloudstack    文件:HypervisorHostHelper.java   
public static VirtualMachineMO createWorkerVM(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception {

        // Allow worker VM to float within cluster so that we will have better chance to
        // create it successfully
        ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
        if (morCluster != null)
            hyperHost = new ClusterMO(hyperHost.getContext(), morCluster);

        VirtualMachineMO workingVM = null;
        VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
        vmConfig.setName(vmName);
        vmConfig.setMemoryMB((long)4);
        vmConfig.setNumCPUs(1);
        vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value());
        VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
        fileInfo.setVmPathName(dsMo.getDatastoreRootPath());
        vmConfig.setFiles(fileInfo);

        VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
        scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
        scsiController.setBusNumber(0);
        scsiController.setKey(1);
        VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
        scsiControllerSpec.setDevice(scsiController);
        scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

        vmConfig.getDeviceChange().add(scsiControllerSpec);
        if (hyperHost.createVm(vmConfig)) {
            // Ugly work-around, it takes time for newly created VM to appear
            for (int i = 0; i < 10 && workingVM == null; i++) {
                workingVM = hyperHost.findVmOnHyperHost(vmName);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    s_logger.debug("[ignored] interupted while waiting to config vm.");
                }
            }
        }

        if (workingVM != null) {
            workingVM.setCustomFieldValue(CustomFieldConstants.CLOUD_WORKER, "true");
            String workerTag = String.format("%d-%s", System.currentTimeMillis(), hyperHost.getContext().getStockObject("noderuninfo"));
            workingVM.setCustomFieldValue(CustomFieldConstants.CLOUD_WORKER_TAG, workerTag);
        }
        return workingVM;
    }
项目:cloudstack    文件:VirtualMachineMO.java   
public VirtualMachineFileInfo getFileInfo() throws Exception {
    return (VirtualMachineFileInfo)_context.getVimClient().getDynamicProperty(_mor, "config.files");
}
项目:cloudstack    文件:VirtualMachineMO.java   
@Deprecated
public void setSnapshotDirectory(String snapshotDir) throws Exception {
    VirtualMachineFileInfo fileInfo = getFileInfo();
    Pair<DatacenterMO, String> dcInfo = getOwnerDatacenter();
    String vmxUrl = _context.composeDatastoreBrowseUrl(dcInfo.second(), fileInfo.getVmPathName());
    byte[] vmxContent = _context.getResourceContent(vmxUrl);

    BufferedReader in = null;
    BufferedWriter out = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    boolean replaced = false;
    try {
        in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmxContent),"UTF-8"));
        out = new BufferedWriter(new OutputStreamWriter(bos,"UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            if (line.startsWith("workingDir")) {
                replaced = true;
                out.write(String.format("workingDir=\"%s\"", snapshotDir));
                out.newLine();
            } else {
                out.write(line);
                out.newLine();
            }
        }

        if (!replaced) {
            out.newLine();
            out.write(String.format("workingDir=\"%s\"", snapshotDir));
            out.newLine();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
    _context.uploadResourceContent(vmxUrl, bos.toByteArray());

    // It seems that I don't need to do re-registration. VMware has bug in writing the correct snapshot's VMDK path to
    // its disk backing info anyway.
    // redoRegistration();
}
项目:cloudstack    文件:VirtualMachineMO.java   
public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs, String destDsDirectory, String destName, boolean includeBase) throws Exception {

        SnapshotDescriptor descriptor = getSnapshotDescriptor();
        SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain();
        if (snapshotInfo.length == 0) {
            String msg = "No snapshot found in this VM";
            throw new Exception(msg);
        }

        HostMO hostMo = getRunningHost();
        DatacenterMO dcMo = getOwnerDatacenter().first();
        List<Pair<ManagedObjectReference, String>> mounts = hostMo.getDatastoreMountsOnHost();
        VirtualMachineFileInfo vmFileInfo = getFileInfo();

        List<Ternary<String, String, String>> backupInfo = new ArrayList<Ternary<String, String, String>>();

        for (int i = 0; i < snapshotInfo.length; i++) {
            if (!includeBase && i == snapshotInfo.length - 1) {
                break;
            }

            SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks();
            if (disks != null) {
                String destBaseFileName;
                String destFileName;
                String destParentFileName;
                for (SnapshotDescriptor.DiskInfo disk : disks) {
                    if (deviceName == null || deviceName.equals(disk.getDeviceName())) {
                        String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, mounts, disk.getDiskFileName());
                        Pair<DatastoreMO, String> srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath);

                        Pair<VmdkFileDescriptor, byte[]> vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath);
                        String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath(srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName());

                        destFileName = destName + (snapshotInfo.length - i - 1) + ".vmdk";
                        if (vmdkInfo.first().getParentFileName() != null) {
                            destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-delta.vmdk";
                            destParentFileName = destName + (snapshotInfo.length - i - 2) + ".vmdk";
                        } else {
                            destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-flat.vmdk";
                            destParentFileName = null;
                        }

                        s_logger.info("Copy VMDK base file " + srcVmdkBaseFilePath + " to " + destDsDirectory + "/" + destBaseFileName);
                        srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(), morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true);

                        byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo(vmdkInfo.second(), destBaseFileName, destParentFileName);
                        String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destFileName);

                        s_logger.info("Upload VMDK content file to " + destDsDirectory + "/" + destFileName);
                        getContext().uploadResourceContent(vmdkUploadUrl, newVmdkContent);

                        backupInfo.add(new Ternary<String, String, String>(destFileName, destBaseFileName, destParentFileName));
                    }
                }
            }
        }

        byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase);
        String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destName + ".vdisk");
        getContext().uploadResourceContent(vdiskUploadUrl, vdiskInfo);
    }