Forums

SSL error: decryption failed or bad record

Hey, so I've been trying to get my website up and running on here. It works; however, I get this SQL error after a few executes, and then the whole connection to the database disconnects - resulting in a fail.

Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/home/LeDiamant/mysite/app.py", line 107, in dashboard cursor.execute("SELECT value FROM level_settings WHERE guild = %s AND type = %s", (str(guild_id), "Level Disabled",)) psycopg2.OperationalError: SSL error: decryption failed or bad record mac

How would I fix this? I don't get this error anywhere else, running locally is fine. I make the connection to the database when the web app is started - I'm not sure if this is the way to do it or make a connection per user that goes onto the website.

Would it be a database issue (like Firewall) or a web app issue?

Are you creating the database connection at module level -- that is, outside of your view functions? If so, that would explain the problem. When a website is started, the system initially imports all of your code, then it forks off multiple subprocesses to run it. If you're creating a database connection at module level, it will be created prior to the fork, so all of the subprocesses will be trying to use the same connection and tripping over each other.

The best solution is to use something like Flask-SQLAlchemy to manage your database connections -- it will abstract all of that away so that you don't need to worry about it.

A second-best solution is to create a fresh connection at the start of each view function that uses the database (and to close it at the end, of course).

Ahhh okay, that makes sense! I shall try that, thank you!

Great! Let us know if you hit any further problems.

i am using flask for my postgres but also facing same issue this is my Logs

2024-09-22 17:46:51 Connection pool created successfully 2024-09-22 17:46:51 WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x5aae2b127e80 pid: 1 (default app) 2024-09-22 17:46:51 *** uWSGI is running in multiple interpreter mode *** 2024-09-22 17:46:51 gracefully (RE)spawned uWSGI master process (pid: 1) 2024-09-22 17:46:51 spawned uWSGI worker 1 (pid: 2, cores: 1) 2024-09-22 17:46:51 spawned 2 offload threads for uWSGI worker 1 2024-09-22 17:46:51 spawned uWSGI worker 2 (pid: 5, cores: 1) 2024-09-22 17:46:51 metrics collector thread started 2024-09-22 17:46:51 spawned 2 offload threads for uWSGI worker 2 2024-09-22 17:46:52 announcing my loyalty to the Emperor... 2024-09-22 17:46:52 announcing my loyalty to the Emperor... 2024-09-22 17:46:58 Error fetching user data: SSL error: decryption failed or bad record mac 2024-09-22 17:46:58 2024-09-22 17:47:26 Error fetching user data: SSL SYSCALL error: EOF detected 2024-09-22 17:47:26 2024-09-22 17:47:52 Error checking task status: SSL error: decryption failed or bad record mac 2024-09-22 17:47:52 2024-09-22 17:47:52 Error checking task status: SSL SYSCALL error: EOF detected 2024-09-22 17:47:52 2024-09-22 17:47:54 Error fetching referral stats: SSL error: decryption failed or bad record mac 2024-09-22 17:47:54 2024-09-22 17:53:10 Sun Sep 22 17:53:10 2024 - received message 0 from emperor

Could you share more context?

here is my code connection

from flask import Flask, request, jsonify, g
from flask_cors import CORS
import psycopg2
from psycopg2 import pool
from datetime import datetime, timedelta
import pytz
from psycopg2.extras import RealDictCursor
import requests  # Import requests module for making HTTP requests
import atexit


# Initialize Flask app
app = Flask(__name__)

# Enable CORS for your backend
CORS(app, resources={r"/*": {"origins": ["http://localhost:3000", "https://hosted.netlify.app", "https://username.pythonanywhere.com"]}})

# Database pool setup for PostgreSQL with ThreadedConnectionPool
try:
    conn_pool = psycopg2.pool.ThreadedConnectionPool(
        minconn=10,
        maxconn=100,
        user="super",
        host="username-7654.postgres.pythonanywhere-services.com",
        database="postgres",
        password="password",  # Replace with your actual password
        port=5432,
        sslmode='require'  # Ensure SSL is used
    )
    if conn_pool:
        print("Connection pool created successfully")
except Exception as e:
    print(f"Error creating connection pool: {e}")

# Dispose of the connection pool when the app shuts down
def close_pool():
    global conn_pool
    if conn_pool:
        print("Disposing connection pool...")
        conn_pool.closeall()

# Register the shutdown function
atexit.register(close_pool)

def get_connection():
    try:
        if 'db_conn' not in g:
            g.db_conn = conn_pool.getconn()  # Fetch connection from pool for each worker thread
        return g.db_conn
    except Exception as e:
        print(f"Error getting connection from pool: {e}")
        return None


def release_connection(conn):
    if conn:
        try:
            conn_pool.putconn(conn)
        except Exception as e:
            print(f"Error releasing connection back to pool: {e}")

@app.teardown_request
def teardown_request(exception=None):
    """Ensure that connection is released back to the pool after the request."""
    conn = getattr(g, 'db_conn', None)  # Check if a connection exists in the request context
    if conn:
        try:
            release_connection(conn)
            del g.db_conn  # Remove the connection from the request context after releasing it
        except Exception as e:
            print(f"Error during teardown request: {e}")


@app.route('/some-endpoint', methods=['GET'])
def some_function():
    conn = None
    try:
        conn = get_connection()
        if conn is None:
            return jsonify({"error": "Could not establish database connection"}), 500

        cur = conn.cursor()
        cur.execute("SELECT * FROM some_table")
        result = cur.fetchall()
        return jsonify(result)

    except Exception as e:
        print(f"Error occurred: {e}")
        return jsonify({"error": "An error occurred"}), 500


# Helper function to make sure datetime objects are timezone-aware
def make_aware(naive_dt):
    """Convert a naive datetime object to a timezone-aware datetime object."""
    if naive_dt is None:
        return None  # Handle case where there is no datetime (None)

    if naive_dt.tzinfo is None:
        return pytz.UTC.localize(naive_dt)
    return naive_dt

And here is my Logs

2024-09-22 23:37:51 Connection pool created successfully
2024-09-22 23:37:51 WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x5b0312259e80 pid: 1 (default app)
2024-09-22 23:37:51 *** uWSGI is running in multiple interpreter mode ***
2024-09-22 23:37:51 gracefully (RE)spawned uWSGI master process (pid: 1)
2024-09-22 23:37:51 spawned uWSGI worker 1 (pid: 2, cores: 1)
2024-09-22 23:37:51 spawned 2 offload threads for uWSGI worker 1
2024-09-22 23:37:51 spawned uWSGI worker 2 (pid: 5, cores: 1)
2024-09-22 23:37:51 metrics collector thread started
2024-09-22 23:37:51 spawned 2 offload threads for uWSGI worker 2
2024-09-22 23:37:52 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:37:52 announcing my loyalty to the Emperor...
2024-09-22 23:37:55 Error fetching tasks: SSL error: decryption failed or bad record mac
2024-09-22 23:37:55 
2024-09-22 23:37:57 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error checking task status: SSL SYSCALL error: EOF detected
2024-09-22 23:38:34 
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:34 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:37 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:37 Error fetching referral stats: SSL error: decryption failed or bad record mac
2024-09-22 23:38:37 
2024-09-22 23:38:37 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:39 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:39 Error fetching user data: SSL SYSCALL error: EOF detected
2024-09-22 23:38:39 
2024-09-22 23:38:39 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:40 Error processing claim: SSL error: decryption failed or bad record mac
2024-09-22 23:38:40 
2024-09-22 23:38:40 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:42 Error processing claim: SSL SYSCALL error: EOF detected
2024-09-22 23:38:42 
2024-09-22 23:38:42 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:47 Error checking task status: SSL error: wrong version number
2024-09-22 23:38:47 
2024-09-22 23:38:47 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:47 Error checking task status: server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.#012server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.
2024-09-22 23:38:47 
2024-09-22 23:38:47 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:47 Error checking task status: SSL error: sslv3 alert bad record mac
2024-09-22 23:38:47 
2024-09-22 23:38:47 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:47 Error checking task status: server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.#012server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.
2024-09-22 23:38:47 
2024-09-22 23:38:47 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:47 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:38:49 Error fetching user data: SSL error: decryption failed or bad record mac
2024-09-22 23:38:49 
2024-09-22 23:38:49 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:10 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:11 Error fetching referral stats: SSL SYSCALL error: EOF detected
2024-09-22 23:39:11 
2024-09-22 23:39:11 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:42 Error processing claim: SSL error: decryption failed or bad record mac
2024-09-22 23:39:42 
2024-09-22 23:39:42 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:44 Error processing claim: SSL SYSCALL error: EOF detected
2024-09-22 23:39:44 
2024-09-22 23:39:44 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:45 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:46 Error checking task status: SSL error: decryption failed or bad record mac
2024-09-22 23:39:46 
2024-09-22 23:39:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:46 Error checking task status: server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.#012server closed the connection unexpectedly#012#011This probably means the server terminated abnormally#012#011before or while processing the request.
2024-09-22 23:39:46 
2024-09-22 23:39:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:46 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:51 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:39:54 Error fetching user data: SSL error: decryption failed or bad record mac
2024-09-22 23:39:54 
2024-09-22 23:39:54 Error releasing connection back to pool: trying to put unkeyed connection
2024-09-22 23:42:07 Sun Sep 22 23:42:07 2024 - received message 0 from emperor
2024-09-22 23:42:07 SIGINT/SIGTERM received...killing workers...
2024-09-22 23:42:07 Disposing connection pool...
2024-09-22 23:42:07 Disposing connection pool...
2024-09-22 23:42:08 worker 1 buried after 1 seconds
2024-09-22 23:42:08 worker 2 buried after 1 seconds
2024-09-22 23:42:08 goodbye to uWSGI.
2024-09-22 23:42:08 VACUUM: unix socket /var/sockets/username.pythonanywhere.com/socket removed.
2024-09-22 23:42:19 *** Starting uWSGI 2.0.20 (64bit) on [Sun Sep 22 23:42:18 2024] ***
2024-09-22 23:42:19 compiled with version: 9.4.0 on 22 July 2022 18:35:26
2024-09-22 23:42:19 os: Linux-6.5.0-1022-aws #22~22.04.1-Ubuntu SMP Fri Jun 14 16:31:00 UTC 2024
2024-09-22 23:42:19 nodename: blue-liveweb11
2024-09-22 23:42:19 machine: x86_64
2024-09-22 23:42:19 clock source: unix
2024-09-22 23:42:19 pcre jit disabled
2024-09-22 23:42:19 detected number of CPU cores: 4`

[formatted by admin]

Could you try moving the connection creation to the view function(s) instead of having it creating at the module level? (See Giles' reply above.)