Search in sources :

Example 36 with APIException

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

the class DrDbHealthMonitor method checkIncrementalSyncingSite.

private void checkIncrementalSyncingSite(Site standbySite, List<Site> sitesToDegrade) {
    String siteId = standbySite.getUuid();
    int nodeCount = standbySite.getNodeCount();
    // We must wait until all the dbsvc/geodbsvc instances are back
    // or the data sync will fail anyways
    int liveDbsvcNodeCount = drUtil.getNumberOfLiveServices(siteId, Constants.DBSVC_NAME);
    int liveGeodbsvcNodeCount = drUtil.getNumberOfLiveServices(siteId, Constants.GEODBSVC_NAME);
    if (liveDbsvcNodeCount != nodeCount || liveGeodbsvcNodeCount != nodeCount) {
        log.info("Not all the dbsvc/geodbsvc instances are back. dbsvc active nodes {}, geodbsvc live nodes {}", liveDbsvcNodeCount, liveGeodbsvcNodeCount);
        boolean quorumLost = (liveDbsvcNodeCount <= nodeCount / 2) || (liveGeodbsvcNodeCount <= nodeCount / 2);
        if (quorumLost) {
            SiteMonitorResult monitorResult = coordinatorClient.getTargetInfo(siteId, SiteMonitorResult.class);
            checkEligibleForDegrade(monitorResult, standbySite, sitesToDegrade);
        }
        return;
    }
    log.info("All the dbsvc/geodbsvc instances are back. {}. Check if we need reset STANDBY_INCR_SYNCING state", standbySite.getUuid());
    InterProcessLock lock;
    try {
        lock = drUtil.getDROperationLock();
    } catch (APIException e) {
        log.warn("There are ongoing DR operations. Try again later.");
        return;
    }
    try {
        // reload site from zookeeper
        Site site = drUtil.getSiteFromLocalVdc(standbySite.getUuid());
        if (site.getState() != SiteState.STANDBY_INCR_SYNCING) {
            log.info("Skip incremental syncing state check. Site {} current state is {}", site.getUuid(), site.getState());
            return;
        }
        String dcName = drUtil.getCassandraDcId(site);
        Collection<String> ipAddrs = drUtil.getLocalSite().getHostIPv4AddressMap().values();
        if (ipAddrs.isEmpty()) {
            ipAddrs = drUtil.getLocalSite().getHostIPv6AddressMap().values();
        }
        for (String host : ipAddrs) {
            boolean isLocaldbsvcSynced = isDataCenterSynced(host, DEFAULTPORT, dcName);
            if (!isLocaldbsvcSynced) {
                return;
            }
            boolean isGeodbsvcSynced = isDataCenterSynced(host, DEFAULTGEOPORT, dcName);
            if (!isGeodbsvcSynced) {
                return;
            }
        }
        log.info("Data synced for dbsvc/geodbsvc of standby site {}", site.getUuid());
        site.setState(SiteState.STANDBY_SYNCED);
        drUtil.getCoordinator().persistServiceConfiguration(site.toConfiguration());
        updateSiteMonitorResult(standbySite);
    } catch (Exception e) {
        log.error("Failed to initiate reset STATNDBY_INCR_SYNCING standby operation. Try again later", e);
    } finally {
        try {
            lock.release();
        } catch (Exception e) {
            log.error("Failed to release the dr operation lock", e);
        }
    }
}
Also used : APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) IOException(java.io.IOException) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) MalformedObjectNameException(javax.management.MalformedObjectNameException)

Example 37 with APIException

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

the class UpgradeService method uploadImage.

/**
 * Upload the image file given.
 * Consumes MediaType.APPLICATION_OCTET_STREAM.
 * This is an asynchronous operation.
 *
 * @brief Upload the specified image file
 * @prereq Cluster state should be STABLE
 * @return Cluster information.
 */
@POST
@Path("image/upload")
@CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN })
@Consumes({ MediaType.APPLICATION_OCTET_STREAM })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response uploadImage(@Context HttpServletRequest request) {
    File file = null;
    String svcId = _coordinator.getMySvcId();
    _log.info("uploadImage to {} start", svcId);
    // validate
    if (!_coordinator.isClusterUpgradable()) {
        throw APIException.serviceUnavailable.clusterStateNotStable();
    }
    // maximal install number check
    RepositoryInfo targetInfo = null;
    try {
        targetInfo = _coordinator.getTargetInfo(RepositoryInfo.class);
    } catch (Exception e) {
        throw APIException.internalServerErrors.getObjectFromError("target repository info", "coordinator", e);
    }
    if (targetInfo.getVersions().size() > SyncInfoBuilder.MAX_SOFTWARE_VERSIONS) {
        throw APIException.badRequests.numberOfInstalledExceedsMax();
    }
    // length check
    String contentLength = request.getHeader("Content-Length");
    if (Long.parseLong(contentLength) <= 0 || Long.parseLong(contentLength) > MAX_UPLOAD_SIZE) {
        throw APIException.badRequests.fileSizeExceedsLimit(MAX_UPLOAD_SIZE);
    }
    try {
        // remove previous and upload to a temp file
        UpgradeImageUploader uploader = UpgradeImageUploader.getInstance(_upgradeManager);
        uploader.cleanUploadFiles();
        long versionSize = Long.valueOf(contentLength);
        _log.info("The size of the image is:" + versionSize);
        String version = VIPR_UNKNOWN_IMAGE_VERSION;
        initializeDownloadProgress(version, versionSize);
        file = uploader.startUpload(request.getInputStream(), version);
        // install image
        if (file == null || file != null && !file.exists()) {
            throw APIException.internalServerErrors.targetIsNullOrEmpty("Uploaded file");
        }
        version = _upgradeManager.getLocalRepository().installImage(file);
        // set target
        List<SoftwareVersion> newList = new ArrayList<SoftwareVersion>(targetInfo.getVersions());
        SoftwareVersion newVersion = new SoftwareVersion(version);
        if (newList.contains(newVersion)) {
            _log.info("Version has already been installed");
        } else {
            newList.add(newVersion);
            _coordinator.setTargetInfo(new RepositoryInfo(targetInfo.getCurrentVersion(), newList));
            DownloadingInfo temp = _coordinator.getNodeGlobalScopeInfo(DownloadingInfo.class, DOWNLOADINFO_KIND, svcId);
            _coordinator.setNodeGlobalScopeInfo(new DownloadingInfo(version, versionSize, versionSize, DownloadStatus.COMPLETED, temp._errorCounter), DOWNLOADINFO_KIND, svcId);
            _coordinator.setTargetInfo(new DownloadingInfo(version, versionSize), false);
        }
        _log.info("uploadImage to {} end", svcId);
        auditUpgrade(OperationTypeEnum.UPLOAD_IMAGE, AuditLogManager.AUDITLOG_SUCCESS, null, targetInfo.getCurrentVersion().toString(), svcId);
        // return cluster status
        ClusterInfo clusterInfo = _coordinator.getClusterInfo();
        if (clusterInfo == null) {
            throw APIException.internalServerErrors.targetIsNullOrEmpty("Cluster info");
        }
        return toClusterResponse(clusterInfo);
    } catch (APIException ae) {
        throw ae;
    } catch (Exception e) {
        throw APIException.internalServerErrors.uploadInstallError(e);
    } finally {
        if (file != null && file.exists()) {
            file.delete();
        }
    }
}
Also used : DownloadingInfo(com.emc.storageos.coordinator.client.model.DownloadingInfo) ClusterInfo(com.emc.vipr.model.sys.ClusterInfo) SoftwareVersion(com.emc.storageos.coordinator.client.model.SoftwareVersion) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) RepositoryInfo(com.emc.storageos.coordinator.client.model.RepositoryInfo) ArrayList(java.util.ArrayList) File(java.io.File) RemoteRepositoryException(com.emc.storageos.systemservices.exceptions.RemoteRepositoryException) ServiceUnavailableException(com.emc.storageos.svcs.errorhandling.resources.ServiceUnavailableException) InvalidSoftwareVersionException(com.emc.storageos.coordinator.exceptions.InvalidSoftwareVersionException) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) LocalRepositoryException(com.emc.storageos.systemservices.exceptions.LocalRepositoryException) IOException(java.io.IOException) CoordinatorClientException(com.emc.storageos.systemservices.exceptions.CoordinatorClientException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) CheckPermission(com.emc.storageos.security.authorization.CheckPermission)

Example 38 with APIException

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

the class TokenBasedAuthenticationFilter method doFilter.

// Overriding doFilter even though it is in the base class.
// Need a different logic to forward to authsvc when authenticate fails.
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    AbstractRequestWrapper reqWrapper = null;
    try {
        reqWrapper = authenticate(servletRequest);
    } catch (APIException e) {
        _logger.debug("unauthorized request: serviceUrl = " + request.getRequestURI(), e);
        response.setStatus(toHTTPStatus(e));
        response.getOutputStream().print(toServiceErrorXml(e));
        response.setHeader("Content-Type", "application/xml");
        return;
    } catch (final InternalException e) {
        response.setStatus(toHTTPStatus(e));
        response.getOutputStream().print(toServiceErrorXml(e));
        response.setHeader("Content-Type", "application/xml");
        return;
    }
    if (reqWrapper != null) {
        // we are done, forward it to resource service
        forwardToService(servletRequest, servletResponse, reqWrapper);
    } else {
        // We need to go get a token from authsvc.
        forwardToAuthService(request, response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) HttpServletResponse(javax.servlet.http.HttpServletResponse) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException)

Example 39 with APIException

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

the class ScheduledEventService method updateEvent.

/**
 * Update a scheduled event for one or a series of future orders.
 * @param updateParam   including schedule time info
 * @return                ScheduledEventRestRep
 */
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ScheduledEventRestRep updateEvent(@PathParam("id") String id, ScheduledEventUpdateParam updateParam) {
    ScheduledEvent scheduledEvent = queryResource(uri(id));
    ArgValidator.checkEntity(scheduledEvent, uri(id), true);
    validateParam(updateParam.getScheduleInfo());
    try {
        OrderCreateParam orderCreateParam = OrderCreateParam.deserialize(org.apache.commons.codec.binary.Base64.decodeBase64(scheduledEvent.getOrderCreationParam().getBytes(UTF_8)));
        validateAutomaticExpirationNumber(updateParam.getAdditionalScheduleInfo());
        orderCreateParam.setAdditionalScheduleInfo(updateParam.getAdditionalScheduleInfo());
        scheduledEvent.setOrderCreationParam(new String(org.apache.commons.codec.binary.Base64.encodeBase64(orderCreateParam.serialize()), UTF_8));
        updateScheduledEvent(scheduledEvent, updateParam.getScheduleInfo());
    } catch (APIException ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return map(scheduledEvent);
}
Also used : APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) URIUtil.asString(com.emc.storageos.db.client.URIUtil.asString) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) BadRequestException(com.emc.storageos.svcs.errorhandling.resources.BadRequestException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) ParseException(java.text.ParseException)

Example 40 with APIException

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

the class CustomTokenBasedAthenticationFilter method doFilter.

// This filter will forward to authsvc only if the resource is /user and there is no
// authenticated context. Else, just let it through to authsvc (it will know what to
// to do)
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    AbstractRequestWrapper reqWrapper = null;
    try {
        reqWrapper = authenticate(servletRequest);
    } catch (APIException e) {
        _log.debug("unauthorized request: serviceUrl = " + request.getRequestURI(), e);
        response.sendError(toHTTPStatus(e), toServiceErrorXml(e));
        return;
    } catch (final InternalException e) {
        response.sendError(toHTTPStatus(e), toServiceErrorXml(e));
        return;
    }
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    String uri = req.getRequestURI();
    if (reqWrapper.getUserPrincipal() == null && uri.toLowerCase().startsWith("/user/")) {
        forwardToAuthService(request, response);
    } else {
        forwardToService(servletRequest, servletResponse, reqWrapper);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) HttpServletResponse(javax.servlet.http.HttpServletResponse) InternalException(com.emc.storageos.svcs.errorhandling.resources.InternalException)

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