import threading import random import time import datetime from daemonJwtHandler import config from daemonJwtHandler.loggly import get_current_logger as logger from daemonJwtHandler.logic import jwt_services from daemonJwtHandler.constants import auth from daemonJwtHandler.logic import jwt_expiry class ThreadingAsynch(object): def __init__(self, appname): """Create asynch threads to refresh data in cache at intervals.""" self.appname = appname jwt_token_refresh_thread = threading.Thread( target=self.run_jwt_token_refresh) jwt_token_refresh_thread.daemon = True jwt_token_refresh_thread.start() thread_jwt_services = threading.Thread( target=self.run_jwt_services_refresh) thread_jwt_services.daemon = True thread_jwt_services.start() def run_jwt_token_refresh(self): while True: jwtInstance = jwt_services.JwtServices.getInstance() if (not jwtInstance.isCached('jwt_token') or jwtInstance.getCache('jwt_token') is None) \ or jwtInstance.getCache('jwt_expiration_time') - \ datetime.datetime.utcnow() <= datetime.timedelta( seconds=auth.TOKEN_EXPIRATION_CHECK): jwtInstance.cacheJwtToken() data = jwtInstance.getCache(auth.JWT_SECRET_KEY) log = jwtInstance.logger() log.info( f'For Daemon, JwtToken: ' f'Refresh cache in {self.appname} service ' f'in {config.ENVIRONMENT}') time.sleep(random.randint(300, 900)) def run_jwt_services_refresh(self): while True: jwtInstance = jwt_services.JwtServices.getInstance() jwtInstance.cacheEnableList() data = jwtInstance.getCache(auth.JWT_ENABLED_SERVICES_SECRET_KEY) log = jwtInstance.logger() log.info( f'For Daemon, JwtEnabledServices: ' f'Refresh cache in {self.appname} service after every ' f'{auth.JWT_ENABLED_SERVICES_REFRESH_INTERVAL}' f' seconds of interval in {config.ENVIRONMENT} {data}') time.sleep(auth.JWT_ENABLED_SERVICES_REFRESH_INTERVAL)