Search in sources :

Example 6 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class HealthMonitor method doHealthChecks.

private void doHealthChecks() {
    if (status != STATUS.OPEN) {
        return;
    }
    final TimeDuration timeSinceLastUpdate = TimeDuration.fromCurrent(lastHealthCheckTime);
    if (timeSinceLastUpdate.isShorterThan(settings.getMinimumCheckInterval().getTotalMilliseconds(), TimeUnit.MILLISECONDS)) {
        return;
    }
    final Instant startTime = Instant.now();
    LOGGER.trace("beginning background health check process");
    final List<HealthRecord> tempResults = new ArrayList<>();
    for (final HealthChecker loopChecker : HEALTH_CHECKERS) {
        try {
            final List<HealthRecord> loopResults = loopChecker.doHealthCheck(pwmApplication);
            if (loopResults != null) {
                tempResults.addAll(loopResults);
            }
        } catch (Exception e) {
            if (status == STATUS.OPEN) {
                LOGGER.warn("unexpected error during healthCheck: " + e.getMessage(), e);
            }
        }
    }
    for (final PwmService service : pwmApplication.getPwmServices()) {
        try {
            final List<HealthRecord> loopResults = service.healthCheck();
            if (loopResults != null) {
                tempResults.addAll(loopResults);
            }
        } catch (Exception e) {
            if (status == STATUS.OPEN) {
                LOGGER.warn("unexpected error during healthCheck: " + e.getMessage(), e);
            }
        }
    }
    healthRecords.clear();
    healthRecords.addAll(tempResults);
    lastHealthCheckTime = Instant.now();
    LOGGER.trace("health check process completed (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
}
Also used : PwmService(password.pwm.svc.PwmService) Instant(java.time.Instant) ArrayList(java.util.ArrayList) TimeDuration(password.pwm.util.java.TimeDuration) PwmException(password.pwm.error.PwmException)

Example 7 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class LdapOperationsHelper method readLdapGuidValue.

public static String readLdapGuidValue(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final UserIdentity userIdentity, final boolean throwExceptionOnError) throws ChaiUnavailableException, PwmUnrecoverableException {
    final boolean enableCache = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_USER_GUID_ENABLE));
    final CacheKey cacheKey = CacheKey.makeCacheKey(LdapOperationsHelper.class, null, "guidValue-" + userIdentity.toDelimitedKey());
    if (enableCache) {
        final String cachedValue = pwmApplication.getCacheService().get(cacheKey);
        if (cachedValue != null) {
            return NULL_CACHE_GUID.equals(cachedValue) ? null : cachedValue;
        }
    }
    final String existingValue = GUIDHelper.readExistingGuidValue(pwmApplication, sessionLabel, userIdentity, throwExceptionOnError);
    final LdapProfile ldapProfile = pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID());
    final String guidAttributeName = ldapProfile.readSettingAsString(PwmSetting.LDAP_GUID_ATTRIBUTE);
    if (StringUtil.isEmpty(existingValue)) {
        if (!"DN".equalsIgnoreCase(guidAttributeName) && !"VENDORGUID".equalsIgnoreCase(guidAttributeName)) {
            if (ldapProfile.readSettingAsBoolean(PwmSetting.LDAP_GUID_AUTO_ADD)) {
                LOGGER.trace("assigning new GUID to user " + userIdentity);
                return GUIDHelper.assignGuidToUser(pwmApplication, sessionLabel, userIdentity, guidAttributeName);
            }
        }
        final String errorMsg = "unable to resolve GUID value for user " + userIdentity.toString();
        GUIDHelper.processError(errorMsg, throwExceptionOnError);
    }
    if (enableCache) {
        final long cacheSeconds = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_USER_GUID_SECONDS));
        final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpiration(new TimeDuration(cacheSeconds, TimeUnit.SECONDS));
        final String cacheValue = existingValue == null ? NULL_CACHE_GUID : existingValue;
        pwmApplication.getCacheService().put(cacheKey, cachePolicy, cacheValue);
    }
    return existingValue;
}
Also used : CachePolicy(password.pwm.svc.cache.CachePolicy) TimeDuration(password.pwm.util.java.TimeDuration) LdapProfile(password.pwm.config.profile.LdapProfile) CacheKey(password.pwm.svc.cache.CacheKey)

Example 8 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PasswordChangeProgressChecker method figureReplicationStatusCompletion.

private ProgressRecord figureReplicationStatusCompletion(final ProgressTracker tracker) {
    final long initDelayMs = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_PASSWORD_REPLICA_CHECK_INIT_DELAY_MS));
    final long cycleDelayMs = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_PASSWORD_REPLICA_CHECK_CYCLE_DELAY_MS));
    final TimeDuration initialReplicaDelay = new TimeDuration(initDelayMs);
    final TimeDuration cycleReplicaDelay = new TimeDuration(cycleDelayMs);
    if (passwordSyncCheckMode == PasswordSyncCheckMode.DISABLED) {
        LOGGER.trace(pwmSession, "skipping replica sync check, disabled");
        return tracker.itemCompletions.get(PROGRESS_KEY_REPLICATION);
    }
    if (tracker.itemCompletions.containsKey(PROGRESS_KEY_REPLICATION)) {
        if (tracker.itemCompletions.get(PROGRESS_KEY_REPLICATION).complete) {
            LOGGER.trace(pwmSession, "skipping replica sync check, replica sync completed previously");
            return tracker.itemCompletions.get(PROGRESS_KEY_REPLICATION);
        }
    }
    if (tracker.lastReplicaCheckTime == null) {
        if (TimeDuration.fromCurrent(tracker.beginTime).isShorterThan(initialReplicaDelay)) {
            LOGGER.trace(pwmSession, "skipping replica sync check, initDelay has not yet passed");
            return null;
        }
    } else if (TimeDuration.fromCurrent(tracker.lastReplicaCheckTime).isShorterThan(cycleReplicaDelay)) {
        LOGGER.trace(pwmSession, "skipping replica sync check, cycleDelay has not yet passed");
        return null;
    }
    tracker.lastReplicaCheckTime = Instant.now();
    LOGGER.trace(pwmSession, "beginning password replication time check for " + userIdentity.toDelimitedKey());
    try {
        final Map<String, Instant> checkResults = PasswordUtility.readIndividualReplicaLastPasswordTimes(pwmApplication, pwmSession, userIdentity);
        if (checkResults.size() <= 1) {
            LOGGER.trace("only one replica returned data, marking as complete");
            return completedReplicationRecord;
        } else {
            final HashSet<Instant> tempHashSet = new HashSet<>();
            int duplicateValues = 0;
            for (final Instant date : checkResults.values()) {
                if (tempHashSet.contains(date)) {
                    duplicateValues++;
                } else {
                    tempHashSet.add(date);
                }
            }
            final Percent pctComplete = new Percent(duplicateValues + 1, checkResults.size());
            final ProgressRecord progressRecord = makeReplicaProgressRecord(pctComplete);
            LOGGER.trace("read password replication sync status as: " + JsonUtil.serialize(progressRecord));
            return progressRecord;
        }
    } catch (PwmUnrecoverableException e) {
        LOGGER.error(pwmSession, "error during password replication status check: " + e.getMessage());
    }
    return null;
}
Also used : Percent(password.pwm.util.java.Percent) Instant(java.time.Instant) TimeDuration(password.pwm.util.java.TimeDuration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) HashSet(java.util.HashSet)

Example 9 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PasswordChangeProgressChecker method figureProgress.

public PasswordChangeProgress figureProgress(final ProgressTracker tracker) {
    if (tracker == null) {
        throw new IllegalArgumentException("tracker cannot be null");
    }
    final Map<String, ProgressRecord> newItemProgress = new LinkedHashMap<>();
    newItemProgress.putAll(tracker.itemCompletions);
    if (tracker.beginTime == null || Instant.now().isAfter(maxCompletionTime(tracker))) {
        return PasswordChangeProgress.COMPLETE;
    }
    newItemProgress.putAll(figureItemProgresses(tracker));
    final Instant estimatedCompletion = figureEstimatedCompletion(tracker, newItemProgress.values());
    final long elapsedMs = TimeDuration.fromCurrent(tracker.beginTime).getTotalMilliseconds();
    final long remainingMs = TimeDuration.fromCurrent(estimatedCompletion).getTotalMilliseconds();
    final Percent percentage;
    if (Instant.now().isAfter(estimatedCompletion)) {
        percentage = Percent.ONE_HUNDRED;
    } else {
        final long totalMs = new TimeDuration(tracker.beginTime, estimatedCompletion).getTotalMilliseconds();
        percentage = new Percent(elapsedMs, totalMs + 1);
    }
    tracker.itemCompletions.putAll(newItemProgress);
    return new PasswordChangeProgress(percentage.isComplete(), percentage.asBigDecimal(2), newItemProgress.values(), new TimeDuration(elapsedMs).asLongString(locale), new TimeDuration(remainingMs).asLongString(locale));
}
Also used : Percent(password.pwm.util.java.Percent) Instant(java.time.Instant) TimeDuration(password.pwm.util.java.TimeDuration) LinkedHashMap(java.util.LinkedHashMap)

Example 10 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PwmServiceManager method initService.

private PwmService initService(final Class<? extends PwmService> serviceClass) throws PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    final PwmService newServiceInstance;
    final String serviceName = serviceClass.getName();
    try {
        final Object newInstance = serviceClass.newInstance();
        newServiceInstance = (PwmService) newInstance;
    } catch (Exception e) {
        final String errorMsg = "unexpected error instantiating service class '" + serviceName + "', error: " + e.toString();
        LOGGER.fatal(errorMsg, e);
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
    }
    try {
        LOGGER.debug("initializing service " + serviceName);
        newServiceInstance.init(pwmApplication);
        final TimeDuration startupDuration = TimeDuration.fromCurrent(startTime);
        LOGGER.debug("completed initialization of service " + serviceName + " in " + startupDuration.asCompactString() + ", status=" + newServiceInstance.status());
    } catch (PwmException e) {
        LOGGER.warn("error instantiating service class '" + serviceName + "', service will remain unavailable, error: " + e.getMessage());
    } catch (Exception e) {
        String errorMsg = "unexpected error instantiating service class '" + serviceName + "', cannot load, error: " + e.getMessage();
        if (e.getCause() != null) {
            errorMsg += ", cause: " + e.getCause();
        }
        LOGGER.fatal(errorMsg);
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
    }
    return newServiceInstance;
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) Instant(java.time.Instant) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) TimeDuration(password.pwm.util.java.TimeDuration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException)

Aggregations

TimeDuration (password.pwm.util.java.TimeDuration)75 Instant (java.time.Instant)28 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)19 PwmException (password.pwm.error.PwmException)14 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 IOException (java.io.IOException)9 Configuration (password.pwm.config.Configuration)8 PwmOperationalException (password.pwm.error.PwmOperationalException)8 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)7 Map (java.util.Map)7 UserIdentity (password.pwm.bean.UserIdentity)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)6 MacroMachine (password.pwm.util.macro.MacroMachine)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Locale (java.util.Locale)5