Search in sources :

Example 1 with OrderStatus

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

the class RecentOrdersDataTable method getCanBeDeletedOrderStatuses.

public static String getCanBeDeletedOrderStatuses() {
    List<OrderStatus> canBeDeletedStatus = new ArrayList<OrderStatus>(Arrays.asList(OrderStatus.values()));
    CollectionUtils.filter(canBeDeletedStatus, new Predicate() {

        @Override
        public boolean evaluate(Object o) {
            return ((OrderStatus) o).canBeDeleted();
        }
    });
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < canBeDeletedStatus.size(); i++) {
        if (i != 0) {
            builder.append(", ");
        }
        if (i == canBeDeletedStatus.size() - 1) {
            builder.append("or ");
        }
        builder.append(canBeDeletedStatus.get(i).name());
    }
    return builder.toString();
}
Also used : OrderStatus(com.emc.storageos.db.client.model.uimodels.OrderStatus) ArrayList(java.util.ArrayList) Predicate(org.apache.commons.collections.Predicate)

Example 2 with OrderStatus

use of com.emc.storageos.db.client.model.uimodels.OrderStatus 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 3 with OrderStatus

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

the class OrderService method downloadOrders.

/**
 * Get log data from the specified virtual machines that are filtered, merged,
 * and sorted based on the passed request parameters and streams the log
 * messages back to the client as JSON formatted strings.
 *
 * @brief Show logs from all or specified virtual machine
 * @param startTimeStr The start datetime of the desired time window. Value is
 *            inclusive.
 *            Allowed values: "yyyy-MM-dd_HH:mm:ss" formatted date or
 *            datetime in ms.
 *            Default: Set to yesterday same time
 * @param endTimeStr The end datetime of the desired time window. Value is
 *            inclusive.
 *            Allowed values: "yyyy-MM-dd_HH:mm:ss" formatted date or
 *            datetime in ms.
 * @param tenantIDsStr a list of tenant IDs separated by ','
 * @param orderIDsStr a list of order IDs separated by ','
 * @prereq one of tenantIDsStr and orderIDsStr should be empty
 * @return A reference to the StreamingOutput to which the log data is
 *         written.
 * @throws WebApplicationException When an invalid request is made.
 */
@GET
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.SYSTEM_MONITOR, Role.SECURITY_ADMIN })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
@Path("/download")
public Response downloadOrders(@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 orderStatusStr, @DefaultValue("") @QueryParam(SearchConstants.ORDER_IDS) String orderIDsStr) throws Exception {
    if (tenantIDsStr.isEmpty() && orderIDsStr.isEmpty()) {
        InvalidParameterException cause = new InvalidParameterException("Both tenant and order IDs are empty");
        throw APIException.badRequests.invalidParameterWithCause(SearchConstants.TENANT_ID_PARAM, tenantIDsStr, cause);
    }
    final long startTimeInMS = getTime(startTimeStr, 0);
    final long endTimeInMS = getTime(endTimeStr, System.currentTimeMillis());
    if (startTimeInMS > endTimeInMS) {
        throw APIException.badRequests.endTimeBeforeStartTime(startTimeStr, endTimeStr);
    }
    OrderStatus orderStatus = getOrderStatus(orderStatusStr, false);
    if (isJobRunning()) {
        throw APIException.badRequests.cannotExecuteOperationWhilePendingTask("Deleting/Downloading orders");
    }
    final List<URI> tids = toIDs(SearchConstants.TENANT_IDS_PARAM, tenantIDsStr);
    StorageOSUser user = getUserFromContext();
    URI tid = URI.create(user.getTenantId());
    URI uid = URI.create(user.getName());
    final OrderJobStatus status = new OrderJobStatus(OrderServiceJob.JobType.DOWNLOAD_ORDER, startTimeInMS, endTimeInMS, tids, tid, uid, orderStatus);
    List<URI> orderIDs = toIDs(SearchConstants.ORDER_IDS, orderIDsStr);
    status.setOrderIDs(orderIDs);
    if (!orderIDs.isEmpty()) {
        status.setStartTime(0);
        status.setEndTime(0);
    }
    try {
        saveJobInfo(status);
    } catch (Exception e) {
        log.error("Failed to save job info e=", e);
        throw APIException.internalServerErrors.getLockFailed();
    }
    StreamingOutput out = new StreamingOutput() {

        @Override
        public void write(OutputStream outputStream) {
            exportOrders(tids, startTimeInMS, endTimeInMS, outputStream, status);
        }
    };
    return Response.ok(out).build();
}
Also used : InvalidParameterException(java.security.InvalidParameterException) OrderStatus(com.emc.storageos.db.client.model.uimodels.OrderStatus) StorageOSUser(com.emc.storageos.security.authentication.StorageOSUser) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) 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) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 4 with OrderStatus

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

the class OrderService method dumpOrder.

private void dumpOrder(PrintStream out, URI id, OrderJobStatus status) throws Exception {
    Order order = null;
    Object[] parameters = null;
    OrderStatus orderStatus;
    try {
        order = _dbClient.queryObject(Order.class, id);
        orderStatus = status.getStatus();
        if (orderStatus != null && !orderStatus.name().equals(order.getOrderStatus())) {
            log.info("Order({})'s status {} is not {}, so skip downloading", id, order.getOrderStatus(), orderStatus);
            status.addFailed(1);
            return;
        }
        dumpOrder(out, order);
        status.addCompleted(1);
        saveJobInfo(status);
    } catch (Exception e) {
        log.error("Failed to download order {} e=", id, e);
        throw e;
    }
}
Also used : Order(com.emc.storageos.db.client.model.uimodels.Order) OrderStatus(com.emc.storageos.db.client.model.uimodels.OrderStatus) OrderMapper.createNewObject(com.emc.sa.api.mapper.OrderMapper.createNewObject) 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)

Example 5 with OrderStatus

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

the class OrderServiceJobConsumer method consumeItem.

/**
 * @param job The object provisioning job which is being worked on. This could be either creation or deletion job
 * @param callback This must be executed, after the item is processed successfully to remove the item
 *            from the distributed queue
 *
 * @throws Exception
 */
@Override
public void consumeItem(OrderServiceJob job, DistributedQueueItemProcessedCallback callback) throws Exception {
    while (true) {
        try {
            OrderJobStatus jobStatus = orderService.queryJobInfo(OrderServiceJob.JobType.DELETE_ORDER);
            long startTime = jobStatus.getStartTime();
            long endTime = jobStatus.getEndTime();
            OrderStatus status = jobStatus.getStatus();
            List<URI> tids = jobStatus.getTids();
            List<URI> orderIds = new ArrayList();
            log.info("jobstatus={}", jobStatus);
            long total = 0;
            long numberOfOrdersDeletedInGC = orderService.getDeletedOrdersInCurrentPeriodWithSort(jobStatus);
            long numberOfOrdersCanBeDeletedInGC = maxOrderDeletedPerGC - numberOfOrdersDeletedInGC;
            if (numberOfOrdersCanBeDeletedInGC <= 0) {
                log.info("Max number of order objects ({}) have been deleted in the current GC period", maxOrderDeletedPerGC);
                Thread.sleep(CHECK_INTERVAL);
                continue;
            }
            boolean stop = false;
            for (URI tid : tids) {
                TimeSeriesConstraint constraint = TimeSeriesConstraint.Factory.getOrders(tid, startTime, endTime);
                NamedElementQueryResultList ids = new NamedElementQueryResultList();
                dbClient.queryByConstraint(constraint, ids);
                for (NamedElementQueryResultList.NamedElement namedID : ids) {
                    URI id = namedID.getId();
                    Order order = orderManager.getOrderById(id);
                    try {
                        orderManager.canBeDeleted(order, status);
                        if (orderIds.size() < numberOfOrdersCanBeDeletedInGC) {
                            orderIds.add(id);
                        } else if (jobStatus.getTotal() != -1) {
                            stop = true;
                            break;
                        }
                        total++;
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (stop) {
                    break;
                }
            }
            if (jobStatus.getTotal() == -1) {
                // It's the first time to run the job, so get the total number of orders to be deleted
                jobStatus.setTotal(total);
                orderService.saveJobInfo(jobStatus);
                if (total == 0) {
                    log.info("No orders can be deleted");
                    break;
                }
            }
            log.info("{} orders to be deleted within current GC period", orderIds.size());
            long nDeleted = 0;
            long nFailed = 0;
            long start = System.currentTimeMillis();
            long tempCount = 0;
            for (URI id : orderIds) {
                Order order = orderManager.getOrderById(id);
                try {
                    log.info("To delete order {}", order.getId());
                    orderManager.deleteOrder(order);
                    nDeleted++;
                    tempCount++;
                    if (tempCount >= NUMBER_PER_RECORD) {
                        jobStatus.addCompleted(tempCount);
                        orderService.saveJobInfo(jobStatus);
                        tempCount = 0;
                    }
                } catch (BadRequestException e) {
                    log.warn("Failed to delete order {} e=", id, e);
                    nFailed++;
                    jobStatus.setFailed(nFailed);
                    orderService.saveJobInfo(jobStatus);
                } catch (Exception e) {
                    log.warn("Failed to delete order={} e=", id, e);
                    nFailed++;
                    jobStatus.setFailed(nFailed);
                    orderService.saveJobInfo(jobStatus);
                }
            }
            if (tempCount > 0) {
                jobStatus.addCompleted(tempCount);
                orderService.saveJobInfo(jobStatus);
                tempCount = 0;
            }
            long end = System.currentTimeMillis();
            long speed = (end - start) / (nDeleted + nFailed);
            jobStatus.setTimeUsedPerOrder(speed);
            orderService.saveJobInfo(jobStatus);
            if (jobStatus.isFinished()) {
                break;
            }
            Thread.sleep(CHECK_INTERVAL);
        } catch (Exception e) {
            log.error("e=", e);
            throw e;
        }
    }
    log.info("remove order job from the queue");
    callback.itemProcessed();
}
Also used : Order(com.emc.storageos.db.client.model.uimodels.Order) TimeSeriesConstraint(com.emc.storageos.db.client.constraint.TimeSeriesConstraint) ArrayList(java.util.ArrayList) URI(java.net.URI) BadRequestException(com.emc.storageos.svcs.errorhandling.resources.BadRequestException) OrderStatus(com.emc.storageos.db.client.model.uimodels.OrderStatus) BadRequestException(com.emc.storageos.svcs.errorhandling.resources.BadRequestException) NamedElementQueryResultList(com.emc.storageos.db.client.constraint.NamedElementQueryResultList)

Aggregations

OrderStatus (com.emc.storageos.db.client.model.uimodels.OrderStatus)5 DatabaseException (com.emc.storageos.db.exceptions.DatabaseException)3 APIException (com.emc.storageos.svcs.errorhandling.resources.APIException)3 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 InvalidParameterException (java.security.InvalidParameterException)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 OrderJobStatus (com.emc.sa.api.utils.OrderJobStatus)2 Order (com.emc.storageos.db.client.model.uimodels.Order)2 StorageOSUser (com.emc.storageos.security.authentication.StorageOSUser)2 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)2 ArrayList (java.util.ArrayList)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 OrderMapper.createNewObject (com.emc.sa.api.mapper.OrderMapper.createNewObject)1 OrderServiceJob (com.emc.sa.api.utils.OrderServiceJob)1 URIUtil.asString (com.emc.storageos.db.client.URIUtil.asString)1 NamedElementQueryResultList (com.emc.storageos.db.client.constraint.NamedElementQueryResultList)1 TimeSeriesConstraint (com.emc.storageos.db.client.constraint.TimeSeriesConstraint)1 BadRequestException (com.emc.storageos.svcs.errorhandling.resources.BadRequestException)1