Improve exception handling on db_session_cleanup decorator

The previous commit [1] introduced a decorator to cleanup db sessions
at the end of the call. If an exception happen before calling the
db_api, sys.exc_info() will still carry the exception information,
which can lead to problems depending on the use case. This commit
makes sure that we only use the exception value of the db function
execution.

Test plan:
  - PASS: Build a custom ISO with the changes and deploy a DX system
          controller and a SX subcloud. Verify the system works as
          expected.
  - PASS: Manage a subcloud and verify the sync_status is "in-sync".
  - PASS: Soak the system and verify there was no connection leak and
          no sessions stuck in "idle in transaction" state.

[1]: https://review.opendev.org/c/starlingx/ha/+/943391

Story: 2011311
Task: 51791

Change-Id: I68df4a56d31f6fd015de3f1e7be756b42e56907f
Signed-off-by: Victor Romano <victor.gluzromano@windriver.com>
This commit is contained in:
Victor Romano
2025-03-14 09:57:22 -03:00
parent e4d6ecf22d
commit 6859be1d0d

View File

@@ -15,7 +15,7 @@
# License for the specific language governing permissions and limitations
# under the License.
#
# Copyright (c) 2013-2018 Wind River Systems, Inc.
# Copyright (c) 2013-2018, 2025 Wind River Systems, Inc.
#
@@ -75,16 +75,20 @@ def db_session_cleanup(cls):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
_context = eventlet.greenthread.getcurrent()
exc_info = (None, None, None)
try:
return method(self, *args, **kwargs)
except Exception:
exc_info = sys.exc_info()
raise
finally:
if (hasattr(_context, "_db_session_context") and
_context._db_session_context is not None):
if (
hasattr(_context, "_db_session_context") and
_context._db_session_context is not None
):
try:
if hasattr(_context, "_db_session_context"):
exc_info = sys.exc_info()
_context._db_session_context.__exit__(*exc_info)
_context._db_session_context.__exit__(*exc_info)
except Exception as e:
LOG.warning(f"Error closing database session: {e}")