-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgres_ready.py
65 lines (56 loc) · 2.3 KB
/
postgres_ready.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
import psycopg2
import click
import time
import sys
@click.command()
@click.option('--retries', default=10, help='Default 10 - Max number of connection retries.')
@click.option('--seconds', default=1, help='Default 1 - Seconds to wait between retries.')
@click.option('--db', default='postgres', help='Default \'postgres\' - Postgres db name.')
@click.option('--user', default='postgres', help='Default \'postgres\' - Postgres user name.')
@click.option('--password', default='mysecretpassword', help='Default \'mysecretpassword\' - Postgres password.')
@click.option('--host', default='localhost', help='Default \'localhost\' - Postgres ip or hostname.')
@click.option('--port', default=5432, help='Default 5432 - Postgres port.')
@click.option('--prevent_ssl', is_flag=True, help='Disabled by default - BE CAREFUL! This flag disables ssl for Postgres connection.')
def postgres_ready(retries, seconds, db, user, password, host, port, prevent_ssl):
"""
This script accepts options as documented here but it also
accepts environment variables! All the options can be passed
as environment vars using uppercase and prefixing with 'POSTGRES_'
For example:
--db option can be alternatively passed as POSTGRES_DB environment
variable.
You can even mix environment variables and options. Enjoy!
"""
credentials = {
'dbname': db,
'user': user,
'password': password,
'host': host,
'port': port
}
if not prevent_ssl:
credentials['sslmode'] = 'require'
with click.progressbar(length=retries, label='Reaching Postgres') as bar:
is_postgres_up = False
for retry in range(retries):
try:
conn = psycopg2.connect(**credentials)
except psycopg2.OperationalError:
time.sleep(seconds)
bar.update(retry + 1)
else:
conn.close()
is_postgres_up = True
bar.update(retries)
break
print('\n')
if is_postgres_up:
print('Postgres is up and running!')
code = 0
else:
print('Could not connect to Postgres!')
code = -1
sys.exit(code)
if __name__ == '__main__':
postgres_ready(auto_envvar_prefix='POSTGRES')