Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion web/pgadmin/utils/driver/psycopg3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,8 @@ def gc_timeout(self):
m for m in sess_mgr.values() if isinstance(m,
ServerManager)
]:
mgr.release()
with mgr.releasing_for_other_session():
mgr.release()
# Expired sessions stay in self.managers, so only run the
# callbacks once per idle period rather than on every sweep.
if not sess_mgr.get('gc_callbacks_run'):
Expand Down
28 changes: 28 additions & 0 deletions web/pgadmin/utils/driver/psycopg3/server_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import os
import config
import logging
import threading
import warnings
from contextlib import contextmanager
from flask import current_app, session
from flask_security import current_user
from flask_babel import gettext
Expand Down Expand Up @@ -55,6 +57,13 @@
DB_STRING = 'DB:{0}'


# ids of the managers that this thread is releasing on behalf of another
# session; see ServerManager.releasing_for_other_session(). It is per
# thread because a manager is shared by the requests of its own session
# and by any other request's idle-session sweep.
_other_session_releases = threading.local()


class ServerManager(object):
"""
class ServerManager
Expand Down Expand Up @@ -570,7 +579,26 @@ def _update_password(self, passwd):
if conn.conn is not None or conn.wasConnected is True:
conn.password = passwd

@contextmanager
def releasing_for_other_session(self):
"""
Used by Driver.gc_timeout() whilst it releases this manager during
another session's request. The Flask session then belongs to that
request rather than to the session that owns this manager, so
update_session() must not write to it, or it would overwrite or
drop that user's own saved state for a server with the same id.
"""
ids = _other_session_releases.__dict__.setdefault('ids', set())
ids.add(id(self))
try:
yield
finally:
ids.discard(id(self))

def update_session(self):
if id(self) in getattr(_other_session_releases, 'ids', ()):
return

managers = session['__pgsql_server_managers'] \
if '__pgsql_server_managers' in session else dict()
updated_mgr = self.as_dict()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2026, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################

"""Regression test for #10917: releasing an idle session's connections in
gc_timeout() must not change the saved connection state in the Flask
session of the request that runs the sweep."""

import datetime
import threading
from unittest.mock import MagicMock, patch

from flask import session

from config import PG_DEFAULT_DRIVER
from pgadmin.utils.driver import get_driver
import pgadmin.utils.driver.psycopg3 as psycopg3_driver
from pgadmin.utils.driver.psycopg3.server_manager import ServerManager
from pgadmin.utils.route import BaseTestGenerator


class GcTimeoutKeepsCurrentSessionStateTest(BaseTestGenerator):
"""gc_timeout() releases the idle session's manager without touching
the current session's saved state for the same server id."""

scenarios = [
('Current session has saved state for the same server',
dict(saved={1: {'sid': 1, 'ver': 'saved'}})),
('Current session has no saved state',
dict(saved=None)),
]

def runTest(self):
idle_mgr = ServerManager.__new__(ServerManager)
idle_mgr.sid = 1
idle_mgr.connections = {'CONN:1': MagicMock(conn_id='CONN:1')}
idle_mgr.connections['CONN:1'].connected.return_value = False

managers = {
'idle': {'pinged': datetime.datetime.now() -
datetime.timedelta(days=1),
'1': idle_mgr},
}

with self.app.test_request_context():
if self.saved is not None:
session['__pgsql_server_managers'] = dict(self.saved)
driver = get_driver(PG_DEFAULT_DRIVER)
with patch.object(driver, 'managers', managers), \
patch.object(psycopg3_driver, 'session',
MagicMock(sid='current')), \
patch.object(driver, 'run_session_gc_callbacks'), \
patch.object(ServerManager, 'stop_ssh_tunnel'):
driver.gc_timeout()

self.assertEqual(session.get('__pgsql_server_managers'),
self.saved)
self.assertEqual(idle_mgr.connections, {})

# Once the sweep is done, the manager's own session can save
# its state again.
idle_mgr.ver = 'idle'
idle_mgr.connections = {'CONN:1': MagicMock()}
with patch.object(ServerManager, 'as_dict',
return_value={'sid': 1, 'ver': 'idle'}):
idle_mgr.update_session()
self.assertEqual(session['__pgsql_server_managers'][1],
{'sid': 1, 'ver': 'idle'})


class OtherSessionMarkerIsPerThreadTest(BaseTestGenerator):
"""Whilst one thread releases a manager for another session, a request
of the manager's own session on another thread still saves its
state."""

scenarios = [
('Marker does not affect other threads', dict()),
]

def runTest(self):
mgr = ServerManager.__new__(ServerManager)
mgr.sid = 1
saved = {}

def own_session_request():
with self.app.test_request_context():
mgr.update_session()
saved.update(session['__pgsql_server_managers'])

with patch.object(ServerManager, 'as_dict',
return_value={'sid': 1}), \
self.app.test_request_context():
with mgr.releasing_for_other_session():
mgr.update_session()
other = threading.Thread(target=own_session_request)
other.start()
other.join()
self.assertNotIn('__pgsql_server_managers', session)

self.assertEqual(saved, {1: {'sid': 1}})
Loading