Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/dev/project/util.py
Views: 286
1
from __future__ import print_function
2
3
import os, json, socket, subprocess
4
5
join = os.path.join
6
7
8
def cmd(s):
9
print(s)
10
if subprocess.check_call(["bash", "-c", s]):
11
raise RuntimeError
12
13
14
def chdir():
15
os.chdir(os.path.split(os.path.abspath(__file__))[0])
16
17
18
def base_url(port=None, write=True):
19
print("base_url(port=%s)" % port)
20
try:
21
project_id = os.environ['COCALC_PROJECT_ID']
22
except KeyError:
23
raise RuntimeError(
24
"COCALC_PROJECT_ID environment variable not found. You can only use dev/project to run CoCalc from inside of a CoCalc project."
25
)
26
if port is None and write:
27
write_base_url = True
28
port = get_ports()['hub']
29
else:
30
write_base_url = False
31
base_url = "/{project_id}/port/{port}".format(
32
project_id=project_id, port=port)
33
if write_base_url:
34
open("../../data/base_url", 'w').write(base_url)
35
return base_url
36
37
38
# http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python
39
def get_open_port():
40
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41
s.bind(("", 0))
42
s.listen(1)
43
port = s.getsockname()[1]
44
s.close()
45
return port
46
47
48
def get_ports():
49
P = os.path.split(os.path.abspath(__file__))[0]
50
path = join(P, 'ports')
51
if not os.path.exists(path):
52
os.mkdir(path)
53
ports = {'hub': 0, 'hub-api': 0, 'hub-share': 0, 'hub-share-2': 0, 'agent-port': 0}
54
for x in ports.keys():
55
file = join(path, x)
56
if os.path.exists(file):
57
ports[x] = int(open(file).read())
58
else:
59
ports[x] = get_open_port()
60
open(file, 'w').write(str(ports[x]))
61
return ports
62
63
64
def test():
65
import sys
66
if len(sys.argv) >= 2 and sys.argv[1] == 'test':
67
return '--test'
68
else:
69
return ''
70
71