Search in sources :

Example 31 with EndPoint

use of org.apache.cloudstack.engine.subsystem.api.storage.EndPoint in project cloudstack by apache.

the class UploadMonitorImpl method createEntityDownloadURL.

@Override
public UploadVO createEntityDownloadURL(VMTemplateVO template, TemplateDataStoreVO vmTemplateHost, Long dataCenterId, long eventId) {
    String errorString = "";
    boolean success = false;
    Type type = (template.getFormat() == ImageFormat.ISO) ? Type.ISO : Type.TEMPLATE;
    // find an endpoint to send command
    DataStore store = storeMgr.getDataStore(vmTemplateHost.getDataStoreId(), DataStoreRole.Image);
    EndPoint ep = _epSelector.select(store);
    if (ep == null) {
        String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
        s_logger.error(errMsg);
        return null;
    }
    //Check if it already exists.
    List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(template.getId(), type, UploadVO.Status.DOWNLOAD_URL_CREATED);
    if (extractURLList.size() > 0) {
        // do some check here
        UploadVO upload = extractURLList.get(0);
        String uploadUrl = extractURLList.get(0).getUploadUrl();
        String[] token = uploadUrl.split("/");
        // example: uploadUrl = https://10-11-101-112.realhostip.com/userdata/2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso
        // then token[2] = 10-11-101-112.realhostip.com, token[4] = 2fdd9a70-9c4a-4a04-b1d5-1e41c221a1f9.iso
        String hostname = ep.getPublicAddr().replace(".", "-") + ".";
        if (// ssvm publicip and domain suffix not changed
        (token != null) && (token.length == 5) && (token[2].equals(hostname + _ssvmUrlDomain)))
            return extractURLList.get(0);
        else if ((token != null) && (token.length == 5) && (token[2].startsWith(hostname))) {
            // domain suffix changed
            String uuid = token[4];
            uploadUrl = generateCopyUrl(ep.getPublicAddr(), uuid);
            UploadVO vo = _uploadDao.createForUpdate();
            vo.setLastUpdated(new Date());
            vo.setUploadUrl(uploadUrl);
            _uploadDao.update(upload.getId(), vo);
            return _uploadDao.findById(upload.getId(), true);
        } else {
            // ssvm publicip changed
            return null;
        }
    }
    // It doesn't exist so create a DB entry.
    UploadVO uploadTemplateObj = new UploadVO(vmTemplateHost.getDataStoreId(), template.getId(), new Date(), Status.DOWNLOAD_URL_NOT_CREATED, 0, type, Mode.HTTP_DOWNLOAD);
    uploadTemplateObj.setInstallPath(vmTemplateHost.getInstallPath());
    _uploadDao.persist(uploadTemplateObj);
    try {
        // Create Symlink at ssvm
        String path = vmTemplateHost.getInstallPath();
        // adding "." + vhd/ova... etc.
        String uuid = UUID.randomUUID().toString() + "." + template.getFormat().getFileExtension();
        CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity) store).getMountPoint(), path, uuid, null);
        Answer ans = ep.sendMessage(cmd);
        if (ans == null || !ans.getResult()) {
            errorString = "Unable to create a link for " + type + " id:" + template.getId() + "," + (ans == null ? "" : ans.getDetails());
            s_logger.error(errorString);
            throw new CloudRuntimeException(errorString);
        }
        //Construct actual URL locally now that the symlink exists at SSVM
        String extractURL = generateCopyUrl(ep.getPublicAddr(), uuid);
        UploadVO vo = _uploadDao.createForUpdate();
        vo.setLastUpdated(new Date());
        vo.setUploadUrl(extractURL);
        vo.setUploadState(Status.DOWNLOAD_URL_CREATED);
        _uploadDao.update(uploadTemplateObj.getId(), vo);
        success = true;
        return _uploadDao.findById(uploadTemplateObj.getId(), true);
    } finally {
        if (!success) {
            UploadVO uploadJob = _uploadDao.createForUpdate(uploadTemplateObj.getId());
            uploadJob.setLastUpdated(new Date());
            uploadJob.setErrorString(errorString);
            uploadJob.setUploadState(Status.ERROR);
            _uploadDao.update(uploadTemplateObj.getId(), uploadJob);
        }
    }
}
Also used : CreateEntityDownloadURLCommand(com.cloud.agent.api.storage.CreateEntityDownloadURLCommand) Answer(com.cloud.agent.api.Answer) Type(com.cloud.storage.Upload.Type) RequestType(com.cloud.agent.api.storage.UploadProgressCommand.RequestType) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) UploadVO(com.cloud.storage.UploadVO) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) Date(java.util.Date)

Example 32 with EndPoint

use of org.apache.cloudstack.engine.subsystem.api.storage.EndPoint in project cloudstack by apache.

the class UploadListener method sendCommand.

public void sendCommand(RequestType reqType) {
    if (getJobId() != null) {
        if (s_logger.isTraceEnabled()) {
            log("Sending progress command ", Level.TRACE);
        }
        try {
            EndPoint ep = _epSelector.select(sserver);
            if (ep == null) {
                String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
                s_logger.error(errMsg);
                return;
            }
            ep.sendMessageAsync(new UploadProgressCommand(getCommand(), getJobId(), reqType), new Callback(ep.getId(), this));
        } catch (Exception e) {
            s_logger.debug("Send command failed", e);
            setDisconnected();
        }
    }
}
Also used : AsyncCompletionCallback(org.apache.cloudstack.framework.async.AsyncCompletionCallback) UploadProgressCommand(com.cloud.agent.api.storage.UploadProgressCommand) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 33 with EndPoint

use of org.apache.cloudstack.engine.subsystem.api.storage.EndPoint in project cloudstack by apache.

the class UploadMonitorImpl method createVolumeDownloadURL.

@Override
public void createVolumeDownloadURL(Long entityId, String path, Type type, Long dataCenterId, Long uploadId, ImageFormat format) {
    String errorString = "";
    boolean success = false;
    try {
        List<HostVO> storageServers = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.SecondaryStorage, dataCenterId);
        if (storageServers == null) {
            errorString = "No Storage Server found at the datacenter - " + dataCenterId;
            throw new CloudRuntimeException(errorString);
        }
        // Update DB for state = DOWNLOAD_URL_NOT_CREATED.
        UploadVO uploadJob = _uploadDao.createForUpdate(uploadId);
        uploadJob.setUploadState(Status.DOWNLOAD_URL_NOT_CREATED);
        uploadJob.setLastUpdated(new Date());
        _uploadDao.update(uploadJob.getId(), uploadJob);
        // Create Symlink at ssvm
        String uuid = UUID.randomUUID().toString() + "." + format.toString().toLowerCase();
        DataStore secStore = storeMgr.getDataStore(ApiDBUtils.findUploadById(uploadId).getDataStoreId(), DataStoreRole.Image);
        EndPoint ep = _epSelector.select(secStore);
        if (ep == null) {
            errorString = "There is no secondary storage VM for secondary storage host " + secStore.getName();
            throw new CloudRuntimeException(errorString);
        }
        CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity) secStore).getMountPoint(), path, uuid, null);
        Answer ans = ep.sendMessage(cmd);
        if (ans == null || !ans.getResult()) {
            errorString = "Unable to create a link for " + type + " id:" + entityId + "," + (ans == null ? "" : ans.getDetails());
            s_logger.warn(errorString);
            throw new CloudRuntimeException(errorString);
        }
        List<SecondaryStorageVmVO> ssVms = _secStorageVmDao.getSecStorageVmListInStates(SecondaryStorageVm.Role.templateProcessor, dataCenterId, State.Running);
        if (ssVms.size() > 0) {
            SecondaryStorageVmVO ssVm = ssVms.get(0);
            if (ssVm.getPublicIpAddress() == null) {
                errorString = "A running secondary storage vm has a null public ip?";
                s_logger.error(errorString);
                throw new CloudRuntimeException(errorString);
            }
            //Construct actual URL locally now that the symlink exists at SSVM
            String extractURL = generateCopyUrl(ssVm.getPublicIpAddress(), uuid);
            UploadVO vo = _uploadDao.createForUpdate();
            vo.setLastUpdated(new Date());
            vo.setUploadUrl(extractURL);
            vo.setUploadState(Status.DOWNLOAD_URL_CREATED);
            _uploadDao.update(uploadId, vo);
            success = true;
            return;
        }
        errorString = "Couldnt find a running SSVM in the zone" + dataCenterId + ". Couldnt create the extraction URL.";
        throw new CloudRuntimeException(errorString);
    } finally {
        if (!success) {
            UploadVO uploadJob = _uploadDao.createForUpdate(uploadId);
            uploadJob.setLastUpdated(new Date());
            uploadJob.setErrorString(errorString);
            uploadJob.setUploadState(Status.ERROR);
            _uploadDao.update(uploadId, uploadJob);
        }
    }
}
Also used : SecondaryStorageVmVO(com.cloud.vm.SecondaryStorageVmVO) UploadVO(com.cloud.storage.UploadVO) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) HostVO(com.cloud.host.HostVO) Date(java.util.Date) CreateEntityDownloadURLCommand(com.cloud.agent.api.storage.CreateEntityDownloadURLCommand) Answer(com.cloud.agent.api.Answer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore)

Example 34 with EndPoint

use of org.apache.cloudstack.engine.subsystem.api.storage.EndPoint in project cloudstack by apache.

the class StorageManagerImpl method cleanupStorage.

@Override
public void cleanupStorage(boolean recurring) {
    GlobalLock scanLock = GlobalLock.getInternLock("storagemgr.cleanup");
    try {
        if (scanLock.lock(3)) {
            try {
                // Cleanup primary storage pools
                if (_templateCleanupEnabled) {
                    List<StoragePoolVO> storagePools = _storagePoolDao.listAll();
                    for (StoragePoolVO pool : storagePools) {
                        try {
                            List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool);
                            s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName());
                            for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) {
                                if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
                                    s_logger.debug("Storage pool garbage collector is skipping template with ID: " + templatePoolVO.getTemplateId() + " on pool " + templatePoolVO.getPoolId() + " because it is not completely downloaded.");
                                    continue;
                                }
                                if (!templatePoolVO.getMarkedForGC()) {
                                    templatePoolVO.setMarkedForGC(true);
                                    _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO);
                                    s_logger.debug("Storage pool garbage collector has marked template with ID: " + templatePoolVO.getTemplateId() + " on pool " + templatePoolVO.getPoolId() + " for garbage collection.");
                                    continue;
                                }
                                _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO);
                            }
                        } catch (Exception e) {
                            s_logger.warn("Problem cleaning up primary storage pool " + pool, e);
                        }
                    }
                }
                cleanupSecondaryStorage(recurring);
                List<VolumeVO> vols = _volsDao.listVolumesToBeDestroyed(new Date(System.currentTimeMillis() - ((long) StorageCleanupDelay.value() << 10)));
                for (VolumeVO vol : vols) {
                    try {
                        // If this fails, just log a warning. It's ideal if we clean up the host-side clustered file
                        // system, but not necessary.
                        handleManagedStorage(vol);
                    } catch (Exception e) {
                        s_logger.warn("Unable to destroy host-side clustered file system " + vol.getUuid(), e);
                    }
                    try {
                        VolumeInfo volumeInfo = volFactory.getVolume(vol.getId());
                        if (volumeInfo != null) {
                            volService.expungeVolumeAsync(volumeInfo);
                        } else {
                            s_logger.debug("Volume " + vol.getUuid() + " is already destroyed");
                        }
                    } catch (Exception e) {
                        s_logger.warn("Unable to destroy volume " + vol.getUuid(), e);
                    }
                }
                // remove snapshots in Error state
                List<SnapshotVO> snapshots = _snapshotDao.listAllByStatus(Snapshot.State.Error);
                for (SnapshotVO snapshotVO : snapshots) {
                    try {
                        List<SnapshotDataStoreVO> storeRefs = _snapshotStoreDao.findBySnapshotId(snapshotVO.getId());
                        for (SnapshotDataStoreVO ref : storeRefs) {
                            _snapshotStoreDao.expunge(ref.getId());
                        }
                        _snapshotDao.expunge(snapshotVO.getId());
                    } catch (Exception e) {
                        s_logger.warn("Unable to destroy snapshot " + snapshotVO.getUuid(), e);
                    }
                }
                // destroy uploaded volumes in abandoned/error state
                List<VolumeDataStoreVO> volumeDataStores = _volumeDataStoreDao.listByVolumeState(Volume.State.UploadError, Volume.State.UploadAbandoned);
                for (VolumeDataStoreVO volumeDataStore : volumeDataStores) {
                    VolumeVO volume = _volumeDao.findById(volumeDataStore.getVolumeId());
                    if (volume == null) {
                        s_logger.warn("Uploaded volume with id " + volumeDataStore.getVolumeId() + " not found, so cannot be destroyed");
                        continue;
                    }
                    try {
                        DataStore dataStore = _dataStoreMgr.getDataStore(volumeDataStore.getDataStoreId(), DataStoreRole.Image);
                        EndPoint ep = _epSelector.select(dataStore, volumeDataStore.getExtractUrl());
                        if (ep == null) {
                            s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded volume " + volume.getUuid());
                            continue;
                        }
                        Host host = _hostDao.findById(ep.getId());
                        if (host != null && host.getManagementServerId() != null) {
                            if (_serverId == host.getManagementServerId().longValue()) {
                                if (!volService.destroyVolume(volume.getId())) {
                                    s_logger.warn("Unable to destroy uploaded volume " + volume.getUuid());
                                    continue;
                                }
                                // decrement volume resource count
                                _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, volume.isDisplayVolume());
                                // expunge volume from secondary if volume is on image store
                                VolumeInfo volOnSecondary = volFactory.getVolume(volume.getId(), DataStoreRole.Image);
                                if (volOnSecondary != null) {
                                    s_logger.info("Expunging volume " + volume.getUuid() + " uploaded using HTTP POST from secondary data store");
                                    AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volOnSecondary);
                                    VolumeApiResult result = future.get();
                                    if (!result.isSuccess()) {
                                        s_logger.warn("Failed to expunge volume " + volume.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult());
                                    }
                                }
                            }
                        }
                    } catch (Throwable th) {
                        s_logger.warn("Unable to destroy uploaded volume " + volume.getUuid() + ". Error details: " + th.getMessage());
                    }
                }
                // destroy uploaded templates in abandoned/error state
                List<TemplateDataStoreVO> templateDataStores = _templateStoreDao.listByTemplateState(VirtualMachineTemplate.State.UploadError, VirtualMachineTemplate.State.UploadAbandoned);
                for (TemplateDataStoreVO templateDataStore : templateDataStores) {
                    VMTemplateVO template = _templateDao.findById(templateDataStore.getTemplateId());
                    if (template == null) {
                        s_logger.warn("Uploaded template with id " + templateDataStore.getTemplateId() + " not found, so cannot be destroyed");
                        continue;
                    }
                    try {
                        DataStore dataStore = _dataStoreMgr.getDataStore(templateDataStore.getDataStoreId(), DataStoreRole.Image);
                        EndPoint ep = _epSelector.select(dataStore, templateDataStore.getExtractUrl());
                        if (ep == null) {
                            s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded template " + template.getUuid());
                            continue;
                        }
                        Host host = _hostDao.findById(ep.getId());
                        if (host != null && host.getManagementServerId() != null) {
                            if (_serverId == host.getManagementServerId().longValue()) {
                                AsyncCallFuture<TemplateApiResult> future = _imageSrv.deleteTemplateAsync(tmplFactory.getTemplate(template.getId(), dataStore));
                                TemplateApiResult result = future.get();
                                if (!result.isSuccess()) {
                                    s_logger.warn("Failed to delete template " + template.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult());
                                    continue;
                                }
                                // remove from template_zone_ref
                                List<VMTemplateZoneVO> templateZones = _vmTemplateZoneDao.listByZoneTemplate(((ImageStoreEntity) dataStore).getDataCenterId(), template.getId());
                                if (templateZones != null) {
                                    for (VMTemplateZoneVO templateZone : templateZones) {
                                        _vmTemplateZoneDao.remove(templateZone.getId());
                                    }
                                }
                                // mark all the occurrences of this template in the given store as destroyed
                                _templateStoreDao.removeByTemplateStore(template.getId(), dataStore.getId());
                                // find all eligible image stores for this template
                                List<DataStore> imageStores = _tmpltMgr.getImageStoreByTemplate(template.getId(), null);
                                if (imageStores == null || imageStores.size() == 0) {
                                    template.setState(VirtualMachineTemplate.State.Inactive);
                                    _templateDao.update(template.getId(), template);
                                    // decrement template resource count
                                    _resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
                                }
                            }
                        }
                    } catch (Throwable th) {
                        s_logger.warn("Unable to destroy uploaded template " + template.getUuid() + ". Error details: " + th.getMessage());
                    }
                }
            } finally {
                scanLock.unlock();
            }
        }
    } finally {
        scanLock.releaseRef();
    }
}
Also used : VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) VolumeApiResult(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult) GlobalLock(com.cloud.utils.db.GlobalLock) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) VolumeDataStoreVO(org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO) SnapshotDataStoreVO(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO) Host(com.cloud.host.Host) ManagementServerHost(com.cloud.cluster.ManagementServerHost) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO) ConnectionException(com.cloud.exception.ConnectionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) StorageConflictException(com.cloud.exception.StorageConflictException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) ResourceInUseException(com.cloud.exception.ResourceInUseException) URISyntaxException(java.net.URISyntaxException) DiscoveryException(com.cloud.exception.DiscoveryException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Date(java.util.Date) TemplateApiResult(org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult)

Example 35 with EndPoint

use of org.apache.cloudstack.engine.subsystem.api.storage.EndPoint in project cloudstack by apache.

the class AncientDataMotionStrategy method cloneVolume.

protected Answer cloneVolume(DataObject template, DataObject volume) {
    CopyCommand cmd = new CopyCommand(template.getTO(), addFullCloneFlagOnVMwareDest(volume.getTO()), 0, VirtualMachineManager.ExecuteInSequence.value());
    try {
        EndPoint ep = selector.select(volume.getDataStore());
        Answer answer = null;
        if (ep == null) {
            String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
            s_logger.error(errMsg);
            answer = new Answer(cmd, false, errMsg);
        } else {
            answer = ep.sendMessage(cmd);
        }
        return answer;
    } catch (Exception e) {
        s_logger.debug("Failed to send to storage pool", e);
        throw new CloudRuntimeException("Failed to send to storage pool", e);
    }
}
Also used : Answer(com.cloud.agent.api.Answer) MigrateVolumeAnswer(com.cloud.agent.api.storage.MigrateVolumeAnswer) CopyCommand(org.apache.cloudstack.storage.command.CopyCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) RemoteHostEndPoint(org.apache.cloudstack.storage.RemoteHostEndPoint) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Aggregations

EndPoint (org.apache.cloudstack.engine.subsystem.api.storage.EndPoint)44 Answer (com.cloud.agent.api.Answer)28 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)22 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)17 RemoteHostEndPoint (org.apache.cloudstack.storage.RemoteHostEndPoint)13 DataObject (org.apache.cloudstack.engine.subsystem.api.storage.DataObject)10 CopyCmdAnswer (org.apache.cloudstack.storage.command.CopyCmdAnswer)9 Date (java.util.Date)8 CopyCommand (org.apache.cloudstack.storage.command.CopyCommand)8 MigrateVolumeAnswer (com.cloud.agent.api.storage.MigrateVolumeAnswer)7 ZoneScope (org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope)6 ResizeVolumeAnswer (com.cloud.agent.api.storage.ResizeVolumeAnswer)5 HostVO (com.cloud.host.HostVO)5 CopyCommandResult (org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult)5 UploadVO (com.cloud.storage.UploadVO)4 URISyntaxException (java.net.URISyntaxException)4 ClusterScope (org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope)4 VolumeInfo (org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo)4 VolumeDataStoreVO (org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO)4 CreateEntityDownloadURLCommand (com.cloud.agent.api.storage.CreateEntityDownloadURLCommand)3