-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtiny_process_manager
More file actions
executable file
·280 lines (233 loc) · 7.64 KB
/
tiny_process_manager
File metadata and controls
executable file
·280 lines (233 loc) · 7.64 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#! /usr/bin/env python3
"""Provides a simple process manager with a simple http GET interface.
See `--help` for information on the options when running the manager.
The server provides a GET interface with the following endpoints
- /start/{name_of_service} -- Start a service
- /services -- List available services
- /stop/{name_of_service} -- Stop a running services
- /list -- List laumnched services
- /status/{name_of_service} -- Get information on a running service
The services are defined in a configuration json file,
which contains a single json list of the form:
[
{name: "servicename",
command: "command",
env: {"VAR1" : VAL1}}
]
"""
import argparse
import json
import logging
import os
import shlex
import signal
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path, PosixPath
from urllib.parse import parse_qsl, urlparse
logger = logging.getLogger(__name__)
try:
from systemd.journal import JournalHandler
logger.addHandler(JournalHandler())
logger.setLevel(logging.INFO)
except ImportError:
pass
class Process:
def __init__(self, name, command, env=None):
self.name = name
self.command = command
self.env = env or {}
self.process = None
self.launched = False
def start(self):
if self.running:
raise RuntimeError("Cannot start already running process")
new_env = os.environ.copy()
new_env.update(self.env)
self.process = subprocess.Popen(self.command, shell=True, env=self.env, preexec_fn=os.setsid)
self.launched = True
def stop(self):
if not self.running:
raise RuntimeError("Cannot stop dead process")
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
self.launched = False
@property
def running(self):
if not self.launched:
return False
else:
return self.process.poll() is None
@property
def pid(self):
if self.running:
return self.process.pid
else:
return None
def protect(func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return {
"result": "ERROR",
"reason": "Exception thrown",
"exception": str(e),
}
return inner
class Service:
def __init__(self, name, command, env=None):
self.name = name
self.command = command
self.env = env or {}
def toDict(self):
return dict(name=self.name, command=self.command, env=self.env)
class Manager:
def __init__(self):
self.running = False
self.processes = {}
self.services = {}
self.command_dispatch = {
"start": self.start_process,
"stop": self.stop_process,
"status": self.status,
"services": self.list_services,
"list": self.list_processes,
}
def start_process(self, name):
if name not in self.services:
return {
"result": "ERROR",
"reason": f"Unknown service '{name}'",
}
service = self.services[name]
p = Process(service.name, service.command, service.env)
p.start()
if name in self.processes and self.processes[name].running:
return {
"result": "ERROR",
"reason": f"Process with name {name} is already running.",
}
if p.running:
self.processes[name] = p
return {"result": "OK", "pid": p.pid}
else:
return {
"result": "ERROR",
"reason": f"Process launched but is not running",
}
def list_processes(self):
l = {
n: {"pid": p.pid, "is_running": p.running}
for n, p in self.processes.items()
}
return {"result": "OK", "data": l}
def list_services(self):
return {"result": "OK", "data": [x.toDict() for x in self.services.values()]}
def stop_process(self, name):
if not name in self.processes:
return {
"result": "ERROR",
"reason": f"No process {name}",
}
p = self.processes[name]
if not p.running:
return {
"result": "ERROR",
"reason": f"Process {name} is not currently running",
}
p.stop()
if not p.running:
del self.processes[name]
return {"result": "OK", "name": name}
else:
return {
"result": "ERROR",
"reason": f"Process killed but still running",
}
def status(self, name):
if not name in self.processes:
return {
"result": "ERROR",
"reason": f"No process {name}",
}
p = self.processes[name]
return {"result": "OK", "name": name, "pid": p.pid, "is_running": p.running}
@protect
def processCommand(self, command, *args, **kwargs):
if command in self.command_dispatch:
resp = self.command_dispatch[command](*args, **kwargs)
else:
resp = {"result": "ERROR", "reason": f"Unknown command '{command}'"}
return resp
def addServices(self, data):
for serv in data:
s = Service(serv["name"], serv["command"], serv.get("env", None))
self.services[s.name] = s
def loadServices(self, path=None):
if path is None:
path = os.environ.get("PM_CONFIG", None)
if path is None:
path = "/etc/TinyProcessManager/commands.json"
path = Path(path)
try:
with open(path, "r") as f:
d = json.load(f)
self.addServices(d)
except OSError:
logger.info(f"Failed to load services from path '{path}'")
def cleanup(self):
for name, process in self.processes.items():
if process.running:
process.stop()
class ProcessManagmentHandler(BaseHTTPRequestHandler):
manager = None
@property
def url(self):
return urlparse(self.path)
@property
def query_data(self):
return dict(parse_qsl(self.url.query))
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write((json.dumps(self.get_response()) + "\n").encode("utf-8"))
def get_response(self):
path = PosixPath(self.url.path)
parts = path.parts
if len(parts) < 2:
return {"result": "ERROR", "reason": "Must provide a command"}
return m.processCommand(parts[1], *parts[2:])
def parseArgs():
parser = argparse.ArgumentParser(
prog="ProcessManager",
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"-c",
"--config",
default=os.environ.get("PM_CONFIG", None),
help="Path to configuration file, default to $PM_CONFIG",
)
parser.add_argument(
"-p",
"--port",
default=8888,
type=int,
help="Port on which to run the http server",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
m = Manager()
args = parseArgs()
m.loadServices(args.config)
ProcessManagmentHandler.manager = m
server = HTTPServer(("0.0.0.0", args.port), ProcessManagmentHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
m.cleanup()