Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/smc_pyutil/smc_pyutil/status.py
Views: 285
1
#!/usr/bin/python
2
# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details
4
5
from __future__ import absolute_import, print_function
6
import json, os, time
7
8
REMOTE_TIMEOUT_S = 90
9
SMC = os.environ['SMC']
10
os.chdir(SMC)
11
12
status = {}
13
14
15
def set(prop, val):
16
status[prop] = val
17
18
19
def read(prop, filename, strip=False, int_value=False, to_int=False):
20
try:
21
s = open(filename).read()
22
if strip:
23
s = s.strip()
24
if '.port' in prop:
25
try:
26
s = int(s)
27
except TypeError:
28
pass
29
if int_value:
30
s = int(s.split('=')[1])
31
if to_int:
32
s = int(s)
33
status[prop] = s
34
except:
35
status[prop] = False
36
37
38
def local_status():
39
for [daemon, pidfile] in [['project', 'project.pid'],
40
['sage_server', 'sage_server/sage_server.pid']]:
41
if os.path.exists(pidfile):
42
try:
43
pid = int(open(pidfile).read())
44
os.kill(pid, 0)
45
set(daemon + '.pid', pid)
46
except:
47
set(daemon + '.pid', False)
48
else:
49
set(daemon + '.pid', False)
50
51
for name in [
52
'api-server.port', 'browser-server.port', 'hub-server.port',
53
'secret_token'
54
]:
55
to_int = 'port' in name
56
read(name.split('/')[-1], os.path.join(SMC, name), to_int=to_int)
57
58
59
def remote_status():
60
"""
61
If there is a file ~/.smc/remote that is recent, then this project is assumed
62
to be running "remote compute", so we stop the local hub and output the contents
63
of the file ~/.smc/remote.
64
"""
65
remote = os.path.join(SMC, "remote")
66
if not os.path.exists(remote):
67
return False
68
if time.time() - os.path.getmtime(remote) >= REMOTE_TIMEOUT_S:
69
return False
70
return json.loads(open(remote).read())
71
72
73
def main():
74
s = remote_status()
75
if s:
76
x = s
77
else:
78
local_status()
79
x = status
80
print(json.dumps(x))
81
82
83
if __name__ == "__main__":
84
main()
85
86