grasp/server/setup

72 lines
2 KiB
Plaintext
Raw Normal View History

2019-01-05 06:44:36 -08:00
#!/usr/bin/env python3
2019-01-07 14:53:08 -08:00
import argparse
import shlex
2019-01-05 06:44:36 -08:00
from pathlib import Path
from subprocess import check_call, run
2019-01-05 06:44:36 -08:00
from grasp_server import setup_parser
2019-01-05 06:44:36 -08:00
2019-01-07 14:53:08 -08:00
SYSTEMD_CONFIG = """
2019-01-05 06:44:36 -08:00
[Unit]
Description=Grasp extension server conterpart
[Install]
WantedBy=default.target
[Service]
2019-01-07 14:53:08 -08:00
ExecStart={server} {extra_args}
2019-01-05 06:44:36 -08:00
Type=simple
Restart=always
"""
def systemd(*args, method=check_call):
method([
2019-01-05 06:44:36 -08:00
'systemctl', '--user', *args,
])
2019-01-07 14:53:08 -08:00
def setup(args):
base_path = '~/.config/systemd/user'
if not Path(base_path).expanduser().is_dir():
Path(base_path).expanduser().mkdir(parents=True, exist_ok=True)
2019-01-07 14:53:08 -08:00
unit_name = args.unit_name
out = Path(f'{base_path}/{unit_name}').expanduser()
2019-01-07 14:53:08 -08:00
print(f"Writing systemd config to {out}:")
server_bin = Path(__file__).parent.joinpath('grasp_server.py').absolute()
2019-01-13 07:34:13 -08:00
template = args.template.replace('%', '%%').replace('\n', r'\n') # escape for systemd...
2020-04-12 07:56:24 -07:00
args = [
'--port', args.port,
'--path', args.path,
'--template', template,
2020-04-12 08:39:45 -07:00
*([] if args.config is None else ['--config' , args.config]),
2020-04-12 07:56:24 -07:00
]
extra_args = ' '.join(map(shlex.quote, args))
2019-01-07 14:53:08 -08:00
with out.open('w') as fo:
fo.write(SYSTEMD_CONFIG.format(
server=server_bin,
extra_args=extra_args,
))
try:
systemd('stop' , unit_name, method=run) # ignore errors here if it wasn't running in the first place
2019-01-07 14:53:08 -08:00
systemd('daemon-reload')
systemd('enable', unit_name)
systemd('start' , unit_name)
systemd('status', unit_name)
except Exception as e:
print(f"Something has gone wrong... you might want to use 'journalctl --user -u {unit_name}' to debug")
raise e
def main():
2019-01-13 07:34:13 -08:00
p = argparse.ArgumentParser('grasp server setup', formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, width=100)) # type: ignore
2019-01-07 14:53:08 -08:00
p.add_argument('--unit-name', type=str, default='grasp.service', help='Systemd unit name')
setup_parser(p)
args = p.parse_args()
setup(args)
if __name__ == '__main__':
main()