Search in sources :

Example 41 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 42 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 43 with EndPoint

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

the class SamplePrimaryDataStoreDriverImpl method createAsync.

/*
     * private class CreateVolumeFromBaseImageContext<T> extends
     * AsyncRpcContext<T> { private final VolumeObject volume;
     *
     * public CreateVolumeFromBaseImageContext(AsyncCompletionCallback<T>
     * callback, VolumeObject volume) { super(callback); this.volume = volume; }
     *
     * public VolumeObject getVolume() { return this.volume; }
     *
     * }
     *
     * @Override public void createVolumeFromBaseImageAsync(VolumeObject volume,
     * TemplateInfo template, AsyncCompletionCallback<CommandResult> callback) {
     * VolumeTO vol = this.dataStore.getVolumeTO(volume); List<EndPoint>
     * endPoints = this.dataStore.getEndPoints(); EndPoint ep =
     * endPoints.get(0); String templateUri =
     * template.getDataStore().grantAccess(template, ep);
     * CreateVolumeFromBaseImageCommand cmd = new
     * CreateVolumeFromBaseImageCommand(vol, templateUri);
     *
     * CreateVolumeFromBaseImageContext<CommandResult> context = new
     * CreateVolumeFromBaseImageContext<CommandResult>(callback, volume);
     * AsyncCallbackDispatcher<DefaultPrimaryDataStoreDriverImpl, Answer> caller
     * = AsyncCallbackDispatcher.create(this); caller.setContext(context)
     * .setCallback
     * (caller.getTarget().createVolumeFromBaseImageAsyncCallback(null, null));
     *
     * ep.sendMessageAsync(cmd, caller); }
     */
/*
     * public Object
     * createVolumeFromBaseImageAsyncCallback(AsyncCallbackDispatcher
     * <DefaultPrimaryDataStoreDriverImpl, Answer> callback,
     * CreateVolumeFromBaseImageContext<CommandResult> context) {
     * CreateVolumeAnswer answer = (CreateVolumeAnswer)callback.getResult();
     * CommandResult result = new CommandResult(); if (answer == null ||
     * answer.getDetails() != null) { result.setSuccess(false); if (answer !=
     * null) { result.setResult(answer.getDetails()); } } else {
     * result.setSuccess(true); VolumeObject volume = context.getVolume();
     * volume.setPath(answer.getVolumeUuid()); }
     * AsyncCompletionCallback<CommandResult> parentCall =
     * context.getParentCallback(); parentCall.complete(result); return null; }
     */
@Override
public void createAsync(DataStore dataStore, DataObject vol, AsyncCompletionCallback<CreateCmdResult> callback) {
    EndPoint ep = selector.select(vol);
    if (ep == null) {
        String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
        s_logger.error(errMsg);
        throw new CloudRuntimeException(errMsg);
    }
    CreateObjectCommand createCmd = new CreateObjectCommand(null);
    CreateVolumeContext<CreateCmdResult> context = new CreateVolumeContext<CreateCmdResult>(callback, vol);
    AsyncCallbackDispatcher<SamplePrimaryDataStoreDriverImpl, Answer> caller = AsyncCallbackDispatcher.create(this);
    caller.setContext(context).setCallback(caller.getTarget().createAsyncCallback(null, null));
    ep.sendMessageAsync(createCmd, caller);
}
Also used : Answer(com.cloud.agent.api.Answer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) CreateCmdResult(org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult) CreateObjectCommand(org.apache.cloudstack.storage.command.CreateObjectCommand)

Example 44 with EndPoint

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

the class CloudStackPrimaryDataStoreDriverImpl method createVolume.

public Answer createVolume(VolumeInfo volume) throws StorageUnavailableException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Creating volume: " + volume);
    }
    CreateObjectCommand cmd = new CreateObjectCommand(volume.getTO());
    EndPoint ep = epSelector.select(volume);
    Answer answer = null;
    if (ep == null) {
        String errMsg = "No remote endpoint to send DeleteCommand, check if host or ssvm is down?";
        s_logger.error(errMsg);
        answer = new Answer(cmd, false, errMsg);
    } else {
        answer = ep.sendMessage(cmd);
    }
    return answer;
}
Also used : ResizeVolumeAnswer(com.cloud.agent.api.storage.ResizeVolumeAnswer) Answer(com.cloud.agent.api.Answer) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) CreateObjectCommand(org.apache.cloudstack.storage.command.CreateObjectCommand)

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