Search in sources :

Example 41 with TimeDuration

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

the class StatisticsManager method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    for (final EpsStatistic type : EpsStatistic.values()) {
        for (final Statistic.EpsDuration duration : Statistic.EpsDuration.values()) {
            epsMeterMap.put(type.toString() + duration.toString(), new EventRateMeter(duration.getTimeDuration()));
        }
    }
    status = STATUS.OPENING;
    this.localDB = pwmApplication.getLocalDB();
    this.pwmApplication = pwmApplication;
    if (localDB == null) {
        LOGGER.error("LocalDB is not available, will remain closed");
        status = STATUS.CLOSED;
        return;
    }
    {
        final String storedCummulativeBundleStr = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_CUMULATIVE);
        if (storedCummulativeBundleStr != null && storedCummulativeBundleStr.length() > 0) {
            try {
                statsCummulative = StatisticsBundle.input(storedCummulativeBundleStr);
            } catch (Exception e) {
                LOGGER.warn("error loading saved stored statistics: " + e.getMessage());
            }
        }
    }
    {
        for (final EpsStatistic loopEpsType : EpsStatistic.values()) {
            for (final EpsStatistic loopEpsDuration : EpsStatistic.values()) {
                final String key = "EPS-" + loopEpsType.toString() + loopEpsDuration.toString();
                final String storedValue = localDB.get(LocalDB.DB.PWM_STATS, key);
                if (storedValue != null && storedValue.length() > 0) {
                    try {
                        final EventRateMeter eventRateMeter = JsonUtil.deserialize(storedValue, EventRateMeter.class);
                        epsMeterMap.put(loopEpsType.toString() + loopEpsDuration.toString(), eventRateMeter);
                    } catch (Exception e) {
                        LOGGER.error("unexpected error reading last EPS rate for " + loopEpsType + " from LocalDB: " + e.getMessage());
                    }
                }
            }
        }
    }
    {
        final String storedInitialString = localDB.get(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY);
        if (storedInitialString != null && storedInitialString.length() > 0) {
            initialDailyKey = new DailyKey(storedInitialString);
        }
    }
    {
        currentDailyKey = new DailyKey(new Date());
        final String storedDailyStr = localDB.get(LocalDB.DB.PWM_STATS, currentDailyKey.toString());
        if (storedDailyStr != null && storedDailyStr.length() > 0) {
            statsDaily = StatisticsBundle.input(storedDailyStr);
        }
    }
    try {
        localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_TEMP, JavaHelper.toIsoDate(new Date()));
    } catch (IllegalStateException e) {
        LOGGER.error("unable to write to localDB, will remain closed, error: " + e.getMessage());
        status = STATUS.CLOSED;
        return;
    }
    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_VERSION, DB_VALUE_VERSION);
    localDB.put(LocalDB.DB.PWM_STATS, DB_KEY_INITIAL_DAILY_KEY, initialDailyKey.toString());
    {
        // setup a timer to roll over at 0 Zula and one to write current stats every 10 seconds
        executorService = JavaHelper.makeSingleThreadExecutorService(pwmApplication, this.getClass());
        executorService.scheduleAtFixedRate(new FlushTask(), 10 * 1000, DB_WRITE_FREQUENCY.getTotalMilliseconds(), TimeUnit.MILLISECONDS);
        final TimeDuration delayTillNextZulu = TimeDuration.fromCurrent(JavaHelper.nextZuluZeroTime());
        executorService.scheduleAtFixedRate(new NightlyTask(), delayTillNextZulu.getTotalMilliseconds(), TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
    }
    status = STATUS.OPEN;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration) LocalDBException(password.pwm.util.localdb.LocalDBException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) Date(java.util.Date)

Example 42 with TimeDuration

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

the class ReportSettings method readSettingsFromConfig.

public static ReportSettings readSettingsFromConfig(final Configuration config) {
    final ReportSettings settings = new ReportSettings();
    settings.maxCacheAge = new TimeDuration(config.readSettingAsLong(PwmSetting.REPORTING_MAX_CACHE_AGE) * 1000);
    settings.searchFilter = config.readSettingAsString(PwmSetting.REPORTING_SEARCH_FILTER);
    settings.maxSearchSize = (int) config.readSettingAsLong(PwmSetting.REPORTING_MAX_QUERY_SIZE);
    if (settings.searchFilter == null || settings.searchFilter.isEmpty()) {
        settings.searchFilter = null;
    }
    settings.jobOffsetSeconds = (int) config.readSettingAsLong(PwmSetting.REPORTING_JOB_TIME_OFFSET);
    if (settings.jobOffsetSeconds > 60 * 60 * 24) {
        settings.jobOffsetSeconds = 0;
    }
    settings.trackDays = parseDayIntervalStr(config);
    settings.reportJobThreads = Integer.parseInt(config.readAppProperty(AppProperty.REPORTING_LDAP_SEARCH_THREADS));
    settings.reportJobIntensity = config.readSettingAsEnum(PwmSetting.REPORTING_JOB_INTENSITY, JobIntensity.class);
    return settings;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration)

Example 43 with TimeDuration

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

the class CryptoCookieBeanImpl method validateCookie.

private boolean validateCookie(final PwmRequest pwmRequest, final String cookieName, final PwmSessionBean cookieBean) {
    if (cookieBean == null) {
        return false;
    }
    if (cookieBean.getType() == PwmSessionBean.Type.AUTHENTICATED) {
        if (cookieBean.getGuid() == null) {
            LOGGER.trace(pwmRequest, "disregarded existing " + cookieName + " cookie bean due to missing guid");
            return false;
        }
        final String sessionGuid = pwmRequest.getPwmSession().getLoginInfoBean().getGuid();
        if (!cookieBean.getGuid().equals(sessionGuid)) {
            LOGGER.trace(pwmRequest, "disregarded existing " + cookieName + " cookie bean due to session change");
            return false;
        }
    }
    if (cookieBean.getType() == PwmSessionBean.Type.PUBLIC) {
        if (cookieBean.getTimestamp() == null) {
            LOGGER.trace(pwmRequest, "disregarded existing " + cookieName + " cookie bean due to missing timestamp");
            return false;
        }
        final TimeDuration cookieLifeDuration = TimeDuration.fromCurrent(cookieBean.getTimestamp());
        final long maxIdleSeconds = pwmRequest.getConfig().readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
        if (cookieLifeDuration.isLongerThan(maxIdleSeconds, TimeUnit.SECONDS)) {
            LOGGER.trace(pwmRequest, "disregarded existing " + cookieName + " cookie bean due to outdated timestamp (" + cookieLifeDuration.asCompactString() + ")");
            return false;
        }
    }
    return true;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration)

Example 44 with TimeDuration

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

the class UserSearchEngine method executeSearch.

private Map<UserIdentity, Map<String, String>> executeSearch(final UserSearchJob userSearchJob, final SessionLabel sessionLabel, final int searchID, final int jobID) throws PwmOperationalException, PwmUnrecoverableException {
    debugOutputTask.conditionallyExecuteTask();
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setMaxResults(userSearchJob.getMaxResults());
    searchHelper.setFilter(userSearchJob.getSearchFilter());
    searchHelper.setAttributes(userSearchJob.getReturnAttributes());
    searchHelper.setTimeLimit((int) userSearchJob.getTimeoutMs());
    final String debugInfo;
    {
        final Map<String, String> props = new LinkedHashMap<>();
        props.put("profile", userSearchJob.getLdapProfile().getIdentifier());
        props.put("base", userSearchJob.getContext());
        props.put("maxCount", String.valueOf(searchHelper.getMaxResults()));
        debugInfo = "[" + StringUtil.mapToString(props) + "]";
    }
    log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "performing ldap search for user; " + debugInfo);
    final Instant startTime = Instant.now();
    final Map<String, Map<String, String>> results;
    try {
        results = userSearchJob.getChaiProvider().search(userSearchJob.getContext(), searchHelper);
    } catch (ChaiUnavailableException e) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_DIRECTORY_UNAVAILABLE, e.getMessage()));
    } catch (ChaiOperationException e) {
        throw new PwmOperationalException(PwmError.forChaiError(e.getErrorCode()), "ldap error during searchID=" + searchID + ", error=" + e.getMessage());
    }
    final TimeDuration searchDuration = TimeDuration.fromCurrent(startTime);
    if (pwmApplication.getStatisticsManager() != null && pwmApplication.getStatisticsManager().status() == PwmService.STATUS.OPEN) {
        pwmApplication.getStatisticsManager().updateAverageValue(Statistic.AVG_LDAP_SEARCH_TIME, searchDuration.getTotalMilliseconds());
    }
    if (results.isEmpty()) {
        log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "no matches from search (" + searchDuration.asCompactString() + "); " + debugInfo);
        return Collections.emptyMap();
    }
    log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "found " + results.size() + " results in " + searchDuration.asCompactString() + "; " + debugInfo);
    final Map<UserIdentity, Map<String, String>> returnMap = new LinkedHashMap<>();
    for (final Map.Entry<String, Map<String, String>> entry : results.entrySet()) {
        final String userDN = entry.getKey();
        final Map<String, String> attributeMap = entry.getValue();
        final UserIdentity userIdentity = new UserIdentity(userDN, userSearchJob.getLdapProfile().getIdentifier());
        returnMap.put(userIdentity, attributeMap);
    }
    return returnMap;
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) PwmOperationalException(password.pwm.error.PwmOperationalException) LinkedHashMap(java.util.LinkedHashMap) ErrorInformation(password.pwm.error.ErrorInformation) TimeDuration(password.pwm.util.java.TimeDuration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 45 with TimeDuration

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

the class AuditService method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    this.status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;
    settings = new AuditSettings(pwmApplication.getConfig());
    if (pwmApplication.getApplicationMode() == null || pwmApplication.getApplicationMode() == PwmApplicationMode.READ_ONLY) {
        this.status = STATUS.CLOSED;
        LOGGER.warn("unable to start - Application is in read-only mode");
        return;
    }
    if (pwmApplication.getLocalDB() == null || pwmApplication.getLocalDB().status() != LocalDB.Status.OPEN) {
        this.status = STATUS.CLOSED;
        LOGGER.warn("unable to start - LocalDB is not available");
        return;
    }
    final List<String> syslogConfigString = pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.AUDIT_SYSLOG_SERVERS);
    if (syslogConfigString != null && !syslogConfigString.isEmpty()) {
        try {
            syslogManager = new SyslogAuditService(pwmApplication);
        } catch (Exception e) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SYSLOG_WRITE_ERROR, "startup error: " + e.getMessage());
            LOGGER.error(errorInformation.toDebugStr());
        }
    }
    {
        final UserEventStorageMethod userEventStorageMethod = pwmApplication.getConfig().readSettingAsEnum(PwmSetting.EVENTS_USER_STORAGE_METHOD, UserEventStorageMethod.class);
        final String debugMsg;
        final DataStorageMethod storageMethodUsed;
        switch(userEventStorageMethod) {
            case AUTO:
                if (pwmApplication.getConfig().hasDbConfigured()) {
                    debugMsg = "starting using auto-configured data store, Remote Database selected";
                    this.userHistoryStore = new DatabaseUserHistory(pwmApplication);
                    storageMethodUsed = DataStorageMethod.DB;
                } else {
                    debugMsg = "starting using auto-configured data store, LDAP selected";
                    this.userHistoryStore = new LdapXmlUserHistory(pwmApplication);
                    storageMethodUsed = DataStorageMethod.LDAP;
                }
                break;
            case DATABASE:
                this.userHistoryStore = new DatabaseUserHistory(pwmApplication);
                debugMsg = "starting using Remote Database data store";
                storageMethodUsed = DataStorageMethod.DB;
                break;
            case LDAP:
                this.userHistoryStore = new LdapXmlUserHistory(pwmApplication);
                debugMsg = "starting using LocalDB data store";
                storageMethodUsed = DataStorageMethod.LDAP;
                break;
            default:
                lastError = new ErrorInformation(PwmError.ERROR_UNKNOWN, "unknown storageMethod selected: " + userEventStorageMethod);
                status = STATUS.CLOSED;
                return;
        }
        LOGGER.info(debugMsg);
        serviceInfo = new ServiceInfoBean(Collections.singletonList(storageMethodUsed));
    }
    {
        final TimeDuration maxRecordAge = new TimeDuration(pwmApplication.getConfig().readSettingAsLong(PwmSetting.EVENTS_AUDIT_MAX_AGE) * 1000);
        final long maxRecords = pwmApplication.getConfig().readSettingAsLong(PwmSetting.EVENTS_AUDIT_MAX_EVENTS);
        final AuditVault.Settings settings = new AuditVault.Settings(maxRecords, maxRecordAge);
        if (pwmApplication.getLocalDB() != null && pwmApplication.getApplicationMode() != PwmApplicationMode.READ_ONLY) {
            if (maxRecords < 1) {
                LOGGER.debug("localDB audit vault will remain closed due to max records setting");
                pwmApplication.getLocalDB().truncate(LocalDB.DB.AUDIT_EVENTS);
            } else {
                auditVault = new LocalDbAuditVault();
                auditVault.init(pwmApplication, pwmApplication.getLocalDB(), settings);
            }
        } else {
            LOGGER.debug("localDB audit vault will remain closed due to application mode");
        }
    }
    this.status = STATUS.OPEN;
}
Also used : UserEventStorageMethod(password.pwm.config.option.UserEventStorageMethod) DataStorageMethod(password.pwm.config.option.DataStorageMethod) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) ErrorInformation(password.pwm.error.ErrorInformation) TimeDuration(password.pwm.util.java.TimeDuration)

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