Path: blob/master/src/smc_pyutil/smc_pyutil/status.py
Views: 285
#!/usr/bin/python1# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details34from __future__ import absolute_import, print_function5import json, os, time67REMOTE_TIMEOUT_S = 908SMC = os.environ['SMC']9os.chdir(SMC)1011status = {}121314def set(prop, val):15status[prop] = val161718def read(prop, filename, strip=False, int_value=False, to_int=False):19try:20s = open(filename).read()21if strip:22s = s.strip()23if '.port' in prop:24try:25s = int(s)26except TypeError:27pass28if int_value:29s = int(s.split('=')[1])30if to_int:31s = int(s)32status[prop] = s33except:34status[prop] = False353637def local_status():38for [daemon, pidfile] in [['project', 'project.pid'],39['sage_server', 'sage_server/sage_server.pid']]:40if os.path.exists(pidfile):41try:42pid = int(open(pidfile).read())43os.kill(pid, 0)44set(daemon + '.pid', pid)45except:46set(daemon + '.pid', False)47else:48set(daemon + '.pid', False)4950for name in [51'api-server.port', 'browser-server.port', 'hub-server.port',52'secret_token'53]:54to_int = 'port' in name55read(name.split('/')[-1], os.path.join(SMC, name), to_int=to_int)565758def remote_status():59"""60If there is a file ~/.smc/remote that is recent, then this project is assumed61to be running "remote compute", so we stop the local hub and output the contents62of the file ~/.smc/remote.63"""64remote = os.path.join(SMC, "remote")65if not os.path.exists(remote):66return False67if time.time() - os.path.getmtime(remote) >= REMOTE_TIMEOUT_S:68return False69return json.loads(open(remote).read())707172def main():73s = remote_status()74if s:75x = s76else:77local_status()78x = status79print(json.dumps(x))808182if __name__ == "__main__":83main()848586