Psycopg2 operationalerror ssl syscall error eof detected

Solution 1 The error: psycopg2.operationalerror: SSL SYSCALL error: EOF detected The setup: Airflow + Redshift + psycopg2 When: Queries take a long time to execute (more than 300 seconds). A socket timeout occurs in this instance. What solves this specific variant of the error is adding keepalive arguments to the connection string. keepalive_kwargs = { "keepalives": 1, "keepalives_idle": 30, "keepalives_interval": 5, "keepalives_count": 5, } conection = psycopg2.connect(connection_string, **keepalive_kwargs) Redshift requires a keepalives_idle of less than 300. A value of 30 worked for me, your mileage may vary. It is also possible that the keepalives_idle argument is the only one you

Solution 1

The error: psycopg2.operationalerror: SSL SYSCALL error: EOF detected

The setup: Airflow + Redshift + psycopg2

When: Queries take a long time to execute (more than 300 seconds).

A socket timeout occurs in this instance. What solves this specific variant of the error is adding keepalive arguments to the connection string.

keepalive_kwargs = {
    "keepalives": 1,
    "keepalives_idle": 30,
    "keepalives_interval": 5,
    "keepalives_count": 5,
}

conection = psycopg2.connect(connection_string, **keepalive_kwargs)

Redshift requires a keepalives_idle of less than 300. A value of 30 worked for me, your mileage may vary. It is also possible that the keepalives_idle argument is the only one you need to set — but ensure keepalives is set to 1.

Link to docs on postgres keepalives.

Link to airflow doc advising on 300 timeout.

Solution 2

I ran into this problem when running a slow query in a Droplet on a Digital Ocean instance. All other SQL would run fine and it worked on my laptop. After scaling up to a 1 GB RAM instance instead of 512 MB it works fine so it seems that this error could occur if the process is running out of memory.

Solution 3

Very similar answer to what @FoxMulder900 did, except I could not get his first select to work. This works, though:

WITH long_running AS (
    SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state
    FROM pg_stat_activity
    WHERE (now() - pg_stat_activity.query_start) > interval '1 minutes'
      and state = 'active'
)
SELECT * from long_running;

If you want to kill the processes from long_running just comment out the last line and insert SELECT pg_cancel_backend(long_running.pid) from long_running ;

Solution 4

This issue occurred for me when I had some rogue queries running causing tables to be locked indefinitely. I was able to see the queries by running:

SELECT * from STV_RECENTS where status='Running' order by starttime desc;

then kill them with:

SELECT pg_terminate_backend(<pid>);

Solution 5

In my case that was OOM killer (query is too heavy)

Check dmesg:

dmesg | grep -A2 Kill

In my case:

Out of memory: Kill process 28715 (postgres) score 150 or sacrifice child

Related videos on Youtube

psycopg2 python Bulk Insert with mogrify, Update, Delete rows, error handling

18 : 48

psycopg2 python Bulk Insert with mogrify, Update, Delete rows, error handling

CREATE USER CREDENTIALS PYTHON to MYSQL & POSTGRESQL | CONFIG FILES | .INI FILES

10 : 09

CREATE USER CREDENTIALS PYTHON to MYSQL & POSTGRESQL | CONFIG FILES | .INI FILES

Databases: PostgreSQL: SSL SYSCALL error: EOF detected

02 : 20

Databases: PostgreSQL: SSL SYSCALL error: EOF detected

Connect to PostgreSQL from Python (Using SQL in Python) | Python to PostgreSQL

22 : 58

Connect to PostgreSQL from Python (Using SQL in Python) | Python to PostgreSQL

Error trying to install Postgres for python psycopg2 | pip install python psycopg2 (solved 100%)

04 : 09

Error trying to install Postgres for python psycopg2 | pip install python psycopg2 (solved 100%)

How to fix: SSL: CERTIFICATE_VERIFY_FAILED Error in Python (2022)

01 : 20

How to fix: SSL: CERTIFICATE_VERIFY_FAILED Error in Python (2022)

Postgres SSL SYSCALL error EOF detected with python and psycopg - PYTHON

01 : 17

Postgres SSL SYSCALL error EOF detected with python and psycopg — PYTHON

Comments

  • Using psycopg2 package with python 2.7 I keep getting the titled error: psycopg2.DatabaseError: SSL SYSCALL error: EOF detected

    It only occurs when I add a WHERE column LIKE ''%X%'' clause to my pgrouting query. An example:

    SELECT id1 as node, cost FROM PGR_Driving_Distance(
      'SELECT id, source, target, cost 
         FROM edge_table
         WHERE cost IS NOT NULL and column LIKE ''%x%'' ',
      1, 10, false, false)
    

    Threads on the internet suggest it is an issue with SSL intuitively, but whenever I comment out the pattern matching side of things the query and connection to the database works fine.

    This is on a local database running Xubuntu 13.10.

    After further investigation: It looks like this may be cause by the pgrouting extension crashing the database because it is a bad query and their are not links which have this pattern.

    Will post an answer soon …

    • Why the subquery? makes no sense to ne.

    • The subquery is for the PGR_DrivingDistance function.

    • famous last words: Will post an answer soon ...

    • Sometimes SO did, make me laugh :D

    • @PhilDonovan Did you resolve this issue ?

    • @PhilDonovan don’t leave us hanging!

    • No sorry, I tried an alternative means.

  • it appears that isn’t always the fix- I’m using a machine with 160gb ram and still having this error while using pg_dump on a SSL-only database. only 15gb is in use.

  • Well this might work, but it doesn’t sound like a real solution. There should be a way to optimise this somehow

  • Exactly what I’ve run into! Added 4GB of swap space to a 512MB instance and everything worked as a charm.

  • To the uninitiated it’s not really clear what you are saying. Please provide some explanation on what dmesg is and why you are running it.

  • this could be useful, dmesg is just where a lot of the linux kernel errors ends, usually these means driver’s messages (e.g. I have been in dmesg looking for how to fix my wifi a lot of times). When Linux (and OSs in general) runs out of memory (and swap), then the kernel picks one of the current process and kills it in order to reclaim the memory. Note that at that point the OS has two options: kill one process or freeze forever.

  • My db has 16GB RAM dedicated, no swap of system is getting used but still running into this issue.. Does only happen in a small amount of queries… Weird.

  • @gies0r This problem probably has more causes than memory issues, even though I wouldn’t completely rule it out.

  • Besides freeing more memory, what other solutions can be done. Can we do a timeout to let the user know?

  • this helped me avoid the SSL SYSCALL error

  • Amazing answer. Thanks.

  • that’s not what’s causing their issue, but it is true for executing a query string from Python.

Recents

I was running a scraping job from a Docker container using Python and the psycopg2 adapter that wrote the results to a Postgres database managed on DigitalOcean (DO). On random occasions, the container died, for some reason. I started debugging and these are my findings.

The error I ran into was the following:

Error: SSL SYSCALL error: EOF detected

I literally had no idea what to expect when Googling this error. Here’s what I found.

Make the queries run faster

It tends to happen with Postgres deployments that have very little RAM allocated to them. For example, I’m using the cheapest Postgres hosting on DO, it only has 512mb of memory attached to it .

In other words: the lower the memory, the longer it takes to run complex queries, with a higher probability that the connection times out.

If you can spare the bucks: add more memory.

Adjust the connection timeout

If adding more memory is not an option, try changing the keepalives parameters of your Postgres connection. For example, in psycopg2, you can do that as follows.

keepalive_kwargs = {
  "keepalives": 1,
  "keepalives_idle": 60,
  "keepalives_interval": 10,
  "keepalives_count": 5
}

conn = psycopg2.connect(
  host = 'YOUR_HOST>',
  database = '<DB_NAME>',
  user = '<USER>',
  password = '<PASSWORD>',
  port = 25060,
  **keepalive_kwargs
)

Let’s go over these four parameters quickly:

  • keepalives (boolean): By setting this to 1, you indicate you want to use your own client-side keepalives.
  • keepalives_idle (seconds): Sets the number of seconds of inactivity after which a keepalive message such be sent.
  • keepalives_interval (seconds): Sets the number of seconds to wait before resending a message that has not been acknowledged by the server.
  • keepalives_count (count): Sets the number of non-acknowledged keepalives to determine that the connection is dead.

So, solve the problem by making your queries run faster, or by making sure your connection doesn’t time out.

Great success!

Генератор данных реального мира 1

Используя пакет psycopg2 с python 2.7, я постоянно получаю сообщение об ошибке: psycopg2.DatabaseError: SSL SYSCALL error: обнаружен EOF

Это происходит только тогда, когда я добавляю WHERE column LIKE ''%X%'' предложение к моему запросу pgrouting. Пример:

SELECT id1 as node, cost FROM PGR_Driving_Distance( 'SELECT id, source, target, cost FROM edge_table WHERE cost IS NOT NULL and column LIKE ''%x%'' ', 1, 10, false, false) 

Обсуждения в Интернете предполагают, что это проблема с SSL интуитивно, но всякий раз, когда я комментирую сторону сопоставления с шаблоном, запрос и подключение к базе данных работают нормально.

Это в локальной базе данных под управлением Xubuntu 13.10.

После дальнейшего расследования: похоже, это может быть вызвано тем, что расширение pgrouting приводит к сбою базы данных, потому что это неправильный запрос, и это не ссылки, которые имеют этот шаблон.

Скоро отправлю ответ …

  • Почему подзапрос? не имеет смысла.
  • Подзапрос предназначен для функции PGR_DrivingDistance.
  • 59 знаменитых последних слов: Will post an answer soon ...
  • Иногда ТАК делал, смеши меня: D
  • 2 @PhilDonovan, не бросайте нас!

Я столкнулся с этой проблемой при выполнении медленного запроса в капле на экземпляре Digital Ocean. Все остальные SQL работали нормально, и он работал на моем ноутбуке. После масштабирования до 1 ГБ ОЗУ вместо 512 МБ он работает нормально, поэтому кажется, что эта ошибка может возникнуть, если процессу не хватает памяти.

  • 2 похоже, что это не всегда исправление — я использую машину с оперативной памятью 160 ГБ и все еще имею эту ошибку при использовании pg_dump в базе данных только с SSL. используется только 15 ГБ.
  • Что ж, это может сработать, но это не похоже на настоящее решение. Должен быть способ как-то это оптимизировать
  • 1 Именно с чем я столкнулся! Добавил 4 ГБ пространства подкачки к экземпляру 512 МБ, и все заработало как шарм.
  • У моего db выделено 16 ГБ ОЗУ, своп системы не используется, но проблема все еще возникает … Это происходит только при небольшом количестве запросов … Странно.
  • @ gies0r У этой проблемы, вероятно, больше причин, чем проблем с памятью, хотя я не исключаю ее полностью.

Эта проблема возникла у меня, когда у меня выполнялись некоторые мошеннические запросы, вызывающие блокировку таблиц на неопределенный срок. Я смог увидеть запросы, запустив:

SELECT * from STV_RECENTS where status='Running' order by starttime desc; 

затем убейте их:

SELECT pg_terminate_backend(); 

В моем случае это был убийца OOM (запрос слишком тяжелый)

Проверьте dmesg:

dmesg | grep -A2 Kill 

В моем случае:

Out of memory: Kill process 28715 (postgres) score 150 or sacrifice child 
  • 2 Непосвященным не совсем понятно, о чем вы говорите. Пожалуйста, объясните, что dmesg есть и почему вы его запускаете.
  • 1 это может быть полезно, dmesg Именно там заканчивается множество ошибок ядра Linux, обычно это сообщения драйверов (например, я много раз был в dmesg, ища, как исправить мой Wi-Fi). Когда в Linux (и ОС в целом) заканчивается память (и происходит подкачка), ядро ​​выбирает один из текущих процессов и убивает его, чтобы освободить память. Обратите внимание, что в этот момент у ОС есть два варианта: убить один процесс или заморозить навсегда.

Вам может потребоваться выразить % в качестве %% так как % маркер-заполнитель. http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

Ошибка: psycopg2.operationalerror: SSL SYSCALL error: EOF detected

Настройка: Поток воздуха + Красное смещение + psycopg2

Когда: запросы занимают длинный время выполнения (более 300 секунд).

В этом случае происходит тайм-аут сокета. Что решает этот конкретный вариант ошибки, так это добавление аргументов поддержки активности в строку подключения.

keepalive_kwargs = { 'keepalives': 1, 'keepalives_idle': 30, 'keepalives_interval': 5, 'keepalives_count': 5, } conection = psycopg2.connect(connection_string, **keepalive_kwargs) 

Redshift требует keepalives_idle менее 300. У меня работало значение 30, ваш пробег может отличаться. Также возможно, что keepalives_idle аргумент — единственный, который вам нужно установить, но убедитесь, что keepalives установлен на 1.

Ссылка на документацию по сообщениям поддержки активности postgres.

Ссылка на документ по воздушному потоку, советующий по таймауту 300.

Ответ очень похож на то, что сделал @ FoxMulder900, за исключением того, что я не смог заставить его первый выбор работать. Однако это работает:

WITH long_running AS ( SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state FROM pg_stat_activity WHERE (now() - pg_stat_activity.query_start) > interval '1 minutes' and state = 'active' ) SELECT * from long_running; 

Если вы хотите убить процессы из long_running просто закомментируйте последнюю строку и вставьте SELECT pg_cancel_backend(long_running.pid) from long_running ;

Я получил эту ошибку при выполнении большого оператора UPDATE в таблице с 3 миллионами строк. В моем случае оказалось, что диск заполнен. Как только я добавил больше места, ОБНОВЛЕНИЕ работало нормально.

Tweet

Share

Link

Plus

Send

Send

Pin

Using psycopg2 package with python 2.7 I keep getting the titled error: psycopg2.DatabaseError: SSL SYSCALL error: EOF detected

It only occurs when I add a WHERE column LIKE ''%X%'' clause to my pgrouting query. An example:

SELECT id1 as node, cost FROM PGR_Driving_Distance(
  'SELECT id, source, target, cost 
     FROM edge_table
     WHERE cost IS NOT NULL and column LIKE ''%x%'' ',
  1, 10, false, false)

Threads on the internet suggest it is an issue with SSL intuitively, but whenever I comment out the pattern matching side of things the query and connection to the database works fine.

This is on a local database running Xubuntu 13.10.

After further investigation: It looks like this may be cause by the pgrouting extension crashing the database because it is a bad query and their are not links which have this pattern.

Will post an answer soon …

asked Jun 9 ’14 at 22:53

Phil DonovanPhil Donovan

8751 gold badge7 silver badges18 bronze badges

7

The error: psycopg2.operationalerror: SSL SYSCALL error: EOF detected

The setup: Airflow + Redshift + psycopg2

When: Queries take a long time to execute (more than 300 seconds).

A socket timeout occurs in this instance. What solves this specific variant of the error is adding keepalive arguments to the connection string.

keepalive_kwargs = {
    "keepalives": 1,
    "keepalives_idle": 30,
    "keepalives_interval": 5,
    "keepalives_count": 5,
}

conection = psycopg2.connect(connection_string, **keepalive_kwargs)

Redshift requires a keepalives_idle of less than 300. A value of 30 worked for me, your mileage may vary. It is also possible that the keepalives_idle argument is the only one you need to set — but ensure keepalives is set to 1.

Link to docs on postgres keepalives.

Link to airflow doc advising on 300 timeout.

answered Jul 28 ’20 at 9:16

1

I ran into this problem when running a slow query in a Droplet on a Digital Ocean instance. All other SQL would run fine and it worked on my laptop. After scaling up to a 1 GB RAM instance instead of 512 MB it works fine so it seems that this error could occur if the process is running out of memory.

answered Mar 18 ’16 at 13:58

antonagestamantonagestam

3,9743 gold badges29 silver badges42 bronze badges

5

This issue occurred for me when I had some rogue queries running causing tables to be locked indefinitely. I was able to see the queries by running:

SELECT * from STV_RECENTS where status='Running' order by starttime desc;

then kill them with:

SELECT pg_terminate_backend(<pid>);

answered Dec 18 ’17 at 19:08

FoxMulder900FoxMulder900

1,11211 silver badges22 bronze badges

Very similar answer to what @FoxMulder900 did, except I could not get his first select to work. This works, though:

WITH long_running AS (
    SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state
    FROM pg_stat_activity
    WHERE (now() - pg_stat_activity.query_start) > interval '1 minutes'
      and state = 'active'
)
SELECT * from long_running;

If you want to kill the processes from long_running just comment out the last line and insert SELECT pg_cancel_backend(long_running.pid) from long_running ;

answered Oct 30 ’18 at 18:55

Charles FCharles F

4095 silver badges9 bronze badges

1

In my case that was OOM killer (query is too heavy)

Check dmesg:

dmesg | grep -A2 Kill

In my case:

Out of memory: Kill process 28715 (postgres) score 150 or sacrifice child

answered Feb 1 ’19 at 11:24

papko26papko26

811 silver badge2 bronze badges

3

I encountered the same error. By CPU, RAM usage everything was ok, solution by @antonagestam didn’t work for me.

Basically, the issue was at the step of engine creation. pool_pre_ping=True solved the problem:

engine = sqlalchemy.create_engine(connection_string, pool_pre_ping=True)

What it does, is that each time when the connection is being used, it sends SELECT 1 query to check the connection. If it is failed, then the connection is recycled and checked again. Upon success, the query is then executed.

sqlalchemy docs on pool_pre_ping

In my case, I had the same error in python logs. I checked the log file in /var/log/postgresql/, and there were a lot of error messages could not receive data from client: Connection reset by peer and unexpected EOF on client connection with an open transaction. This can happen due to network issues.

answered Mar 7 ’21 at 10:51

Ali TlekbaiAli Tlekbai

1462 silver badges9 bronze badges

answered Aug 2 ’14 at 23:16

piropiro

12.2k5 gold badges33 silver badges35 bronze badges

1

I got this error running a large UPDATE statement on a 3 million row table. In my case it turned out the disk was full. Once I had added more space the UPDATE worked fine.

answered Apr 26 ’17 at 9:42

Not the answer you’re looking for? Browse other questions tagged python postgresql ssl psycopg2 pgrouting or ask your own question.

Понравилась статья? Поделить с друзьями:
  • Psycopg2 errors syntaxerror syntax error at end of input
  • Psycopg install error
  • Psychonauts has encountered an error crash 0xc0000005
  • Pstream connect error or disconnect reset before headers reset reason connection failure
  • Pstocapt3 write error