Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/dev/project/start_postgres.py
Views: 687
#!/usr/bin/env python31"""2This is a script for starting postgres for development purposes3in an SMC project.4"""56import os, sys, time, util78path = os.path.split(os.path.realpath(__file__))[0]9os.chdir(path)10sys.path.insert(0, path)1112PG_DATA = os.path.abspath(os.path.join(path, "../../data/postgres"))13PGHOST = os.environ.get("PGHOST", "")1415if not os.path.exists(PG_DATA):16util.cmd("pg_ctl init -D '%s'" % PG_DATA)1718# Lock down authentication so it is ONLY via unix socket19open(os.path.join(PG_DATA, 'pg_hba.conf'), 'w').write("""20# This is safe since we only enable a socket protected by file system permissions:21local all all trust2223# You can uncomment this and comment out the above if you want to test password auth.24#local all all md525""")2627conf = os.path.join(PG_DATA, 'postgresql.conf')28s = open(conf).read()29s += '\n'3031# The very first time running this script, if PGHOST is NOT set, we do the32# following (we want to allow users to override this via setting PGHOST33# the first time, since this approach sucks in some situations):34# Make it so the socket is in this subdirectory, so that it is35# protected by UNIX permissions. This approach avoids any need36# for accounts/passwords for development and the Docker image.37# Move the default directory where the socket is from /tmp to right here.38if PGHOST:39socket_dir = PGHOST40else:41socket_dir = os.path.join(PG_DATA, 'socket')42# Increase max connections since in dev mode nextjs is constantly restarting causing lots of hanging connections (TODO)43s += "unix_socket_directories = '%s'\nlisten_addresses=''\nmax_connections=1000\n" % socket_dir44if not os.path.exists(socket_dir):45os.makedirs(socket_dir)46util.cmd("chmod og-rwx '%s'" % PG_DATA) # just in case -- be paranoid...47open(conf, 'w').write(s)4849# Create script so that clients will know where socket dir is.50open("postgres-env", 'w').write("""#!/bin/sh51export PGUSER='smc'52export PGHOST='%s'53""" % socket_dir)5455util.cmd('chmod +x postgres-env')5657# Start database running in background as daemon58util.cmd("postgres -D '%s' >%s/postgres.log 2>&1 &" % (PG_DATA, PG_DATA))59time.sleep(5)6061# Create the smc user with no password (not needed since we are using local file permissions)62util.cmd("unset PGUSER; unset PGHOST; createuser -h '%s' -sE smc" %63socket_dir)6465# Stop database daemon66util.cmd("kill %s" %67(open(os.path.join(PG_DATA, 'postmaster.pid')).read().split()[0]))68# Let it die and remove lock file.69time.sleep(3)7071util.cmd("postgres -D '%s'" % PG_DATA)727374