Search in sources :

Example 66 with DatabaseException

use of com.emc.storageos.db.exceptions.DatabaseException in project coprhd-controller by CoprHD.

the class DBClient method queryForCustomDayEvents.

/**
 * Query events
 *
 * @param dateTime
 */
public void queryForCustomDayEvents(DateTime dateTime, String filename) {
    System.out.println("\n\n -> Querying Events");
    ExecutorService executor = Executors.newFixedThreadPool(100);
    EventQueryResult result = new EventQueryResult(filename);
    try {
        _dbClient.queryTimeSeries(EventTimeSeries.class, dateTime, TimeSeriesMetadata.TimeBucket.HOUR, result, executor);
        System.out.println(" --- Job Exceution for Querying Events completed ---");
        return;
    } catch (DatabaseException e) {
        System.err.println("Exception Query " + e);
        log.error("Exception Query ", e);
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException)

Example 67 with DatabaseException

use of com.emc.storageos.db.exceptions.DatabaseException in project coprhd-controller by CoprHD.

the class SchemaUtil method queryLocalVdc.

private VirtualDataCenter queryLocalVdc(DbClient dbClient) {
    // all vdc info stored in local db
    try {
        _log.debug("my vdcid: " + _vdcShortId);
        URIQueryResultList list = new URIQueryResultList();
        AlternateIdConstraint constraints = AlternateIdConstraint.Factory.getVirtualDataCenterByShortIdConstraint(_vdcShortId);
        dbClient.queryByConstraint(constraints, list);
        if (list.iterator().hasNext()) {
            URI vdcId = list.iterator().next();
            VirtualDataCenter vdc = dbClient.queryObject(VirtualDataCenter.class, vdcId);
            return vdc;
        } else {
            _log.info("vdc resource query returned no results");
            return null;
        }
    } catch (DatabaseException ex) {
        _log.error("failed querying for vdc resource", ex);
        // Throw an DatabaseException and retry
        throw ex;
    } catch (Exception ex) {
        _log.error("unexpected error during querying for vdc info", ex);
        // throw IllegalStateExcpetion and stop
        throw new IllegalStateException("vdc resource query failed");
    }
}
Also used : VirtualDataCenter(com.emc.storageos.db.client.model.VirtualDataCenter) NamedURI(com.emc.storageos.db.client.model.NamedURI) URI(java.net.URI) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) AlternateIdConstraint(com.emc.storageos.db.client.constraint.AlternateIdConstraint) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) OperationException(com.netflix.astyanax.connectionpool.exceptions.OperationException) ConnectionException(com.netflix.astyanax.connectionpool.exceptions.ConnectionException) UnknownHostException(java.net.UnknownHostException)

Example 68 with DatabaseException

use of com.emc.storageos.db.exceptions.DatabaseException in project coprhd-controller by CoprHD.

the class GarbageCollectionRunnable method run.

@Override
public void run() {
    log.info("Starting GC loop: type: {}", type.getSimpleName());
    try {
        URIQueryResultList list = getDecommissionedObjectsOfType(type);
        int found = 0, deleted = 0;
        for (Iterator<URI> iterator = list.iterator(); iterator.hasNext(); ) {
            URI uri = iterator.next();
            found++;
            log.debug("GC checks dependencies for {}", uri);
            try {
                if (!canBeGC(uri)) {
                    continue;
                }
                DataObject obj = dbClient.queryObject(type, uri);
                if (obj != null) {
                    log.info("No dependencies found. Removing {}", uri);
                    ((DbClientImpl) dbClient).internalRemoveObjects(obj);
                    deleted++;
                }
            } catch (DatabaseException ex) {
                log.warn("Exception from database access: ", ex);
            // To Do - we should skip the whole loop and retry later?
            }
        }
        if (found > 0) {
            log.info(String.format("Done GC loop: type: %s, processed %s, deleted %s", type.getSimpleName(), found, deleted));
        }
    } catch (Exception e) {
        log.error("Exception e=", e);
    }
}
Also used : DataObject(com.emc.storageos.db.client.model.DataObject) DbClientImpl(com.emc.storageos.db.client.impl.DbClientImpl) URI(java.net.URI) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException)

Example 69 with DatabaseException

use of com.emc.storageos.db.exceptions.DatabaseException in project coprhd-controller by CoprHD.

the class GeoServiceJobQueue method consumeItem.

/**
 * Verify the hosting device has not migrated states while waiting for dispatching and continue task
 *
 * @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(GeoServiceJob job, DistributedQueueItemProcessedCallback callback) throws Exception {
    // verify job, db may not stable right now after reboot, retry may need
    VirtualDataCenter vdcInfo = null;
    int retry = 0;
    while (retry < MAX_DB_RETRY) {
        try {
            vdcInfo = _dbClient.queryObject(VirtualDataCenter.class, job.getVdcId());
            break;
        } catch (DatabaseException e) {
            _log.info("db not stable yet, retry");
            try {
                TimeUnit.SECONDS.sleep(WAIT_INTERVAL_IN_SEC);
            } catch (InterruptedException ex) {
            // Ignore this exception
            }
        }
        retry = retry + 1;
    }
    if (vdcInfo == null) {
        _log.info("Failed to query vdc {} from DB. Retry later", job.getVdcId());
        return;
    }
    String task = job.getTask();
    if (task == null) {
        _log.error("The vdc connect job for {} does not have an associated task", job.getVdcId());
        return;
    }
    try {
        _controller.setKeystore(viprKeyStore);
        // these methods will obtain lock and do nothing if operation is already in progress
        GeoServiceJob.JobType type = job.getType();
        switch(type) {
            case VDC_CONNECT_JOB:
                _log.info("Continuing initialization operation {} for {}", task, job.getVdcId());
                _controller.connectVdc(vdcInfo, task, job.getParams());
                break;
            case VDC_REMOVE_JOB:
                _log.info("vdc operation {} for {}", task, job.getVdcId());
                _controller.removeVdc(vdcInfo, task, job.getParams());
                break;
            case VDC_UPDATE_JOB:
                _log.info("Updating operation {} for {}", task, job.getVdcId());
                _controller.updateVdc(job.getVdc(), task, job.getParams());
                break;
            case VDC_DISCONNECT_JOB:
                _log.info("Disconnecting operation {} for {}", task, job.getVdcId());
                _controller.disconnectVdc(vdcInfo, task, job.getParams());
                break;
            case VDC_RECONNECT_JOB:
                _log.info("Reconnecting operation {} for {}", task, job.getVdcId());
                _controller.reconnectVdc(vdcInfo, task, job.getParams());
                break;
            default:
                _log.error("Invalid operation type {} on {}/{}", new Object[] { job.getType(), task, job.getVdcId() });
        }
    } catch (Exception e) {
        // TODO: retry the task if it is retryable exception
        _log.error("Execute job failed", e);
    }
    // removes item from queue
    callback.itemProcessed();
    _log.info("The job type={} vdcId={} task={} is removed", new Object[] { job.getType(), job.getVdcId(), job.getTask() });
}
Also used : GeoServiceJob(com.emc.storageos.security.geo.GeoServiceJob) VirtualDataCenter(com.emc.storageos.db.client.model.VirtualDataCenter) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException)

Example 70 with DatabaseException

use of com.emc.storageos.db.exceptions.DatabaseException in project coprhd-controller by CoprHD.

the class TokenService method getToken.

/**
 * Retrieves Token and UserDAO records from a passed in auth token (header)
 * TokenKeysRequest can also contain key ids to look at. If they don't match the local
 * TokenKeysBundle, send the updated bundle in the response
 *
 * @param httpRequest
 * @return TokenResponse with token and userDAO records populated.
 */
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public TokenResponse getToken(@Context HttpServletRequest httpRequest, TokenKeysRequest req) {
    String rawToken = httpRequest.getHeader(RequestProcessingUtils.AUTH_TOKEN_HEADER);
    String firstKey = req.getFirstKeyId();
    String secondKey = req.getSecondKeyId();
    Token token = null;
    StorageOSUserDAO user = null;
    TokenKeysBundle updatedBundle = null;
    // validate token if provided
    if (StringUtils.isNotBlank(rawToken)) {
        token = (Token) tokenValidator.verifyToken(rawToken);
        if (token != null) {
            user = tokenValidator.resolveUser(token);
        }
        if (user == null || token == null) {
            throw APIException.unauthorized.noTokenFoundForUserFromForeignVDC();
        }
        if (user.getIsLocal()) {
            throw APIException.forbidden.localUsersNotAllowedForSingleSignOn(user.getUserName());
        }
    }
    // not has been a rotation yet.
    if (StringUtils.isNotBlank(firstKey)) {
        try {
            updatedBundle = tokenKeyGenerator.readBundle();
        } catch (Exception ex) {
            log.error("Could not look at local token keys bundle");
        }
        if (updatedBundle != null) {
            // if we found a bundle
            log.debug("Read the local key bundle");
            // look at its key ids
            List<String> keyIds = updatedBundle.getKeyEntries();
            if ((firstKey.equals(keyIds.get(0)) && secondKey == null && keyIds.size() == 1) || (firstKey.equals(keyIds.get(0)) && secondKey != null && secondKey.equals(keyIds.get(1)))) {
                log.info("Key id match.  Not returning a bundle");
                // if they both match what was passed in, make the bundle null and
                // return that. Caller has updated keys and does not need them.
                updatedBundle = null;
            } else {
                log.info("Key ids do not match.  Returning updated bundle");
            }
        }
    }
    if (token != null) {
        tokenMapHelper.addOrRemoveRequestingVDC(Operation.ADD_VDC, token.getId().toString(), req.getRequestingVDC());
        // update idle time on original token. Since it is being borrowed by another vdc,
        // it just got accessed.
        token.setLastAccessTime(CassandraTokenValidator.getCurrentTimeInMins());
        try {
            dbClient.persistObject(token);
        } catch (DatabaseException ex) {
            log.error("failed updating last access time for borrowed token {}", token.getId());
        }
    }
    return TokenResponseBuilder.buildTokenResponse(token, user, updatedBundle);
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) TokenKeysBundle(com.emc.storageos.security.authentication.TokenKeyGenerator.TokenKeysBundle) Token(com.emc.storageos.db.client.model.Token) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

DatabaseException (com.emc.storageos.db.exceptions.DatabaseException)109 URI (java.net.URI)71 ArrayList (java.util.ArrayList)29 URIQueryResultList (com.emc.storageos.db.client.constraint.URIQueryResultList)22 IOException (java.io.IOException)21 StorageSystem (com.emc.storageos.db.client.model.StorageSystem)20 DeviceControllerException (com.emc.storageos.exceptions.DeviceControllerException)19 ServiceError (com.emc.storageos.svcs.errorhandling.model.ServiceError)18 BlockSnapshot (com.emc.storageos.db.client.model.BlockSnapshot)17 BaseCollectionException (com.emc.storageos.plugins.BaseCollectionException)16 NamedURI (com.emc.storageos.db.client.model.NamedURI)14 ControllerException (com.emc.storageos.volumecontroller.ControllerException)13 TenantOrg (com.emc.storageos.db.client.model.TenantOrg)12 HashMap (java.util.HashMap)12 HashSet (java.util.HashSet)12 List (java.util.List)12 StoragePool (com.emc.storageos.db.client.model.StoragePool)11 StoragePort (com.emc.storageos.db.client.model.StoragePort)11 Volume (com.emc.storageos.db.client.model.Volume)11 WBEMException (javax.wbem.WBEMException)11