0
|
1 from starlette.applications import Starlette
|
|
2 from starlette.exceptions import HTTPException
|
|
3 from starlette.requests import Request
|
|
4 from starlette.responses import JSONResponse, HTMLResponse
|
|
5 from starlette.staticfiles import StaticFiles
|
|
6 from starlette.routing import Route, Mount
|
|
7 from starlette.templating import Jinja2Templates
|
|
8 import uvicorn
|
|
9 import psutil
|
|
10 from starlette_exporter import PrometheusMiddleware, handle_metrics
|
|
11 from prometheus_client import Summary, Gauge
|
|
12 import background_loop
|
|
13 from typing import List, Optional
|
|
14 import logging
|
|
15 import socket
|
|
16 import sys
|
|
17 if sys.implementation._multiarch == 'darwin':
|
|
18 import idle_osx as idle
|
1
|
19 import volume_osx as volume
|
0
|
20 elif 'linux' in sys.implementation._multiarch:
|
|
21 import idle_linux as idle
|
1
|
22 import volume_linux as volume
|
0
|
23 else:
|
|
24 raise NotImplementedError(repr(sys.implementation))
|
|
25
|
|
26 hostname = socket.gethostname().split('.')[0]
|
|
27 logging.basicConfig(level=logging.INFO)
|
|
28 log = logging.getLogger()
|
|
29
|
|
30
|
|
31 def progname(cmdline: List[str]) -> Optional[str]:
|
|
32 if len(cmdline) < 1:
|
|
33 return None
|
|
34 if cmdline[-1].endswith('/steam'):
|
|
35 return 'steam'
|
|
36 if cmdline[0].endswith('/minecraft-launcher'):
|
|
37 return 'minecraft-launcher'
|
|
38 if cmdline[0].endswith('/java') and '--versionType' in cmdline:
|
|
39 return 'minecraft'
|
|
40
|
|
41
|
|
42 RACC_RUNNING = Gauge("racc_running", "program is running", ['host', 'prog'])
|
|
43 RACC_IDLE = Gauge("racc_idle", "desktop mouse/kb idle seconds", ['host'])
|
|
44
|
|
45
|
|
46 def update_progs(first_run):
|
|
47 out = []
|
|
48 progs = set()
|
|
49 for proc in psutil.process_iter(['pid', 'name']):
|
|
50 try:
|
|
51 prog = progname(proc.cmdline())
|
|
52 if prog:
|
|
53 progs.add(prog)
|
|
54 except (psutil.AccessDenied, psutil.NoSuchProcess):
|
|
55 pass
|
|
56
|
|
57 for p in [
|
|
58 'minecraft',
|
|
59 'minecraft-launcher',
|
|
60 'steam',
|
|
61 ]:
|
|
62 RACC_RUNNING.labels(host=hostname, prog=p).set(p in progs)
|
|
63 RACC_IDLE.labels(host=hostname).set(idle.get_idle_seconds())
|
|
64
|
|
65
|
1
|
66 async def root(req: Request) -> HTMLResponse:
|
|
67 vol = await volume.get_volume()
|
|
68 return HTMLResponse(f'''controls for {hostname} whose volume is {vol}''')
|
0
|
69
|
|
70
|
|
71 def main():
|
|
72 app = Starlette(debug=True,
|
|
73 routes=[
|
|
74 Route('/', root),
|
|
75 ],
|
|
76 on_startup=[
|
|
77 lambda: background_loop.loop_forever(update_progs, 3),
|
|
78 ])
|
|
79
|
|
80 app.add_middleware(PrometheusMiddleware, app_name='racc')
|
|
81 app.add_route("/metrics", handle_metrics)
|
|
82 return app
|
|
83
|
|
84
|
|
85 if __name__ == "__main__":
|
|
86 uvicorn.run(main(), host='0.0.0.0', port=5150)
|