Search in sources :

Example 6 with NamedURI

use of com.emc.storageos.db.client.model.NamedURI in project coprhd-controller by CoprHD.

the class TenantsService method createPolicy.

/**
 * Worker method for create schedule policy. Allows external requests (REST) as well as
 * internal requests that may not have a security context.
 *
 * @param id the URN of a CoprHD Tenant/Subtenant
 * @param param schedule policy parameters
 * @brief Create schedule policy
 * @return No data returned in response body
 * @throws BadRequestException
 */
public SchedulePolicyResp createPolicy(URI id, PolicyParam param) {
    TenantOrg tenant = getTenantById(id, true);
    // Make policy name as mandatory field
    ArgValidator.checkFieldNotNull(param.getPolicyName(), "policyName");
    // Check for duplicate policy name
    if (param.getPolicyName() != null && !param.getPolicyName().isEmpty()) {
        checkForDuplicateName(param.getPolicyName(), SchedulePolicy.class);
    }
    // check schedule policy type is valid or not
    if (!ArgValidator.isValidEnum(param.getPolicyType(), SchedulePolicyType.class)) {
        throw APIException.badRequests.invalidSchedulePolicyType(param.getPolicyType());
    }
    _log.info("Schedule policy creation started -- ");
    SchedulePolicy schedulePolicy = new SchedulePolicy();
    StringBuilder errorMsg = new StringBuilder();
    // Validate Schedule policy parameters
    boolean isValidSchedule = SchedulePolicyService.validateSchedulePolicyParam(param.getPolicySchedule(), schedulePolicy, errorMsg);
    if (!isValidSchedule && errorMsg != null && errorMsg.length() > 0) {
        _log.error("Failed to create schedule policy due to {} ", errorMsg.toString());
        throw APIException.badRequests.invalidSchedulePolicyParam(param.getPolicyName(), errorMsg.toString());
    }
    // Validate snapshot expire parameters
    boolean isValidSnapshotExpire = false;
    if (param.getSnapshotExpire() != null) {
        // check snapshot expire type is valid or not
        String expireType = param.getSnapshotExpire().getExpireType();
        if (!ArgValidator.isValidEnum(expireType, SnapshotExpireType.class)) {
            _log.error("Invalid schedule snapshot expire type {}. Valid Snapshot expire types are hours, days, weeks, months and never", expireType);
            throw APIException.badRequests.invalidScheduleSnapshotExpireType(expireType);
        }
        isValidSnapshotExpire = SchedulePolicyService.validateSnapshotExpireParam(param.getSnapshotExpire());
        if (!isValidSnapshotExpire) {
            int expireTime = param.getSnapshotExpire().getExpireValue();
            int minExpireTime = 2;
            int maxExpireTime = 10;
            _log.error("Invalid schedule snapshot expire time {}. Try an expire time between {} hours to {} years", expireTime, minExpireTime, maxExpireTime);
            throw APIException.badRequests.invalidScheduleSnapshotExpireValue(expireTime, minExpireTime, maxExpireTime);
        }
    } else {
        if (param.getPolicyType().equalsIgnoreCase(SchedulePolicyType.file_snapshot.toString())) {
            errorMsg.append("Required parameter snapshot_expire was missing or empty");
            _log.error("Failed to create schedule policy due to {} ", errorMsg.toString());
            throw APIException.badRequests.invalidSchedulePolicyParam(param.getPolicyName(), errorMsg.toString());
        }
    }
    if (isValidSchedule) {
        schedulePolicy.setId(URIUtil.createId(SchedulePolicy.class));
        schedulePolicy.setPolicyType(param.getPolicyType());
        schedulePolicy.setLabel(param.getPolicyName());
        schedulePolicy.setPolicyName(param.getPolicyName());
        schedulePolicy.setScheduleFrequency(param.getPolicySchedule().getScheduleFrequency().toLowerCase());
        if (isValidSnapshotExpire) {
            schedulePolicy.setSnapshotExpireType(param.getSnapshotExpire().getExpireType().toLowerCase());
            if (!param.getSnapshotExpire().getExpireType().equalsIgnoreCase(SnapshotExpireType.NEVER.toString())) {
                schedulePolicy.setSnapshotExpireTime((long) param.getSnapshotExpire().getExpireValue());
            }
        }
        schedulePolicy.setTenantOrg(new NamedURI(tenant.getId(), schedulePolicy.getLabel()));
        _dbClient.createObject(schedulePolicy);
        _log.info("Schedule policy {} created successfully", schedulePolicy);
    }
    recordTenantEvent(OperationTypeEnum.CREATE_SCHEDULE_POLICY, tenant.getId(), schedulePolicy.getId());
    return new SchedulePolicyResp(schedulePolicy.getId(), toLink(ResourceTypeEnum.SCHEDULE_POLICY, schedulePolicy.getId()), schedulePolicy.getLabel());
}
Also used : SchedulePolicyResp(com.emc.storageos.model.schedulepolicy.SchedulePolicyResp) NamedURI(com.emc.storageos.db.client.model.NamedURI) TenantOrg(com.emc.storageos.db.client.model.TenantOrg) SchedulePolicyType(com.emc.storageos.db.client.model.SchedulePolicy.SchedulePolicyType) SchedulePolicy(com.emc.storageos.db.client.model.SchedulePolicy) AlternateIdConstraint(com.emc.storageos.db.client.constraint.AlternateIdConstraint) ContainmentConstraint(com.emc.storageos.db.client.constraint.ContainmentConstraint) ContainmentPermissionsConstraint(com.emc.storageos.db.client.constraint.ContainmentPermissionsConstraint) Constraint(com.emc.storageos.db.client.constraint.Constraint) SnapshotExpireType(com.emc.storageos.db.client.model.SchedulePolicy.SnapshotExpireType)

Example 7 with NamedURI

use of com.emc.storageos.db.client.model.NamedURI in project coprhd-controller by CoprHD.

the class InternalFileResource method releaseFileSystemInternal.

/**
 * Release a file system from its current tenant & project for internal object usage
 *
 * @param id the URN of a ViPR file system to be released
 * @return the updated file system
 * @throws InternalException
 */
@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/release")
public FileShareRestRep releaseFileSystemInternal(@PathParam("id") URI id) throws InternalException {
    ArgValidator.checkFieldUriType(id, FileShare.class, "id");
    FileShare fs = _fileService.queryResource(id);
    // and just return success down at the bottom
    if (!fs.checkInternalFlags(Flag.INTERNAL_OBJECT)) {
        URI tenantURI = fs.getTenant().getURI();
        if (!_permissionsHelper.userHasGivenRole(getUserFromContext(), tenantURI, Role.TENANT_ADMIN)) {
            throw APIException.forbidden.onlyAdminsCanReleaseFileSystems(Role.TENANT_ADMIN.toString());
        }
        // we can't release a fs that has exports
        FSExportMap exports = fs.getFsExports();
        if ((exports != null) && (!exports.isEmpty())) {
            throw APIException.badRequests.cannotReleaseFileSystemExportExists(exports.keySet().toString());
        }
        // we can't release a fs that has shares
        SMBShareMap shares = fs.getSMBFileShares();
        if ((shares != null) && (!shares.isEmpty())) {
            throw APIException.badRequests.cannotReleaseFileSystemSharesExists(shares.keySet().toString());
        }
        // files systems with pending operations can't be released
        if (fs.getOpStatus() != null) {
            for (String opId : fs.getOpStatus().keySet()) {
                Operation op = fs.getOpStatus().get(opId);
                if (Operation.Status.pending.name().equals(op.getStatus())) {
                    throw APIException.badRequests.cannotReleaseFileSystemWithTasksPending();
                }
            }
        }
        // file systems with snapshots can't be released
        Integer snapCount = _fileService.getNumSnapshots(fs);
        if (snapCount > 0) {
            throw APIException.badRequests.cannotReleaseFileSystemSnapshotExists(snapCount);
        }
        TenantOrg rootTenant = _permissionsHelper.getRootTenant();
        // we can't release the file system to the root tenant if the root tenant has no access
        // to the filesystem's virtual pool
        ArgValidator.checkFieldNotNull(fs.getVirtualPool(), "virtualPool");
        VirtualPool virtualPool = _permissionsHelper.getObjectById(fs.getVirtualPool(), VirtualPool.class);
        ArgValidator.checkEntity(virtualPool, fs.getVirtualPool(), false);
        if (!_permissionsHelper.tenantHasUsageACL(rootTenant.getId(), virtualPool)) {
            throw APIException.badRequests.cannotReleaseFileSystemRootTenantLacksVPoolACL(virtualPool.getId().toString());
        }
        fs.setOriginalProject(fs.getProject().getURI());
        fs.setTenant(new NamedURI(rootTenant.getId(), fs.getLabel()));
        fs.setProject(new NamedURI(_internalProject.getId(), fs.getLabel()));
        fs.addInternalFlags(INTERNAL_FILESHARE_FLAGS);
        _dbClient.updateAndReindexObject(fs);
        // audit against the source project, not the new dummy internal project
        auditOp(OperationTypeEnum.RELEASE_FILE_SYSTEM, true, null, fs.getId().toString(), fs.getOriginalProject().toString());
    }
    return map(fs);
}
Also used : SMBShareMap(com.emc.storageos.db.client.model.SMBShareMap) NamedURI(com.emc.storageos.db.client.model.NamedURI) TenantOrg(com.emc.storageos.db.client.model.TenantOrg) Operation(com.emc.storageos.db.client.model.Operation) VirtualPool(com.emc.storageos.db.client.model.VirtualPool) FSExportMap(com.emc.storageos.db.client.model.FSExportMap) FileShare(com.emc.storageos.db.client.model.FileShare) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI)

Example 8 with NamedURI

use of com.emc.storageos.db.client.model.NamedURI in project coprhd-controller by CoprHD.

the class InternalFileResource method undoReleaseFileSystemInternal.

/**
 * Undo the release of a file system
 *
 * @param id the URN of a ViPR file system to undo
 * @return the updated file system
 * @throws InternalException
 */
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/release/undo")
public FileShareRestRep undoReleaseFileSystemInternal(@PathParam("id") URI id) throws InternalException {
    ArgValidator.checkFieldUriType(id, FileShare.class, "id");
    FileShare fs = _fileService.queryResource(id);
    checkFileShareInternal(fs);
    URI releasedProject = fs.getOriginalProject();
    if (releasedProject == null) {
        throw APIException.forbidden.onlyPreviouslyReleasedFileSystemsCanBeUndone();
    }
    Project project = _permissionsHelper.getObjectById(releasedProject, Project.class);
    ArgValidator.checkEntity(project, releasedProject, false);
    ArgValidator.checkFieldNotNull(project.getTenantOrg(), "tenantOrg");
    ArgValidator.checkFieldNotNull(project.getTenantOrg().getURI(), "tenantOrg");
    fs.setTenant(new NamedURI(project.getTenantOrg().getURI(), fs.getLabel()));
    fs.setProject(new NamedURI(releasedProject, fs.getLabel()));
    fs.setOriginalProject(null);
    fs.clearInternalFlags(INTERNAL_FILESHARE_FLAGS);
    _dbClient.updateAndReindexObject(fs);
    // audit against the new project, not the old dummy internal project
    auditOp(OperationTypeEnum.UNDO_RELEASE_FILE_SYSTEM, true, null, fs.getId().toString(), project.getId().toString());
    return map(fs);
}
Also used : Project(com.emc.storageos.db.client.model.Project) NamedURI(com.emc.storageos.db.client.model.NamedURI) FileShare(com.emc.storageos.db.client.model.FileShare) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI)

Example 9 with NamedURI

use of com.emc.storageos.db.client.model.NamedURI in project coprhd-controller by CoprHD.

the class ProjectService method updateProject.

/**
 * Update info for project including project name and owner
 *
 * @param projectUpdate Project update parameters
 * @param id the URN of a ViPR Project
 * @prereq none
 * @brief Update project
 * @return No data returned in response body
 */
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}")
@CheckPermission(roles = { Role.TENANT_ADMIN }, acls = { ACL.OWN })
public Response updateProject(@PathParam("id") URI id, ProjectUpdateParam projectUpdate) {
    Project project = getProjectById(id, true);
    if (null != projectUpdate.getName() && !projectUpdate.getName().isEmpty() && !project.getLabel().equalsIgnoreCase(projectUpdate.getName())) {
        // check if any filepolicies are assigned to project
        if ((project.getFilePolicies() != null) && !(project.getFilePolicies().isEmpty())) {
            _log.error(String.format("Failed to update the name of project %s as a policy is assigned", project.getLabel()));
            throw APIException.badRequests.cannotUpdateProjectNameAssignedFilePolicy(project.getLabel());
        }
        checkForDuplicateName(projectUpdate.getName(), Project.class, project.getTenantOrg().getURI(), "tenantOrg", _dbClient);
        project.setLabel(projectUpdate.getName());
        NamedURI tenant = project.getTenantOrg();
        if (tenant != null) {
            tenant.setName(projectUpdate.getName());
            project.setTenantOrg(tenant);
        }
    }
    if (null != projectUpdate.getOwner() && !projectUpdate.getOwner().isEmpty() && !projectUpdate.getOwner().equalsIgnoreCase(project.getOwner())) {
        StringBuilder error = new StringBuilder();
        if (!Validator.isValidPrincipal(new StorageOSPrincipal(projectUpdate.getOwner(), StorageOSPrincipal.Type.User), project.getTenantOrg().getURI(), error)) {
            throw APIException.forbidden.specifiedOwnerIsNotValidForProjectTenant(error.toString());
        }
        // in GEO scenario, root can't be assigned as project owner
        boolean isRootInGeo = (projectUpdate.getOwner().equalsIgnoreCase("root") && !VdcUtil.isLocalVdcSingleSite());
        if (isRootInGeo) {
            throw APIException.forbidden.specifiedOwnerIsNotValidForProjectTenant("in GEO scenario, root can't be assigned as project owner");
        }
        // set owner acl
        project.removeAcl(new PermissionsKey(PermissionsKey.Type.SID, project.getOwner(), project.getTenantOrg().getURI()).toString(), ACL.OWN.toString());
        project.setOwner(projectUpdate.getOwner());
        // set owner acl
        project.addAcl(new PermissionsKey(PermissionsKey.Type.SID, project.getOwner(), project.getTenantOrg().getURI()).toString(), ACL.OWN.toString());
    }
    _dbClient.updateAndReindexObject(project);
    recordOperation(OperationTypeEnum.UPDATE_PROJECT, true, project);
    return Response.ok().build();
}
Also used : MapProject(com.emc.storageos.api.mapper.functions.MapProject) Project(com.emc.storageos.db.client.model.Project) NamedURI(com.emc.storageos.db.client.model.NamedURI) PermissionsKey(com.emc.storageos.security.authorization.PermissionsKey) StorageOSPrincipal(com.emc.storageos.security.validator.StorageOSPrincipal) 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 10 with NamedURI

use of com.emc.storageos.db.client.model.NamedURI in project coprhd-controller by CoprHD.

the class SRDFBlockServiceApiImpl method prepareVolume.

/**
 * Prepare Volume for an SRDF protected volume
 *
 * @param volume
 *            pre-created volume from the api service
 * @param param
 *            volume request
 * @param project
 *            project requested
 * @param varray
 *            varray requested
 * @param vpool
 *            vpool requested
 * @param size
 *            size of the volume
 * @param placement
 *            recommendation for placement
 * @param label
 *            volume label
 * @param consistencyGroup
 *            consistency group
 * @param token
 *            task id
 * @param remote
 *            is this a target volume
 * @param personality
 *            normal volume or metadata
 * @param srcVolumeId
 *            source volume ID; only for target volumes
 * @param raGroupURI
 *            RDF Group of the source array to use
 * @param copyMode
 *            copy policy, like async or sync
 *
 * @return a persisted volume
 */
private Volume prepareVolume(Volume volume, final Project project, final VirtualArray varray, final VirtualPool vpool, final String size, final Recommendation placement, final String label, final BlockConsistencyGroup consistencyGroup, final String token, final boolean remote, final Volume.PersonalityTypes personality, final URI srcVolumeId, final URI raGroupURI, final String copyMode) {
    boolean newVolume = false;
    if (volume == null) {
        // check for duplicate label
        validateVolumeLabel(label, project);
        newVolume = true;
        volume = new Volume();
        volume.setId(URIUtil.createId(Volume.class));
        volume.setOpStatus(new OpStatusMap());
    } else {
        volume = _dbClient.queryObject(Volume.class, volume.getId());
    }
    volume.setLabel(label);
    volume.setCapacity(SizeUtil.translateSize(size));
    volume.setThinlyProvisioned(VirtualPool.ProvisioningType.Thin.toString().equalsIgnoreCase(vpool.getSupportedProvisioningType()));
    volume.setVirtualPool(vpool.getId());
    volume.setProject(new NamedURI(project.getId(), volume.getLabel()));
    volume.setTenant(new NamedURI(project.getTenantOrg().getURI(), volume.getLabel()));
    volume.setVirtualArray(varray.getId());
    volume.setSrdfGroup(raGroupURI);
    volume.setSrdfCopyMode(copyMode);
    if (null != placement.getSourceStoragePool()) {
        StoragePool pool = _dbClient.queryObject(StoragePool.class, placement.getSourceStoragePool());
        if (null != pool) {
            volume.setProtocol(new StringSet());
            volume.getProtocol().addAll(VirtualPoolUtil.getMatchingProtocols(vpool.getProtocols(), pool.getProtocols()));
        }
    }
    volume.setPersonality(personality.toString());
    if (personality.equals(Volume.PersonalityTypes.SOURCE)) {
        volume.setAccessState(VolumeAccessState.READWRITE.name());
    } else if (personality.equals(Volume.PersonalityTypes.TARGET)) {
        volume.setAccessState(VolumeAccessState.NOT_READY.name());
    }
    URI storageSystemUri = null;
    if (!remote) {
        storageSystemUri = placement.getSourceStorageSystem();
        volume.setStorageController(storageSystemUri);
        volume.setPool(placement.getSourceStoragePool());
    } else {
        storageSystemUri = ((SRDFRecommendation) placement).getVirtualArrayTargetMap().get(varray.getId()).getTargetStorageDevice();
        volume.setStorageController(storageSystemUri);
        volume.setPool(((SRDFRecommendation) placement).getVirtualArrayTargetMap().get(varray.getId()).getTargetStoragePool());
    }
    StorageSystem storageSystem = _dbClient.queryObject(StorageSystem.class, storageSystemUri);
    String systemType = storageSystem.checkIfVmax3() ? DiscoveredDataObject.Type.vmax3.name() : storageSystem.getSystemType();
    volume.setSystemType(systemType);
    volume.setOpStatus(new OpStatusMap());
    Operation op = new Operation();
    op.setResourceType(ResourceOperationTypeEnum.CREATE_BLOCK_VOLUME);
    op.setStartTime(Calendar.getInstance());
    volume.getOpStatus().put(token, op);
    if (consistencyGroup != null) {
        volume.setConsistencyGroup(consistencyGroup.getId());
        volume.setReplicationGroupInstance(consistencyGroup.getLabel());
    }
    if (null != vpool.getAutoTierPolicyName()) {
        URI autoTierPolicyUri = StorageScheduler.getAutoTierPolicy(volume.getPool(), vpool.getAutoTierPolicyName(), _dbClient);
        if (null != autoTierPolicyUri) {
            volume.setAutoTieringPolicyUri(autoTierPolicyUri);
        }
    }
    // Keep track of target volumes associated with the source volume
    if (srcVolumeId != null) {
        Volume srcVolume = _dbClient.queryObject(Volume.class, srcVolumeId);
        if (srcVolume.getSrdfTargets() == null) {
            srcVolume.setSrdfTargets(new StringSet());
        }
        // This is done in prepare, but the source volume may be a cos change volume that didn't
        // go through that process.
        srcVolume.setPersonality(Volume.PersonalityTypes.SOURCE.toString());
        srcVolume.getSrdfTargets().add(volume.getId().toString());
        _dbClient.updateObject(srcVolume);
        volume.setSrdfParent(new NamedURI(srcVolume.getId(), srcVolume.getLabel()));
        computeCapacityforSRDFV3ToV2(volume, vpool);
    }
    if (newVolume) {
        _dbClient.createObject(volume);
    } else {
        _dbClient.updateObject(volume);
    }
    return volume;
}
Also used : StoragePool(com.emc.storageos.db.client.model.StoragePool) Volume(com.emc.storageos.db.client.model.Volume) NamedURI(com.emc.storageos.db.client.model.NamedURI) OpStatusMap(com.emc.storageos.db.client.model.OpStatusMap) StringSet(com.emc.storageos.db.client.model.StringSet) Operation(com.emc.storageos.db.client.model.Operation) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI) StorageSystem(com.emc.storageos.db.client.model.StorageSystem)

Aggregations

NamedURI (com.emc.storageos.db.client.model.NamedURI)196 URI (java.net.URI)98 Volume (com.emc.storageos.db.client.model.Volume)74 StringSet (com.emc.storageos.db.client.model.StringSet)65 Project (com.emc.storageos.db.client.model.Project)54 ArrayList (java.util.ArrayList)46 TenantOrg (com.emc.storageos.db.client.model.TenantOrg)43 StorageSystem (com.emc.storageos.db.client.model.StorageSystem)42 BlockSnapshot (com.emc.storageos.db.client.model.BlockSnapshot)36 Test (org.junit.Test)32 StoragePool (com.emc.storageos.db.client.model.StoragePool)31 VirtualPool (com.emc.storageos.db.client.model.VirtualPool)31 VirtualArray (com.emc.storageos.db.client.model.VirtualArray)27 BlockConsistencyGroup (com.emc.storageos.db.client.model.BlockConsistencyGroup)26 StringMap (com.emc.storageos.db.client.model.StringMap)26 List (java.util.List)23 OpStatusMap (com.emc.storageos.db.client.model.OpStatusMap)20 StringSetMap (com.emc.storageos.db.client.model.StringSetMap)20 VirtualPoolCapabilityValuesWrapper (com.emc.storageos.volumecontroller.impl.utils.VirtualPoolCapabilityValuesWrapper)18 FileShare (com.emc.storageos.db.client.model.FileShare)17