Search in sources :

Example 56 with DELETE

use of javax.ws.rs.DELETE in project coprhd-controller by CoprHD.

the class FilePolicyService method deleteFilePolicy.

/**
 * @brief Delete file policy.
 * @param id
 *            of the file policy.
 * @return
 */
@DELETE
@Path("/{id}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN })
public Response deleteFilePolicy(@PathParam("id") URI id) {
    FilePolicy filepolicy = queryResource(id);
    ArgValidator.checkEntity(filepolicy, id, true);
    ArgValidator.checkReference(FilePolicy.class, filepolicy.getFilePolicyName(), checkForDelete(filepolicy));
    StringSet assignedResources = filepolicy.getAssignedResources();
    if (assignedResources != null && !assignedResources.isEmpty()) {
        _log.error("Delete file pocicy failed because the policy has associacted resources");
        throw APIException.badRequests.failedToDeleteFilePolicy(filepolicy.getFilePolicyName(), "This policy has assigned resources.");
    }
    _dbClient.markForDeletion(filepolicy);
    auditOp(OperationTypeEnum.DELETE_FILE_POLICY, true, null, filepolicy.getId().toString(), filepolicy.getLabel());
    return Response.ok().build();
}
Also used : FilePolicy(com.emc.storageos.db.client.model.FilePolicy) MapFilePolicy(com.emc.storageos.api.mapper.functions.MapFilePolicy) StringSet(com.emc.storageos.db.client.model.StringSet) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 57 with DELETE

use of javax.ws.rs.DELETE 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 58 with DELETE

use of javax.ws.rs.DELETE in project coprhd-controller by CoprHD.

the class SnapshotService method deleteSnapshot.

/**
 * Delete a specific snapshot
 *
 * @prereq none
 *
 * @param tenant_id
 *            the URN of the tenant
 * @param snapshot_id
 *            the URN of the snapshot
 *
 * @brief Delete Snapshot
 * @return Task result
 */
@DELETE
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{snapshot_id}")
@CheckPermission(roles = { Role.SYSTEM_MONITOR, Role.TENANT_ADMIN }, acls = { ACL.ANY })
public Response deleteSnapshot(@PathParam("tenant_id") String openstack_tenant_id, @PathParam("snapshot_id") String snapshot_id) {
    _log.info("Delete Snapshot: id = {}", snapshot_id);
    BlockSnapshot snap = findSnapshot(snapshot_id, openstack_tenant_id);
    if (snap == null) {
        _log.error("Not Found : Invalid volume snapshot id");
        return CinderApiUtils.createErrorResponse(404, "Not Found : Invalid volume snapshot id");
    } else if (snap.hasConsistencyGroup()) {
        _log.error("Not Found : Snapshot belongs to a consistency group");
        return CinderApiUtils.createErrorResponse(400, "Invalid snapshot: Snapshot belongs to consistency group");
    }
    URI snapshotURI = snap.getId();
    String task = UUID.randomUUID().toString();
    TaskList response = new TaskList();
    ArgValidator.checkReference(BlockSnapshot.class, snapshotURI, checkForDelete(snap));
    // Not an error if the snapshot we try to delete is already deleted
    if (snap.getInactive()) {
        Operation op = new Operation();
        op.ready("The snapshot has already been deleted");
        op.setResourceType(ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT);
        _dbClient.createTaskOpStatus(BlockSnapshot.class, snap.getId(), task, op);
        response.getTaskList().add(toTask(snap, task, op));
        return Response.status(202).build();
    }
    StorageSystem device = _dbClient.queryObject(StorageSystem.class, snap.getStorageController());
    List<BlockSnapshot> snapshots = new ArrayList<BlockSnapshot>();
    final URI cgId = snap.getConsistencyGroup();
    if (!NullColumnValueGetter.isNullURI(cgId)) {
        // Collect all the BlockSnapshots if part of a CG.
        URIQueryResultList results = new URIQueryResultList();
        _dbClient.queryByConstraint(AlternateIdConstraint.Factory.getBlockSnapshotsBySnapsetLabel(snap.getSnapsetLabel()), results);
        while (results.iterator().hasNext()) {
            URI uri = results.iterator().next();
            _log.info("BlockSnapshot being deactivated: " + uri);
            BlockSnapshot snapshot = _dbClient.queryObject(BlockSnapshot.class, uri);
            if (snapshot != null) {
                snapshots.add(snapshot);
            }
        }
    } else {
        // Snap is not part of a CG so only delete the snap
        snapshots.add(snap);
    }
    for (BlockSnapshot snapshot : snapshots) {
        Operation snapOp = _dbClient.createTaskOpStatus(BlockSnapshot.class, snapshot.getId(), task, ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT);
        response.getTaskList().add(toTask(snapshot, task, snapOp));
    }
    // Note that for snapshots of VPLEX volumes, the parent volume for the
    // snapshot is the source side backend volume, which will have the same
    // vpool as the VPLEX volume and therefore, the correct implementation
    // should be returned.
    Volume volume = _permissionsHelper.getObjectById(snap.getParent(), Volume.class);
    BlockServiceApi blockServiceApiImpl = BlockService.getBlockServiceImpl(volume, _dbClient);
    blockServiceApiImpl.deleteSnapshot(snap, snapshots, task, VolumeDeleteTypeEnum.FULL.name());
    StringMap extensions = snap.getExtensions();
    if (extensions == null) {
        extensions = new StringMap();
    }
    for (TaskResourceRep rep : response.getTaskList()) {
        extensions.put("taskid", rep.getId().toString());
        break;
    }
    snap.setExtensions(extensions);
    _dbClient.updateObject(snap);
    auditOp(OperationTypeEnum.DELETE_VOLUME_SNAPSHOT, true, AuditLogManager.AUDITOP_BEGIN, snapshot_id, snap.getLabel(), snap.getParent().getName(), device.getId().toString());
    return Response.status(202).build();
}
Also used : StringMap(com.emc.storageos.db.client.model.StringMap) TaskList(com.emc.storageos.model.TaskList) BlockSnapshot(com.emc.storageos.db.client.model.BlockSnapshot) ArrayList(java.util.ArrayList) 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) Volume(com.emc.storageos.db.client.model.Volume) StorageSystem(com.emc.storageos.db.client.model.StorageSystem) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 59 with DELETE

use of javax.ws.rs.DELETE in project coprhd-controller by CoprHD.

the class OrderService method deleteOrders.

/**
 * @brief delete orders (that can be deleted) under given tenants within a time range
 * @param startTimeStr the start time of the range (exclusive)
 * @param endTimeStr the end time of the range (inclusive)
 * @param tenantIDsStr A list of tenant IDs separated by ','
 * @param statusStr Order status
 * @return OK if a background job is submitted successfully
 */
@DELETE
@Path("")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.TENANT_ADMIN })
public Response deleteOrders(@DefaultValue("") @QueryParam(SearchConstants.START_TIME_PARAM) String startTimeStr, @DefaultValue("") @QueryParam(SearchConstants.END_TIME_PARAM) String endTimeStr, @DefaultValue("") @QueryParam(SearchConstants.TENANT_IDS_PARAM) String tenantIDsStr, @DefaultValue("") @QueryParam(SearchConstants.ORDER_STATUS_PARAM2) String statusStr) {
    long startTimeInMS = getTime(startTimeStr, 0);
    long endTimeInMS = getTime(endTimeStr, System.currentTimeMillis());
    if (startTimeInMS > endTimeInMS) {
        throw APIException.badRequests.endTimeBeforeStartTime(startTimeStr, endTimeStr);
    }
    if (tenantIDsStr.isEmpty()) {
        throw APIException.badRequests.invalidParameterWithCause(SearchConstants.TENANT_IDS_PARAM, tenantIDsStr, new InvalidParameterException("tenant IDs should not be empty"));
    }
    OrderStatus orderStatus = getOrderStatus(statusStr, true);
    if (isJobRunning()) {
        throw APIException.badRequests.cannotExecuteOperationWhilePendingTask("Deleting/Downloading orders");
    }
    List<URI> tids = toIDs(SearchConstants.TENANT_IDS_PARAM, tenantIDsStr);
    StorageOSUser user = getUserFromContext();
    URI tid = URI.create(user.getTenantId());
    URI uid = URI.create(user.getName());
    OrderJobStatus status = new OrderJobStatus(OrderServiceJob.JobType.DELETE_ORDER, startTimeInMS, endTimeInMS, tids, tid, uid, orderStatus);
    try {
        saveJobInfo(status);
    } catch (Exception e) {
        log.error("Failed to save job info e=", e);
        throw APIException.internalServerErrors.getLockFailed();
    }
    OrderServiceJob job = new OrderServiceJob(OrderServiceJob.JobType.DELETE_ORDER);
    try {
        queue.put(job);
    } catch (Exception e) {
        String errMsg = String.format("Failed to put the job into the queue %s", ORDER_SERVICE_QUEUE_NAME);
        log.error("{} e=", errMsg, e);
        APIException.internalServerErrors.genericApisvcError(errMsg, e);
    }
    String auditLogMsg = genDeletingOrdersMessage(startTimeStr, endTimeStr);
    auditOpSuccess(OperationTypeEnum.DELETE_ORDER, auditLogMsg);
    return Response.status(Response.Status.ACCEPTED).build();
}
Also used : InvalidParameterException(java.security.InvalidParameterException) OrderStatus(com.emc.storageos.db.client.model.uimodels.OrderStatus) StorageOSUser(com.emc.storageos.security.authentication.StorageOSUser) URIUtil.asString(com.emc.storageos.db.client.URIUtil.asString) OrderJobStatus(com.emc.sa.api.utils.OrderJobStatus) URI(java.net.URI) InvalidParameterException(java.security.InvalidParameterException) WebApplicationException(javax.ws.rs.WebApplicationException) URISyntaxException(java.net.URISyntaxException) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) OrderServiceJob(com.emc.sa.api.utils.OrderServiceJob) 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 DELETE

use of javax.ws.rs.DELETE in project coprhd-controller by CoprHD.

the class StorageDriverService method uninstall.

@DELETE
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN })
@Path("/{driverName}")
public Response uninstall(@PathParam("driverName") String driverName) {
    log.info("Start to uninstall driver {} ...", driverName);
    Set<String> driverNames = getAllDriverNames();
    if (!driverNames.contains(driverName)) {
        throw APIException.badRequests.driverNameNotFound(driverName);
    }
    precheckForEnv();
    List<StorageSystemType> toUninstallTypes = filterTypesByDriver(driverName);
    precheckForDriverStatus(toUninstallTypes, driverName);
    InterProcessLock lock = getStorageDriverOperationLock();
    try {
        StorageDriversInfo info = coordinator.getTargetInfo(StorageDriversInfo.class);
        if (info == null) {
            info = new StorageDriversInfo();
        }
        for (StorageSystemType type : toUninstallTypes) {
            type.setDriverStatus(StorageSystemType.STATUS.UNISNTALLING.toString());
            dbClient.updateObject(type);
            info.getInstalledDrivers().remove(type.getDriverFileName());
        }
        // update target list in ZK
        coordinator.setTargetInfo(info);
        log.info("Successfully triggered uninstall operation for driver {}", driverName);
        auditOperation(OperationTypeEnum.UNINSTALL_STORAGE_DRIVER, AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_BEGIN, driverName);
        return Response.ok().build();
    } catch (Exception e) {
        log.error("Error happened when installing driver file", e);
        auditOperation(OperationTypeEnum.UNINSTALL_STORAGE_DRIVER, AuditLogManager.AUDITLOG_FAILURE, null, driverName);
        throw APIException.internalServerErrors.uninstallDriverFailed(e.getMessage());
    } finally {
        try {
            lock.release();
        } catch (Exception ignore) {
            log.error(String.format("Lock release failed when uninstalling driver %s", driverName));
        }
    }
}
Also used : InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) StorageSystemType(com.emc.storageos.db.client.model.StorageSystemType) StorageDriversInfo(com.emc.storageos.coordinator.client.model.StorageDriversInfo) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Aggregations

DELETE (javax.ws.rs.DELETE)587 Path (javax.ws.rs.Path)539 Produces (javax.ws.rs.Produces)194 ApiOperation (io.swagger.annotations.ApiOperation)153 ApiResponses (io.swagger.annotations.ApiResponses)127 Consumes (javax.ws.rs.Consumes)78 Timed (com.codahale.metrics.annotation.Timed)59 Response (javax.ws.rs.core.Response)54 IOException (java.io.IOException)47 WebApplicationException (javax.ws.rs.WebApplicationException)46 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)42 Identity (org.olat.core.id.Identity)36 AuditEvent (org.graylog2.audit.jersey.AuditEvent)32 NotFoundException (javax.ws.rs.NotFoundException)23 POST (javax.ws.rs.POST)21 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)20 ApiResponse (io.swagger.annotations.ApiResponse)20 RestSecurityHelper.getIdentity (org.olat.restapi.security.RestSecurityHelper.getIdentity)20 HashMap (java.util.HashMap)19 GET (javax.ws.rs.GET)19