Search in sources :

Example 46 with InterProcessLock

use of org.apache.curator.framework.recipes.locks.InterProcessLock in project coprhd-controller by CoprHD.

the class TokenKeyGenerator method globalInit.

/**
 * Initialization method to be called by authsvc. It will create the key configuration if it doesn't exist
 * on first startup. Else it will just load the cache.
 *
 * @throws Exception
 */
public void globalInit() throws Exception {
    computeRotationTime();
    InterProcessLock lock = null;
    try {
        lock = _coordinator.getLock(DISTRIBUTED_KEY_TOKEN_LOCK);
        lock.acquire();
        if (!doesConfigExist()) {
            TokenKeysBundle bundle = TokenKeysBundle.createNewTokenKeysBundle();
            createOrUpdateBundle(bundle);
            updateCachedTokenKeys(bundle);
        } else {
            updateCachedKeys();
            _log.debug("Token keys configuration exists, loaded keys");
            _log.debug("Current token key {}", _cachedTokenKeysBundle.getCurrentKeyEntry());
        }
        keyRotationExecutor.scheduleWithFixedDelay(new KeyRotationThread(), 0, _keyRotationIntervalInMsecs, TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
        _log.error("Exception during initialization of TokenKeyGenerator", ex);
    } finally {
        try {
            if (lock != null) {
                lock.release();
            }
        } catch (Exception ex) {
            _log.error("Could not release the lock during TokenKeyGenerator.init()");
            throw ex;
        }
    }
}
Also used : InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 47 with InterProcessLock

use of org.apache.curator.framework.recipes.locks.InterProcessLock in project coprhd-controller by CoprHD.

the class RequestedTokenHelper method addOrRemoveRequestingVDC.

/**
 * Adds or removes a VDCid to the list of VDCids that requested the given token
 *
 * @param op ADD_VDC or REMOVE_VDC
 * @param tokenId the token for which the map should be updated
 * @param requestingVDC the short vdcid of the vdc to add or remove
 */
public void addOrRemoveRequestingVDC(Operation op, String tokenId, String requestingVDC) {
    InterProcessLock tokenLock = null;
    String lockName = String.format(TOKEN_MAP_LOCK_PREFIX, tokenId.toString());
    try {
        tokenLock = coordinator.getLock(lockName);
        if (tokenLock == null) {
            log.error("Could not acquire lock for requested token map update");
            throw SecurityException.fatals.couldNotAcquireRequestedTokenMapCaching();
        }
        tokenLock.acquire();
        if (op == Operation.ADD_VDC) {
            addRequestingVDC(tokenId, requestingVDC);
        } else {
            removeRequestingVDC(tokenId, requestingVDC);
        }
    } catch (Exception ex) {
        log.error("Could not acquire lock while trying to update requested token map.", ex);
    } finally {
        try {
            if (tokenLock != null) {
                tokenLock.release();
            }
        } catch (Exception ex) {
            log.error("Unable to release requested token map lock", ex);
        }
    }
}
Also used : InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) RetryableSecurityException(com.emc.storageos.security.exceptions.RetryableSecurityException) SecurityException(com.emc.storageos.security.exceptions.SecurityException)

Example 48 with InterProcessLock

use of org.apache.curator.framework.recipes.locks.InterProcessLock in project coprhd-controller by CoprHD.

the class CoordinatorConfigStoringHelper method createOrUpdateConfig.

/**
 * Creates or updates a new entry of the specified type in coordinator. If siteId
 * is not null, the config is in zk site specific area. Otherwise in global area
 *
 * @param objToPersist
 *            the object to store in coordinator
 * @param lockName
 *            the name of the lock to use while storing this object
 *            If passed as Null, lock is assumed to be already owned
 * @param configKInd
 * @param configId
 * @param ConfigKey
 * @throws Exception
 */
public void createOrUpdateConfig(Object objToPersist, String lockName, String siteId, String configKInd, String configId, String ConfigKey) throws Exception {
    InterProcessLock lock = acquireLock(lockName);
    try {
        if (lock != null) {
            Configuration config = coordinator.queryConfiguration(siteId, configKInd, configId);
            ConfigurationImpl configImpl = null;
            if (config == null) {
                configImpl = new ConfigurationImpl();
                configImpl.setId(configId);
                configImpl.setKind(configKInd);
                log.debug("Creating new config");
            } else {
                configImpl = (ConfigurationImpl) config;
                if (config.getKind() == null) {
                    ((ConfigurationImpl) config).setKind(configKInd);
                }
                if (config.getId() == null) {
                    ((ConfigurationImpl) config).setId(configId);
                }
                log.debug("Updating existing config");
            }
            configImpl.setConfig(ConfigKey, SerializerUtils.serializeAsBase64EncodedString(objToPersist));
            coordinator.persistServiceConfiguration(siteId, configImpl);
            log.debug("Updated config successfully");
        }
    } finally {
        releaseLock(lock);
    }
}
Also used : Configuration(com.emc.storageos.coordinator.common.Configuration) InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) ConfigurationImpl(com.emc.storageos.coordinator.common.impl.ConfigurationImpl)

Example 49 with InterProcessLock

use of org.apache.curator.framework.recipes.locks.InterProcessLock in project coprhd-controller by CoprHD.

the class DistributedKeyStoreImpl method setupKeyCertificatePair.

private KeyCertificateEntry setupKeyCertificatePair() throws IOException, ClassNotFoundException {
    InterProcessLock lock = null;
    try {
        lock = acquireKeyCertificatePairLock();
        // re-read the key/cert pair after lock acquired. avoid the case another concurrent thread may have done that
        KeyCertificateEntry entryToReturn = readKeyCertificateEntry();
        if (entryToReturn == null) {
            log.info("ViPR certificate not found");
            entryToReturn = generator.tryGetV1Cert();
            if (entryToReturn != null) {
                KeyStoreUtil.setSelfGeneratedCertificate(coordConfigStoringHelper, Boolean.FALSE);
                entryToReturn.setCreationDate(new Date());
                setKeyCertificatePair(entryToReturn);
            } else {
                log.info("Generating new certificate");
                entryToReturn = generateNewKeyCertificatePair();
            }
        }
        return entryToReturn;
    } finally {
        coordConfigStoringHelper.releaseLock(lock);
    }
}
Also used : InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) Date(java.util.Date)

Example 50 with InterProcessLock

use of org.apache.curator.framework.recipes.locks.InterProcessLock in project coprhd-controller by CoprHD.

the class VdcManager method auditCompletedDrOperation.

/**
 * Check if ongoing DR operation succeeded or failed, then record audit log accordingly and remove this operation record from ZK.
 */
private void auditCompletedDrOperation() {
    if (!drUtil.isActiveSite()) {
        return;
    }
    InterProcessLock lock = coordinator.getCoordinatorClient().getSiteLocalLock(AUDIT_DR_OPERATION_LOCK);
    boolean hasLock = false;
    try {
        hasLock = lock.acquire(AUDIT_LOCK_WAIT_TIME_SEC, TimeUnit.SECONDS);
        if (!hasLock) {
            return;
        }
        log.info("Local site is active, local node acquired lock, starting audit complete DR operations ...");
        List<Configuration> configs = coordinator.getCoordinatorClient().queryAllConfiguration(DrOperationStatus.CONFIG_KIND);
        if (configs == null || configs.isEmpty()) {
            return;
        }
        for (Configuration config : configs) {
            DrOperationStatus operation = new DrOperationStatus(config);
            String siteId = operation.getSiteUuid();
            InterState interState = operation.getInterState();
            Site site = null;
            try {
                site = drUtil.getSiteFromLocalVdc(siteId);
            } catch (RetryableCoordinatorException e) {
                // Under this situation, just record audit log and clear DR operation status
                if (interState.equals(InterState.REMOVING_STANDBY) && e.getServiceCode() == ServiceCode.COORDINATOR_SITE_NOT_FOUND) {
                    this.auditMgr.recordAuditLog(null, null, EVENT_SERVICE_TYPE, getOperationType(interState), System.currentTimeMillis(), AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_END, siteId);
                    coordinator.getCoordinatorClient().removeServiceConfiguration(config);
                    log.info("DR operation status has been cleared: {}", operation);
                    continue;
                }
                throw e;
            }
            SiteState currentState = site.getState();
            if (currentState.equals(SiteState.STANDBY_ERROR)) {
                // Failed
                this.auditMgr.recordAuditLog(null, null, EVENT_SERVICE_TYPE, getOperationType(interState), System.currentTimeMillis(), AuditLogManager.AUDITLOG_FAILURE, AuditLogManager.AUDITOP_END, site.toBriefString());
            } else if (!currentState.isDROperationOngoing()) {
                // Succeeded
                this.auditMgr.recordAuditLog(null, null, EVENT_SERVICE_TYPE, getOperationType(interState), System.currentTimeMillis(), AuditLogManager.AUDITLOG_SUCCESS, AuditLogManager.AUDITOP_END, site.toBriefString());
            } else {
                // Still ongoing, do nothing
                continue;
            }
            log.info(String.format("Site %s state has transformed from %s to %s", siteId, interState, currentState));
            // clear this operation status
            coordinator.getCoordinatorClient().removeServiceConfiguration(config);
            log.info("DR operation status has been cleared: {}", operation);
        }
    } catch (Exception e) {
        log.error("Auditing DR operation failed with exception", e);
    } finally {
        try {
            if (hasLock) {
                lock.release();
            }
        } catch (Exception e) {
            log.error("Failed to release DR operation audit lock", e);
        }
    }
}
Also used : InterState(com.emc.storageos.coordinator.client.model.DrOperationStatus.InterState) Configuration(com.emc.storageos.coordinator.common.Configuration) RetryableCoordinatorException(com.emc.storageos.coordinator.exceptions.RetryableCoordinatorException) InterProcessLock(org.apache.curator.framework.recipes.locks.InterProcessLock) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) RetryableCoordinatorException(com.emc.storageos.coordinator.exceptions.RetryableCoordinatorException) InvalidLockOwnerException(com.emc.storageos.systemservices.exceptions.InvalidLockOwnerException) CoordinatorClientException(com.emc.storageos.systemservices.exceptions.CoordinatorClientException)

Aggregations

InterProcessLock (org.apache.curator.framework.recipes.locks.InterProcessLock)98 APIException (com.emc.storageos.svcs.errorhandling.resources.APIException)25 DatabaseException (com.emc.storageos.db.exceptions.DatabaseException)21 DeviceControllerException (com.emc.storageos.exceptions.DeviceControllerException)15 IOException (java.io.IOException)15 ControllerException (com.emc.storageos.volumecontroller.ControllerException)14 Configuration (com.emc.storageos.coordinator.common.Configuration)12 CoordinatorException (com.emc.storageos.coordinator.exceptions.CoordinatorException)12 UnknownHostException (java.net.UnknownHostException)12 Site (com.emc.storageos.coordinator.client.model.Site)11 RetryableCoordinatorException (com.emc.storageos.coordinator.exceptions.RetryableCoordinatorException)11 NetworkDeviceControllerException (com.emc.storageos.networkcontroller.exceptions.NetworkDeviceControllerException)10 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)9 ServiceError (com.emc.storageos.svcs.errorhandling.model.ServiceError)9 BiosCommandResult (com.emc.storageos.volumecontroller.impl.BiosCommandResult)9 ArrayList (java.util.ArrayList)9 POST (javax.ws.rs.POST)9 NetworkSystem (com.emc.storageos.db.client.model.NetworkSystem)8 Path (javax.ws.rs.Path)8 ConfigurationImpl (com.emc.storageos.coordinator.common.impl.ConfigurationImpl)6