This commit is contained in:
1 parent
ccc1f625e8
commit
5874ffba9f
13 files changed
+258
-34
No files matched your search
+78
-3
@@ -228,6 +228,36 @@ class DetailsService:
|
||||
self._queued.discard(appid)
|
||||
|
||||
|
||||
def suspend_process(pid):
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
handle = ctypes.windll.kernel32.OpenProcess(0x0800, False, pid)
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
return ctypes.windll.ntdll.NtSuspendProcess(handle) == 0
|
||||
finally:
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
import signal
|
||||
os.kill(pid, signal.SIGSTOP)
|
||||
return True
|
||||
|
||||
|
||||
def resume_process(pid):
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
handle = ctypes.windll.kernel32.OpenProcess(0x0800, False, pid)
|
||||
if not handle:
|
||||
return False
|
||||
try:
|
||||
return ctypes.windll.ntdll.NtResumeProcess(handle) == 0
|
||||
finally:
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
import signal
|
||||
os.kill(pid, signal.SIGCONT)
|
||||
return True
|
||||
|
||||
|
||||
class JobManager:
|
||||
"""Runs a maintenance script in the background and exposes its state."""
|
||||
|
||||
@@ -236,8 +266,9 @@ class JobManager:
|
||||
self._proc = None
|
||||
self._last = None
|
||||
self._state = {
|
||||
"name": None, "running": False, "cancelled": False, "exit_code": None,
|
||||
"started_at": None, "finished_at": None, "progress": None, "output": [],
|
||||
"name": None, "running": False, "cancelled": False, "paused": False,
|
||||
"exit_code": None, "started_at": None, "finished_at": None,
|
||||
"progress": None, "output": [],
|
||||
}
|
||||
|
||||
def start(self, name, args):
|
||||
@@ -247,7 +278,8 @@ class JobManager:
|
||||
self._proc = None
|
||||
self._last = (name, list(args))
|
||||
self._state = {
|
||||
"name": name, "running": True, "cancelled": False, "exit_code": None,
|
||||
"name": name, "running": True, "cancelled": False, "paused": False,
|
||||
"exit_code": None,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"finished_at": None, "progress": None, "output": [],
|
||||
}
|
||||
@@ -262,6 +294,39 @@ class JobManager:
|
||||
name, args = self._last
|
||||
return self.start(name, args)
|
||||
|
||||
def pause(self):
|
||||
deadline = time.time() + 2
|
||||
while True:
|
||||
with self._lock:
|
||||
if not self._state["running"] or self._state["paused"]:
|
||||
return False
|
||||
proc = self._proc
|
||||
if proc is not None:
|
||||
name = self._state["name"]
|
||||
break
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(0.02)
|
||||
if not suspend_process(proc.pid):
|
||||
return False
|
||||
with self._lock:
|
||||
self._state["paused"] = True
|
||||
log_event("job_pause", name=name)
|
||||
return True
|
||||
|
||||
def resume(self):
|
||||
with self._lock:
|
||||
if not self._state["running"] or not self._state["paused"] or not self._proc:
|
||||
return False
|
||||
proc = self._proc
|
||||
name = self._state["name"]
|
||||
if not resume_process(proc.pid):
|
||||
return False
|
||||
with self._lock:
|
||||
self._state["paused"] = False
|
||||
log_event("job_resume", name=name)
|
||||
return True
|
||||
|
||||
def cancel(self):
|
||||
deadline = time.time() + 2
|
||||
while True:
|
||||
@@ -272,10 +337,15 @@ class JobManager:
|
||||
if proc is not None:
|
||||
self._state["cancelled"] = True
|
||||
name = self._state["name"]
|
||||
was_paused = self._state["paused"]
|
||||
break
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(0.02)
|
||||
if was_paused:
|
||||
resume_process(proc.pid)
|
||||
with self._lock:
|
||||
self._state["paused"] = False
|
||||
try:
|
||||
proc.terminate()
|
||||
except OSError:
|
||||
@@ -334,6 +404,7 @@ class JobManager:
|
||||
pass
|
||||
with self._lock:
|
||||
self._state["running"] = False
|
||||
self._state["paused"] = False
|
||||
self._state["exit_code"] = code
|
||||
self._state["finished_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
cancelled = self._state["cancelled"]
|
||||
@@ -704,6 +775,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._update_personal(appid, self._body())
|
||||
elif path == "/api/job/cancel":
|
||||
self._json({"cancelled": JOBS.cancel()})
|
||||
elif path == "/api/job/pause":
|
||||
self._json({"paused": JOBS.pause()})
|
||||
elif path == "/api/job/resume":
|
||||
self._json({"paused": JOBS.resume()})
|
||||
elif path == "/api/job/retry":
|
||||
self._json({"started": JOBS.retry()})
|
||||
elif path == "/api/hltb":
|
||||
|
||||
+28
-4
@@ -1624,9 +1624,9 @@ const JOB_BUTTONS = ["#refreshInc", "#refreshFull", "#translate", "#translateAbo
|
||||
const JOB_LABELS = { translate: "перевод", hltb: "HLTB", import: "обновление БД" };
|
||||
const JOB_CONTEXTS = {
|
||||
services: { status: "#jobStatus", bar: "#jobBar", log: "#jobLog",
|
||||
cancel: "#jobCancel", retry: "#jobRetry" },
|
||||
cancel: "#jobCancel", retry: "#jobRetry", pause: "#jobPause" },
|
||||
hltb: { status: "#hltbJobStatus", bar: "#hltbJobBar", log: "#hltbJobLog",
|
||||
cancel: "#hltbJobCancel", retry: "#hltbJobRetry" },
|
||||
cancel: "#hltbJobCancel", retry: "#hltbJobRetry", pause: "#hltbJobPause" },
|
||||
};
|
||||
|
||||
function jobContext(name) {
|
||||
@@ -1644,6 +1644,8 @@ async function pollJob(silent = false) {
|
||||
for (const context of Object.values(JOB_CONTEXTS)) {
|
||||
$(context.cancel).hidden = true;
|
||||
$(context.retry).hidden = true;
|
||||
$(context.pause).hidden = true;
|
||||
$(context.pause).disabled = false;
|
||||
}
|
||||
const context = jobContext(st.name);
|
||||
const statusEl = $(context.status);
|
||||
@@ -1652,6 +1654,10 @@ async function pollJob(silent = false) {
|
||||
$(context.log).hidden = !logLines.length;
|
||||
if (busy) {
|
||||
$(context.cancel).hidden = false;
|
||||
const pause = $(context.pause);
|
||||
pause.hidden = false;
|
||||
pause.dataset.paused = st.paused ? "1" : "0";
|
||||
pause.textContent = st.paused ? "продолжить" : "пауза";
|
||||
const label = JOB_LABELS[st.name] || "обновление БД";
|
||||
const last = (st.output || []).slice(-1)[0] || "";
|
||||
const p = st.progress;
|
||||
@@ -1662,7 +1668,8 @@ async function pollJob(silent = false) {
|
||||
extra = ` ${p.current}/${p.total} (${p.percent}%)`;
|
||||
if (p.eta_seconds != null) extra += ` · ~${formatEta(p.eta_seconds)}`;
|
||||
}
|
||||
statusEl.textContent = `${label}…${extra} ${last}`.trim();
|
||||
statusEl.textContent = st.paused ? `пауза · ${last}`.trim()
|
||||
: `${label}…${extra} ${last}`.trim();
|
||||
$(context.bar).style.width = `${percent}%`;
|
||||
await loadMeta();
|
||||
clearTimeout(jobTimer);
|
||||
@@ -1727,7 +1734,7 @@ async function cancelJob(event) {
|
||||
event.currentTarget.disabled = true;
|
||||
try {
|
||||
const result = await api("/api/job/cancel", { method: "POST", body: "{}" });
|
||||
toast(result.cancelled ? "Остановка запрошена" : "Задача уже завершена");
|
||||
toast(result.cancelled ? "Отмена запрошена" : "Задача уже завершена");
|
||||
} catch (err) {
|
||||
toast(err.message);
|
||||
event.currentTarget.disabled = false;
|
||||
@@ -1736,6 +1743,23 @@ async function cancelJob(event) {
|
||||
$("#jobCancel").addEventListener("click", cancelJob);
|
||||
$("#hltbJobCancel").addEventListener("click", cancelJob);
|
||||
|
||||
async function togglePause(event) {
|
||||
const wasPaused = event.currentTarget.dataset.paused === "1";
|
||||
event.currentTarget.disabled = true;
|
||||
try {
|
||||
const result = await api(wasPaused ? "/api/job/resume" : "/api/job/pause",
|
||||
{ method: "POST", body: "{}" });
|
||||
const failed = wasPaused ? result.paused : !result.paused;
|
||||
if (failed) toast("Не удалось изменить состояние задачи");
|
||||
pollJob();
|
||||
} catch (err) {
|
||||
toast(err.message);
|
||||
event.currentTarget.disabled = false;
|
||||
}
|
||||
}
|
||||
$("#jobPause").addEventListener("click", togglePause);
|
||||
$("#hltbJobPause").addEventListener("click", togglePause);
|
||||
|
||||
async function retryJob(event) {
|
||||
event.currentTarget.disabled = true;
|
||||
try {
|
||||
|
||||
@@ -315,7 +315,8 @@ try {
|
||||
<div class="bar"><i id="hltbJobBar"></i></div>
|
||||
<pre id="hltbJobLog" class="hltb-log" hidden></pre>
|
||||
<div class="refresh-actions">
|
||||
<button id="hltbJobCancel" class="ghost" type="button" hidden>остановить</button>
|
||||
<button id="hltbJobPause" class="ghost" type="button" hidden>пауза</button>
|
||||
<button id="hltbJobCancel" class="ghost" type="button" hidden>отменить</button>
|
||||
<button id="hltbJobRetry" class="ghost" type="button" hidden>повторить</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -386,7 +387,8 @@ try {
|
||||
<div class="bar"><i id="jobBar"></i></div>
|
||||
<pre id="jobLog" class="hltb-log" hidden></pre>
|
||||
<div class="refresh-actions">
|
||||
<button id="jobCancel" class="ghost" type="button" hidden>остановить</button>
|
||||
<button id="jobPause" class="ghost" type="button" hidden>пауза</button>
|
||||
<button id="jobCancel" class="ghost" type="button" hidden>отменить</button>
|
||||
<button id="jobRetry" class="ghost" type="button" hidden>повторить</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
Reference in new issue
Block a user