user1190707
user1190707

Reputation:

PostgreSQL Cluster Startup Race Condition?

My software process depends on the existence of a specific database in the local PostgreSQL cluster. PostgreSQL and my software process are both started by upstart on system start. A script is executed after PostgreSQL starts and before my software process starts to ensure the database is in the correct state.

The script dumps the schema of the database using pg_dump. If the server is not running or ready for connections I see the following

$ pg_dump -U postgres -s testdb
pg_dump: [archiver (db)] connection to database "testdb" failed: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

If the database does not exist I see the following

$ pg_dump -U postgres -s testdb
pg_dump: [archiver (db)] connection to database "testdb" failed: FATAL:  database "testdb" does not exist

There appears to be a time window where even though the cluster does contain database 'testdb' the call to pg_dump reports that the database does not exist. I can avoid the problem by adding a short sleep between server startup and running my script. I would prefer a solution that does not include a sleep for an arbitrary length of time. Any suggestions?

I'm running PostgreSQL 9.1 on 32bit Ubuntu 12.04 LTS.

Upvotes: 1

Views: 316

Answers (1)

Chris Travers
Chris Travers

Reputation: 26464

Assuming this is a shell script, my guess is that you are not waiting for the create database command to complete. You could be running createdb n the background or psql in the background. If you run these in the foreground this should not happen because they will block until the database completes.

Upvotes: 1

Related Questions