Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/dev/minimal/start_postgres.py
Views: 286
1
#!/usr/bin/env python
2
3
"""
4
This is a script for starting postgres for development purposes on a laptop.
5
"""
6
7
import os, sys, time, util
8
9
path = os.path.split(os.path.realpath(__file__))[0]; os.chdir(path); sys.path.insert(0, path)
10
11
PG_DATA = os.path.join(path, "postgres_data")
12
13
if not os.path.exists(PG_DATA):
14
util.cmd("pg_ctl init -D '%s'"%PG_DATA)
15
16
# Lock down authentication so it is ONLY via unix socket
17
open(os.path.join(PG_DATA,'pg_hba.conf'), 'w').write(
18
"""
19
# This is safe since we only enable a socket protected by filesystem permissions:
20
local all all trust
21
22
# You can uncomment this and comment out the above if you want to test password auth.
23
#local all all md5
24
""")
25
26
# Make it so the socket is in this subdirectory, so that it is
27
# protected by UNIX permissions. This approach avoids any need
28
# for accounts/passwords for development and the Docker image.
29
conf = os.path.join(PG_DATA, 'postgresql.conf')
30
s = open(conf).read()
31
s += '\n'
32
33
# Move the default directory where the socket is from /tmp to right here.
34
socket_dir = os.path.join(PG_DATA, 'socket')
35
s += "unix_socket_directories = '%s'\nlisten_addresses=''\n"%socket_dir
36
os.makedirs(socket_dir)
37
util.cmd("chmod og-rwx '%s'"%PG_DATA) # just in case -- be paranoid...
38
open(conf,'w').write(s)
39
40
# Create script so that clients will know where socket dir is.
41
open("postgres-env", 'w').write("""#!/bin/sh
42
export PGUSER='smc'
43
export PGHOST='%s'
44
"""%socket_dir)
45
46
util.cmd('chmod +x postgres-env')
47
48
# Start database running in background as daemon
49
util.cmd("postgres -D '%s' >%s/postgres.log 2>&1 &"%(PG_DATA, PG_DATA))
50
time.sleep(5)
51
52
# Create the smc user with no password (not needed since we are using local file permissions)
53
util.cmd("unset PGUSER; unset PGHOST; createuser -h '%s' -sE smc"%socket_dir)
54
55
# Stop database daemon
56
util.cmd("kill %s"%(open(os.path.join(PG_DATA, 'postmaster.pid')).read().split()[0]))
57
# Let it die and remove lock file.
58
time.sleep(3)
59
60
61
util.cmd("postgres -D '%s'"%PG_DATA)
62
63