forked from nebulabroadcast/nebula-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manage
executable file
·93 lines (75 loc) · 2.41 KB
/
manage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
import os
import socket
import sys
import time
from nxtools import xml
import nebula
orig_dir = os.getcwd()
if orig_dir != "/opt/nebula":
os.chdir("/opt/nebula")
nebula.log.user = "manage"
def run_service(service):
while True:
try:
service.on_main()
last_run = time.time()
while True:
time.sleep(min(loop_delay, 2))
service.heartbeat()
if time.time() - last_run >= loop_delay:
break
except (KeyboardInterrupt):
nebula.log.warning("Keyboard interrupt")
break
except (SystemExit):
break
except Exception:
nebula.log.traceback()
time.sleep(2)
sys.exit(1)
try:
if sys.argv[1] == "once":
break
except IndexError:
pass
if __name__ == "__main__":
if len(sys.argv) < 3:
nebula.log.critical("Usage: ./manage run {id_service}")
command = os.path.basename(sys.argv[1])
subcommand = sys.argv[2] if len(sys.argv) > 1 else None
if not (command == "run" and subcommand and subcommand.isdigit()):
nebula.log.critical("Usage: ./manage.py run <service_id>")
try:
id_service = int(subcommand)
except ValueError:
nebula.log.critical("Service ID must be integer")
db = nebula.DB()
db.query(
"""
SELECT service_type, title, host, loop_delay, settings
FROM services WHERE id=%s
""",
[id_service],
)
try:
agent, title, host, loop_delay, settings = db.fetchall()[0]
except IndexError:
nebula.log.critical(f"Unable to start service {id_service}. No such service")
if host != socket.gethostname():
nebula.log.critical("This service should not run here.")
if settings:
try:
settings = xml(settings)
except Exception:
nebula.log.traceback()
nebula.log.error("Malformed settings XML:\n", settings)
db.query("UPDATE services SET autostart=0 WHERE id=%s", [id_service])
db.commit()
nebula.log.critical("Unable to start service")
nebula.log.user = title
_module = __import__("services." + agent, globals(), locals(), ["Service"])
Service = _module.Service
service = Service(id_service, settings)
run_service(service)
os.chdir(orig_dir)