Search in sources :

Example 1 with TemplateObjectTO

use of com.cloud.storage.to.TemplateObjectTO in project cosmic by MissionCriticalCloud.

the class TemplateServiceImpl method handleTemplateSync.

@Override
public void handleTemplateSync(final DataStore store) {
    if (store == null) {
        s_logger.warn("Huh? image store is null");
        return;
    }
    final long storeId = store.getId();
    // add lock to make template sync for a data store only be done once
    final String lockString = "templatesync.storeId:" + storeId;
    final GlobalLock syncLock = GlobalLock.getInternLock(lockString);
    try {
        if (syncLock.lock(3)) {
            try {
                final Long zoneId = store.getScope().getScopeId();
                final Map<String, TemplateProp> templateInfos = listTemplate(store);
                if (templateInfos == null) {
                    return;
                }
                final Set<VMTemplateVO> toBeDownloaded = new HashSet<>();
                List<VMTemplateVO> allTemplates = null;
                if (zoneId == null) {
                    // region wide store
                    allTemplates = _templateDao.listByState(VirtualMachineTemplate.State.Active, VirtualMachineTemplate.State.NotUploaded, VirtualMachineTemplate.State.UploadInProgress);
                } else {
                    // zone wide store
                    allTemplates = _templateDao.listInZoneByState(zoneId, VirtualMachineTemplate.State.Active, VirtualMachineTemplate.State.NotUploaded, VirtualMachineTemplate.State.UploadInProgress);
                }
                final List<VMTemplateVO> rtngTmplts = _templateDao.listAllSystemVMTemplates();
                final List<VMTemplateVO> defaultBuiltin = _templateDao.listDefaultBuiltinTemplates();
                if (rtngTmplts != null) {
                    for (final VMTemplateVO rtngTmplt : rtngTmplts) {
                        if (!allTemplates.contains(rtngTmplt)) {
                            allTemplates.add(rtngTmplt);
                        }
                    }
                }
                if (defaultBuiltin != null) {
                    for (final VMTemplateVO builtinTmplt : defaultBuiltin) {
                        if (!allTemplates.contains(builtinTmplt)) {
                            allTemplates.add(builtinTmplt);
                        }
                    }
                }
                toBeDownloaded.addAll(allTemplates);
                final StateMachine2<VirtualMachineTemplate.State, VirtualMachineTemplate.Event, VirtualMachineTemplate> stateMachine = VirtualMachineTemplate.State.getStateMachine();
                for (final VMTemplateVO tmplt : allTemplates) {
                    final String uniqueName = tmplt.getUniqueName();
                    TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId());
                    if (templateInfos.containsKey(uniqueName)) {
                        final TemplateProp tmpltInfo = templateInfos.remove(uniqueName);
                        toBeDownloaded.remove(tmplt);
                        if (tmpltStore != null) {
                            s_logger.info("Template Sync found " + uniqueName + " already in the image store");
                            if (tmpltStore.getDownloadState() != Status.DOWNLOADED) {
                                tmpltStore.setErrorString("");
                            }
                            if (tmpltInfo.isCorrupted()) {
                                tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR);
                                String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId();
                                tmpltStore.setErrorString(msg);
                                s_logger.info(msg);
                                _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPLOAD_FAILED, zoneId, null, msg, msg);
                                if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) {
                                    s_logger.info("Template Sync found " + uniqueName + " on image store " + storeId + " uploaded using SSVM as corrupted, marking it as " + "failed");
                                    tmpltStore.setState(State.Failed);
                                    try {
                                        stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationFailed, null, _templateDao);
                                    } catch (final NoTransitionException e) {
                                        s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage());
                                    }
                                } else if (tmplt.getUrl() == null) {
                                    msg = "Private template (" + tmplt + ") with install path " + tmpltInfo.getInstallPath() + " is corrupted, please check in image store: " + tmpltStore.getDataStoreId();
                                    s_logger.warn(msg);
                                } else {
                                    s_logger.info("Removing template_store_ref entry for corrupted template " + tmplt.getName());
                                    _vmTemplateStoreDao.remove(tmpltStore.getId());
                                    toBeDownloaded.add(tmplt);
                                }
                            } else {
                                tmpltStore.setDownloadPercent(100);
                                tmpltStore.setDownloadState(Status.DOWNLOADED);
                                tmpltStore.setState(ObjectInDataStoreStateMachine.State.Ready);
                                tmpltStore.setInstallPath(tmpltInfo.getInstallPath());
                                tmpltStore.setSize(tmpltInfo.getSize());
                                tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize());
                                tmpltStore.setLastUpdated(new Date());
                                // update size in vm_template table
                                final VMTemplateVO tmlpt = _templateDao.findById(tmplt.getId());
                                tmlpt.setSize(tmpltInfo.getSize());
                                _templateDao.update(tmplt.getId(), tmlpt);
                                if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) {
                                    try {
                                        stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationSucceeded, null, _templateDao);
                                    } catch (final NoTransitionException e) {
                                        s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage());
                                    }
                                }
                                // which already got checked and incremented during createTemplate API call.
                                if (tmpltInfo.getSize() > 0 && tmplt.getAccountId() != Account.ACCOUNT_ID_SYSTEM && tmplt.getUrl() != null) {
                                    final long accountId = tmplt.getAccountId();
                                    try {
                                        _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(accountId), com.cloud.configuration.Resource.ResourceType.secondary_storage, tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl()));
                                    } catch (final ResourceAllocationException e) {
                                        s_logger.warn(e.getMessage());
                                        _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, e.getMessage(), e.getMessage());
                                    } finally {
                                        _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
                                    }
                                }
                            }
                            _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore);
                        } else {
                            tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, tmpltInfo.getInstallPath(), tmplt.getUrl());
                            tmpltStore.setSize(tmpltInfo.getSize());
                            tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize());
                            tmpltStore.setDataStoreRole(store.getRole());
                            _vmTemplateStoreDao.persist(tmpltStore);
                            // update size in vm_template table
                            final VMTemplateVO tmlpt = _templateDao.findById(tmplt.getId());
                            tmlpt.setSize(tmpltInfo.getSize());
                            _templateDao.update(tmplt.getId(), tmlpt);
                            associateTemplateToZone(tmplt.getId(), zoneId);
                        }
                    } else if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) {
                        s_logger.info("Template Sync did not find " + uniqueName + " on image store " + storeId + " uploaded using SSVM, marking it as failed");
                        toBeDownloaded.remove(tmplt);
                        tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR);
                        final String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId();
                        tmpltStore.setErrorString(msg);
                        tmpltStore.setState(State.Failed);
                        _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore);
                        try {
                            stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationFailed, null, _templateDao);
                        } catch (final NoTransitionException e) {
                            s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage());
                        }
                    } else {
                        s_logger.info("Template Sync did not find " + uniqueName + " on image store " + storeId + ", may request download based on available hypervisor types");
                        if (tmpltStore != null) {
                            if (_storeMgr.isRegionStore(store) && tmpltStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED && tmpltStore.getState() == State.Ready && tmpltStore.getInstallPath() == null) {
                                s_logger.info("Keep fake entry in template store table for migration of previous NFS to object store");
                            } else if (tmpltStore.getState() == State.Ready && tmpltStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
                                s_logger.info("Keep template " + uniqueName + " entry as state is Ready and downloaded. No need to download again.");
                            } else {
                                s_logger.info("Removing leftover template " + uniqueName + " entry from template store table");
                                // remove those leftover entries
                                _vmTemplateStoreDao.remove(tmpltStore.getId());
                            }
                        }
                    }
                }
                if (toBeDownloaded.size() > 0) {
                    /* Only download templates whose hypervirsor type is in the zone */
                    final List<HypervisorType> availHypers = _clusterDao.getAvailableHypervisorInZone(zoneId);
                    if (availHypers.isEmpty()) {
                        /*
                             * This is for cloudzone, local secondary storage resource
                             * started before cluster created
                             */
                        availHypers.add(HypervisorType.KVM);
                    }
                    // bug 9809: resume ISO
                    availHypers.add(HypervisorType.None);
                    // download.
                    for (final VMTemplateVO tmplt : toBeDownloaded) {
                        if (tmplt.getUrl() == null) {
                            // If url is null, skip downloading
                            s_logger.info("Skip downloading template " + tmplt.getUniqueName() + " since no url is specified.");
                            continue;
                        }
                        // means that this is a duplicate entry from migration of previous NFS to staging.
                        if (_storeMgr.isRegionStore(store)) {
                            final TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId());
                            if (tmpltStore != null && tmpltStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED && tmpltStore.getState() == State.Ready && tmpltStore.getInstallPath() == null) {
                                s_logger.info("Skip sync template for migration of previous NFS to object store");
                                continue;
                            }
                        }
                        if (availHypers.contains(tmplt.getHypervisorType())) {
                            s_logger.info("Downloading template " + tmplt.getUniqueName() + " to image store " + store.getName());
                            associateTemplateToZone(tmplt.getId(), zoneId);
                            final TemplateInfo tmpl = _templateFactory.getTemplate(tmplt.getId(), DataStoreRole.Image);
                            createTemplateAsync(tmpl, store, null);
                        } else {
                            s_logger.info("Skip downloading of a template because it's not part of the supported hypervisors");
                        }
                    }
                }
                for (final String uniqueName : templateInfos.keySet()) {
                    final TemplateProp tInfo = templateInfos.get(uniqueName);
                    if (_tmpltMgr.templateIsDeleteable(tInfo.getId())) {
                        // we cannot directly call deleteTemplateSync here to reuse delete logic since in this case db does not have this template at all.
                        final TemplateObjectTO tmplTO = new TemplateObjectTO();
                        tmplTO.setDataStore(store.getTO());
                        tmplTO.setPath(tInfo.getInstallPath());
                        tmplTO.setId(tInfo.getId());
                        final DeleteCommand dtCommand = new DeleteCommand(tmplTO);
                        final EndPoint ep = _epSelector.select(store);
                        Answer answer = null;
                        if (ep == null) {
                            final String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
                            s_logger.error(errMsg);
                            answer = new Answer(dtCommand, false, errMsg);
                        } else {
                            answer = ep.sendMessage(dtCommand);
                        }
                        if (answer == null || !answer.getResult()) {
                            s_logger.info("Failed to deleted template at store: " + store.getName());
                        } else {
                            final String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + storeId;
                            s_logger.info(description);
                        }
                    }
                }
            } finally {
                syncLock.unlock();
            }
        } else {
            s_logger.info("Couldn't get global lock on " + lockString + ", another thread may be doing template sync on data store " + storeId + " now.");
        }
    } finally {
        syncLock.releaseRef();
    }
}
Also used : TemplateProp(com.cloud.storage.template.TemplateProp) VMTemplateVO(com.cloud.storage.VMTemplateVO) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) GlobalLock(com.cloud.utils.db.GlobalLock) DeleteCommand(com.cloud.storage.command.DeleteCommand) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) HashSet(java.util.HashSet) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) Date(java.util.Date) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Answer(com.cloud.agent.api.Answer) ListTemplateAnswer(com.cloud.agent.api.storage.ListTemplateAnswer) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) State(com.cloud.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) Event(com.cloud.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO)

Example 2 with TemplateObjectTO

use of com.cloud.storage.to.TemplateObjectTO in project cosmic by MissionCriticalCloud.

the class KvmStorageProcessor method copyTemplateToPrimaryStorage.

@Override
public Answer copyTemplateToPrimaryStorage(final CopyCommand cmd) {
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    final TemplateObjectTO template = (TemplateObjectTO) srcData;
    final DataStoreTO imageStore = template.getDataStore();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) destData.getDataStore();
    if (!(imageStore instanceof NfsTO)) {
        return new CopyCmdAnswer("unsupported protocol");
    }
    final NfsTO nfsImageStore = (NfsTO) imageStore;
    final String tmplturl = nfsImageStore.getUrl() + File.separator + template.getPath();
    final int index = tmplturl.lastIndexOf("/");
    final String mountpoint = tmplturl.substring(0, index);
    String tmpltname = null;
    if (index < tmplturl.length() - 1) {
        tmpltname = tmplturl.substring(index + 1);
    }
    KvmPhysicalDisk tmplVol = null;
    KvmStoragePool secondaryPool = null;
    try {
        secondaryPool = storagePoolMgr.getStoragePoolByUri(mountpoint);
        /* Get template vol */
        if (tmpltname == null) {
            secondaryPool.refresh();
            final List<KvmPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
            if (disks == null || disks.isEmpty()) {
                return new PrimaryStorageDownloadAnswer("Failed to get volumes from pool: " + secondaryPool.getUuid());
            }
            for (final KvmPhysicalDisk disk : disks) {
                if (disk.getName().endsWith("qcow2")) {
                    tmplVol = disk;
                    break;
                }
            }
        } else {
            tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
        }
        if (tmplVol == null) {
            return new PrimaryStorageDownloadAnswer("Failed to get template from pool: " + secondaryPool.getUuid());
        }
        /* Copy volume to primary storage */
        logger.debug("Copying template to primary storage, template format is " + tmplVol.getFormat());
        final KvmStoragePool primaryPool = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
        KvmPhysicalDisk primaryVol;
        if (destData instanceof VolumeObjectTO) {
            final VolumeObjectTO volume = (VolumeObjectTO) destData;
            // rather than cloning on deploy
            if (volume.getSize() != null && volume.getSize() > tmplVol.getVirtualSize()) {
                logger.debug("Using configured size of " + volume.getSize());
                tmplVol.setSize(volume.getSize());
                tmplVol.setVirtualSize(volume.getSize());
            } else {
                logger.debug("Using template's size of " + tmplVol.getVirtualSize());
            }
            primaryVol = storagePoolMgr.copyPhysicalDisk(tmplVol, volume.getUuid(), primaryPool, cmd.getWaitInMillSeconds());
        } else if (destData instanceof TemplateObjectTO) {
            final TemplateObjectTO destTempl = (TemplateObjectTO) destData;
            primaryVol = storagePoolMgr.copyPhysicalDisk(tmplVol, destTempl.getUuid(), primaryPool, cmd.getWaitInMillSeconds());
        } else {
            primaryVol = storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, cmd.getWaitInMillSeconds());
        }
        DataTO data = null;
        if (destData.getObjectType() == DataObjectType.TEMPLATE) {
            final TemplateObjectTO newTemplate = new TemplateObjectTO();
            newTemplate.setPath(primaryVol.getName());
            newTemplate.setSize(primaryVol.getSize());
            if (primaryPool.getType() == StoragePoolType.RBD) {
                newTemplate.setFormat(ImageFormat.RAW);
            } else {
                newTemplate.setFormat(ImageFormat.QCOW2);
            }
            data = newTemplate;
        } else if (destData.getObjectType() == DataObjectType.VOLUME) {
            final VolumeObjectTO volumeObjectTo = new VolumeObjectTO();
            volumeObjectTo.setPath(primaryVol.getName());
            volumeObjectTo.setSize(primaryVol.getSize());
            if (primaryVol.getFormat() == PhysicalDiskFormat.RAW) {
                volumeObjectTo.setFormat(ImageFormat.RAW);
            } else if (primaryVol.getFormat() == PhysicalDiskFormat.QCOW2) {
                volumeObjectTo.setFormat(ImageFormat.QCOW2);
            }
            data = volumeObjectTo;
        }
        return new CopyCmdAnswer(data);
    } catch (final CloudRuntimeException e) {
        return new CopyCmdAnswer(e.toString());
    } finally {
        try {
            if (secondaryPool != null) {
                secondaryPool.delete();
            }
        } catch (final Exception e) {
            logger.debug("Failed to clean up secondary storage", e);
        }
    }
}
Also used : PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) NfsTO(com.cloud.agent.api.to.NfsTO) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) QemuImgException(com.cloud.utils.qemu.QemuImgException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) PrimaryStorageDownloadAnswer(com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(com.cloud.storage.to.VolumeObjectTO) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) CopyCmdAnswer(com.cloud.storage.command.CopyCmdAnswer)

Example 3 with TemplateObjectTO

use of com.cloud.storage.to.TemplateObjectTO in project cosmic by MissionCriticalCloud.

the class CitrixResourceBase method mount.

protected VDI mount(final Connection conn, final String vmName, final DiskTO volume) throws XmlRpcException, XenAPIException {
    final DataTO data = volume.getData();
    final Volume.Type type = volume.getType();
    if (type == Volume.Type.ISO) {
        final TemplateObjectTO iso = (TemplateObjectTO) data;
        final DataStoreTO store = iso.getDataStore();
        if (store == null) {
            // It's a fake iso
            return null;
        }
        // corer case, xenserver pv driver iso
        final String templateName = iso.getName();
        if (templateName.startsWith("xs-tools")) {
            try {
                final Set<VDI> vdis = VDI.getByNameLabel(conn, templateName);
                if (vdis.isEmpty()) {
                    throw new CloudRuntimeException("Could not find ISO with URL: " + templateName);
                }
                return vdis.iterator().next();
            } catch (final XenAPIException e) {
                throw new CloudRuntimeException("Unable to get pv iso: " + templateName + " due to " + e.toString());
            } catch (final Exception e) {
                throw new CloudRuntimeException("Unable to get pv iso: " + templateName + " due to " + e.toString());
            }
        }
        if (!(store instanceof NfsTO)) {
            throw new CloudRuntimeException("only support mount iso on nfs");
        }
        final NfsTO nfsStore = (NfsTO) store;
        final String isoPath = nfsStore.getUrl() + File.separator + iso.getPath();
        final int index = isoPath.lastIndexOf("/");
        final String mountpoint = isoPath.substring(0, index);
        final URI uri;
        try {
            uri = new URI(mountpoint);
        } catch (final URISyntaxException e) {
            throw new CloudRuntimeException("Incorrect uri " + mountpoint, e);
        }
        final SR isoSr = createIsoSRbyURI(conn, uri, vmName, false);
        final String isoname = isoPath.substring(index + 1);
        final VDI isoVdi = getVDIbyLocationandSR(conn, isoname, isoSr);
        if (isoVdi == null) {
            throw new CloudRuntimeException("Unable to find ISO " + isoPath);
        }
        return isoVdi;
    } else {
        final VolumeObjectTO vol = (VolumeObjectTO) data;
        return VDI.getByUuid(conn, vol.getPath());
    }
}
Also used : DataStoreTO(com.cloud.agent.api.to.DataStoreTO) XenAPIException(com.xensource.xenapi.Types.XenAPIException) URISyntaxException(java.net.URISyntaxException) NfsTO(com.cloud.agent.api.to.NfsTO) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) SAXException(org.xml.sax.SAXException) ConfigurationException(javax.naming.ConfigurationException) MalformedURLException(java.net.MalformedURLException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DataTO(com.cloud.agent.api.to.DataTO) Volume(com.cloud.storage.Volume) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(com.cloud.storage.to.VolumeObjectTO) VDI(com.xensource.xenapi.VDI) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) SR(com.xensource.xenapi.SR)

Example 4 with TemplateObjectTO

use of com.cloud.storage.to.TemplateObjectTO in project cosmic by MissionCriticalCloud.

the class XenServerStorageProcessor method attachIso.

@Override
public AttachAnswer attachIso(final AttachCommand cmd) {
    final DiskTO disk = cmd.getDisk();
    final DataTO data = disk.getData();
    final DataStoreTO store = data.getDataStore();
    String isoURL = null;
    if (store == null) {
        final TemplateObjectTO iso = (TemplateObjectTO) disk.getData();
        isoURL = iso.getName();
    } else {
        if (!(store instanceof NfsTO)) {
            s_logger.debug("Can't attach a iso which is not created on nfs: ");
            return new AttachAnswer("Can't attach a iso which is not created on nfs: ");
        }
        final NfsTO nfsStore = (NfsTO) store;
        isoURL = nfsStore.getUrl() + nfsStore.getPathSeparator() + data.getPath();
    }
    final String vmName = cmd.getVmName();
    try {
        final Connection conn = hypervisorResource.getConnection();
        VBD isoVBD = null;
        // Find the VM
        final VM vm = hypervisorResource.getVM(conn, vmName);
        // Find the ISO VDI
        final VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL);
        // Find the VM's CD-ROM VBD
        final Set<VBD> vbds = vm.getVBDs(conn);
        for (final VBD vbd : vbds) {
            final String userDevice = vbd.getUserdevice(conn);
            final Types.VbdType type = vbd.getType(conn);
            if (userDevice.equals("3") && type == Types.VbdType.CD) {
                isoVBD = vbd;
                break;
            }
        }
        if (isoVBD == null) {
            throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName);
        } else {
            // If an ISO is already inserted, eject it
            if (!isoVBD.getEmpty(conn)) {
                isoVBD.eject(conn);
            }
            // Insert the new ISO
            isoVBD.insert(conn, isoVDI);
        }
        return new AttachAnswer(disk);
    } catch (final XenAPIException e) {
        s_logger.warn("Failed to attach iso" + ": " + e.toString(), e);
        return new AttachAnswer(e.toString());
    } catch (final Exception e) {
        s_logger.warn("Failed to attach iso" + ": " + e.toString(), e);
        return new AttachAnswer(e.toString());
    }
}
Also used : Types(com.xensource.xenapi.Types) PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) Connection(com.xensource.xenapi.Connection) XenAPIException(com.xensource.xenapi.Types.XenAPIException) NfsTO(com.cloud.agent.api.to.NfsTO) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataTO(com.cloud.agent.api.to.DataTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VM(com.xensource.xenapi.VM) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) DiskTO(com.cloud.agent.api.to.DiskTO) AttachAnswer(com.cloud.storage.command.AttachAnswer)

Example 5 with TemplateObjectTO

use of com.cloud.storage.to.TemplateObjectTO in project cosmic by MissionCriticalCloud.

the class XenServerStorageProcessor method createTemplateFromSnapshot.

@Override
public Answer createTemplateFromSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final SnapshotObjectTO snapshotObjTO = (SnapshotObjectTO) cmd.getSrcTO();
    final TemplateObjectTO templateObjTO = (TemplateObjectTO) cmd.getDestTO();
    if (!(snapshotObjTO.getDataStore() instanceof PrimaryDataStoreTO) || !(templateObjTO.getDataStore() instanceof NfsTO)) {
        return null;
    }
    final String userSpecifiedTemplateName = templateObjTO.getName();
    NfsTO destStore = null;
    URI destUri = null;
    try {
        destStore = (NfsTO) templateObjTO.getDataStore();
        destUri = new URI(destStore.getUrl());
    } catch (final Exception ex) {
        s_logger.debug("Invalid URI", ex);
        return new CopyCmdAnswer("Invalid URI: " + ex.toString());
    }
    SR srcSr = null;
    SR destSr = null;
    final String destDir = templateObjTO.getPath();
    VDI destVdi = null;
    boolean result = false;
    try {
        final Map<String, String> srcDetails = cmd.getOptions();
        final String iScsiName = srcDetails.get(DiskTO.IQN);
        final String storageHost = srcDetails.get(DiskTO.STORAGE_HOST);
        final String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME);
        final String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET);
        srcSr = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true);
        final String destNfsPath = destUri.getHost() + ":" + destUri.getPath();
        if (!hypervisorResource.createSecondaryStorageFolder(conn, destNfsPath, destDir)) {
            final String details = " Failed to create folder " + destDir + " in secondary storage";
            s_logger.warn(details);
            return new CopyCmdAnswer(details);
        }
        final URI templateUri = new URI(destStore.getUrl() + "/" + destDir);
        destSr = hypervisorResource.createNfsSRbyURI(conn, templateUri, false);
        // there should only be one VDI in this SR
        final VDI srcVdi = srcSr.getVDIs(conn).iterator().next();
        destVdi = srcVdi.copy(conn, destSr);
        // scan makes XenServer pick up VDI physicalSize
        destSr.scan(conn);
        if (userSpecifiedTemplateName != null) {
            destVdi.setNameLabel(conn, userSpecifiedTemplateName);
        }
        final String templateUuid = destVdi.getUuid(conn);
        final String templateFilename = templateUuid + ".vhd";
        final long virtualSize = destVdi.getVirtualSize(conn);
        final long physicalSize = destVdi.getPhysicalUtilisation(conn);
        // create the template.properties file
        String templatePath = destNfsPath + "/" + destDir;
        templatePath = templatePath.replaceAll("//", "/");
        result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, templateFilename, templateUuid, userSpecifiedTemplateName, null, physicalSize, virtualSize, templateObjTO.getId());
        if (!result) {
            throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir: " + templateUri);
        }
        final TemplateObjectTO newTemplate = new TemplateObjectTO();
        newTemplate.setPath(destDir + "/" + templateFilename);
        newTemplate.setFormat(Storage.ImageFormat.VHD);
        newTemplate.setHypervisorType(HypervisorType.XenServer);
        newTemplate.setSize(virtualSize);
        newTemplate.setPhysicalSize(physicalSize);
        newTemplate.setName(templateUuid);
        result = true;
        return new CopyCmdAnswer(newTemplate);
    } catch (final Exception ex) {
        s_logger.error("Failed to create a template from a snapshot", ex);
        return new CopyCmdAnswer("Failed to create a template from a snapshot: " + ex.toString());
    } finally {
        if (!result) {
            if (destVdi != null) {
                try {
                    destVdi.destroy(conn);
                } catch (final Exception e) {
                    s_logger.debug("Cleaned up leftover VDI on destination storage due to failure: ", e);
                }
            }
        }
        if (srcSr != null) {
            hypervisorResource.removeSR(conn, srcSr);
        }
        if (destSr != null) {
            hypervisorResource.removeSR(conn, destSr);
        }
    }
}
Also used : SnapshotObjectTO(com.cloud.storage.to.SnapshotObjectTO) Connection(com.xensource.xenapi.Connection) NfsTO(com.cloud.agent.api.to.NfsTO) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) InternalErrorException(com.cloud.exception.InternalErrorException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PrimaryDataStoreTO(com.cloud.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VDI(com.xensource.xenapi.VDI) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) CopyCmdAnswer(com.cloud.storage.command.CopyCmdAnswer) SR(com.xensource.xenapi.SR)

Aggregations

TemplateObjectTO (com.cloud.storage.to.TemplateObjectTO)24 CopyCmdAnswer (com.cloud.storage.command.CopyCmdAnswer)17 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)17 NfsTO (com.cloud.agent.api.to.NfsTO)15 InternalErrorException (com.cloud.exception.InternalErrorException)14 PrimaryDataStoreTO (com.cloud.storage.to.PrimaryDataStoreTO)12 XenAPIException (com.xensource.xenapi.Types.XenAPIException)11 XmlRpcException (org.apache.xmlrpc.XmlRpcException)11 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)10 DataTO (com.cloud.agent.api.to.DataTO)10 VDI (com.xensource.xenapi.VDI)10 Connection (com.xensource.xenapi.Connection)9 SR (com.xensource.xenapi.SR)9 URI (java.net.URI)8 VolumeObjectTO (com.cloud.storage.to.VolumeObjectTO)7 DiskTO (com.cloud.agent.api.to.DiskTO)6 URISyntaxException (java.net.URISyntaxException)6 ConfigurationException (javax.naming.ConfigurationException)6 IOException (java.io.IOException)5 Answer (com.cloud.agent.api.Answer)4