|
22 | 22 | import subprocess |
23 | 23 | import sys |
24 | 24 | import tempfile |
| 25 | +import time |
25 | 26 |
|
26 | 27 | # Logging |
27 | 28 | logger = logging.getLogger(__name__) |
|
30 | 31 | with open('/root/accounts.json', 'r', encoding='utf-8') as f: |
31 | 32 | USERS = json.load(f) |
32 | 33 |
|
33 | | -SYSTEMD = True |
34 | | -RUNIT = False |
35 | | - |
36 | 34 | if not len(USERS): |
37 | 35 | logger.info('accounts.json is empty. Using the hardcoded folks.') |
38 | 36 | USERS = { |
|
60 | 58 | # } |
61 | 59 | } |
62 | 60 |
|
63 | | -HOSTNAME = "capistrano" |
64 | | -POSTGRES_HOST = "localhost" |
65 | | -POSTGRES_ROOT_PASSWORD = "root" |
| 61 | +HOSTNAME = os.environ.get("HOSTNAME", "capistrano") |
| 62 | +POSTGRES_HOST = os.environ.get("POSTGRES_HOST", "localhost") |
| 63 | +POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD", "root") |
| 64 | + |
| 65 | +SYSTEMD = "RUNIT" not in os.environ |
| 66 | +RUNIT = "RUNIT" in os.environ |
66 | 67 |
|
67 | 68 |
|
68 | 69 | def pwgen(length=64): |
@@ -278,19 +279,46 @@ def init_user(user, keys, environ): |
278 | 279 | return 0 |
279 | 280 |
|
280 | 281 |
|
| 282 | +def init_postgres(password): |
| 283 | + p = pwd.getpwnam('postgres') |
| 284 | + uid, gid = p.pw_uid, p.pw_gid |
| 285 | + homedir = p.pw_dir |
| 286 | + |
| 287 | + os.initgroups('postgres', gid) |
| 288 | + os.setgid(gid) |
| 289 | + os.setuid(uid) |
| 290 | + os.chdir(homedir) |
| 291 | + |
| 292 | + subprocess.check_call([ |
| 293 | + 'psql', '-c', |
| 294 | + "ALTER USER postgres WITH PASSWORD '{}';".format(password) |
| 295 | + ]) |
| 296 | + |
| 297 | + |
281 | 298 | def main(argv): |
282 | 299 | environ = {} |
283 | 300 | environ["GEM_HOME"] = ".gem/ruby/2.4.0" |
284 | | - environ["POSTGRES_HOST"] = os.environ.get('POSTGRES_HOST', POSTGRES_HOST) |
| 301 | + environ["POSTGRES_HOST"] = POSTGRES_HOST |
285 | 302 | environ["POSTGRES_PORT"] = "5432" |
286 | 303 |
|
287 | 304 | delete = False if len(argv) < 2 else argv[1] == 'DELETE' |
288 | 305 |
|
| 306 | + # Handle a local Postgres setup. |
| 307 | + if POSTGRES_HOST == 'localhost': |
| 308 | + logger.info('init postgres (with 5s of pause)') |
| 309 | + |
| 310 | + # Wait for Postgres |
| 311 | + time.sleep(5) |
| 312 | + p = multiprocessing.Process( |
| 313 | + target=init_postgres, args=(POSTGRES_PASSWORD, )) |
| 314 | + p.start() |
| 315 | + p.join() |
| 316 | + |
289 | 317 | with tempfile.NamedTemporaryFile() as fp: |
290 | 318 | logging.info('create temporary .pgpass') |
291 | 319 | fp.write( |
292 | | - bytearray('{}:*:*:postgres:{}'.format(environ[ |
293 | | - "POSTGRES_HOST"], POSTGRES_ROOT_PASSWORD), 'utf-8')) |
| 320 | + bytearray('{}:*:*:postgres:{}'.format(environ["POSTGRES_HOST"], |
| 321 | + POSTGRES_PASSWORD), 'utf-8')) |
294 | 322 | fp.seek(0) |
295 | 323 | os.chmod(fp.name, mode=0o600) |
296 | 324 | environ['PGPASSFILE'] = fp.name |
|
0 commit comments