CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/dev/project/start_postgres.py
Views: 687
1
#!/usr/bin/env python3
2
"""
3
This is a script for starting postgres for development purposes
4
in an SMC project.
5
"""
6
7
import os, sys, time, util
8
9
path = os.path.split(os.path.realpath(__file__))[0]
10
os.chdir(path)
11
sys.path.insert(0, path)
12
13
PG_DATA = os.path.abspath(os.path.join(path, "../../data/postgres"))
14
PGHOST = os.environ.get("PGHOST", "")
15
16
if not os.path.exists(PG_DATA):
17
util.cmd("pg_ctl init -D '%s'" % PG_DATA)
18
19
# Lock down authentication so it is ONLY via unix socket
20
open(os.path.join(PG_DATA, 'pg_hba.conf'), 'w').write("""
21
# This is safe since we only enable a socket protected by file system permissions:
22
local all all trust
23
24
# You can uncomment this and comment out the above if you want to test password auth.
25
#local all all md5
26
""")
27
28
conf = os.path.join(PG_DATA, 'postgresql.conf')
29
s = open(conf).read()
30
s += '\n'
31
32
# The very first time running this script, if PGHOST is NOT set, we do the
33
# following (we want to allow users to override this via setting PGHOST
34
# the first time, since this approach sucks in some situations):
35
# Make it so the socket is in this subdirectory, so that it is
36
# protected by UNIX permissions. This approach avoids any need
37
# for accounts/passwords for development and the Docker image.
38
# Move the default directory where the socket is from /tmp to right here.
39
if PGHOST:
40
socket_dir = PGHOST
41
else:
42
socket_dir = os.path.join(PG_DATA, 'socket')
43
# Increase max connections since in dev mode nextjs is constantly restarting causing lots of hanging connections (TODO)
44
s += "unix_socket_directories = '%s'\nlisten_addresses=''\nmax_connections=1000\n" % socket_dir
45
if not os.path.exists(socket_dir):
46
os.makedirs(socket_dir)
47
util.cmd("chmod og-rwx '%s'" % PG_DATA) # just in case -- be paranoid...
48
open(conf, 'w').write(s)
49
50
# Create script so that clients will know where socket dir is.
51
open("postgres-env", 'w').write("""#!/bin/sh
52
export PGUSER='smc'
53
export PGHOST='%s'
54
""" % socket_dir)
55
56
util.cmd('chmod +x postgres-env')
57
58
# Start database running in background as daemon
59
util.cmd("postgres -D '%s' >%s/postgres.log 2>&1 &" % (PG_DATA, PG_DATA))
60
time.sleep(5)
61
62
# Create the smc user with no password (not needed since we are using local file permissions)
63
util.cmd("unset PGUSER; unset PGHOST; createuser -h '%s' -sE smc" %
64
socket_dir)
65
66
# Stop database daemon
67
util.cmd("kill %s" %
68
(open(os.path.join(PG_DATA, 'postmaster.pid')).read().split()[0]))
69
# Let it die and remove lock file.
70
time.sleep(3)
71
72
util.cmd("postgres -D '%s'" % PG_DATA)
73
74