Search in sources :

Example 6 with APIException

use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.

the class BlockSnapshotService method deactivateSnapshot.

/**
 * Deactivate volume snapshot, will result in permanent deletion of the requested snapshot from the storage system it was created on
 * and will move the snapshot to a "marked-for-delete" state after the deletion happens on the array side.
 * It will be deleted by the garbage collector on a subsequent iteration
 * If this snapshot was created from a volume that is part of a consistency group,
 * then all the related snapshots will be deactivated, as well.
 *
 * If "?type=VIPR_ONLY" is added to the path, it will delete snapshot only from ViPR data base and leaves the snapshot on storage array
 * as it is.
 * Possible value for attribute type : FULL, VIPR_ONLY
 * FULL : Deletes the snapshot permanently on array and ViPR data base.
 * VIPR_ONLY : Deletes the snapshot only from ViPR data base and leaves the snapshot on array as it is.
 *
 * @prereq none
 * @param id the URN of a ViPR snapshot
 * @param type the type of deletion {@link DefaultValue} FULL
 * @brief Delete snapshot
 * @return Snapshot information
 */
@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/deactivate")
@CheckPermission(roles = { Role.TENANT_ADMIN }, acls = { ACL.ANY })
public TaskList deactivateSnapshot(@PathParam("id") URI id, @DefaultValue("FULL") @QueryParam("type") String type) {
    _log.info("Executing {} snapshot delete for snapshot {}", type, id);
    String opStage = null;
    boolean successStatus = true;
    String taskId = UUID.randomUUID().toString();
    TaskList response = new TaskList();
    // Get the snapshot.
    BlockSnapshot snap = (BlockSnapshot) queryResource(id);
    // We can ignore dependencies on BlockSnapshotSession. In this case
    // the BlockSnapshot instance is a linked target for a BlockSnapshotSession
    // and we will unlink the snapshot from the session and delete it.
    List<Class<? extends DataObject>> excludeTypes = new ArrayList<Class<? extends DataObject>>();
    excludeTypes.add(BlockSnapshotSession.class);
    if (VolumeDeleteTypeEnum.VIPR_ONLY.name().equals(type)) {
        excludeTypes.add(ExportGroup.class);
        excludeTypes.add(ExportMask.class);
    }
    ArgValidator.checkReference(BlockSnapshot.class, id, checkForDelete(snap, excludeTypes));
    if (!VolumeDeleteTypeEnum.VIPR_ONLY.name().equals(type)) {
        // The audit log message operation stage.
        opStage = AuditLogManager.AUDITOP_BEGIN;
        // If the BlockSnapshot instance represents a linked target, then
        // we need to unlink the target form the snapshot session and then
        // delete the target.
        URIQueryResultList snapSessionURIs = new URIQueryResultList();
        _dbClient.queryByConstraint(ContainmentConstraint.Factory.getLinkedTargetSnapshotSessionConstraint(id), snapSessionURIs);
        Iterator<URI> snapSessionURIsIter = snapSessionURIs.iterator();
        if (snapSessionURIsIter.hasNext()) {
            _log.info("Snapshot is linked target for a snapshot session");
            SnapshotSessionUnlinkTargetsParam param = new SnapshotSessionUnlinkTargetsParam();
            List<SnapshotSessionUnlinkTargetParam> targetInfoList = new ArrayList<SnapshotSessionUnlinkTargetParam>();
            SnapshotSessionUnlinkTargetParam targetInfo = new SnapshotSessionUnlinkTargetParam(id, Boolean.TRUE);
            targetInfoList.add(targetInfo);
            param.setLinkedTargets(targetInfoList);
            response.getTaskList().add(getSnapshotSessionManager().unlinkTargetVolumesFromSnapshotSession(snapSessionURIsIter.next(), param, OperationTypeEnum.DELETE_VOLUME_SNAPSHOT));
            return response;
        }
        // Not an error if the snapshot we try to delete is already deleted
        if (snap.getInactive()) {
            _log.info("Snapshot is already inactive");
            Operation op = new Operation();
            op.ready("The snapshot has already been deleted");
            op.setResourceType(ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT);
            _dbClient.createTaskOpStatus(BlockSnapshot.class, snap.getId(), taskId, op);
            response.getTaskList().add(toTask(snap, taskId, op));
            return response;
        }
    }
    // Get the storage system.
    StorageSystem device = _dbClient.queryObject(StorageSystem.class, snap.getStorageController());
    // Determine all snapshots to delete.
    List<BlockSnapshot> snapshots = new ArrayList<BlockSnapshot>();
    final URI cgId = snap.getConsistencyGroup();
    if (!NullColumnValueGetter.isNullURI(cgId) && !NullColumnValueGetter.isNullValue(snap.getReplicationGroupInstance())) {
        // Collect all the BlockSnapshots if part of a CG.
        snapshots = ControllerUtils.getSnapshotsPartOfReplicationGroup(snap, _dbClient);
    } else {
        // Snap is not part of a CG so only delete the snap
        snapshots.add(snap);
    }
    // Get the snapshot parent volume.
    Volume parentVolume = _permissionsHelper.getObjectById(snap.getParent(), Volume.class);
    // Check that there are no pending tasks for these snapshots.
    checkForPendingTasks(Arrays.asList(parentVolume.getTenant().getURI()), snapshots);
    // Create tasks on the volume.
    for (BlockSnapshot snapshot : snapshots) {
        Operation snapOp = _dbClient.createTaskOpStatus(BlockSnapshot.class, snapshot.getId(), taskId, ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT);
        response.getTaskList().add(toTask(snapshot, taskId, snapOp));
    }
    // should be returned.
    try {
        BlockServiceApi blockServiceApiImpl = BlockService.getBlockServiceImpl(parentVolume, _dbClient);
        blockServiceApiImpl.deleteSnapshot(snap, snapshots, taskId, type);
    } catch (APIException | InternalException e) {
        successStatus = false;
        String errorMsg = String.format("Exception attempting to delete snapshot %s: %s", snap.getId(), e.getMessage());
        _log.error(errorMsg);
        for (TaskResourceRep taskResourceRep : response.getTaskList()) {
            taskResourceRep.setState(Operation.Status.error.name());
            taskResourceRep.setMessage(errorMsg);
            _dbClient.error(BlockSnapshot.class, taskResourceRep.getResource().getId(), taskId, e);
        }
    } catch (Exception e) {
        successStatus = false;
        String errorMsg = String.format("Exception attempting to delete snapshot %s: %s", snap.getId(), e.getMessage());
        _log.error(errorMsg);
        ServiceCoded sc = APIException.internalServerErrors.genericApisvcError(errorMsg, e);
        for (TaskResourceRep taskResourceRep : response.getTaskList()) {
            taskResourceRep.setState(Operation.Status.error.name());
            taskResourceRep.setMessage(sc.getMessage());
            _dbClient.error(BlockSnapshot.class, taskResourceRep.getResource().getId(), taskId, sc);
        }
    }
    auditOp(OperationTypeEnum.DELETE_VOLUME_SNAPSHOT, successStatus, opStage, id.toString(), snap.getLabel(), snap.getParent().getName(), device.getId().toString());
    return response;
}
Also used : TaskList(com.emc.storageos.model.TaskList) ArrayList(java.util.ArrayList) Operation(com.emc.storageos.db.client.model.Operation) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) SnapshotSessionUnlinkTargetsParam(com.emc.storageos.model.block.SnapshotSessionUnlinkTargetsParam) StorageSystem(com.emc.storageos.db.client.model.StorageSystem) MapBlockSnapshot(com.emc.storageos.api.mapper.functions.MapBlockSnapshot) BlockSnapshot(com.emc.storageos.db.client.model.BlockSnapshot) TaskResourceRep(com.emc.storageos.model.TaskResourceRep) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException) ServiceCodeException(com.emc.storageos.svcs.errorhandling.resources.ServiceCodeException) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException) DataObject(com.emc.storageos.db.client.model.DataObject) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) SnapshotSessionUnlinkTargetParam(com.emc.storageos.model.block.SnapshotSessionUnlinkTargetParam) Volume(com.emc.storageos.db.client.model.Volume) ServiceCoded(com.emc.storageos.svcs.errorhandling.model.ServiceCoded) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 7 with APIException

use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.

the class ComputeVirtualPoolService method assignMatchedElements.

/**
 * Assign Compute Elements to the Compute Virtual Pool
 *
 * @param param The Compute Virtual Pool Compute Elements to be added and removed
 * @brief Assign compute elements to the compute virtual pool
 * @return ComputeVirtualPoolRestRep The updated Compute Virtual Pool
 */
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/assign-matched-elements")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN })
public ComputeVirtualPoolRestRep assignMatchedElements(@PathParam("id") URI id, ComputeVirtualPoolElementUpdateParam param) throws APIException {
    // Validate that Virtual Pool exists
    ArgValidator.checkFieldUriType(id, ComputeVirtualPool.class, "id");
    ComputeVirtualPool cvp = this.queryObject(ComputeVirtualPool.class, id, true);
    _log.debug("Assign compute elements to compute pool " + cvp.getLabel());
    if (cvp.getUseMatchedElements()) {
        _log.error("Cannot assign compute elements when pool is set to use automatic matching");
        throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Cannot assign compute elements when pool is set to use automatic matching.");
    }
    StringSet currentElements = new StringSet();
    if (cvp.getMatchedComputeElements() != null) {
        currentElements.addAll(cvp.getMatchedComputeElements());
    }
    _log.debug("Currently " + currentElements.size() + " existing compute elements: " + currentElements);
    boolean addRequest = param.getComputeVirtualPoolAssignmentChanges().getAdd() != null && param.getComputeVirtualPoolAssignmentChanges().getAdd().getComputeElements() != null;
    if (addRequest) {
        Set<String> addElementsUris = param.getComputeVirtualPoolAssignmentChanges().getAdd().getComputeElements();
        _log.debug("Add " + addElementsUris.size() + " compute elements: " + addElementsUris);
        // Validate
        Collection<ComputeElement> addElements = _dbClient.queryObject(ComputeElement.class, toUriList(addElementsUris));
        // exists
        if (addElementsUris.size() != addElements.size()) {
            _log.error("Invalid add compute element(s) specified - Requested " + addElementsUris.size() + " but only " + addElements.size() + " found");
            throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Invalid add compute element(s) specified.");
        }
        List<URI> staticCeUris = findAllStaticallyAssignedComputeElementsInOtherPools(cvp);
        for (ComputeElement computeElement : addElements) {
            if (staticCeUris.contains(computeElement.getId())) {
                _log.error("Compute element " + computeElement.getId() + " already statically assigned to a different pool");
                throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Cannot assign compute element(s) already manually assigned to different pool(s).");
            }
        }
        // Add against the current collection of compute elements
        for (String computeElementUriString : addElementsUris) {
            boolean added = currentElements.add(computeElementUriString);
            _log.info("Compute pool " + cvp.getLabel() + " already contained compute element " + computeElementUriString + ": " + added);
        }
    }
    boolean removeRequest = param.getComputeVirtualPoolAssignmentChanges().getRemove() != null && param.getComputeVirtualPoolAssignmentChanges().getRemove().getComputeElements() != null;
    if (removeRequest) {
        Set<String> removeElementsUris = param.getComputeVirtualPoolAssignmentChanges().getRemove().getComputeElements();
        _log.debug("Remove " + removeElementsUris.size() + " compute elements: " + removeElementsUris);
        // Validate
        Collection<ComputeElement> removeElements = _dbClient.queryObject(ComputeElement.class, toUriList(removeElementsUris));
        // exists
        if (removeElementsUris.size() != removeElements.size()) {
            _log.error("Invalid remove compute element(s) specified - Requested " + removeElementsUris.size() + " but only " + removeElements.size() + " found");
            throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Invalid remove compute element(s) specified.");
        }
        // Remove against the current collection of compute elements
        for (String computeElementUriString : removeElementsUris) {
            boolean removed = currentElements.remove(computeElementUriString);
            _log.debug("Compute pool " + cvp.getLabel() + " needed removal of compute element " + computeElementUriString + ": " + removed);
        }
        removeHostToCVPRelation(removeElements, cvp);
    }
    // Validate
    Collection<ComputeElement> assignedElements = _dbClient.queryObject(ComputeElement.class, toUriList(currentElements));
    // exists
    for (ComputeElement element : assignedElements) {
        boolean inUse = false;
        if (!element.getAvailable()) {
            inUse = true;
        }
        // validate that this is element matches the current vcp criteria
        try {
            validateComputeElement(cvp, element);
        } catch (APIException e) {
            _log.warn("Compute Element " + element.getLabel() + ":" + element.getDn() + " is in use(" + inUse + ") and does not meet criteria " + e.toString());
            /*
                 * Since we are disallowing more restrictive changes if the VCP is in use, the if block below will not be used for the 2.2
                 * release.
                 */
            if (inUse) {
                throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Updates to pool not allowed because compute virtual pool is already in use and some compute elements being assigned do not meet criteria.");
            }
            // if ces not in use then simply remove
            currentElements.remove(element.getId().toString());
            _log.warn("Compute Element does not meet criteria; so being removed");
        }
    }
    cvp.setMatchedComputeElements(currentElements);
    updateHostToCVPRelation(cvp);
    _dbClient.updateAndReindexObject(cvp);
    // Crucial that we save the static assignments before running updateOtherPoolsComputeElements
    // so that the dynamic matching reassignments happen with latest static assignments
    updateOtherPoolsComputeElements(cvp);
    return toComputeVirtualPool(_dbClient, cvp, isComputeVirtualPoolInUse(cvp));
}
Also used : APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) ComputeElement(com.emc.storageos.db.client.model.ComputeElement) StringSet(com.emc.storageos.db.client.model.StringSet) URI(java.net.URI) ComputeVirtualPool(com.emc.storageos.db.client.model.ComputeVirtualPool) ComputeVirtualPoolMapper.toComputeVirtualPool(com.emc.storageos.api.mapper.ComputeVirtualPoolMapper.toComputeVirtualPool) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 8 with APIException

use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.

the class ComputeVirtualPoolService method updateComputeVirtualPool.

/**
 * Update a Compute Virtual Pool
 *
 * @brief Update a compute virtual pool
 * @param param The Compute Virtual Pool update spec
 * @return ComputeVirtualPoolRestRep The updated Compute Virtual Pool
 */
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN })
public ComputeVirtualPoolRestRep updateComputeVirtualPool(@PathParam("id") URI id, ComputeVirtualPoolUpdateParam param) {
    ComputeVirtualPool cvp = null;
    _log.debug("Update Parameters:\n" + param.toString());
    // Validate that Virtual Pool exists
    ArgValidator.checkFieldUriType(id, ComputeVirtualPool.class, "id");
    cvp = this.queryObject(ComputeVirtualPool.class, id, true);
    boolean nicOrHbaRangeChanges = false;
    // If current value not set OR if param is more restrictive then change is more restrictive
    boolean moreRestrictiveChange = false;
    // Process the update parameters
    // If a name is specified on request and that value is different that current name
    boolean nameChange = (param.getName() != null && !(cvp.getLabel().equals(param.getName())));
    if (nameChange) {
        checkForDuplicateName(param.getName(), ComputeVirtualPool.class);
        cvp.setLabel(param.getName());
    }
    if (null != param.getDescription()) {
        cvp.setDescription(param.getDescription());
    }
    if (null != param.getSystemType()) {
        ArgValidator.checkFieldValueFromEnum(param.getSystemType(), "system_type", ComputeVirtualPool.SupportedSystemTypes.class);
        // Don't allow changes of system type if there are service profile templates already set
        if (cvp.getServiceProfileTemplates() != null) {
            if (!cvp.getServiceProfileTemplates().isEmpty()) {
                throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Cannot change system type when Service Profile Temples are associated");
            }
        }
        cvp.setSystemType(param.getSystemType());
    }
    if (isParamSet(param.getMinProcessors()) && ((cvp.getMinProcessors() == null) || (cvp.getMinProcessors() < param.getMinProcessors()))) {
        moreRestrictiveChange = true;
        _log.debug("Min Processors increased from " + cvp.getMinProcessors() + " to " + param.getMinProcessors());
    }
    cvp.setMinProcessors(getParamValue(param.getMinProcessors()));
    if (isParamSet(param.getMaxProcessors()) && ((cvp.getMaxProcessors() == null) || (cvp.getMaxProcessors() == -1) || (cvp.getMaxProcessors() > param.getMaxProcessors()))) {
        moreRestrictiveChange = true;
        _log.debug("Max Processors decreased from " + cvp.getMaxProcessors() + " to " + param.getMaxProcessors());
    }
    cvp.setMaxProcessors(getParamMaxValue(param.getMaxProcessors()));
    validateMinMaxIntValues(cvp.getMinProcessors(), cvp.getMaxProcessors(), "min_processors", "max_processors");
    if (isParamSet(param.getMinTotalCores()) && ((cvp.getMinTotalCores() == null) || (cvp.getMinTotalCores() < param.getMinTotalCores()))) {
        moreRestrictiveChange = true;
        _log.debug("Min TotalCores increased from " + cvp.getMinTotalCores() + " to " + param.getMinTotalCores());
    }
    cvp.setMinTotalCores(getParamValue(param.getMinTotalCores()));
    if (isParamSet(param.getMaxTotalCores()) && ((cvp.getMaxTotalCores() == null) || (cvp.getMaxTotalCores() == -1) || (cvp.getMaxTotalCores() > param.getMaxTotalCores()))) {
        moreRestrictiveChange = true;
        _log.debug("Max TotalCores decreased from " + cvp.getMaxTotalCores() + " to " + param.getMaxTotalCores());
    }
    cvp.setMaxTotalCores(getParamMaxValue(param.getMaxTotalCores()));
    validateMinMaxIntValues(cvp.getMinTotalCores(), cvp.getMaxTotalCores(), "min_total_cores", "max_total_cores");
    if (isParamSet(param.getMinTotalThreads()) && ((cvp.getMinTotalThreads() == null) || (cvp.getMinTotalThreads() < param.getMinTotalThreads()))) {
        moreRestrictiveChange = true;
        _log.debug("Min TotalThreads increased from " + cvp.getMinTotalThreads() + " to " + param.getMinTotalThreads());
    }
    cvp.setMinTotalThreads(getParamValue(param.getMinTotalThreads()));
    if (isParamSet(param.getMaxTotalThreads()) && ((cvp.getMaxTotalThreads() == null) || (cvp.getMaxTotalThreads() == -1) || (cvp.getMaxTotalThreads() > param.getMaxTotalThreads()))) {
        moreRestrictiveChange = true;
        _log.debug("Max TotalThreads decreased from " + cvp.getMaxTotalThreads() + " to " + param.getMaxMemory());
    }
    cvp.setMaxTotalThreads(getParamMaxValue(param.getMaxTotalThreads()));
    validateMinMaxIntValues(cvp.getMinTotalThreads(), cvp.getMaxTotalThreads(), "min_total_threads", "max_total_threads");
    if (isParamSet(param.getMinCpuSpeed()) && ((cvp.getMinCpuSpeed() == null) || (cvp.getMinCpuSpeed() < param.getMinCpuSpeed()))) {
        moreRestrictiveChange = true;
        _log.debug("Min CpuSpeed increased from " + cvp.getMinCpuSpeed() + " to " + param.getMinCpuSpeed());
    }
    cvp.setMinCpuSpeed(getParamValue(param.getMinCpuSpeed()));
    if (isParamSet(param.getMaxCpuSpeed()) && ((cvp.getMaxCpuSpeed() == null) || (cvp.getMaxCpuSpeed() == -1) || (cvp.getMaxCpuSpeed() > param.getMaxCpuSpeed()))) {
        moreRestrictiveChange = true;
        _log.debug("Max CpuSpeed decreased from " + cvp.getMaxCpuSpeed() + " to " + param.getMaxCpuSpeed());
    }
    cvp.setMaxCpuSpeed(getParamMaxValue(param.getMaxCpuSpeed()));
    validateMinMaxIntValues(cvp.getMinCpuSpeed(), cvp.getMaxCpuSpeed(), "min_processor_speed", "max_processor_speed");
    if (isParamSet(param.getMinMemory()) && ((cvp.getMinMemory() == null) || (cvp.getMinMemory() < param.getMinMemory()))) {
        moreRestrictiveChange = true;
        _log.debug("Min Memory increased from " + cvp.getMinMemory() + " to " + param.getMinMemory());
    }
    cvp.setMinMemory(getParamValue(param.getMinMemory()));
    if (isParamSet(param.getMaxMemory()) && ((cvp.getMaxMemory() == null) || (cvp.getMaxMemory() == -1) || (cvp.getMaxMemory() > param.getMaxMemory()))) {
        moreRestrictiveChange = true;
        _log.debug("Max Memory decreased from " + cvp.getMaxMemory() + " to " + param.getMaxMemory());
    }
    cvp.setMaxMemory(getParamMaxValue(param.getMaxMemory()));
    validateMinMaxIntValues(cvp.getMinMemory(), cvp.getMaxMemory(), "min_memory", "max_memory");
    // If current value not set OR if param is more restrictive then change is more
    boolean moreRestrictiveNicHbaChange = false;
    if (isParamSet(param.getMinNics()) && ((cvp.getMinNics() == null) || (cvp.getMinNics() < param.getMinNics()))) {
        moreRestrictiveNicHbaChange = true;
        _log.debug("Min nic increased from " + cvp.getMinNics() + " to " + param.getMinNics());
    }
    cvp.setMinNics(getParamValue(param.getMinNics()));
    if (isParamSet(param.getMaxNics()) && ((cvp.getMaxNics() == null) || (cvp.getMaxNics() == -1) || (cvp.getMaxNics() > param.getMaxNics()))) {
        moreRestrictiveNicHbaChange = true;
        _log.debug("Max nic decreased from " + cvp.getMaxNics() + " to " + param.getMaxNics());
    }
    cvp.setMaxNics(getParamMaxValue(param.getMaxNics()));
    validateMinMaxIntValues(cvp.getMinNics(), cvp.getMaxNics(), "min_nics", "max_nics");
    if (isParamSet(param.getMinHbas()) && ((cvp.getMinHbas() == null) || (cvp.getMinHbas() < param.getMinHbas()))) {
        moreRestrictiveNicHbaChange = true;
        _log.debug("Min hba increased from " + cvp.getMinHbas() + " to " + param.getMinHbas());
    }
    cvp.setMinHbas(getParamValue(param.getMinHbas()));
    if (isParamSet(param.getMaxHbas()) && ((cvp.getMaxHbas() == null) || (cvp.getMaxHbas() == -1) || (cvp.getMaxHbas() > param.getMaxHbas()))) {
        moreRestrictiveNicHbaChange = true;
        _log.debug("Max hba decreased from " + cvp.getMaxHbas() + " to " + param.getMaxHbas());
    }
    cvp.setMaxHbas(getParamMaxValue(param.getMaxHbas()));
    validateMinMaxIntValues(cvp.getMinHbas(), cvp.getMaxHbas(), "min_hbas", "max_hbas");
    boolean changeToStaticAssignment = false;
    boolean changeToDynamicAssignment = false;
    Collection<ComputeElement> staticElements = new HashSet<ComputeElement>();
    if (!cvp.getUseMatchedElements() && cvp.getMatchedComputeElements() != null && !cvp.getMatchedComputeElements().isEmpty()) {
        staticElements.addAll(_dbClient.queryObject(ComputeElement.class, toUriList(cvp.getMatchedComputeElements())));
        _log.debug("static elements count:" + staticElements.size());
    }
    if (null != param.getUseMatchedElements()) {
        // Will need to clear current matches when changing to static assignment
        changeToStaticAssignment = (param.getUseMatchedElements() == false) && (param.getUseMatchedElements() != cvp.getUseMatchedElements());
        changeToDynamicAssignment = (param.getUseMatchedElements() == true) && (param.getUseMatchedElements() != cvp.getUseMatchedElements());
        cvp.setUseMatchedElements(param.getUseMatchedElements());
    }
    if (changeToStaticAssignment) {
        // Clear dynamic matches when changing to static to get ready for upcoming assignments
        if (cvp.getMatchedComputeElements() != null) {
            cvp.getMatchedComputeElements().clear();
        }
    }
    if (null != param.getVarrayChanges()) {
        updateVirtualArrays(cvp, param.getVarrayChanges());
    }
    if (null != param.getSptChanges()) {
        if (cvp.getSystemType().contentEquals(ComputeVirtualPool.SupportedSystemTypes.Cisco_UCSM.toString())) {
            updateServiceProfileTemplates(cvp, param.getSptChanges());
        }
    }
    // Check SPTs meet criteria after updates above
    if (moreRestrictiveNicHbaChange) {
        if (isComputeVirtualPoolInUse(cvp)) {
            _log.warn("VCP is in use; more restrictive Nic or Hba change is not allowed");
            throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "More restrictive updates to network adapter and hba range not allowed because compute virtual pool is already in use.");
        }
        Set<String> sptsNotMeetingCriteria = new HashSet<String>();
        Collection<UCSServiceProfileTemplate> templates = _dbClient.queryObject(UCSServiceProfileTemplate.class, toUriList(cvp.getServiceProfileTemplates()));
        for (UCSServiceProfileTemplate template : templates) {
            boolean inUse = isServiceProfileTemplateInUse(cvp, template);
            try {
                validateServiceProfileTemplate(cvp, template);
            } catch (APIException e) {
                _log.warn("SPT " + template.getLabel() + ":" + template.getDn() + " is in use(" + inUse + ") and does not meet criteria " + e.toString());
                /*
                     * Since we are disallowing more restrictive changes if the VCP is in use, the if block below will not be used for the
                     * 2.2 release.
                     */
                if (inUse) {
                    throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Updates to pool not allowed because service profile template(s) already in use do not meet requested criteria.");
                }
                // if spt not in use then simply remove
                sptsNotMeetingCriteria.add(template.getId().toString());
                _log.warn("SPT does not meet criteria; so being removed");
            }
        }
        cvp.removeServiceProfileTemplates(sptsNotMeetingCriteria);
    }
    if (cvp.getUseMatchedElements()) {
        _log.debug("Compute pool " + cvp.getLabel() + " configured to use dynamic matching");
        getMatchingCEsforCVPAttributes(cvp);
    }
    if (changeToDynamicAssignment && !staticElements.isEmpty()) {
        // to possibly include them
        for (ComputeElement computeElement : staticElements) {
            if (!isAvailable(computeElement)) {
                _log.error("Cannot change to dynamic matching because statically assigned compute element(s) have been used in pool " + cvp.getId());
                throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Cannot change to automatic matching because manually assigned compute element(s) already in use.");
            }
        }
        updateOtherPoolsComputeElements(cvp);
    }
    if (moreRestrictiveChange) {
        if (isComputeVirtualPoolInUse(cvp)) {
            _log.warn("VCP is in use; more restrictive change is not allowed");
            throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "More restrictive updates to qualifiers not allowed because compute virtual pool is already in use.");
        }
        // VCP is not in use. So check if there are statically assigned members that need to be removed from vcp membership
        _log.info("VCP is not in use. So check if there are statically assigned members that need to be removed from vcp membership");
        if (!cvp.getUseMatchedElements() && !staticElements.isEmpty()) {
            Set<ComputeElement> cesNotMeetingCriteria = new HashSet<ComputeElement>();
            Collection<ComputeElement> computeElements = _dbClient.queryObject(ComputeElement.class, getURIs(staticElements));
            for (ComputeElement element : computeElements) {
                _log.debug("Blade:" + element.getChassisId() + "/" + element.getSlotId());
                boolean inUse = (element.getAvailable() == false);
                try {
                    validateComputeElement(cvp, element);
                } catch (APIException e) {
                    _log.warn("Compute Element " + element.getLabel() + ":" + element.getDn() + " is in use(" + inUse + ") and does not meet criteria " + e.toString());
                    /*
                         * Since we are disallowing more restrictive changes if the VCP is in use, the if block below will not be used for
                         * the 2.2 release.
                         */
                    if (inUse) {
                        throw APIException.badRequests.changeToComputeVirtualPoolNotSupported(cvp.getLabel(), "Updates to pool not allowed because compute element(s) already in use do not meet requested criteria.");
                    }
                    // if ces not in use then simply remove
                    cesNotMeetingCriteria.add(element);
                    _log.warn("Compute Element does not meet criteria; so being removed");
                }
            }
        }
    }
    updateHostToCVPRelation(cvp);
    _dbClient.updateAndReindexObject(cvp);
    recordOperation(OperationTypeEnum.UPDATE_COMPUTE_VPOOL, VPOOL_UPDATED_DESCRIPTION, cvp);
    return toComputeVirtualPool(_dbClient, cvp, isComputeVirtualPoolInUse(cvp));
}
Also used : UCSServiceProfileTemplate(com.emc.storageos.db.client.model.UCSServiceProfileTemplate) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) ComputeElement(com.emc.storageos.db.client.model.ComputeElement) ComputeVirtualPool(com.emc.storageos.db.client.model.ComputeVirtualPool) ComputeVirtualPoolMapper.toComputeVirtualPool(com.emc.storageos.api.mapper.ComputeVirtualPoolMapper.toComputeVirtualPool) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 9 with APIException

use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.

the class DisasterRecoveryService method pause.

/**
 * Pause data replication to multiple standby sites.
 *
 * @param idList site uuid list to be removed
 * @brief Pause data replication to multiple standby sites.
 * @return Response
 */
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SECURITY_ADMIN, Role.RESTRICTED_SECURITY_ADMIN, Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN }, blockProxies = true)
@Path("/pause")
public Response pause(SiteIdListParam idList) {
    List<String> siteIdList = idList.getIds();
    String siteIdStr = StringUtils.join(siteIdList, ",");
    log.info("Begin to pause standby site from local vdc by uuid: {}", siteIdStr);
    List<Site> toBePausedSites = new ArrayList<>();
    List<String> siteNameList = new ArrayList<>();
    for (String siteId : siteIdList) {
        Site site;
        try {
            site = drUtil.getSiteFromLocalVdc(siteId);
        } catch (Exception ex) {
            log.error("Can't load site {} from ZK", siteId);
            throw APIException.badRequests.siteIdNotFound();
        }
        SiteState state = site.getState();
        if (state.equals(SiteState.ACTIVE)) {
            log.error("Unable to pause this site {}. It is active", siteId);
            throw APIException.badRequests.operationNotAllowedOnActiveSite();
        }
        if (!state.equals(SiteState.STANDBY_SYNCED)) {
            log.error("Unable to pause this site {}. It is in state {}", siteId, state);
            throw APIException.badRequests.operationOnlyAllowedOnSyncedSite(site.getName(), state.toString());
        }
        toBePausedSites.add(site);
        siteNameList.add(site.getName());
    }
    // This String is only used to output human readable message to user when Exception is thrown
    String siteNameStr = StringUtils.join(siteNameList, ',');
    precheckForPause(siteNameStr);
    try {
        // the site(s) to be paused must be checked as well
        commonPrecheck();
    } catch (APIException e) {
        throw e;
    } catch (Exception e) {
        throw APIException.internalServerErrors.pauseStandbyPrecheckFailed(siteNameStr, e.getMessage());
    }
    InterProcessLock lock = drUtil.getDROperationLock();
    // any error is not retry-able beyond this point.
    List<String> sitesString = new ArrayList<>();
    try {
        log.info("Pausing sites");
        long vdcTargetVersion = DrUtil.newVdcConfigVersion();
        coordinator.startTransaction();
        for (Site site : toBePausedSites) {
            site.setState(SiteState.STANDBY_PAUSING);
            site.setLastStateUpdateTime(System.currentTimeMillis());
            coordinator.persistServiceConfiguration(site.toConfiguration());
            drUtil.recordDrOperationStatus(site.getUuid(), InterState.PAUSING_STANDBY);
            sitesString.add(site.toBriefString());
            // notify the to-be-paused sites before others.
            drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_PAUSE_STANDBY, vdcTargetVersion);
        }
        log.info("Notify all sites for reconfig");
        for (Site site : drUtil.listSites()) {
            if (toBePausedSites.contains(site)) {
                // already notified
                continue;
            }
            drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_PAUSE_STANDBY, vdcTargetVersion);
        }
        coordinator.commitTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.PAUSE_STANDBY, AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_BEGIN, StringUtils.join(sitesString, ','));
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (Exception e) {
        log.error("Failed to pause site {}", siteIdStr, e);
        coordinator.discardTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.PAUSE_STANDBY, AuditLogManager.AUDITLOG_FAILURE, null, StringUtils.join(sitesString, ','));
        throw APIException.internalServerErrors.pauseStandbyFailed(siteNameStr, e.getMessage());
    } finally {
        try {
            lock.release();
        } catch (Exception ignore) {
            log.error(String.format("Lock release failed when pausing standby site: %s", siteIdStr));
        }
    }
}
Also used : Site(com.emc.storageos.coordinator.client.model.Site) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) SiteState(com.emc.storageos.coordinator.client.model.SiteState) ArrayList(java.util.ArrayList) InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) InternalServerErrorException(com.emc.storageos.svcs.errorhandling.resources.InternalServerErrorException) CoordinatorException(com.emc.storageos.coordinator.exceptions.CoordinatorException) RetryableCoordinatorException(com.emc.storageos.coordinator.exceptions.RetryableCoordinatorException) UnknownHostException(java.net.UnknownHostException) Path(javax.ws.rs.Path) ZkPath(com.emc.storageos.coordinator.common.impl.ZkPath) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 10 with APIException

use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.

the class AuthenticationResource method changePassword.

/**
 * Change a local user's password without login.
 *
 * This interface need be provided with clear text old password and new password
 *
 * @brief Change your password
 * @throws APIException
 */
@PUT
@Path("change-password")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response changePassword(@Context HttpServletRequest httpRequest, @Context HttpServletResponse servletResponse, @DefaultValue("true") @QueryParam("logout_user") boolean logout, PasswordChangeParam passwordChange) {
    String clientIP = _invLoginManager.getClientIP(httpRequest);
    isClientIPBlocked(clientIP);
    // internal call to password service
    Response response = _passwordUtils.changePassword(passwordChange, false);
    if (response.getStatus() != Status.OK.getStatusCode()) {
        String message = response.getEntity().toString();
        if (message.contains(_invLoginManager.OLD_PASSWORD_INVALID_ERROR)) {
            _invLoginManager.markErrorLogin(clientIP);
        }
    } else {
        // change password successfully, do some cleanup
        try {
            _invLoginManager.removeInvalidRecord(clientIP);
            if (logout) {
                _log.info("logout active sessions for: " + passwordChange.getUsername());
                _tokenManager.deleteAllTokensForUser(passwordChange.getUsername(), false);
            }
        } catch (Exception cleanupException) {
            _log.error("clean up failed: {0}", cleanupException.getMessage());
        }
    }
    return response;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) URISyntaxException(java.net.URISyntaxException) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException)

Aggregations

APIException (com.emc.storageos.svcs.errorhandling.resources.APIException)55 URI (java.net.URI)28 InternalException (com.emc.storageos.svcs.errorhandling.resources.InternalException)25 Produces (javax.ws.rs.Produces)22 Path (javax.ws.rs.Path)21 TaskResourceRep (com.emc.storageos.model.TaskResourceRep)20 ArrayList (java.util.ArrayList)19 POST (javax.ws.rs.POST)19 Volume (com.emc.storageos.db.client.model.Volume)18 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)18 TaskList (com.emc.storageos.model.TaskList)17 Consumes (javax.ws.rs.Consumes)16 NullColumnValueGetter.isNullURI (com.emc.storageos.db.client.util.NullColumnValueGetter.isNullURI)13 InternalServerErrorException (com.emc.storageos.svcs.errorhandling.resources.InternalServerErrorException)12 Operation (com.emc.storageos.db.client.model.Operation)10 DataObject (com.emc.storageos.db.client.model.DataObject)9 NamedURI (com.emc.storageos.db.client.model.NamedURI)9 BadRequestException (com.emc.storageos.svcs.errorhandling.resources.BadRequestException)9 BlockConsistencyGroup (com.emc.storageos.db.client.model.BlockConsistencyGroup)8 StorageSystem (com.emc.storageos.db.client.model.StorageSystem)7