3 * Copyright (C) 2009-2020 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 package org.sonar.server.authentication.purge;
23 import java.util.concurrent.TimeUnit;
24 import org.sonar.api.Startable;
25 import org.sonar.api.config.Configuration;
26 import org.sonar.api.utils.log.Logger;
27 import org.sonar.api.utils.log.Loggers;
28 import org.sonar.db.DbClient;
29 import org.sonar.db.DbSession;
30 import org.sonar.server.util.GlobalLockManager;
32 public class SessionTokensCleaner implements Startable {
34 private static final Logger LOG = Loggers.get(SessionTokensCleaner.class);
36 private static final String PURGE_DELAY_CONFIGURATION = "sonar.authentication.session.tokens.purge.delay";
37 private static final long DEFAULT_PURGE_DELAY_IN_SECONDS = 24 * 60 * 60L;
38 private static final String LOCK_NAME = "SessionCleaner";
40 private final SessionTokensCleanerExecutorService executorService;
41 private final DbClient dbClient;
42 private final Configuration configuration;
43 private final GlobalLockManager lockManager;
45 public SessionTokensCleaner(SessionTokensCleanerExecutorService executorService, DbClient dbClient, Configuration configuration, GlobalLockManager lockManager) {
46 this.executorService = executorService;
47 this.dbClient = dbClient;
48 this.configuration = configuration;
49 this.lockManager = lockManager;
54 this.executorService.scheduleAtFixedRate(this::executePurge, 0, configuration.getLong(PURGE_DELAY_CONFIGURATION).orElse(DEFAULT_PURGE_DELAY_IN_SECONDS), TimeUnit.SECONDS);
57 private void executePurge() {
58 if (!lockManager.tryLock(LOCK_NAME)) {
61 LOG.debug("Start of cleaning expired session tokens");
62 try (DbSession dbSession = dbClient.openSession(false)) {
63 int deletedSessionTokens = dbClient.sessionTokensDao().deleteExpired(dbSession);
65 LOG.info("Purge of expired session tokens has removed {} elements", deletedSessionTokens);