|
| 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 | + |
| 19 | +def with_cursor(func): |
| 20 | + def wrapper(self, *args, **kwargs): |
| 21 | + tries = 0 |
| 22 | + while True: |
| 23 | + tries += 1 |
| 24 | + try: |
| 25 | + return func(self, *args, **kwargs) |
| 26 | + except psycopg2.InterfaceError as e: |
| 27 | + _logger.info("Session in DB connection Retry %s/5" % tries) |
| 28 | + if tries > 4: |
| 29 | + raise e |
| 30 | + self._open_connection() |
| 31 | + |
| 32 | + return wrapper |
| 33 | + |
| 34 | + |
| 35 | +class PGSessionStore(sessions.SessionStore): |
| 36 | + def __init__(self, uri, session_class=None): |
| 37 | + super().__init__(session_class) |
| 38 | + self._uri = uri |
| 39 | + self._cr = None |
| 40 | + # FIXME This class is NOT thread-safe. Only use in worker mode |
| 41 | + if odoo.tools.config["workers"] == 0: |
| 42 | + raise ValueError("session_db requires multiple workers") |
| 43 | + self._open_connection() |
| 44 | + self._setup_db() |
| 45 | + |
| 46 | + def __del__(self): |
| 47 | + if self._cr is not None: |
| 48 | + self._cr.close() |
| 49 | + |
| 50 | + def _open_connection(self): |
| 51 | + cnx = odoo.sql_db.db_connect(self._uri, allow_uri=True) |
| 52 | + self._cr = cnx.cursor() |
| 53 | + self._cr._cnx.autocommit = True |
| 54 | + |
| 55 | + @with_cursor |
| 56 | + def _setup_db(self): |
| 57 | + self._cr.execute( |
| 58 | + """ |
| 59 | + CREATE TABLE IF NOT EXISTS http_sessions ( |
| 60 | + sid varchar PRIMARY KEY, |
| 61 | + write_date timestamp without time zone NOT NULL, |
| 62 | + payload text NOT NULL |
| 63 | + ) |
| 64 | + """ |
| 65 | + ) |
| 66 | + |
| 67 | + @with_cursor |
| 68 | + def save(self, session): |
| 69 | + payload = json.dumps(dict(session)) |
| 70 | + self._cr.execute( |
| 71 | + """ |
| 72 | + INSERT INTO http_sessions(sid, write_date, payload) |
| 73 | + VALUES (%(sid)s, now() at time zone 'UTC', %(payload)s) |
| 74 | + ON CONFLICT (sid) |
| 75 | + DO UPDATE SET payload = %(payload)s, |
| 76 | + write_date = now() at time zone 'UTC' |
| 77 | + """, |
| 78 | + dict(sid=session.sid, payload=payload), |
| 79 | + ) |
| 80 | + |
| 81 | + @with_cursor |
| 82 | + def delete(self, session): |
| 83 | + self._cr.execute("DELETE FROM http_sessions WHERE sid=%s", (session.sid,)) |
| 84 | + |
| 85 | + @with_cursor |
| 86 | + def get(self, sid): |
| 87 | + self._cr.execute( |
| 88 | + "UPDATE http_sessions " |
| 89 | + "SET write_date = now() at time zone 'UTC' " |
| 90 | + "WHERE sid=%s", |
| 91 | + [sid], |
| 92 | + ) |
| 93 | + self._cr.execute("SELECT payload FROM http_sessions WHERE sid=%s", (sid,)) |
| 94 | + try: |
| 95 | + data = json.loads(self._cr.fetchone()[0]) |
| 96 | + except Exception: |
| 97 | + return self.new() |
| 98 | + |
| 99 | + return self.session_class(data, sid, False) |
| 100 | + |
| 101 | + # This method is not part of the Session interface but is called nevertheless, |
| 102 | + # so let's get it from FilesystemSessionStore. |
| 103 | + rotate = http.FilesystemSessionStore.rotate |
| 104 | + |
| 105 | + @with_cursor |
| 106 | + def vacuum(self): |
| 107 | + self._cr.execute( |
| 108 | + "DELETE FROM http_sessions " |
| 109 | + "WHERE now() at time zone 'UTC' - write_date > '7 days'" |
| 110 | + ) |
| 111 | + |
| 112 | + |
| 113 | +_original_session_store = http.root.__class__.session_store |
| 114 | + |
| 115 | + |
| 116 | +@lazy_property |
| 117 | +def session_store(self): |
| 118 | + session_db_uri = os.environ.get("SESSION_DB_URI") |
| 119 | + if session_db_uri: |
| 120 | + _logger.debug("HTTP sessions stored in: db") |
| 121 | + return PGSessionStore(session_db_uri, session_class=http.Session) |
| 122 | + return _original_session_store.__get__(self, self.__class__) |
| 123 | + |
| 124 | + |
| 125 | +# Monkey patch of standard methods |
| 126 | +_logger.debug("Monkey patching session store") |
| 127 | +http.root.__class__.session_store = session_store |
| 128 | +# Reset the lazy property cache |
| 129 | +vars(http.root).pop("session_store", None) |
0 commit comments