|
| 1 | +# Copyright (c) Odoo SA 2017 |
| 2 | +# @author Nicolas Seinlet |
| 3 | +# Copyright (c) ACSONE SA 2022 |
| 4 | +# @author Stéphane Bidoul |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import os |
| 8 | + |
| 9 | +import psycopg2 |
| 10 | + |
| 11 | +import odoo |
| 12 | +from odoo import http |
| 13 | +from odoo.tools._vendor import sessions |
| 14 | +from odoo.tools.func import lazy_property |
| 15 | + |
| 16 | +_logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +lock = None |
| 19 | +if odoo.evented: |
| 20 | + import gevent.lock |
| 21 | + |
| 22 | + lock = gevent.lock.RLock() |
| 23 | +elif odoo.tools.config["workers"] == 0: |
| 24 | + import threading |
| 25 | + |
| 26 | + lock = threading.RLock() |
| 27 | + |
| 28 | + |
| 29 | +def with_lock(func): |
| 30 | + def wrapper(*args, **kwargs): |
| 31 | + try: |
| 32 | + if lock is not None: |
| 33 | + lock.acquire() |
| 34 | + return func(*args, **kwargs) |
| 35 | + finally: |
| 36 | + if lock is not None: |
| 37 | + lock.release() |
| 38 | + |
| 39 | + return wrapper |
| 40 | + |
| 41 | + |
| 42 | +def with_cursor(func): |
| 43 | + def wrapper(self, *args, **kwargs): |
| 44 | + tries = 0 |
| 45 | + while True: |
| 46 | + tries += 1 |
| 47 | + try: |
| 48 | + self._ensure_connection() |
| 49 | + return func(self, *args, **kwargs) |
| 50 | + except (psycopg2.InterfaceError, psycopg2.OperationalError): |
| 51 | + self._close_connection() |
| 52 | + if tries > 4: |
| 53 | + _logger.warning( |
| 54 | + "session_db operation try %s/5 failed, aborting", tries |
| 55 | + ) |
| 56 | + raise |
| 57 | + _logger.info("session_db operation try %s/5 failed, retrying", tries) |
| 58 | + |
| 59 | + return wrapper |
| 60 | + |
| 61 | + |
| 62 | +class PGSessionStore(sessions.SessionStore): |
| 63 | + def __init__(self, uri, session_class=None): |
| 64 | + super().__init__(session_class) |
| 65 | + self._uri = uri |
| 66 | + self._cr = None |
| 67 | + self._open_connection() |
| 68 | + self._setup_db() |
| 69 | + |
| 70 | + def __del__(self): |
| 71 | + self._close_connection() |
| 72 | + |
| 73 | + @with_lock |
| 74 | + def _ensure_connection(self): |
| 75 | + if self._cr is None: |
| 76 | + self._open_connection() |
| 77 | + |
| 78 | + @with_lock |
| 79 | + def _open_connection(self): |
| 80 | + self._close_connection() |
| 81 | + cnx = odoo.sql_db.db_connect(self._uri, allow_uri=True) |
| 82 | + self._cr = cnx.cursor() |
| 83 | + self._cr._cnx.autocommit = True |
| 84 | + |
| 85 | + @with_lock |
| 86 | + def _close_connection(self): |
| 87 | + """Return cursor to the pool.""" |
| 88 | + if self._cr is not None: |
| 89 | + try: |
| 90 | + self._cr.close() |
| 91 | + except Exception: # pylint: disable=except-pass |
| 92 | + pass |
| 93 | + self._cr = None |
| 94 | + |
| 95 | + @with_lock |
| 96 | + @with_cursor |
| 97 | + def _setup_db(self): |
| 98 | + self._cr.execute( |
| 99 | + """ |
| 100 | + CREATE TABLE IF NOT EXISTS http_sessions ( |
| 101 | + sid varchar PRIMARY KEY, |
| 102 | + write_date timestamp without time zone NOT NULL, |
| 103 | + payload text NOT NULL |
| 104 | + ) |
| 105 | + """ |
| 106 | + ) |
| 107 | + |
| 108 | + @with_lock |
| 109 | + @with_cursor |
| 110 | + def save(self, session): |
| 111 | + payload = json.dumps(dict(session)) |
| 112 | + self._cr.execute( |
| 113 | + """ |
| 114 | + INSERT INTO http_sessions(sid, write_date, payload) |
| 115 | + VALUES (%(sid)s, now() at time zone 'UTC', %(payload)s) |
| 116 | + ON CONFLICT (sid) |
| 117 | + DO UPDATE SET payload = %(payload)s, |
| 118 | + write_date = now() at time zone 'UTC' |
| 119 | + """, |
| 120 | + dict(sid=session.sid, payload=payload), |
| 121 | + ) |
| 122 | + |
| 123 | + @with_lock |
| 124 | + @with_cursor |
| 125 | + def delete(self, session): |
| 126 | + self._cr.execute("DELETE FROM http_sessions WHERE sid=%s", (session.sid,)) |
| 127 | + |
| 128 | + @with_lock |
| 129 | + @with_cursor |
| 130 | + def get(self, sid): |
| 131 | + self._cr.execute("SELECT payload FROM http_sessions WHERE sid=%s", (sid,)) |
| 132 | + try: |
| 133 | + data = json.loads(self._cr.fetchone()[0]) |
| 134 | + except Exception: |
| 135 | + return self.new() |
| 136 | + |
| 137 | + return self.session_class(data, sid, False) |
| 138 | + |
| 139 | + # This method is not part of the Session interface but is called nevertheless, |
| 140 | + # so let's get it from FilesystemSessionStore. |
| 141 | + rotate = http.FilesystemSessionStore.rotate |
| 142 | + |
| 143 | + @with_lock |
| 144 | + @with_cursor |
| 145 | + def vacuum(self, max_lifetime=http.SESSION_LIFETIME): |
| 146 | + self._cr.execute( |
| 147 | + "DELETE FROM http_sessions " |
| 148 | + "WHERE now() at time zone 'UTC' - write_date > %s", |
| 149 | + (f"{max_lifetime} seconds",), |
| 150 | + ) |
| 151 | + |
| 152 | + |
| 153 | +_original_session_store = http.root.__class__.session_store |
| 154 | + |
| 155 | + |
| 156 | +@lazy_property |
| 157 | +def session_store(self): |
| 158 | + session_db_uri = os.environ.get("SESSION_DB_URI") |
| 159 | + if session_db_uri: |
| 160 | + _logger.debug("HTTP sessions stored in: db") |
| 161 | + return PGSessionStore(session_db_uri, session_class=http.Session) |
| 162 | + return _original_session_store.__get__(self, self.__class__) |
| 163 | + |
| 164 | + |
| 165 | +# Monkey patch of standard methods |
| 166 | +_logger.debug("Monkey patching session store") |
| 167 | +http.root.__class__.session_store = session_store |
| 168 | +# Reset the lazy property cache |
| 169 | +vars(http.root).pop("session_store", None) |
0 commit comments