This repository has been archived by the owner on Oct 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
process.py
273 lines (231 loc) · 8.86 KB
/
process.py
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
import asyncio
import mimetypes
import os
import re
import shutil
import subprocess
import threading
import time
from base64 import b64encode
from itertools import count
from pathlib import Path
from typing import Any, Awaitable, Callable, Optional, TypeVar
import psutil
from nonebot.utils import escape_tag, run_sync
from ..exceptions import ProcessAlreadyStarted
from ..log import LogStorage as BaseLogStorage
from ..log import logger
from ..plugin_config import AccountConfig
from ..plugin_config import config as plugin_config
from .config import AccountConfigHelper, AccountDeviceHelper, SessionTokenHelper
from .download import ACCOUNTS_DATA_PATH, BINARY_PATH
from .models import (
ProcessInfo,
ProcessLog,
ProcessStatus,
RunningProcessDetail,
StoppedProcessDetail,
)
LOG_REGEX = re.compile(
r"^"
r"\[(?P<time>\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] "
r"\[(?P<level>[A-Z]+?)\]: "
r"(?P<message>.*)"
r"$"
)
STARTUP_FINISH_PROMPT = "アトリは、高性能ですから!"
LogListener = Callable[[ProcessLog], Awaitable[Any]]
LogListener_T = TypeVar("LogListener_T", bound=LogListener)
class LogStorage(BaseLogStorage[ProcessLog]):
pass
class GoCQProcess:
process: Optional[subprocess.Popen] = None
worker_thread: Optional[threading.Thread] = None
worker_thread_running = False
def __init__(
self,
account: AccountConfig,
predefined: bool = False,
/,
kill_timeout: float = 5,
stop_timeout: float = 6,
max_restarts: int = -1,
restart_interval: float = 3,
print_process_log: bool = True,
log_rotation: float = 5 * 60,
post_delay: float = 3,
):
self.cwd = (ACCOUNTS_DATA_PATH / str(account.uin)).absolute()
self.cwd.mkdir(parents=True, exist_ok=True)
self.config = AccountConfigHelper(account)
if not self.config.exists:
self.config.generate()
self.device = AccountDeviceHelper(account)
if not self.device.exists:
self.device.generate()
self.session = SessionTokenHelper(account)
self.account, self.predefined = account, predefined
self.loop = asyncio.get_running_loop()
self.stop_timeout, self.kill_timeout = stop_timeout, kill_timeout
self.max_restarts, self.restart_interval = max_restarts, restart_interval
self.post_delay = post_delay
self.logs, self.restart_count = LogStorage(log_rotation), 0
async def process_log(log: ProcessLog):
logger.log(
log.level.name,
f"<d>[{self.account.uin}]</d> {escape_tag(log.message)}",
)
if print_process_log:
self.logs.listeners.add(process_log)
from .manager import ProcessesManager
ProcessesManager.add(self, account.uin)
def __repr__(self):
return f"<{type(self).__name__} {self.account} process={self.process}>"
@staticmethod
def _terminate_process(process: subprocess.Popen, *, timeout: float):
process.terminate()
try:
return process.wait(timeout)
except subprocess.TimeoutExpired:
process.kill()
def _process_executor(self) -> int:
executable_path = BINARY_PATH
if plugin_config.PROCESS_EXECUTABLE == "@PATH" and (
exec_file := shutil.which(BINARY_PATH.name)
):
executable_path = Path(exec_file)
elif isinstance(plugin_config.PROCESS_EXECUTABLE, Path):
executable_path = plugin_config.PROCESS_EXECUTABLE
self.process = subprocess.Popen(
[executable_path.absolute(), "-faststart", "-update-protocol"],
cwd=self.cwd.absolute(),
env={
**os.environ,
"FORCE_TTY": "true",
}, # see: https://github.com/ifrstr/isatty#using-force_tty
text=False, # fix possible encoding error, see: #341
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
assert self.process.stdout and self.process.stdin
for output in iter(self.process.stdout.readline, b""):
output = output.strip().decode("utf-8", "replace")
if STARTUP_FINISH_PROMPT in output:
logger.success(
"go-cqhttp for "
f"<e>{self.account.uin}</e> has successfully started."
)
log_matched = LOG_REGEX.match(output)
log_model = (
ProcessLog.parse_obj(log_matched.groupdict())
if log_matched
else ProcessLog(message=output)
)
asyncio.run_coroutine_threadsafe(self.logs.add(log_model), loop=self.loop)
if self.process.poll() is None:
self._terminate_process(self.process, timeout=self.post_delay)
return self.process.returncode
def _process_worker(self):
for restarted in count():
if not self.worker_thread_running:
break
if self.max_restarts >= 0 and restarted >= self.max_restarts:
break
code = None
try:
code = self._process_executor()
except Exception:
logger.exception(
f"Thread {self.worker_thread!r} raised unknown exception:"
)
logger.warning(
f"<b>Process for <e>{self.account.uin}</e> exited</b> "
f"with code <r>{code}</r>, retrying to restart... "
f"<y>({restarted}/{self.max_restarts})</y>"
)
self.restart_count += 1
time.sleep(self.restart_interval)
async def _find_duplicate_process(self):
for process in psutil.process_iter():
try:
with process.oneshot():
pid = process.pid
cwd = Path(process.cwd()).absolute()
exe = Path(process.exe()).absolute()
except psutil.Error:
continue
if not (exe.is_file() and cwd.is_dir()):
continue
if BINARY_PATH.absolute().samefile(exe) and self.cwd.samefile(cwd):
process.terminate()
yield pid
return
async def start(self):
if self.worker_thread_running:
raise ProcessAlreadyStarted
async for duplicate_pid in self._find_duplicate_process():
logger.warning(f"Possible {duplicate_pid=} found, terminated.")
if not self.config.exists:
self.config.generate()
self.config.before_run()
if not self.device.exists:
self.device.generate()
self.device.before_run()
self.worker_thread_running = True
self.worker_thread = threading.Thread(target=self._process_worker, daemon=True)
self.worker_thread.name = f"daemon-thread-{self.account.uin}"
self.worker_thread.start()
await asyncio.sleep(self.post_delay)
@run_sync
def stop(self):
self.worker_thread_running = False
if self.process is not None:
self._terminate_process(self.process, timeout=self.post_delay)
if self.worker_thread and self.worker_thread.is_alive():
self.worker_thread.join(self.stop_timeout)
self.worker_thread = None
@run_sync
def status(self) -> ProcessInfo:
qr_path = self.cwd / "qrcode.png"
if qr_path.exists():
mimetype, _ = mimetypes.guess_type(qr_path)
qr_data = qr_path.read_bytes()
qr_uri = f"data:{mimetype};base64,{b64encode(qr_data).decode()}"
else:
qr_uri = None
if not self.process or self.process.returncode is not None:
return ProcessInfo(
status=ProcessStatus.stopped,
total_logs=self.logs.count,
restarts=self.restart_count,
details=(
StoppedProcessDetail(code=self.process.returncode)
if self.process
else None
),
)
with (ps := psutil.Process(self.process.pid)).oneshot():
cpu = ps.cpu_percent()
status = ps.status()
memory = ps.memory_info()
create_time = ps.create_time()
return ProcessInfo(
status=ProcessStatus.running,
total_logs=self.logs.count,
restarts=self.restart_count,
qr_uri=qr_uri,
details=RunningProcessDetail(
pid=self.process.pid,
status=status,
memory_used=memory.rss,
cpu_percent=cpu,
start_time=create_time,
),
)
@run_sync
def write_stdin(self, data: bytes):
assert self.process and self.process.stdin
wrote = self.process.stdin.write(data)
self.process.stdin.flush()
return wrote