forked from OCA/server-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_session_store.py
187 lines (155 loc) · 5.07 KB
/
pg_session_store.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# Copyright (c) Odoo SA 2017
# @author Nicolas Seinlet
# Copyright (c) ACSONE SA 2022
# @author Stéphane Bidoul
import json
import logging
import os
import random
import time
import psycopg2
import werkzeug.contrib.sessions
import odoo
from odoo import http
from odoo.tools.func import lazy_property
_logger = logging.getLogger(__name__)
lock = None
if odoo.evented:
import gevent.lock
lock = gevent.lock.RLock()
elif odoo.tools.config["workers"] == 0:
import threading
lock = threading.RLock()
def with_lock(func):
def wrapper(*args, **kwargs):
try:
if lock is not None:
lock.acquire()
return func(*args, **kwargs)
finally:
if lock is not None:
lock.release()
return wrapper
def with_cursor(func):
def wrapper(self, *args, **kwargs):
tries = 0
while True:
tries += 1
try:
self._ensure_connection()
return func(self, *args, **kwargs)
except (psycopg2.InterfaceError, psycopg2.OperationalError):
self._close_connection()
if tries > 4:
_logger.warning(
"session_db operation try %s/5 failed, aborting", tries
)
raise
_logger.info("session_db operation try %s/5 failed, retrying", tries)
return wrapper
class PGSessionStore(werkzeug.contrib.sessions.SessionStore):
def __init__(self, uri, session_class=None):
super().__init__(session_class)
self._uri = uri
self._cr = None
self._open_connection()
self._setup_db()
def __del__(self):
self._close_connection()
@with_lock
def _ensure_connection(self):
if self._cr is None:
self._open_connection()
@with_lock
def _open_connection(self):
self._close_connection()
cnx = odoo.sql_db.db_connect(self._uri, allow_uri=True)
self._cr = cnx.cursor()
self._cr.autocommit(True)
@with_lock
def _close_connection(self):
"""Return cursor to the pool."""
if self._cr is not None:
try:
self._cr.close()
except Exception: # pylint: disable=except-pass
pass
self._cr = None
@with_lock
@with_cursor
def _setup_db(self):
self._cr.execute(
"""
CREATE TABLE IF NOT EXISTS http_sessions (
sid varchar PRIMARY KEY,
write_date timestamp without time zone NOT NULL,
payload text NOT NULL
)
"""
)
@with_lock
@with_cursor
def save(self, session):
payload = json.dumps(dict(session))
self._cr.execute(
"""
INSERT INTO http_sessions(sid, write_date, payload)
VALUES (%(sid)s, now() at time zone 'UTC', %(payload)s)
ON CONFLICT (sid)
DO UPDATE SET payload = %(payload)s,
write_date = now() at time zone 'UTC'
""",
dict(sid=session.sid, payload=payload),
)
@with_lock
@with_cursor
def delete(self, session):
self._cr.execute("DELETE FROM http_sessions WHERE sid=%s", (session.sid,))
@with_lock
@with_cursor
def get(self, sid):
self._cr.execute("SELECT payload FROM http_sessions WHERE sid=%s", (sid,))
try:
data = json.loads(self._cr.fetchone()[0])
except Exception:
return self.new()
return self.session_class(data, sid, False)
@with_lock
@with_cursor
def gc(self):
self._cr.execute(
"DELETE FROM http_sessions "
"WHERE now() at time zone 'UTC' - write_date > '7 days'"
)
def session_gc(session_store):
"""
Global cleaning of sessions using either the standard way (delete session files),
Or the DB way.
"""
if random.random() < 0.001:
# we keep session one week
if hasattr(session_store, "gc"):
session_store.gc()
return
last_week = time.time() - 60 * 60 * 24 * 7
for fname in os.listdir(session_store.path):
path = os.path.join(session_store.path, fname)
try:
if os.path.getmtime(path) < last_week:
os.unlink(path)
except OSError: # pylint: disable=except-pass
pass
_original_session_store = http.root.__class__.session_store
@lazy_property
def session_store(self):
session_db_uri = os.environ.get("SESSION_DB_URI")
if session_db_uri:
_logger.debug("HTTP sessions stored in: db")
return PGSessionStore(session_db_uri, session_class=http.OpenERPSession)
return _original_session_store.__get__(self, self.__class__)
# Monkey patch of standard methods
_logger.debug("Monkey patching session store")
http.session_gc = session_gc
http.root.__class__.session_store = session_store
# Reset the lazy property cache
vars(http.root).pop("session_store", None)