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