Search in sources :

Example 56 with TaskResourceRep

use of com.emc.storageos.model.TaskResourceRep in project coprhd-controller by CoprHD.

the class IngestVolumesExportedSchedulingThread method run.

@Override
public void run() {
    try {
        _requestContext.reset();
        URI varrayId = null;
        while (_requestContext.hasNext()) {
            UnManagedVolume unManagedVolume = _requestContext.next();
            _logger.info("Ingestion starting for exported unmanaged volume {}", unManagedVolume.getNativeGuid());
            if (null == varrayId) {
                varrayId = _requestContext.getVarray(unManagedVolume).getId();
            }
            TaskResourceRep resourceRep = _taskMap.get(unManagedVolume.getId().toString());
            String taskId = resourceRep != null ? resourceRep.getOpId() : null;
            try {
                URI storageSystemUri = unManagedVolume.getStorageSystemUri();
                StorageSystem system = _requestContext.getStorageSystemCache().get(storageSystemUri.toString());
                if (null == system) {
                    system = _dbClient.queryObject(StorageSystem.class, storageSystemUri);
                    _requestContext.getStorageSystemCache().put(storageSystemUri.toString(), system);
                }
                // Build the Strategy , which contains reference to Block object & export orchestrators
                IngestStrategy ingestStrategy = _ingestStrategyFactory.buildIngestStrategy(unManagedVolume, !IngestStrategyFactory.DISREGARD_PROTECTION);
                @SuppressWarnings("unchecked") BlockObject blockObject = ingestStrategy.ingestBlockObjects(_requestContext, VolumeIngestionUtil.getBlockObjectClass(unManagedVolume));
                if (null == blockObject) {
                    throw IngestionException.exceptions.generalVolumeException(unManagedVolume.getLabel(), "check the logs for more details");
                }
                _requestContext.getBlockObjectsToBeCreatedMap().put(blockObject.getNativeGuid(), blockObject);
                _requestContext.getProcessedUnManagedVolumeMap().put(unManagedVolume.getNativeGuid(), _requestContext.getVolumeContext());
                _logger.info("Volume ingestion completed successfully for exported unmanaged volume {} (export ingestion will follow)", unManagedVolume.getNativeGuid());
            } catch (APIException ex) {
                _logger.error("error: " + ex.getLocalizedMessage(), ex);
                _dbClient.error(UnManagedVolume.class, _requestContext.getCurrentUnManagedVolumeUri(), taskId, ex);
                _requestContext.getVolumeContext().rollback();
            } catch (Exception ex) {
                _logger.error("error: " + ex.getLocalizedMessage(), ex);
                _dbClient.error(UnManagedVolume.class, _requestContext.getCurrentUnManagedVolumeUri(), taskId, IngestionException.exceptions.generalVolumeException(unManagedVolume.getLabel(), ex.getLocalizedMessage()));
                _requestContext.getVolumeContext().rollback();
            }
        }
        _logger.info("Ingestion of all the unmanaged volumes has completed.");
        // next ingest the export masks for the unmanaged volumes which have been fully ingested
        _logger.info("Ingestion of unmanaged export masks for all requested volumes starting.");
        ingestBlockExportMasks(_requestContext, _taskMap);
        for (VolumeIngestionContext volumeContext : _requestContext.getProcessedUnManagedVolumeMap().values()) {
            // If there is a CG involved in the ingestion, organize, pollenate, and commit.
            _unManagedVolumeService.commitIngestedCG(_requestContext, volumeContext.getUnmanagedVolume());
            // commit the volume itself
            volumeContext.commit();
        }
        for (BlockObject bo : _requestContext.getObjectsIngestedByExportProcessing()) {
            _logger.info("Ingestion Wrap Up: Creating BlockObject {} (hash {})", bo.forDisplay(), bo.hashCode());
            _dbClient.createObject(bo);
        }
        for (UnManagedVolume umv : _requestContext.getUnManagedVolumesToBeDeleted()) {
            _logger.info("Ingestion Wrap Up: Deleting UnManagedVolume {} (hash {})", umv.forDisplay(), umv.hashCode());
            _dbClient.updateObject(umv);
        }
        // Update the related objects if any after successful export mask ingestion
        for (Entry<String, Set<DataObject>> updatedObjectsEntry : _requestContext.getDataObjectsToBeUpdatedMap().entrySet()) {
            if (updatedObjectsEntry != null) {
                _logger.info("Ingestion Wrap Up: Updating objects for UnManagedVolume URI " + updatedObjectsEntry.getKey());
                for (DataObject dob : updatedObjectsEntry.getValue()) {
                    if (dob.getInactive()) {
                        _logger.info("Ingestion Wrap Up: Deleting DataObject {} (hash {})", dob.forDisplay(), dob.hashCode());
                    } else {
                        _logger.info("Ingestion Wrap Up: Updating DataObject {} (hash {})", dob.forDisplay(), dob.hashCode());
                    }
                    _dbClient.updateObject(dob);
                }
            }
        }
        // Create the related objects if any after successful export mask ingestion
        for (Set<DataObject> createdObjects : _requestContext.getDataObjectsToBeCreatedMap().values()) {
            if (createdObjects != null && !createdObjects.isEmpty()) {
                for (DataObject dob : createdObjects) {
                    _logger.info("Ingestion Wrap Up: Creating DataObject {} (hash {})", dob.forDisplay(), dob.hashCode());
                    _dbClient.createObject(dob);
                }
            }
        }
        ExportGroup exportGroup = _requestContext.getExportGroup();
        if (_requestContext.isExportGroupCreated()) {
            _logger.info("Ingestion Wrap Up: Creating ExportGroup {} (hash {})", exportGroup.forDisplay(), exportGroup.hashCode());
            _dbClient.createObject(exportGroup);
        } else {
            _logger.info("Ingestion Wrap Up: Updating ExportGroup {} (hash {})", exportGroup.forDisplay(), exportGroup.hashCode());
            _dbClient.updateObject(exportGroup);
        }
        // record the events after they have been persisted
        for (BlockObject volume : _requestContext.getObjectsIngestedByExportProcessing()) {
            _unManagedVolumeService.recordVolumeOperation(_dbClient, _unManagedVolumeService.getOpByBlockObjectType(volume), Status.ready, volume.getId());
        }
    } catch (InternalException e) {
        _logger.error("InternalException occurred due to: {}", e);
        throw e;
    } catch (Exception e) {
        _logger.error("Unexpected exception occurred due to: {}", e);
        throw APIException.internalServerErrors.genericApisvcError(ExceptionUtils.getExceptionMessage(e), e);
    } finally {
        // it, then we should clean it up in the database (CTRL-8520)
        if ((null != _requestContext) && _requestContext.isExportGroupCreated() && _requestContext.getObjectsIngestedByExportProcessing().isEmpty()) {
            _logger.info("Ingestion Wrap Up: an export group was created, but no volumes were ingested into it");
            if (_requestContext.getExportGroup().getVolumes() == null || _requestContext.getExportGroup().getVolumes().isEmpty()) {
                _logger.info("Ingestion Wrap Up: since no volumes are present, marking {} for deletion", _requestContext.getExportGroup().getLabel());
                _dbClient.markForDeletion(_requestContext.getExportGroup());
            }
        }
    }
}
Also used : Set(java.util.Set) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) URI(java.net.URI) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException) ExportGroup(com.emc.storageos.db.client.model.ExportGroup) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) DataObject(com.emc.storageos.db.client.model.DataObject) UnManagedVolume(com.emc.storageos.db.client.model.UnManagedDiscoveredObjects.UnManagedVolume) VolumeIngestionContext(com.emc.storageos.api.service.impl.resource.blockingestorchestration.context.VolumeIngestionContext) BlockObject(com.emc.storageos.db.client.model.BlockObject) StorageSystem(com.emc.storageos.db.client.model.StorageSystem)

Example 57 with TaskResourceRep

use of com.emc.storageos.model.TaskResourceRep in project coprhd-controller by CoprHD.

the class IngestVolumesExportedSchedulingThread method ingestBlockExportMasks.

/**
 * Ingest block export masks for the already-ingested Volumes.
 *
 * @param requestContext the IngestionRequestContext
 * @param taskMap a Map of UnManagedVolume ids to TaskResourceReps
 */
private void ingestBlockExportMasks(IngestionRequestContext requestContext, Map<String, TaskResourceRep> taskMap) {
    for (String unManagedVolumeGUID : requestContext.getProcessedUnManagedVolumeMap().keySet()) {
        BlockObject processedBlockObject = requestContext.getProcessedBlockObject(unManagedVolumeGUID);
        VolumeIngestionContext volumeContext = requestContext.getVolumeContext(unManagedVolumeGUID);
        UnManagedVolume processedUnManagedVolume = volumeContext.getUnmanagedVolume();
        URI unManagedVolumeUri = processedUnManagedVolume.getId();
        TaskResourceRep resourceRep = taskMap.get(processedUnManagedVolume.getId().toString());
        String taskId = resourceRep != null ? resourceRep.getOpId() : null;
        try {
            if (processedBlockObject == null) {
                _logger.warn("The ingested block object is null. Skipping ingestion of export masks for unmanaged volume {}", unManagedVolumeGUID);
                throw IngestionException.exceptions.generalVolumeException(processedUnManagedVolume.getLabel(), "check the logs for more details");
            }
            // Build the Strategy , which contains reference to Block object & export orchestrators
            IngestExportStrategy ingestStrategy = _ingestStrategyFactory.buildIngestExportStrategy(processedUnManagedVolume);
            BlockObject blockObject = ingestStrategy.ingestExportMasks(processedUnManagedVolume, processedBlockObject, requestContext);
            if (null == blockObject) {
                throw IngestionException.exceptions.generalVolumeException(processedUnManagedVolume.getLabel(), "check the logs for more details");
            }
            if (null == blockObject.getCreationTime()) {
                // only add objects to create if they were created this round of ingestion,
                // creationTime will be null unless the object has already been saved to the db
                requestContext.getObjectsIngestedByExportProcessing().add(blockObject);
            }
            // If the ingested object is internal, flag an error. If it's an RP volume, it's exempt from this check.
            if (blockObject.checkInternalFlags(Flag.PARTIALLY_INGESTED) && !(blockObject instanceof Volume && ((Volume) blockObject).getRpCopyName() != null)) {
                StringBuffer taskStatus = requestContext.getTaskStatusMap().get(processedUnManagedVolume.getNativeGuid());
                String taskMessage = "";
                if (taskStatus == null) {
                    // No task status found. Put in a default message.
                    taskMessage = String.format("Not all the parent/replicas of unmanaged volume %s have been ingested", processedUnManagedVolume.getLabel());
                } else {
                    taskMessage = taskStatus.toString();
                }
                _dbClient.error(UnManagedVolume.class, processedUnManagedVolume.getId(), taskId, IngestionException.exceptions.unmanagedVolumeIsNotVisible(processedUnManagedVolume.getLabel(), taskMessage));
            } else {
                _dbClient.ready(UnManagedVolume.class, processedUnManagedVolume.getId(), taskId, INGESTION_SUCCESSFUL_MSG);
            }
        } catch (APIException ex) {
            _logger.warn(ex.getLocalizedMessage(), ex);
            _dbClient.error(UnManagedVolume.class, unManagedVolumeUri, taskId, ex);
            volumeContext.rollback();
        } catch (Exception ex) {
            _logger.warn(ex.getLocalizedMessage(), ex);
            _dbClient.error(UnManagedVolume.class, unManagedVolumeUri, taskId, IngestionException.exceptions.generalVolumeException(processedUnManagedVolume.getLabel(), ex.getLocalizedMessage()));
            volumeContext.rollback();
        }
    }
}
Also used : APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) UnManagedVolume(com.emc.storageos.db.client.model.UnManagedDiscoveredObjects.UnManagedVolume) Volume(com.emc.storageos.db.client.model.Volume) UnManagedVolume(com.emc.storageos.db.client.model.UnManagedDiscoveredObjects.UnManagedVolume) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) VolumeIngestionContext(com.emc.storageos.api.service.impl.resource.blockingestorchestration.context.VolumeIngestionContext) URI(java.net.URI) BlockObject(com.emc.storageos.db.client.model.BlockObject) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException)

Example 58 with TaskResourceRep

use of com.emc.storageos.model.TaskResourceRep in project coprhd-controller by CoprHD.

the class ConsistencyGroupService method deleteConsistencyGroup.

/**
 * Delete consistency group
 *
 * @param openstackTenantId openstack tenant id
 * @param consistencyGroupId consistency group id
 * @param param pojo class to bind request
 * @param isV1Call cinder V1 api
 * @param header HTTP header
 * @brief delete Consistency group
 * @return Response
 */
@POST
@Path("/{consistencyGroup_id}/delete")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response deleteConsistencyGroup(@PathParam("tenant_id") String openstackTenantId, @PathParam("consistencyGroup_id") String consistencyGroupId, ConsistencyGroupDeleteRequest param, @HeaderParam("X-Cinder-V1-Call") String isV1Call, @Context HttpHeaders header) {
    boolean isForced = param.consistencygroup.force;
    final BlockConsistencyGroup consistencyGroup = findConsistencyGroup(consistencyGroupId, openstackTenantId);
    if (consistencyGroup == null) {
        _log.error("Not Found : No Such Consistency Group Found {}", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(404, "Not Found : No Such Consistency Group Found");
    } else if (!consistencyGroupId.equals(CinderApiUtils.splitString(consistencyGroup.getId().toString(), ":", 3))) {
        _log.error("Bad Request : There is no consistency group with id {} , please retry with correct consistency group id", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(400, "Bad Request : There is no consistency group exist, please retry with correct consistency group id");
    }
    String task = UUID.randomUUID().toString();
    TaskResourceRep taskRep = null;
    if (getCinderHelper().verifyConsistencyGroupHasSnapshot(consistencyGroup)) {
        _log.error("Bad Request : Consistency Group {} has Snapshot", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(400, "Bad Request : Consistency Group has Snapshot ");
    }
    if (isForced) {
        final URIQueryResultList cgVolumesResults = new URIQueryResultList();
        _dbClient.queryByConstraint(getVolumesByConsistencyGroup(consistencyGroup.getId()), cgVolumesResults);
        while (cgVolumesResults.iterator().hasNext()) {
            Volume volume = _dbClient.queryObject(Volume.class, cgVolumesResults.iterator().next());
            if (!volume.getInactive()) {
                BlockServiceApi api = BlockService.getBlockServiceImpl(volume, _dbClient);
                URI systemUri = volume.getStorageController();
                List<URI> volumeURIs = new ArrayList<URI>();
                volumeURIs.add(volume.getId());
                api.deleteVolumes(systemUri, volumeURIs, "FULL", null);
                if (volume.getExtensions() == null) {
                    volume.setExtensions(new StringMap());
                }
                volume.getExtensions().put("status", CinderConstants.ComponentStatus.DELETING.getStatus().toLowerCase());
                volume.setInactive(true);
                _dbClient.updateObject(volume);
            }
        }
    }
    try {
        ArgValidator.checkReference(BlockConsistencyGroup.class, consistencyGroup.getId(), checkForDelete(consistencyGroup));
    } catch (APIException e) {
        _log.error("Bad Request : Consistency Group Contains active references of type : {}", e.getMessage());
        return CinderApiUtils.createErrorResponse(400, "Bad Request : Consistency Group Contains active references");
    }
    // RP + VPlex CGs cannot be be deleted without VPlex controller intervention.
    if (!consistencyGroup.getTypes().contains(Types.VPLEX.toString()) || canDeleteConsistencyGroup(consistencyGroup)) {
        final URIQueryResultList cgVolumesResults = new URIQueryResultList();
        _dbClient.queryByConstraint(getVolumesByConsistencyGroup(consistencyGroup.getId()), cgVolumesResults);
        while (cgVolumesResults.iterator().hasNext()) {
            Volume volume = _dbClient.queryObject(Volume.class, cgVolumesResults.iterator().next());
            if (!volume.getInactive()) {
                return CinderApiUtils.createErrorResponse(400, "Bad Request : Try to delete consistency group with --force");
            }
        }
        consistencyGroup.setStorageController(null);
        consistencyGroup.setInactive(true);
        _dbClient.updateObject(consistencyGroup);
        taskRep = finishDeactivateTask(consistencyGroup, task);
        if (taskRep.getState().equals("ready") || taskRep.getState().equals("pending")) {
            return Response.status(202).build();
        }
    }
    final StorageSystem storageSystem = consistencyGroup.created() ? _permissionsHelper.getObjectById(consistencyGroup.getStorageController(), StorageSystem.class) : null;
    // If the consistency group has been created, and the system
    // is a VPlex, then we need to do VPlex related things to destroy
    // the consistency groups on the system. If the consistency group
    // has not been created on the system or the system is not a VPlex
    // revert to the default.
    BlockServiceApi blockServiceApi = BlockService.getBlockServiceImpl("group");
    if (storageSystem != null) {
        String systemType = storageSystem.getSystemType();
        if (DiscoveredDataObject.Type.vplex.name().equals(systemType)) {
            blockServiceApi = BlockService.getBlockServiceImpl(systemType);
        }
        _log.info(String.format("BlockConsistencyGroup %s is associated to StorageSystem %s. Going to delete it on that array.", consistencyGroup.getLabel(), storageSystem.getNativeGuid()));
        // Otherwise, invoke operation to delete CG from the array.
        taskRep = blockServiceApi.deleteConsistencyGroup(storageSystem, consistencyGroup, task);
        if (taskRep.getState().equals("ready") || taskRep.getState().equals("pending")) {
            return Response.status(202).build();
        }
    }
    if (taskRep == null) {
        _log.info(String.format("BlockConsistencyGroup %s was not associated with any storage. Deleting it from ViPR only.", consistencyGroup.getLabel()));
        TaskResourceRep resp = finishDeactivateTask(consistencyGroup, task);
        if (resp.getState().equals("ready") || resp.getState().equals("pending")) {
            return Response.status(202).build();
        }
    }
    return CinderApiUtils.createErrorResponse(400, "Bad Request");
}
Also used : StringMap(com.emc.storageos.db.client.model.StringMap) ArrayList(java.util.ArrayList) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) BlockServiceApi(com.emc.storageos.api.service.impl.resource.BlockServiceApi) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) BlockConsistencyGroup(com.emc.storageos.db.client.model.BlockConsistencyGroup) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) Volume(com.emc.storageos.db.client.model.Volume) StorageSystem(com.emc.storageos.db.client.model.StorageSystem) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 59 with TaskResourceRep

use of com.emc.storageos.model.TaskResourceRep in project coprhd-controller by CoprHD.

the class ConsistencyGroupSnapshotService method deleteConsistencyGroupSnapshot.

/**
 * Delete a consistency group snapshot
 *
 * @param openstackTenantId
 *            openstack tenant id
 * @param consistencyGroupSnapshot_id
 *            consistency group snapshot id
 * @brief Delete a consistency group snapshot
 * @param isV1Call
 *            Cinder V1 call
 * @param header
 *            Http Header
 * @return Response
 */
@DELETE
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{consistencyGroupSnapshot_id}")
@CheckPermission(roles = { Role.SYSTEM_MONITOR, Role.TENANT_ADMIN }, acls = { ACL.ANY })
public Response deleteConsistencyGroupSnapshot(@PathParam("tenant_id") String openstackTenantId, @PathParam("consistencyGroupSnapshot_id") String consistencyGroupSnapshot_id, @HeaderParam("X-Cinder-V1-Call") String isV1Call, @Context HttpHeaders header) {
    final BlockSnapshot snapshot = findSnapshot(consistencyGroupSnapshot_id, openstackTenantId);
    final URI snapshotCgURI = snapshot.getConsistencyGroup();
    URIQueryResultList uris = getCinderHelper().getConsistencyGroupsUris(openstackTenantId, getUserFromContext());
    boolean isConsistencyGroupHasSnapshotId = false;
    if (uris != null && snapshotCgURI != null) {
        for (URI blockCGUri : uris) {
            BlockConsistencyGroup blockCG = _dbClient.queryObject(BlockConsistencyGroup.class, blockCGUri);
            if (blockCG != null && !blockCG.getInactive()) {
                if (snapshotCgURI.equals(blockCG.getId())) {
                    isConsistencyGroupHasSnapshotId = true;
                }
            }
        }
    }
    if (isConsistencyGroupHasSnapshotId) {
        // Generate task id
        final String task = UUID.randomUUID().toString();
        TaskList response = new TaskList();
        // Not an error if the snapshot we try to delete is already deleted
        if (snapshot.getInactive()) {
            Operation op = new Operation();
            op.ready("The consistency group snapshot has already been deactivated");
            op.setResourceType(ResourceOperationTypeEnum.DELETE_CONSISTENCY_GROUP_SNAPSHOT);
            _dbClient.createTaskOpStatus(BlockSnapshot.class, snapshot.getId(), task, op);
            TaskResourceRep taskResponse = toTask(snapshot, task, op);
            if (taskResponse.getState().equals("ready")) {
                return Response.status(202).build();
            }
        }
        Volume volume = _permissionsHelper.getObjectById(snapshot.getParent(), Volume.class);
        BlockServiceApi blockServiceApiImpl = BlockService.getBlockServiceImpl(volume, _dbClient);
        blockServiceApiImpl.deleteSnapshot(snapshot, Arrays.asList(snapshot), task, VolumeDeleteTypeEnum.FULL.name());
        auditBlockConsistencyGroup(OperationTypeEnum.DELETE_CONSISTENCY_GROUP_SNAPSHOT, AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_BEGIN, snapshot.getId().toString(), snapshot.getLabel());
        return Response.status(202).build();
    } else {
        return CinderApiUtils.createErrorResponse(400, "Snapshot not attached to any active consistencygroup");
    }
}
Also used : Volume(com.emc.storageos.db.client.model.Volume) TaskList(com.emc.storageos.model.TaskList) BlockSnapshot(com.emc.storageos.db.client.model.BlockSnapshot) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) Operation(com.emc.storageos.db.client.model.Operation) URI(java.net.URI) BlockServiceApi(com.emc.storageos.api.service.impl.resource.BlockServiceApi) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) BlockConsistencyGroup(com.emc.storageos.db.client.model.BlockConsistencyGroup) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 60 with TaskResourceRep

use of com.emc.storageos.model.TaskResourceRep in project coprhd-controller by CoprHD.

the class ConsistencyGroupSnapshotService method createConsistencyGroupSnapshot.

/**
 * Create consistency group snapshot
 *
 * @param openstackTenantId
 *            openstack tenant Id
 * @param param
 *            Pojo class to bind request
 * @param isV1Call
 *            cinder V1 api
 * @param header
 *            HTTP header
 * @brief Create Consistency Group Snapshot
 * @return Response
 */
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createConsistencyGroupSnapshot(@PathParam("tenant_id") String openstackTenantId, final ConsistencyGroupSnapshotCreateRequest param, @HeaderParam("X-Cinder-V1-Call") String isV1Call, @Context HttpHeaders header) {
    // Query Consistency Group
    final String consistencyGroupId = param.cgsnapshot.consistencygroup_id;
    final BlockConsistencyGroup consistencyGroup = findConsistencyGroup(consistencyGroupId, openstackTenantId);
    if (consistencyGroup == null) {
        _log.error("Not Found : No Such Consistency Group Found {}", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(404, "Not Found : No Such Consistency Group Found");
    } else if (!consistencyGroupId.equals(CinderApiUtils.splitString(consistencyGroup.getId().toString(), ":", 3))) {
        _log.error("Bad Request : Invalid Snapshot Id {} : Please enter valid or full Id", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(400, "Bad Request : No such consistency id exist, Please enter valid or full Id");
    }
    if (!isSnapshotCreationpermissible(consistencyGroup)) {
        _log.error("Bad Request : vpool not being configured for the snapshots creation");
        return CinderApiUtils.createErrorResponse(400, "Bad Request : vpool not being configured for the snapshots creation");
    }
    // system types.
    if (!consistencyGroup.created()) {
        CinderApiUtils.createErrorResponse(400, "No such consistency group created");
    }
    Project project = getCinderHelper().getProject(openstackTenantId, getUserFromContext());
    URI cgStorageControllerURI = consistencyGroup.getStorageController();
    if (!NullColumnValueGetter.isNullURI(cgStorageControllerURI)) {
        // No snapshots for VPLEX consistency groups.
        StorageSystem cgStorageController = _dbClient.queryObject(StorageSystem.class, cgStorageControllerURI);
        if ((DiscoveredDataObject.Type.vplex.name().equals(cgStorageController.getSystemType())) && (!consistencyGroup.checkForType(Types.LOCAL))) {
            CinderApiUtils.createErrorResponse(400, "can't create snapshot for VPLEX");
        }
    }
    // Get the block service implementation
    BlockServiceApi blockServiceApiImpl = getBlockServiceImpl(consistencyGroup);
    // Get the volumes in the consistency group.
    List<Volume> volumeList = blockServiceApiImpl.getActiveCGVolumes(consistencyGroup);
    _log.info("Active CG volume list : " + volumeList);
    // Generate task id
    String taskId = UUID.randomUUID().toString();
    // Set snapshot type.
    String snapshotType = BlockSnapshot.TechnologyType.NATIVE.toString();
    if (consistencyGroup.checkForType(BlockConsistencyGroup.Types.RP)) {
        snapshotType = BlockSnapshot.TechnologyType.RP.toString();
    } else if ((!volumeList.isEmpty()) && (volumeList.get(0).checkForSRDF())) {
        snapshotType = BlockSnapshot.TechnologyType.SRDF.toString();
    }
    // Determine the snapshot volume for RP.
    Volume snapVolume = null;
    if (consistencyGroup.checkForType(BlockConsistencyGroup.Types.RP)) {
        for (Volume volumeToSnap : volumeList) {
            // Get the RP source volume.
            if (volumeToSnap.getPersonality() != null && volumeToSnap.getPersonality().equals(Volume.PersonalityTypes.SOURCE.toString())) {
                snapVolume = volumeToSnap;
                break;
            }
        }
    } else if (!volumeList.isEmpty()) {
        // Any volume.
        snapVolume = volumeList.get(0);
    }
    // Set the create inactive flag.
    Boolean createInactive = Boolean.FALSE;
    Boolean readOnly = Boolean.FALSE;
    // Validate the snapshot request.
    String snapshotName = param.cgsnapshot.name;
    blockServiceApiImpl.validateCreateSnapshot(snapVolume, volumeList, snapshotType, snapshotName, readOnly, getFullCopyManager());
    // Prepare and create the snapshots for the group.
    List<URI> snapIdList = new ArrayList<URI>();
    List<BlockSnapshot> snapshotList = new ArrayList<BlockSnapshot>();
    TaskList response = new TaskList();
    snapshotList.addAll(blockServiceApiImpl.prepareSnapshots(volumeList, snapshotType, snapshotName, snapIdList, taskId));
    for (BlockSnapshot snapshot : snapshotList) {
        response.getTaskList().add(toTask(snapshot, taskId));
    }
    blockServiceApiImpl.createSnapshot(snapVolume, snapIdList, snapshotType, createInactive, readOnly, taskId);
    auditBlockConsistencyGroup(OperationTypeEnum.CREATE_CONSISTENCY_GROUP_SNAPSHOT, AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_BEGIN, param.cgsnapshot.name, consistencyGroup.getId().toString());
    ConsistencyGroupSnapshotCreateResponse cgSnapshotCreateRes = new ConsistencyGroupSnapshotCreateResponse();
    for (TaskResourceRep rep : response.getTaskList()) {
        URI snapshotUri = rep.getResource().getId();
        BlockSnapshot snap = _dbClient.queryObject(BlockSnapshot.class, snapshotUri);
        snap.setId(snapshotUri);
        snap.setConsistencyGroup(consistencyGroup.getId());
        snap.setLabel(snapshotName);
        if (snap != null) {
            StringMap extensions = snap.getExtensions();
            if (extensions == null) {
                extensions = new StringMap();
            }
            extensions.put("status", CinderConstants.ComponentStatus.CREATING.getStatus().toLowerCase());
            extensions.put("taskid", rep.getId().toString());
            snap.setExtensions(extensions);
            ScopedLabelSet tagSet = new ScopedLabelSet();
            snap.setTag(tagSet);
            tagSet.add(new ScopedLabel(project.getTenantOrg().getURI().toString(), CinderApiUtils.splitString(snapshotUri.toString(), ":", 3)));
        }
        _dbClient.updateObject(snap);
        cgSnapshotCreateRes.id = CinderApiUtils.splitString(snapshotUri.toString(), ":", 3);
        cgSnapshotCreateRes.name = param.cgsnapshot.name;
    }
    return CinderApiUtils.getCinderResponse(cgSnapshotCreateRes, header, true, CinderConstants.STATUS_OK);
}
Also used : StringMap(com.emc.storageos.db.client.model.StringMap) TaskList(com.emc.storageos.model.TaskList) ArrayList(java.util.ArrayList) BlockSnapshot(com.emc.storageos.db.client.model.BlockSnapshot) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) URI(java.net.URI) BlockServiceApi(com.emc.storageos.api.service.impl.resource.BlockServiceApi) ScopedLabelSet(com.emc.storageos.db.client.model.ScopedLabelSet) BlockConsistencyGroup(com.emc.storageos.db.client.model.BlockConsistencyGroup) Project(com.emc.storageos.db.client.model.Project) Volume(com.emc.storageos.db.client.model.Volume) ScopedLabel(com.emc.storageos.db.client.model.ScopedLabel) ConsistencyGroupSnapshotCreateResponse(com.emc.storageos.cinder.model.ConsistencyGroupSnapshotCreateResponse) StorageSystem(com.emc.storageos.db.client.model.StorageSystem) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

TaskResourceRep (com.emc.storageos.model.TaskResourceRep)160 URI (java.net.URI)85 TaskList (com.emc.storageos.model.TaskList)82 Operation (com.emc.storageos.db.client.model.Operation)68 Produces (javax.ws.rs.Produces)59 ArrayList (java.util.ArrayList)56 Volume (com.emc.storageos.db.client.model.Volume)55 Path (javax.ws.rs.Path)54 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)53 POST (javax.ws.rs.POST)50 InternalException (com.emc.storageos.svcs.errorhandling.resources.InternalException)49 Consumes (javax.ws.rs.Consumes)36 APIException (com.emc.storageos.svcs.errorhandling.resources.APIException)35 StorageSystem (com.emc.storageos.db.client.model.StorageSystem)32 NamedURI (com.emc.storageos.db.client.model.NamedURI)30 NullColumnValueGetter.isNullURI (com.emc.storageos.db.client.util.NullColumnValueGetter.isNullURI)23 Project (com.emc.storageos.db.client.model.Project)20 URIQueryResultList (com.emc.storageos.db.client.constraint.URIQueryResultList)18 VirtualPool (com.emc.storageos.db.client.model.VirtualPool)17 Copy (com.emc.storageos.model.block.Copy)17