Search in sources :

Example 6 with InternalErrorException

use of com.cloud.legacymodel.exceptions.InternalErrorException in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testPlugNicCommandInternalError.

@Test
public void testPlugNicCommandInternalError() {
    final NicTO nic = Mockito.mock(NicTO.class);
    final String instanceName = "Test";
    final VirtualMachineType vmtype = VirtualMachineType.DomainRouter;
    final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final Connect conn = Mockito.mock(Connect.class);
    final Domain vm = Mockito.mock(Domain.class);
    final VifDriver vifDriver = Mockito.mock(VifDriver.class);
    final List<InterfaceDef> nics = new ArrayList<>();
    final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
    nics.add(intDef);
    when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    when(this.libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
    when(intDef.getDevName()).thenReturn("eth0");
    when(intDef.getBrName()).thenReturn("br0");
    when(intDef.getMacAddress()).thenReturn("00:00:00:00");
    when(nic.getMac()).thenReturn("00:00:00:01");
    try {
        when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
        when(this.libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
        when(this.libvirtComputingResource.getVifDriver(nic.getType())).thenReturn(vifDriver);
        when(vifDriver.plug(nic, "Default - VirtIO capable OS (64-bit)", "")).thenThrow(InternalErrorException.class);
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    } catch (final InternalErrorException e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(this.libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
    try {
        verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
        verify(this.libvirtComputingResource, times(1)).getDomain(conn, instanceName);
        verify(this.libvirtComputingResource, times(1)).getVifDriver(nic.getType());
        verify(vifDriver, times(1)).plug(nic, "Default - VirtIO capable OS (64-bit)", "");
    } catch (final LibvirtException e) {
        fail(e.getMessage());
    } catch (final InternalErrorException e) {
        fail(e.getMessage());
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) ArrayList(java.util.ArrayList) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) VifDriver(com.cloud.agent.resource.kvm.vif.VifDriver) LibvirtUtilitiesHelper(com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper) InterfaceDef(com.cloud.agent.resource.kvm.xml.LibvirtVmDef.InterfaceDef) Answer(com.cloud.legacymodel.communication.answer.Answer) CheckRouterAnswer(com.cloud.legacymodel.communication.answer.CheckRouterAnswer) AttachAnswer(com.cloud.legacymodel.communication.answer.AttachAnswer) LibvirtRequestWrapper(com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper) VirtualMachineType(com.cloud.model.enumeration.VirtualMachineType) Domain(org.libvirt.Domain) PlugNicCommand(com.cloud.legacymodel.communication.command.PlugNicCommand) UnPlugNicCommand(com.cloud.legacymodel.communication.command.UnPlugNicCommand) NicTO(com.cloud.legacymodel.to.NicTO) Test(org.junit.Test)

Example 7 with InternalErrorException

use of com.cloud.legacymodel.exceptions.InternalErrorException in project cosmic by MissionCriticalCloud.

the class LibvirtComputingResourceTest method testCreatePrivateTemplateFromSnapshotCommandConfigurationException.

@Test
public void testCreatePrivateTemplateFromSnapshotCommandConfigurationException() {
    final StoragePool pool = Mockito.mock(StoragePool.class);
    final String secondaryStoragePoolURL = "nfs:/127.0.0.1/storage/secondary";
    final Long dcId = 1l;
    final Long accountId = 1l;
    final Long volumeId = 1l;
    final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
    final String backedUpSnapshotName = "snap";
    final String origTemplateInstallPath = "/install/path/";
    final Long newTemplateId = 2l;
    final String templateName = "templ";
    final int wait = 0;
    final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
    final String templatePath = "/template/path";
    final String localPath = "/mnt/local";
    final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
    final KvmStoragePoolManager storagePoolMgr = Mockito.mock(KvmStoragePoolManager.class);
    final KvmStoragePool secondaryPool = Mockito.mock(KvmStoragePool.class);
    final KvmStoragePool snapshotPool = Mockito.mock(KvmStoragePool.class);
    final KvmPhysicalDisk snapshot = Mockito.mock(KvmPhysicalDisk.class);
    final StorageLayer storage = Mockito.mock(StorageLayer.class);
    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
    final TemplateLocation location = Mockito.mock(TemplateLocation.class);
    final Processor qcow2Processor = Mockito.mock(Processor.class);
    final TemplateFormatInfo info = Mockito.mock(TemplateFormatInfo.class);
    when(this.libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
    String snapshotPath = command.getSnapshotUuid();
    final int index = snapshotPath.lastIndexOf("/");
    snapshotPath = snapshotPath.substring(0, index);
    when(storagePoolMgr.getStoragePoolByUri(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
    when(storagePoolMgr.getStoragePoolByUri(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
    when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
    when(secondaryPool.getLocalPath()).thenReturn(localPath);
    when(this.libvirtComputingResource.getStorage()).thenReturn(storage);
    when(this.libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
    when(this.libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
    final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
    final String templateInstallFolder = "template/tmpl/" + templateFolder;
    final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
    when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
    when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
    when(libvirtUtilitiesHelper.generateUuidName()).thenReturn(tmplName);
    try {
        when(libvirtUtilitiesHelper.buildQcow2Processor(storage)).thenThrow(ConfigurationException.class);
        when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
    } catch (final ConfigurationException e) {
        fail(e.getMessage());
    } catch (final InternalErrorException e) {
        fail(e.getMessage());
    }
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
    verify(storagePoolMgr, times(1)).getStoragePoolByUri(command.getSecondaryStorageUrl() + snapshotPath);
    verify(storagePoolMgr, times(1)).getStoragePoolByUri(command.getSecondaryStorageUrl());
}
Also used : NfsStoragePool(com.cloud.agent.resource.kvm.ha.KvmHaBase.NfsStoragePool) KvmStoragePool(com.cloud.agent.resource.kvm.storage.KvmStoragePool) StoragePool(com.cloud.legacymodel.storage.StoragePool) KvmStoragePool(com.cloud.agent.resource.kvm.storage.KvmStoragePool) StorageLayer(com.cloud.utils.storage.StorageLayer) Processor(com.cloud.common.storageprocessor.Processor) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) LibvirtUtilitiesHelper(com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper) Answer(com.cloud.legacymodel.communication.answer.Answer) CheckRouterAnswer(com.cloud.legacymodel.communication.answer.CheckRouterAnswer) AttachAnswer(com.cloud.legacymodel.communication.answer.AttachAnswer) LibvirtRequestWrapper(com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TemplateLocation(com.cloud.common.storageprocessor.TemplateLocation) CreatePrivateTemplateFromSnapshotCommand(com.cloud.legacymodel.communication.command.CreatePrivateTemplateFromSnapshotCommand) KvmStoragePoolManager(com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager) TemplateFormatInfo(com.cloud.legacymodel.storage.TemplateFormatInfo) KvmPhysicalDisk(com.cloud.agent.resource.kvm.storage.KvmPhysicalDisk) Test(org.junit.Test)

Example 8 with InternalErrorException

use of com.cloud.legacymodel.exceptions.InternalErrorException in project cosmic by MissionCriticalCloud.

the class DownloadManagerImpl method postLocalDownload.

/**
 * Post local download activity (install and cleanup). Executed in context of
 * downloader thread
 *
 * @throws IOException
 */
private String postLocalDownload(final String jobId) {
    final DownloadJob dnld = this.jobs.get(jobId);
    final TemplateDownloader td = dnld.getTemplateDownloader();
    // path with mount
    final String resourcePath = dnld.getInstallPathPrefix();
    // directory
    // template download
    final String finalResourcePath = dnld.getTmpltPath();
    // path on secondary
    // storage
    final ResourceType resourceType = dnld.getResourceType();
    final File originalTemplate = new File(td.getDownloadLocalPath());
    final String checkSum = computeCheckSum(originalTemplate);
    if (checkSum == null) {
        s_logger.warn("Something wrong happened when try to calculate the checksum of downloaded template!");
    }
    dnld.setCheckSum(checkSum);
    int imgSizeGigs = (int) Math.ceil(this._storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
    // add one just in case
    imgSizeGigs++;
    final long timeout = (long) imgSizeGigs * this.installTimeoutPerGig;
    Script scr = null;
    final String script = resourceType == ResourceType.TEMPLATE ? this.createTmpltScr : this.createVolScr;
    scr = new Script(script, timeout, s_logger);
    scr.add("-s", Integer.toString(imgSizeGigs));
    scr.add("-S", Long.toString(td.getMaxTemplateSizeInBytes()));
    if (dnld.getDescription() != null && dnld.getDescription().length() > 1) {
        scr.add("-d", dnld.getDescription());
    }
    // add options common to ISO and template
    final String extension = dnld.getFormat().toString().toLowerCase();
    String templateName = "";
    if (extension.equals("iso")) {
        templateName = this.jobs.get(jobId).getTmpltName().trim().replace(" ", "_");
    } else {
        templateName = java.util.UUID.nameUUIDFromBytes((this.jobs.get(jobId).getTmpltName() + System.currentTimeMillis()).getBytes(StringUtils.getPreferredCharset())).toString();
    }
    // run script to mv the temporary template file to the final template
    // file
    final String templateFilename = templateName + "." + extension;
    dnld.setTmpltPath(finalResourcePath + "/" + templateFilename);
    scr.add("-n", templateFilename);
    scr.add("-t", resourcePath);
    // this is the temporary
    scr.add("-f", td.getDownloadLocalPath());
    // template file downloaded
    if (dnld.getChecksum() != null && dnld.getChecksum().length() > 1) {
        scr.add("-c", dnld.getChecksum());
    }
    // cleanup
    scr.add("-u");
    final String result;
    result = scr.execute();
    if (result != null) {
        return result;
    }
    // Set permissions for the downloaded template
    final File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
    this._storage.setWorldReadableAndWriteable(downloadedTemplate);
    // Set permissions for template/volume.properties
    String propertiesFile = resourcePath;
    if (resourceType == ResourceType.TEMPLATE) {
        propertiesFile += "/template.properties";
    } else {
        propertiesFile += "/volume.properties";
    }
    final File templateProperties = new File(propertiesFile);
    this._storage.setWorldReadableAndWriteable(templateProperties);
    final TemplateLocation loc = new TemplateLocation(this._storage, resourcePath);
    try {
        loc.create(dnld.getId(), true, dnld.getTmpltName());
    } catch (final IOException e) {
        s_logger.warn("Something is wrong with template location " + resourcePath, e);
        loc.purge();
        return "Unable to download due to " + e.getMessage();
    }
    final Iterator<Processor> en = this._processors.values().iterator();
    while (en.hasNext()) {
        final Processor processor = en.next();
        TemplateFormatInfo info = null;
        try {
            info = processor.process(resourcePath, null, templateName);
        } catch (final InternalErrorException e) {
            s_logger.error("Template process exception ", e);
            return e.toString();
        }
        if (info != null) {
            if (!loc.addFormat(info)) {
                loc.purge();
                return "Unable to install due to invalid file format";
            }
            dnld.setTemplatesize(info.virtualSize);
            dnld.setTemplatePhysicalSize(info.size);
            break;
        }
    }
    if (!loc.save()) {
        s_logger.warn("Cleaning up because we're unable to save the formats");
        loc.purge();
    }
    return null;
}
Also used : Script(com.cloud.utils.script.Script) IsoProcessor(com.cloud.common.storageprocessor.IsoProcessor) QCOW2Processor(com.cloud.common.storageprocessor.QCOW2Processor) RawImageProcessor(com.cloud.common.storageprocessor.RawImageProcessor) TARProcessor(com.cloud.common.storageprocessor.TARProcessor) VhdProcessor(com.cloud.common.storageprocessor.VhdProcessor) Processor(com.cloud.common.storageprocessor.Processor) ResourceType(com.cloud.legacymodel.communication.command.DownloadCommand.ResourceType) IOException(java.io.IOException) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) TemplateLocation(com.cloud.common.storageprocessor.TemplateLocation) TemplateFormatInfo(com.cloud.legacymodel.storage.TemplateFormatInfo) File(java.io.File)

Example 9 with InternalErrorException

use of com.cloud.legacymodel.exceptions.InternalErrorException in project cosmic by MissionCriticalCloud.

the class XenServerStorageProcessor method backupSnapshot.

@Override
public Answer backupSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO cacheData = cmd.getCacheTO();
    final DataTO destData = cmd.getDestTO();
    final int wait = cmd.getWait();
    final String primaryStorageNameLabel = srcData.getDataStore().getUuid();
    String secondaryStorageUrl = null;
    NfsTO cacheStore = null;
    String destPath = null;
    if (cacheData != null) {
        cacheStore = (NfsTO) cacheData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = cacheData.getPath();
    } else {
        cacheStore = (NfsTO) destData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = destData.getPath();
    }
    final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
    final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
    final String snapshotUuid = snapshotTO.getPath();
    final String volumeUuid = snapshotTO.getVolume().getPath();
    final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
    final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
    // By default assume failure
    String details = null;
    String snapshotBackupUuid = null;
    Long physicalSize = null;
    final Map<String, String> options = cmd.getOptions();
    boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
    boolean result = false;
    try {
        final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
        if (primaryStorageSR == null) {
            throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel);
        }
        final String psUuid = primaryStorageSR.getUuid(conn);
        final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));
        final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
        String snapshotPaUuid = null;
        if (prevSnapshotUuid != null && !fullbackup) {
            try {
                snapshotPaUuid = getVhdParent(conn, psUuid, snapshotUuid, isISCSI);
                if (snapshotPaUuid != null) {
                    final String snashotPaPaPaUuid = getVhdParent(conn, psUuid, snapshotPaUuid, isISCSI);
                    final String prevSnashotPaUuid = getVhdParent(conn, psUuid, prevSnapshotUuid, isISCSI);
                    if (snashotPaPaPaUuid != null && prevSnashotPaUuid != null && prevSnashotPaUuid.equals(snashotPaPaPaUuid)) {
                        fullbackup = false;
                    } else {
                        fullbackup = true;
                    }
                }
            } catch (final Exception e) {
                s_logger.debug("Failed to get parent snapshots, take full snapshot", e);
                fullbackup = true;
            }
        }
        final URI uri = new URI(secondaryStorageUrl);
        final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
        final DataStoreTO destStore = destData.getDataStore();
        final String folder = destPath;
        String finalPath = null;
        final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
        if (fullbackup) {
            if (!hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, folder)) {
                details = " Filed to create folder " + folder + " in secondary storage";
                s_logger.warn(details);
                return new CopyCmdAnswer(details);
            }
            final String snapshotMountpoint = secondaryStorageUrl + "/" + folder;
            SR snapshotSr = null;
            try {
                snapshotSr = hypervisorResource.createNfsSRbyURI(conn, new URI(snapshotMountpoint), false);
                final VDI backedVdi = hypervisorResource.cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait);
                snapshotBackupUuid = backedVdi.getUuid(conn);
                final String primarySRuuid = snapshotSr.getUuid(conn);
                physicalSize = getSnapshotSize(conn, primarySRuuid, snapshotBackupUuid, isISCSI, wait);
                finalPath = folder + cacheStore.getPathSeparator() + snapshotBackupUuid;
            } finally {
                if (snapshotSr != null) {
                    hypervisorResource.removeSR(conn, snapshotSr);
                }
            }
        } else {
            final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
            final String results = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait);
            final String[] tmp = results.split("#");
            snapshotBackupUuid = tmp[1];
            physicalSize = Long.parseLong(tmp[2]);
            finalPath = folder + cacheStore.getPathSeparator() + snapshotBackupUuid;
        }
        // delete primary snapshots with only the last one left
        destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);
        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(finalPath);
        newSnapshot.setPhysicalSize(physicalSize);
        if (fullbackup) {
            newSnapshot.setParentSnapshotPath(null);
        } else {
            newSnapshot.setParentSnapshotPath(prevBackupUuid);
        }
        result = true;
        return new CopyCmdAnswer(newSnapshot);
    } catch (final XenAPIException e) {
        details = "BackupSnapshot Failed due to " + e.toString();
        s_logger.warn(details, e);
    } catch (final Exception e) {
        details = "BackupSnapshot Failed due to " + e.getMessage();
        s_logger.warn(details, e);
    } finally {
        if (!result) {
            // remove last bad primary snapshot when exception happens
            try {
                destroySnapshotOnPrimaryStorage(conn, snapshotUuid);
            } catch (final Exception e) {
                s_logger.debug("clean up snapshot failed", e);
            }
        }
    }
    return new CopyCmdAnswer(details);
}
Also used : SnapshotObjectTO(com.cloud.legacymodel.to.SnapshotObjectTO) PrimaryDataStoreTO(com.cloud.legacymodel.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.legacymodel.to.DataStoreTO) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) NfsTO(com.cloud.legacymodel.to.NfsTO) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataTO(com.cloud.legacymodel.to.DataTO) VDI(com.xensource.xenapi.VDI) CopyCmdAnswer(com.cloud.legacymodel.communication.answer.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Example 10 with InternalErrorException

use of com.cloud.legacymodel.exceptions.InternalErrorException in project cosmic by MissionCriticalCloud.

the class Xenserver625StorageProcessor method backupSnapshot.

@Override
public Answer backupSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO cacheData = cmd.getCacheTO();
    final DataTO destData = cmd.getDestTO();
    final int wait = cmd.getWait();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
    final String primaryStorageNameLabel = primaryStore.getUuid();
    String secondaryStorageUrl = null;
    NfsTO cacheStore = null;
    String destPath = null;
    if (cacheData != null) {
        cacheStore = (NfsTO) cacheData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = cacheData.getPath();
    } else {
        cacheStore = (NfsTO) destData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = destData.getPath();
    }
    final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
    final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
    final String snapshotUuid = snapshotTO.getPath();
    final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
    final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
    final Map<String, String> options = cmd.getOptions();
    // By default assume failure
    String details = null;
    String snapshotBackupUuid = null;
    final boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
    Long physicalSize = null;
    try {
        final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
        if (primaryStorageSR == null) {
            throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel);
        }
        // String psUuid = primaryStorageSR.getUuid(conn);
        final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));
        final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
        final String snapshotPaUuid = null;
        final URI uri = new URI(secondaryStorageUrl);
        final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
        final DataStoreTO destStore = destData.getDataStore();
        final String folder = destPath;
        String finalPath = null;
        final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
        if (fullbackup) {
            SR snapshotSr = null;
            Task task = null;
            try {
                final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
                mountNfs(conn, secondaryStorageMountPath, localDir);
                final boolean result = makeDirectory(conn, localDir + "/" + folder);
                if (!result) {
                    details = " Filed to create folder " + folder + " in secondary storage";
                    s_logger.warn(details);
                    return new CopyCmdAnswer(details);
                }
                snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder);
                task = snapshotVdi.copyAsync(conn, snapshotSr, null, null);
                // poll every 1 seconds ,
                hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
                hypervisorResource.checkForSuccess(conn, task);
                final VDI backedVdi = Types.toVDI(task, conn);
                snapshotBackupUuid = backedVdi.getUuid(conn);
                physicalSize = backedVdi.getPhysicalUtilisation(conn);
                finalPath = folder + File.separator + snapshotBackupUuid;
            } finally {
                if (task != null) {
                    try {
                        task.destroy(conn);
                    } catch (final Exception e) {
                        s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
                    }
                }
                if (snapshotSr != null) {
                    hypervisorResource.removeSR(conn, snapshotSr);
                }
            }
        } else {
            final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
            final String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait);
            final String[] tmp = result.split("#");
            snapshotBackupUuid = tmp[0];
            physicalSize = Long.parseLong(tmp[1]);
            finalPath = folder + File.separator + snapshotBackupUuid;
        }
        final String volumeUuid = snapshotTO.getVolume().getPath();
        destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);
        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(finalPath);
        newSnapshot.setPhysicalSize(physicalSize);
        if (fullbackup) {
            newSnapshot.setParentSnapshotPath(null);
        } else {
            newSnapshot.setParentSnapshotPath(prevBackupUuid);
        }
        return new CopyCmdAnswer(newSnapshot);
    } catch (final Types.XenAPIException e) {
        details = "BackupSnapshot Failed due to " + e.toString();
        s_logger.warn(details, e);
    } catch (final Exception e) {
        details = "BackupSnapshot Failed due to " + e.getMessage();
        s_logger.warn(details, e);
    }
    return new CopyCmdAnswer(details);
}
Also used : SnapshotObjectTO(com.cloud.legacymodel.to.SnapshotObjectTO) Types(com.xensource.xenapi.Types) PrimaryDataStoreTO(com.cloud.legacymodel.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.legacymodel.to.DataStoreTO) Task(com.xensource.xenapi.Task) Connection(com.xensource.xenapi.Connection) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) NfsTO(com.cloud.legacymodel.to.NfsTO) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) XenAPIException(com.xensource.xenapi.Types.XenAPIException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataTO(com.cloud.legacymodel.to.DataTO) PrimaryDataStoreTO(com.cloud.legacymodel.to.PrimaryDataStoreTO) VDI(com.xensource.xenapi.VDI) CopyCmdAnswer(com.cloud.legacymodel.communication.answer.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Aggregations

InternalErrorException (com.cloud.legacymodel.exceptions.InternalErrorException)37 Connect (org.libvirt.Connect)15 LibvirtException (org.libvirt.LibvirtException)15 KvmStoragePoolManager (com.cloud.agent.resource.kvm.storage.KvmStoragePoolManager)14 Answer (com.cloud.legacymodel.communication.answer.Answer)14 AttachAnswer (com.cloud.legacymodel.communication.answer.AttachAnswer)14 LibvirtRequestWrapper (com.cloud.agent.resource.kvm.wrapper.LibvirtRequestWrapper)12 LibvirtUtilitiesHelper (com.cloud.agent.resource.kvm.wrapper.LibvirtUtilitiesHelper)12 CheckRouterAnswer (com.cloud.legacymodel.communication.answer.CheckRouterAnswer)12 Test (org.junit.Test)12 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)11 TemplateFormatInfo (com.cloud.legacymodel.storage.TemplateFormatInfo)11 NicTO (com.cloud.legacymodel.to.NicTO)11 Processor (com.cloud.common.storageprocessor.Processor)10 TemplateLocation (com.cloud.common.storageprocessor.TemplateLocation)10 LibvirtVmDef (com.cloud.agent.resource.kvm.xml.LibvirtVmDef)9 PrimaryDataStoreTO (com.cloud.legacymodel.to.PrimaryDataStoreTO)9 URISyntaxException (java.net.URISyntaxException)9 CopyCmdAnswer (com.cloud.legacymodel.communication.answer.CopyCmdAnswer)8 VirtualMachineTO (com.cloud.legacymodel.to.VirtualMachineTO)8