Search in sources :

Example 1 with OvfCreateDescriptorParams

use of com.vmware.vim25.OvfCreateDescriptorParams in project cloudstack by apache.

the class HypervisorHostHelper method createOvfFile.

public static void createOvfFile(VmwareHypervisorHost host, String diskFileName, String ovfName, String datastorePath, String templatePath, long diskCapacity, long fileSize, ManagedObjectReference morDs) throws Exception {
    VmwareContext context = host.getContext();
    ManagedObjectReference morOvf = context.getServiceContent().getOvfManager();
    VirtualMachineMO workerVmMo = HypervisorHostHelper.createWorkerVM(host, new DatastoreMO(context, morDs), ovfName, null);
    if (workerVmMo == null)
        throw new Exception("Unable to find just-created worker VM");
    String[] disks = { datastorePath + File.separator + diskFileName };
    try {
        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
        // Reconfigure worker VM with datadisk
        VirtualDevice device = VmwareHelper.prepareDiskDevice(workerVmMo, null, -1, disks, morDs, -1, 1);
        deviceConfigSpec.setDevice(device);
        deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
        vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
        workerVmMo.configureVm(vmConfigSpec);
        // Write OVF descriptor file
        OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
        String deviceId = File.separator + workerVmMo.getMor().getValue() + File.separator + "VirtualIDEController0:0";
        OvfFile ovfFile = new OvfFile();
        ovfFile.setPath(diskFileName);
        ovfFile.setDeviceId(deviceId);
        ovfFile.setSize(fileSize);
        ovfFile.setCapacity(diskCapacity);
        ovfDescParams.getOvfFiles().add(ovfFile);
        OvfCreateDescriptorResult ovfCreateDescriptorResult = context.getService().createDescriptor(morOvf, workerVmMo.getMor(), ovfDescParams);
        String ovfPath = templatePath + File.separator + ovfName + ".ovf";
        try {
            FileWriter out = new FileWriter(ovfPath);
            out.write(ovfCreateDescriptorResult.getOvfDescriptor());
            out.close();
        } catch (Exception e) {
            throw e;
        }
    } finally {
        workerVmMo.detachAllDisksAndDestroy();
    }
}
Also used : VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) FileWriter(java.io.FileWriter) VirtualDevice(com.vmware.vim25.VirtualDevice) OvfCreateDescriptorResult(com.vmware.vim25.OvfCreateDescriptorResult) InvalidParameterException(java.security.InvalidParameterException) CloudException(com.cloud.exception.CloudException) TransformerException(javax.xml.transform.TransformerException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) SAXException(org.xml.sax.SAXException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) OvfCreateDescriptorParams(com.vmware.vim25.OvfCreateDescriptorParams) OvfFile(com.vmware.vim25.OvfFile) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 2 with OvfCreateDescriptorParams

use of com.vmware.vim25.OvfCreateDescriptorParams in project CloudStack-archive by CloudStack-extras.

the class VirtualMachineMO method exportVm.

public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception {
    ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager();
    VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
    HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
    String hostName = hostMo.getHostName();
    String vmName = getVmName();
    DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
    if (runtimeInfo.getPowerState() != VirtualMachinePowerState.poweredOff) {
        String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    ManagedObjectReference morLease = _context.getService().exportVm(getMor());
    if (morLease == null) {
        s_logger.error("exportVm() failed");
        throw new Exception("exportVm() failed");
    }
    HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease);
    HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
    try {
        if (state == HttpNfcLeaseState.ready) {
            final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
            boolean success = false;
            List<String> fileNames = new ArrayList<String>();
            try {
                HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo();
                final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024;
                long totalBytesDownloaded = 0;
                HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl();
                if (deviceUrls != null) {
                    OvfFile[] ovfFiles = new OvfFile[deviceUrls.length];
                    for (int i = 0; i < deviceUrls.length; i++) {
                        String deviceId = deviceUrls[i].getKey();
                        String deviceUrlStr = deviceUrls[i].getUrl();
                        String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
                        String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk"));
                        String diskUrlStr = deviceUrlStr.replace("*", hostName);
                        diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr);
                        String diskLocalPath = exportDir + File.separator + diskFileName;
                        fileNames.add(diskLocalPath);
                        if (s_logger.isInfoEnabled()) {
                            s_logger.info("Download VMDK file for export. url: " + deviceUrlStr);
                        }
                        long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, new ActionDelegate<Long>() {

                            @Override
                            public void action(Long param) {
                                if (s_logger.isTraceEnabled()) {
                                    s_logger.trace("Download progress " + param + "/" + totalBytes);
                                }
                                progressReporter.reportProgress((int) (param * 100 / totalBytes));
                            }
                        });
                        totalBytesDownloaded += lengthOfDiskFile;
                        OvfFile ovfFile = new OvfFile();
                        ovfFile.setPath(diskFileName);
                        ovfFile.setDeviceId(deviceId);
                        ovfFile.setSize(lengthOfDiskFile);
                        ovfFiles[i] = ovfFile;
                    }
                    // write OVF descriptor file
                    OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
                    ovfDescParams.setOvfFiles(ovfFiles);
                    OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
                    String ovfPath = exportDir + File.separator + exportName + ".ovf";
                    fileNames.add(ovfPath);
                    FileWriter out = new FileWriter(ovfPath);
                    out.write(ovfCreateDescriptorResult.getOvfDescriptor());
                    out.close();
                    // tar files into OVA
                    if (packToOva) {
                        // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
                        s_logger.info("Sync file system before we package OVA...");
                        Script commandSync = new Script(true, "sync", 0, s_logger);
                        commandSync.execute();
                        Script command = new Script(false, "tar", 0, s_logger);
                        command.setWorkDir(exportDir);
                        command.add("-cf", exportName + ".ova");
                        // OVF file should be the first file in OVA archive
                        command.add(exportName + ".ovf");
                        for (String name : fileNames) {
                            command.add((new File(name).getName()));
                        }
                        s_logger.info("Package OVA with commmand: " + command.toString());
                        command.execute();
                        // to be safe, physically test existence of the target OVA file
                        if ((new File(exportDir + File.separator + exportName + ".ova")).exists()) {
                            success = true;
                        } else {
                            s_logger.error(exportDir + File.separator + exportName + ".ova is not created as expected");
                        }
                    }
                }
            } catch (Throwable e) {
                s_logger.error("Unexpected exception ", e);
            } finally {
                progressReporter.close();
                if (leaveOvaFileOnly) {
                    for (String name : fileNames) {
                        new File(name).delete();
                    }
                }
                if (!success)
                    throw new Exception("Unable to finish the whole process to package as a OVA file");
            }
        }
    } finally {
        leaseMo.updateLeaseProgress(100);
        leaseMo.completeLease();
    }
}
Also used : VirtualMachineRuntimeInfo(com.vmware.vim25.VirtualMachineRuntimeInfo) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl) Script(com.cloud.utils.script.Script) OvfCreateDescriptorResult(com.vmware.vim25.OvfCreateDescriptorResult) OvfCreateDescriptorParams(com.vmware.vim25.OvfCreateDescriptorParams) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) OvfFile(com.vmware.vim25.OvfFile) OvfFile(com.vmware.vim25.OvfFile) File(java.io.File) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseState(com.vmware.vim25.HttpNfcLeaseState)

Example 3 with OvfCreateDescriptorParams

use of com.vmware.vim25.OvfCreateDescriptorParams in project cloudstack by apache.

the class VirtualMachineMO method exportVm.

public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception {
    ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager();
    VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
    HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
    String hostName = hostMo.getHostName();
    String vmName = getVmName();
    DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
    if (runtimeInfo.getPowerState() != VirtualMachinePowerState.POWERED_OFF) {
        String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    ManagedObjectReference morLease = _context.getService().exportVm(getMor());
    if (morLease == null) {
        s_logger.error("exportVm() failed");
        throw new Exception("exportVm() failed");
    }
    HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease);
    HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
    try {
        if (state == HttpNfcLeaseState.READY) {
            final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
            boolean success = false;
            List<String> fileNames = new ArrayList<String>();
            try {
                HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo();
                final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024;
                long totalBytesDownloaded = 0;
                List<HttpNfcLeaseDeviceUrl> deviceUrls = leaseInfo.getDeviceUrl();
                s_logger.info("volss: copy vmdk and ovf file starts " + System.currentTimeMillis());
                if (deviceUrls != null) {
                    OvfFile[] ovfFiles = new OvfFile[deviceUrls.size()];
                    for (int i = 0; i < deviceUrls.size(); i++) {
                        String deviceId = deviceUrls.get(i).getKey();
                        String deviceUrlStr = deviceUrls.get(i).getUrl();
                        String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
                        String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk"));
                        String diskUrlStr = deviceUrlStr.replace("*", hostName);
                        diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr);
                        String diskLocalPath = exportDir + File.separator + diskFileName;
                        fileNames.add(diskLocalPath);
                        if (s_logger.isInfoEnabled()) {
                            s_logger.info("Download VMDK file for export. url: " + deviceUrlStr);
                        }
                        long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, new ActionDelegate<Long>() {

                            @Override
                            public void action(Long param) {
                                if (s_logger.isTraceEnabled()) {
                                    s_logger.trace("Download progress " + param + "/" + toHumanReadableSize(totalBytes));
                                }
                                progressReporter.reportProgress((int) (param * 100 / totalBytes));
                            }
                        });
                        totalBytesDownloaded += lengthOfDiskFile;
                        OvfFile ovfFile = new OvfFile();
                        ovfFile.setPath(diskFileName);
                        ovfFile.setDeviceId(deviceId);
                        ovfFile.setSize(lengthOfDiskFile);
                        ovfFiles[i] = ovfFile;
                    }
                    // write OVF descriptor file
                    OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
                    ovfDescParams.getOvfFiles().addAll(Arrays.asList(ovfFiles));
                    OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
                    String ovfPath = exportDir + File.separator + exportName + ".ovf";
                    fileNames.add(ovfPath);
                    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(ovfPath), "UTF-8");
                    out.write(ovfCreateDescriptorResult.getOvfDescriptor());
                    out.close();
                    // tar files into OVA
                    if (packToOva) {
                        // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
                        s_logger.info("Sync file system before we package OVA...");
                        Script commandSync = new Script(true, "sync", 0, s_logger);
                        commandSync.execute();
                        Script command = new Script(false, "tar", 0, s_logger);
                        command.setWorkDir(exportDir);
                        command.add("-cf", exportName + ".ova");
                        // OVF file should be the first file in OVA archive
                        command.add(exportName + ".ovf");
                        for (String name : fileNames) {
                            command.add((new File(name).getName()));
                        }
                        s_logger.info("Package OVA with command: " + command.toString());
                        command.execute();
                        // to be safe, physically test existence of the target OVA file
                        if ((new File(exportDir + File.separator + exportName + ".ova")).exists()) {
                            success = true;
                        } else {
                            s_logger.error(exportDir + File.separator + exportName + ".ova is not created as expected");
                        }
                    } else {
                        success = true;
                    }
                }
                s_logger.info("volss: copy vmdk and ovf file finished " + System.currentTimeMillis());
            } catch (Throwable e) {
                s_logger.error("Unexpected exception ", e);
            } finally {
                progressReporter.close();
                if (leaveOvaFileOnly) {
                    for (String name : fileNames) {
                        new File(name).delete();
                    }
                }
                if (!success)
                    throw new Exception("Unable to finish the whole process to package as a OVA file");
            }
        }
    } finally {
        leaseMo.updateLeaseProgress(100);
        leaseMo.completeLease();
    }
}
Also used : VirtualMachineRuntimeInfo(com.vmware.vim25.VirtualMachineRuntimeInfo) ArrayList(java.util.ArrayList) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl) Script(com.cloud.utils.script.Script) OvfCreateDescriptorResult(com.vmware.vim25.OvfCreateDescriptorResult) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) FileOutputStream(java.io.FileOutputStream) OvfCreateDescriptorParams(com.vmware.vim25.OvfCreateDescriptorParams) OutputStreamWriter(java.io.OutputStreamWriter) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) OvfFile(com.vmware.vim25.OvfFile) OvfFile(com.vmware.vim25.OvfFile) File(java.io.File) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseState(com.vmware.vim25.HttpNfcLeaseState)

Aggregations

ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)3 OvfCreateDescriptorParams (com.vmware.vim25.OvfCreateDescriptorParams)3 OvfCreateDescriptorResult (com.vmware.vim25.OvfCreateDescriptorResult)3 OvfFile (com.vmware.vim25.OvfFile)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 Script (com.cloud.utils.script.Script)2 ArrayOfManagedObjectReference (com.vmware.vim25.ArrayOfManagedObjectReference)2 HttpNfcLeaseDeviceUrl (com.vmware.vim25.HttpNfcLeaseDeviceUrl)2 HttpNfcLeaseInfo (com.vmware.vim25.HttpNfcLeaseInfo)2 HttpNfcLeaseState (com.vmware.vim25.HttpNfcLeaseState)2 VirtualMachineRuntimeInfo (com.vmware.vim25.VirtualMachineRuntimeInfo)2 File (java.io.File)2 FileWriter (java.io.FileWriter)2 ArrayList (java.util.ArrayList)2 CloudException (com.cloud.exception.CloudException)1 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)1 VirtualDevice (com.vmware.vim25.VirtualDevice)1 VirtualDeviceConfigSpec (com.vmware.vim25.VirtualDeviceConfigSpec)1 VirtualMachineConfigSpec (com.vmware.vim25.VirtualMachineConfigSpec)1 FileOutputStream (java.io.FileOutputStream)1