-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_manager.py
More file actions
323 lines (285 loc) · 8.37 KB
/
Copy pathservice_manager.py
File metadata and controls
323 lines (285 loc) · 8.37 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
from __future__ import annotations
import subprocess
from dataclasses import dataclass, field
import privileged
import service_assets
SERVICE_CATALOG = [
{
"key": "apache",
"label": "Apache",
"candidates": ["apache2", "httpd"],
"ports": [80, 443],
},
{
"key": "nginx",
"label": "Nginx",
"candidates": ["nginx"],
"ports": [80, 443],
},
{
"key": "mysql",
"label": "MySQL",
"candidates": ["mysql", "mysqld"],
"ports": [3306],
},
{
"key": "mariadb",
"label": "MariaDB",
"candidates": ["mariadb"],
"ports": [3306],
},
{
"key": "postgresql",
"label": "PostgreSQL",
"candidates": ["postgresql"],
"ports": [5432],
"prefix_fallback": "postgresql",
},
{
"key": "redis",
"label": "Redis",
"candidates": ["redis", "redis-server"],
"ports": [6379],
},
{
"key": "mongodb",
"label": "MongoDB",
"candidates": ["mongod", "mongodb"],
"ports": [27017],
},
{
"key": "php",
"label": "PHP",
"candidates": [],
"ports": [],
"detect": "php",
},
{
"key": "phpmyadmin",
"label": "phpMyAdmin",
"candidates": [],
"ports": [80],
"detect": "phpmyadmin",
},
]
_unit_cache: set[str] | None = None
_pending_units: dict[str, subprocess.Popen] = {}
@dataclass
class ServiceInfo:
key: str
label: str
unit: str
ports: list[int] = field(default_factory=list)
state: str = "unknown"
main_pid: int = 0
available: bool = True
sub_state: str = ""
controllable: bool = True
def _run_command(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
capture_output=True,
text=True,
check=False,
)
def _normalize_unit_name(name: str) -> str:
return name.removesuffix(".service")
def _load_unit_cache() -> set[str]:
global _unit_cache
if _unit_cache is not None:
return _unit_cache
result = _run_command(
[
"systemctl",
"list-unit-files",
"--type=service",
"--no-pager",
"--no-legend",
]
)
units: set[str] = set()
for line in result.stdout.splitlines():
parts = line.split()
if parts:
units.add(_normalize_unit_name(parts[0]))
_unit_cache = units
return units
def _resolve_unit(entry: dict) -> str | None:
units = _load_unit_cache()
for candidate in entry["candidates"]:
if candidate in units:
return candidate
prefix = entry.get("prefix_fallback")
if prefix:
matches = sorted(
name for name in units if name.startswith(prefix) and "@" not in name
)
if matches:
return matches[0]
return None
def _parse_show_output(stdout: str) -> tuple[str, int, str]:
state = "unknown"
main_pid = 0
sub_state = ""
for line in stdout.splitlines():
if line.startswith("ActiveState="):
state = line.split("=", 1)[1].strip()
elif line.startswith("MainPID="):
try:
main_pid = int(line.split("=", 1)[1].strip())
except ValueError:
main_pid = 0
elif line.startswith("SubState="):
sub_state = line.split("=", 1)[1].strip()
return state, main_pid, sub_state
def get_service_state(unit: str, key: str = "", label: str = "", ports: list[int] | None = None) -> ServiceInfo:
active_result = _run_command(["systemctl", "is-active", unit])
active_state = active_result.stdout.strip() or "unknown"
show_result = _run_command(
[
"systemctl",
"show",
unit,
"--property=MainPID,ActiveState,SubState",
]
)
show_state, main_pid, sub_state = _parse_show_output(show_result.stdout)
state = show_state if show_state != "unknown" else active_state
return ServiceInfo(
key=key or unit,
label=label or unit,
unit=unit,
ports=ports or [],
state=state,
main_pid=main_pid,
available=True,
sub_state=sub_state,
)
def _apache_is_active() -> bool:
for candidate in ("apache2", "httpd"):
result = _run_command(["systemctl", "is-active", candidate])
if result.stdout.strip() == "active":
return True
return False
def _detect_local_entry(entry: dict) -> ServiceInfo | None:
detect = entry.get("detect")
if detect == "php":
if not service_assets.php_is_installed():
return None
assets = service_assets.get_assets("php")
if not assets.configs:
return None
return ServiceInfo(
key=entry["key"],
label=entry["label"],
unit="",
ports=list(entry["ports"]),
state="active",
main_pid=0,
available=True,
controllable=False,
)
if detect == "phpmyadmin":
if not service_assets.phpmyadmin_is_installed():
return None
state = "active" if _apache_is_active() else "inactive"
return ServiceInfo(
key=entry["key"],
label=entry["label"],
unit="",
ports=list(entry["ports"]),
state=state,
main_pid=0,
available=True,
controllable=False,
)
return None
def _catalog_entry(entry: dict, unit: str | None) -> ServiceInfo:
local = _detect_local_entry(entry)
if local is not None:
return local
if entry.get("detect") and unit is None:
return ServiceInfo(
key=entry["key"],
label=entry["label"],
unit="",
ports=list(entry["ports"]),
state="missing",
main_pid=0,
available=False,
controllable=False,
)
if unit is None:
return ServiceInfo(
key=entry["key"],
label=entry["label"],
unit="",
ports=list(entry["ports"]),
state="missing",
main_pid=0,
available=False,
controllable=False,
)
info = get_service_state(
unit,
key=entry["key"],
label=entry["label"],
ports=list(entry["ports"]),
)
info.controllable = True
return info
def discover_services() -> list[ServiceInfo]:
services: list[ServiceInfo] = []
for entry in SERVICE_CATALOG:
unit = _resolve_unit(entry)
if unit is None:
continue
services.append(_catalog_entry(entry, unit))
return services
def list_catalog_services() -> list[ServiceInfo]:
services: list[ServiceInfo] = []
for entry in SERVICE_CATALOG:
unit = _resolve_unit(entry)
services.append(_catalog_entry(entry, unit))
return services
def refresh_all(services: list[ServiceInfo]) -> list[ServiceInfo]:
refreshed: list[ServiceInfo] = []
for service in services:
if service.key == "phpmyadmin" and service.available:
service.state = "active" if _apache_is_active() else "inactive"
refreshed.append(service)
continue
if not service.available or not service.unit:
refreshed.append(service)
continue
updated = get_service_state(
service.unit,
key=service.key,
label=service.label,
ports=service.ports,
)
updated.controllable = True
refreshed.append(updated)
return refreshed
def is_action_pending(unit: str) -> bool:
process = _pending_units.get(unit)
if process is None:
return False
if process.poll() is None:
return True
_pending_units.pop(unit, None)
return False
def run_service_action(unit: str, action: str) -> subprocess.Popen:
if action not in {"start", "stop", "restart"}:
raise ValueError(action)
existing = _pending_units.get(unit)
if existing is not None and existing.poll() is None:
return existing
process = privileged.popen(["systemctl", action, unit])
_pending_units[unit] = process
return process
def clear_pending(unit: str) -> None:
_pending_units.pop(unit, None)
def invalidate_unit_cache() -> None:
global _unit_cache
_unit_cache = None