Search in sources :

Example 1 with HttpNfcLeaseDeviceUrl

use of com.vmware.vim25.HttpNfcLeaseDeviceUrl in project photon-model by vmware.

the class OvfDeployer method deployOvf.

public ManagedObjectReference deployOvf(URI ovfUri, ManagedObjectReference host, ManagedObjectReference vmFolder, String vmName, List<OvfNetworkMapping> networks, ManagedObjectReference datastore, Collection<KeyValue> ovfProps, String deploymentConfig, ManagedObjectReference resourcePool) throws Exception {
    String ovfDescriptor = getRetriever().retrieveAsString(ovfUri);
    OvfCreateImportSpecParams params = new OvfCreateImportSpecParams();
    params.setHostSystem(host);
    params.setLocale("US");
    params.setEntityName(vmName);
    if (deploymentConfig == null) {
        deploymentConfig = "";
    }
    params.setDeploymentOption(deploymentConfig);
    params.getNetworkMapping().addAll(networks);
    params.setDiskProvisioning(OvfCreateImportSpecParamsDiskProvisioningType.THIN.name());
    if (ovfProps != null) {
        params.getPropertyMapping().addAll(ovfProps);
    }
    ManagedObjectReference ovfManager = this.connection.getServiceContent().getOvfManager();
    OvfCreateImportSpecResult importSpecResult = getVimPort().createImportSpec(ovfManager, ovfDescriptor, resourcePool, datastore, params);
    if (!importSpecResult.getError().isEmpty()) {
        return VimUtils.rethrow(importSpecResult.getError().get(0));
    }
    long totalBytes = getImportSizeBytes(importSpecResult);
    ManagedObjectReference lease = getVimPort().importVApp(resourcePool, importSpecResult.getImportSpec(), vmFolder, host);
    LeaseProgressUpdater leaseUpdater = new LeaseProgressUpdater(this.connection, lease, totalBytes);
    GetMoRef get = new GetMoRef(this.connection);
    HttpNfcLeaseInfo httpNfcLeaseInfo;
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    try {
        leaseUpdater.awaitReady();
        logger.info("Lease ready");
        // start updating the lease
        leaseUpdater.start(executorService);
        httpNfcLeaseInfo = get.entityProp(lease, PROP_INFO);
        List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
        String ip = this.connection.getURI().getHost();
        String basePath = extractBasePath(ovfUri);
        for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
            String deviceKey = deviceUrl.getImportKey();
            for (OvfFileItem ovfFileItem : importSpecResult.getFileItem()) {
                if (deviceKey.equals(ovfFileItem.getDeviceId())) {
                    logger.debug("Importing device id: {}", deviceKey);
                    String sourceUri = computeDiskSourceUri(basePath, ovfFileItem);
                    String uploadUri = makUploadUri(ip, deviceUrl);
                    uploadVmdkFile(ovfFileItem, sourceUri, uploadUri, leaseUpdater, this.ovfRetriever.getClient());
                    logger.info("Completed uploading VMDK file {}", sourceUri);
                }
            }
        }
        // complete lease
        leaseUpdater.complete();
    } catch (Exception e) {
        leaseUpdater.abort(VimUtils.convertExceptionToFault(e));
        logger.info("Error importing ovf", e);
        throw e;
    } finally {
        executorService.shutdown();
    }
    httpNfcLeaseInfo = get.entityProp(lease, PROP_INFO);
    ManagedObjectReference entity = httpNfcLeaseInfo.getEntity();
    // as this is an OVF it makes sense to enable the OVF transport
    // only the guestInfo is enabled by default
    VmConfigSpec spec = new VmConfigSpec();
    spec.getOvfEnvironmentTransport().add(TRANSPORT_GUESTINFO);
    spec.getOvfEnvironmentTransport().add(TRANSPORT_ISO);
    VirtualMachineConfigSpec reconfig = new VirtualMachineConfigSpec();
    reconfig.setVAppConfig(spec);
    ManagedObjectReference reconfigTask = getVimPort().reconfigVMTask(entity, reconfig);
    VimUtils.waitTaskEnd(this.connection, reconfigTask);
    return entity;
}
Also used : OvfFileItem(com.vmware.vim25.OvfFileItem) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) OvfCreateImportSpecResult(com.vmware.vim25.OvfCreateImportSpecResult) FinderException(com.vmware.photon.controller.model.adapters.vsphere.util.finders.FinderException) IOException(java.io.IOException) GetMoRef(com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef) OvfCreateImportSpecParams(com.vmware.vim25.OvfCreateImportSpecParams) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) VmConfigSpec(com.vmware.vim25.VmConfigSpec) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl)

Example 2 with HttpNfcLeaseDeviceUrl

use of com.vmware.vim25.HttpNfcLeaseDeviceUrl 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 HttpNfcLeaseDeviceUrl

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

the class HypervisorHostHelper method importVmFromOVF.

public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
    assert (morRp != null);
    OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
    importSpecParams.setHostSystem(morHost);
    importSpecParams.setLocale("US");
    importSpecParams.setEntityName(vmName);
    importSpecParams.setDeploymentOption("");
    // diskOption: thin, thick, etc
    importSpecParams.setDiskProvisioning(diskOption);
    importSpecParams.setPropertyMapping(null);
    String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath);
    VmwareContext context = host.getContext();
    OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
    if (ovfImportResult == null) {
        String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
    ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
    if (morLease == null) {
        String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new Exception(msg);
    }
    final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
    HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
    try {
        if (state == HttpNfcLeaseState.ready) {
            final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
            File ovfFile = new File(ovfFilePath);
            HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
            HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
            long bytesAlreadyWritten = 0;
            final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
            try {
                for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
                    String deviceKey = deviceUrl.getImportKey();
                    for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
                        if (deviceKey.equals(ovfFileItem.getDeviceId())) {
                            String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
                            String urlToPost = deviceUrl.getUrl();
                            urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
                            context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {

                                public void action(Long param) {
                                    progressReporter.reportProgress((int) (param * 100 / totalBytes));
                                }
                            });
                            bytesAlreadyWritten += ovfFileItem.getSize();
                        }
                    }
                }
            } finally {
                progressReporter.close();
            }
            leaseMo.updateLeaseProgress(100);
        }
    } finally {
        leaseMo.completeLease();
    }
}
Also used : OvfFileItem(com.vmware.vim25.OvfFileItem) OvfCreateImportSpecResult(com.vmware.vim25.OvfCreateImportSpecResult) URISyntaxException(java.net.URISyntaxException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) OvfCreateImportSpecParams(com.vmware.vim25.OvfCreateImportSpecParams) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) File(java.io.File) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseState(com.vmware.vim25.HttpNfcLeaseState) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl)

Example 4 with HttpNfcLeaseDeviceUrl

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

the class HypervisorHostHelper method importVmFromOVF.

/**
 * deploys a new VM from a ovf spec. It ignores network, defaults locale to 'US'
 * @throws Exception shoud be a VmwareResourceException
 */
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost, String configurationId) throws CloudRuntimeException, IOException {
    assert (morRp != null);
    OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
    importSpecParams.setHostSystem(morHost);
    importSpecParams.setLocale("US");
    importSpecParams.setEntityName(vmName);
    String deploymentOption = StringUtils.isNotBlank(configurationId) ? configurationId : "";
    importSpecParams.setDeploymentOption(deploymentOption);
    // diskOption: thin, thick, etc
    importSpecParams.setDiskProvisioning(diskOption);
    String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));
    VmwareContext context = host.getContext();
    OvfCreateImportSpecResult ovfImportResult = null;
    try {
        ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
    } catch (ConcurrentAccessFaultMsg | FileFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidStateFaultMsg | RuntimeFaultFaultMsg | TaskInProgressFaultMsg | VmConfigFaultFaultMsg error) {
        throw new CloudRuntimeException("ImportSpec creation failed", error);
    }
    if (ovfImportResult == null) {
        String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new CloudRuntimeException(msg);
    }
    if (!ovfImportResult.getError().isEmpty()) {
        for (LocalizedMethodFault fault : ovfImportResult.getError()) {
            s_logger.error("createImportSpec error: " + fault.getLocalizedMessage());
        }
        throw new CloudRuntimeException("Failed to create an import spec from " + ovfFilePath + ". Check log for details.");
    }
    if (!ovfImportResult.getWarning().isEmpty()) {
        for (LocalizedMethodFault fault : ovfImportResult.getError()) {
            s_logger.warn("createImportSpec warning: " + fault.getLocalizedMessage());
        }
    }
    DatacenterMO dcMo = null;
    try {
        dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
    } catch (Exception e) {
        throw new CloudRuntimeException(String.format("no datacenter for host '%s' available in context", context.getServerAddress()), e);
    }
    ManagedObjectReference folderMO = null;
    try {
        folderMO = dcMo.getVmFolder();
    } catch (Exception e) {
        throw new CloudRuntimeException("no management handle for VmFolder", e);
    }
    ManagedObjectReference morLease = null;
    try {
        morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), folderMO, morHost);
    } catch (DuplicateNameFaultMsg | FileFaultFaultMsg | InsufficientResourcesFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidNameFaultMsg | OutOfBoundsFaultMsg | RuntimeFaultFaultMsg | VmConfigFaultFaultMsg fault) {
        throw new CloudRuntimeException("import vApp failed", fault);
    }
    if (morLease == null) {
        String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
        s_logger.error(msg);
        throw new CloudRuntimeException(msg);
    }
    boolean importSuccess = true;
    final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
    HttpNfcLeaseState state = null;
    try {
        state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
    } catch (Exception e) {
        throw new CloudRuntimeException("exception while waiting for leaseMO", e);
    }
    try {
        if (state == HttpNfcLeaseState.READY) {
            final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
            File ovfFile = new File(ovfFilePath);
            HttpNfcLeaseInfo httpNfcLeaseInfo = null;
            try {
                httpNfcLeaseInfo = leaseMo.getLeaseInfo();
            } catch (Exception e) {
                throw new CloudRuntimeException("error waiting for lease info", e);
            }
            List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
            long bytesAlreadyWritten = 0;
            final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
            try {
                for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
                    String deviceKey = deviceUrl.getImportKey();
                    for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
                        if (deviceKey.equals(ovfFileItem.getDeviceId())) {
                            String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
                            s_logger.info("Uploading file: " + absoluteFile);
                            File f = new File(absoluteFile);
                            if (f.exists()) {
                                String urlToPost = deviceUrl.getUrl();
                                urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
                                context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {

                                    @Override
                                    public void action(Long param) {
                                        progressReporter.reportProgress((int) (param * 100 / totalBytes));
                                    }
                                });
                                bytesAlreadyWritten += ovfFileItem.getSize();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                String erroMsg = "File upload task failed to complete due to: " + e.getMessage();
                s_logger.error(erroMsg);
                // Set flag to cleanup the stale template left due to failed import operation, if any
                importSuccess = false;
                throw new CloudRuntimeException(erroMsg, e);
            } catch (Throwable th) {
                String errorMsg = "throwable caught during file upload task: " + th.getMessage();
                s_logger.error(errorMsg);
                // Set flag to cleanup the stale template left due to failed import operation, if any
                importSuccess = false;
                throw new CloudRuntimeException(errorMsg, th);
            } finally {
                progressReporter.close();
            }
            if (bytesAlreadyWritten == totalBytes) {
                try {
                    leaseMo.updateLeaseProgress(100);
                } catch (Exception e) {
                    throw new CloudRuntimeException("error while waiting for lease update", e);
                }
            }
        } else if (state == HttpNfcLeaseState.ERROR) {
            LocalizedMethodFault error = null;
            try {
                error = leaseMo.getLeaseError();
            } catch (Exception e) {
                throw new CloudRuntimeException("error getting lease error", e);
            }
            MethodFault fault = error.getFault();
            String erroMsg = "Object creation on vCenter failed due to: Exception: " + fault.getClass().getName() + ", message: " + error.getLocalizedMessage();
            s_logger.error(erroMsg);
            throw new CloudRuntimeException(erroMsg);
        }
    } finally {
        try {
            if (!importSuccess) {
                s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
                leaseMo.abortLease();
            } else {
                leaseMo.completeLease();
            }
        } catch (Exception e) {
            throw new CloudRuntimeException("error completing lease", e);
        }
    }
}
Also used : OvfCreateImportSpecResult(com.vmware.vim25.OvfCreateImportSpecResult) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) InsufficientResourcesFaultFaultMsg(com.vmware.vim25.InsufficientResourcesFaultFaultMsg) ConcurrentAccessFaultMsg(com.vmware.vim25.ConcurrentAccessFaultMsg) InvalidDatastoreFaultMsg(com.vmware.vim25.InvalidDatastoreFaultMsg) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) FileFaultFaultMsg(com.vmware.vim25.FileFaultFaultMsg) InvalidNameFaultMsg(com.vmware.vim25.InvalidNameFaultMsg) HttpNfcLeaseDeviceUrl(com.vmware.vim25.HttpNfcLeaseDeviceUrl) OvfFileItem(com.vmware.vim25.OvfFileItem) MethodFault(com.vmware.vim25.MethodFault) LocalizedMethodFault(com.vmware.vim25.LocalizedMethodFault) LocalizedMethodFault(com.vmware.vim25.LocalizedMethodFault) TaskInProgressFaultMsg(com.vmware.vim25.TaskInProgressFaultMsg) 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) OvfCreateImportSpecParams(com.vmware.vim25.OvfCreateImportSpecParams) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) InvalidStateFaultMsg(com.vmware.vim25.InvalidStateFaultMsg) VmConfigFaultFaultMsg(com.vmware.vim25.VmConfigFaultFaultMsg) DuplicateNameFaultMsg(com.vmware.vim25.DuplicateNameFaultMsg) HttpNfcLeaseInfo(com.vmware.vim25.HttpNfcLeaseInfo) OvfFile(com.vmware.vim25.OvfFile) File(java.io.File) OutOfBoundsFaultMsg(com.vmware.vim25.OutOfBoundsFaultMsg) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) HttpNfcLeaseState(com.vmware.vim25.HttpNfcLeaseState)

Example 5 with HttpNfcLeaseDeviceUrl

use of com.vmware.vim25.HttpNfcLeaseDeviceUrl 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

HttpNfcLeaseDeviceUrl (com.vmware.vim25.HttpNfcLeaseDeviceUrl)5 HttpNfcLeaseInfo (com.vmware.vim25.HttpNfcLeaseInfo)5 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)5 HttpNfcLeaseState (com.vmware.vim25.HttpNfcLeaseState)4 File (java.io.File)4 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 OvfCreateImportSpecParams (com.vmware.vim25.OvfCreateImportSpecParams)3 OvfCreateImportSpecResult (com.vmware.vim25.OvfCreateImportSpecResult)3 OvfFile (com.vmware.vim25.OvfFile)3 OvfFileItem (com.vmware.vim25.OvfFileItem)3 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)2 Script (com.cloud.utils.script.Script)2 ArrayOfManagedObjectReference (com.vmware.vim25.ArrayOfManagedObjectReference)2 OvfCreateDescriptorParams (com.vmware.vim25.OvfCreateDescriptorParams)2 OvfCreateDescriptorResult (com.vmware.vim25.OvfCreateDescriptorResult)2 VirtualMachineRuntimeInfo (com.vmware.vim25.VirtualMachineRuntimeInfo)2 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 ArrayList (java.util.ArrayList)2 CloudException (com.cloud.exception.CloudException)1