From 39e71ff334fb562a977fca23803b4ab292942b78 Mon Sep 17 00:00:00 2001 From: Guewen Baconnier Date: Wed, 3 Jan 2018 14:25:20 +0100 Subject: [PATCH] Expire sessions generated by health checks quickly The default expiration of sessions is 7 days. With healthchecks run every few seconds, we quickly have millions of anonymous sessions in Redis. Allow to define a custom expiration for some sessions and set a very short one for the monitoring requests. --- monitoring_status/controllers/main.py | 9 +++++++++ session_redis/session.py | 7 +++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/monitoring_status/controllers/main.py b/monitoring_status/controllers/main.py index f54bbb7..d575103 100644 --- a/monitoring_status/controllers/main.py +++ b/monitoring_status/controllers/main.py @@ -19,4 +19,13 @@ class Monitoring(http.Controller): # queue job, cron, database, ... headers = {'Content-Type': 'application/json'} info = {'status': 1} + session = http.request.session + # We set a custom expiration of 1 second for this request, as we do a + # lot of health checks, we don't want those anonymous sessions to be + # kept. Beware, it works only when session_redis is used. + # Alternatively, we could set 'session.should_save = False', which is + # tested in odoo source code, but we wouldn't check the health of + # Redis. + if not session.uid: + session.expiration = 1 return werkzeug.wrappers.Response(json.dumps(info), headers=headers) diff --git a/session_redis/session.py b/session_redis/session.py index a82e996..01ff69a 100644 --- a/session_redis/session.py +++ b/session_redis/session.py @@ -37,6 +37,9 @@ class RedisSessionStore(SessionStore): def save(self, session): key = self.build_key(session.sid) + # allow to set a custom expiration for a session + # such as a very short one for monitoring requests + expiration = session.expiration or self.expiration if _logger.isEnabledFor(logging.DEBUG): if session.uid: user_msg = "user '%s' (id: %s)" % ( @@ -45,11 +48,11 @@ class RedisSessionStore(SessionStore): user_msg = "anonymous user" _logger.debug("saving session with key '%s' and " "expiration of %s seconds for %s", - key, self.expiration, user_msg) + key, expiration, user_msg) data = json.dumps(dict(session)).encode('utf-8') if self.redis.set(key, data): - return self.redis.expire(key, self.expiration) + return self.redis.expire(key, expiration) def delete(self, session): key = self.build_key(session.sid)