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/smc/conf/cloud.sagemath.com/gen_conf.py
Views: 687
1
#!/usr/bin/env python2
2
"""
3
Determine which hosts web[n] exist, i.e., for which DNS resolves web[n], for n=0,1,2, etc.
4
5
Then read the file 'haproxy.cfg.template' and make an uncommented copy of all the web0 lines
6
but for all the web[n] hosts that exist.
7
8
(c) William Stein, 2016
9
"""
10
import sys
11
import os
12
13
# EXCLUDE=['web6']
14
EXCLUDE = []
15
16
17
def host_exists(hostname):
18
"""
19
Return true if and only if hostname resolves and is pingable.
20
"""
21
return os.system("ping -c 1 -W 1 '%s' 2>/dev/null 1>/dev/null" % hostname) == 0
22
23
24
def web_hosts_2(bound=9):
25
import subprocess as sp
26
import json
27
cmd = sp.Popen(
28
"gcloud compute instances list --filter='name ~ ^web' --format=json",
29
shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
30
webs, err = cmd.communicate()
31
try:
32
webs = json.loads(webs)
33
assert len(webs) >= 3
34
except Exception as e:
35
print("ERROR, fallback -- %s" % e)
36
webs = ["web%s" % n for n in range(bound)]
37
# maybe filter additionally on something?
38
names = [w['name'] for w in webs if w['status'] == "RUNNING"]
39
return [name for name in names if name not in EXCLUDE]
40
41
42
def web_hosts(bound=20):
43
"""
44
Return all web hosts of the form web[n] that exists for n<bound.
45
"""
46
v = ["web%s" % n for n in range(bound) if host_exists("web%s" % n)]
47
return [x for x in v if x not in EXCLUDE]
48
49
50
def gen_haproxy(x=''):
51
if not x:
52
hosts = web_hosts()
53
else:
54
hosts = [x]
55
v = []
56
for x in open('haproxy.cfg.template').xreadlines():
57
if 'web0' in x:
58
# generate version of x with leading # deleted and web0 replaced by
59
# each web hostname
60
i = x.find('#')
61
t = x[:i] + x[i + 1:]
62
for h in hosts:
63
n = h[3:]
64
v.append(t.replace('web0', h).replace('nginx0', 'nginx' + n)
65
.replace('proxy0', 'proxy' + n).replace('hub0', 'hub' + n))
66
else:
67
v.append(x)
68
# write out our new haproxy config file
69
open('haproxy.cfg', 'w').write(''.join(v))
70
71
if __name__ == "__main__":
72
if len(sys.argv) == 1:
73
gen_haproxy()
74
else:
75
gen_haproxy(sys.argv[1])
76
77