Correctly restore connection if MySQL server has gone away #2421
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Based on this code example I have created and deployed a cloud function, which connects over a socket to the Cloud SQL Instance.
I however noticed that it wasn't behaving correctly: after a while I was getting back the Exception
pymysql.err.InterfaceError: (0, '')
on each request.Scrolling back in the logs of my cloud function I noticed that the Exception started getting thrown after the connection the MySQL server got lost:
Note this error in the logs, after which the
pymysql.err.InterfaceError: (0, '')
Exceptions pop up:When redeploying the function everything worked fine again, but a day later the same issue occurred again.
I narrowed down the problem to the reconnection logic as copied from the code example. It does not correctly restore the connection when the connection gets lost.
Running the code locally with
cloud_sql_proxy
, it behaves like so:This is a reproduction of the behavior as seen when the function runs on GCP.
With the altered code from this PR, this is the behavior:
As you can see the connection correctly restores after the socket has become available again.