From bb301f1ca61c54742af5b8a1909aaa506ab8c32b Mon Sep 17 00:00:00 2001 From: PrimeThai Automation Date: Thu, 29 Oct 2026 16:57:36 +0700 Subject: [PATCH] Keep MT5 server alive when status writes fail and add timed recovery --- mt5_app/README.md | 15 ++++++++++- mt5_app/install-autostart.ps1 | 15 +++++++++-- mt5_app/runtime.py | 49 ++++++++++++++++++++++++++++++----- mt5_app/supervisor.py | 33 ++++++++++++++++++++--- 4 files changed, 99 insertions(+), 13 deletions(-) diff --git a/mt5_app/README.md b/mt5_app/README.md index 8b82e5c..c92ffeb 100644 --- a/mt5_app/README.md +++ b/mt5_app/README.md @@ -305,7 +305,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\mt5_app\install-autost - เปิด supervisor หลังผู้ใช้นี้ล็อกอิน Windows ต้องเปิดและล็อกอิน MT5 ของ Pi ตามเดิม ไม่ตั้งเปิด MT5 หรือ Windows auto-login ให้ - supervisor ตรวจเว็บทุก 5 วินาที หากโปรเซสแอปออก บันทึก exit code และรอ 15 วินาทีก่อนเปิดใหม่ หากเว็บไม่ตอบต่อเนื่องประมาณ 90 วินาที จะปิดเฉพาะ process tree ของแอปที่ supervisor เปิดเองแล้วเริ่มใหม่ -- Windows ตั้งเปิด supervisor กลับหาก supervisor ล้มเอง โดยรอประมาณ 1 นาที และไม่มีเวลาจำกัดการรัน task ตามค่าเริ่มต้นสามวัน +- Windows มีทั้ง trigger หลังล็อกอินและ trigger อิสระที่เรียกทุก 1 นาที เพื่อเปิด supervisor กลับแม้กลไก RestartOnFailure ไม่ถูกเรียก ใช้ IgnoreNew และ process lock ป้องกันเปิดซ้ำ ไม่จำกัดเวลาการรัน task - มี lock ป้องกัน supervisor/แอปซ้ำในโฟลเดอร์นี้ ใช้ฐานข้อมูลคำสั่ง บัญชีที่ผูกไว้ และค่าหยุดอัตโนมัติเดิม การเปิดกลับไม่ล้างรายการที่ส่งแล้วหรือปลดสถานะหยุดเทรด - หน้าแรกแสดงว่ามี Windows ดูแลอยู่ เวลาเริ่ม และ heartbeat ล่าสุด ตัวเว็บรันได้ตลอดวัน ส่วนคำสั่งซื้อขายยังถูกจำกัดด้วยวัน/เวลาตลาดเดิม - ตัวดูแลไม่ทำงานเมื่อเครื่องปิดหรือ Sleep หลังไฟดับต้องเปิดเครื่อง ล็อกอิน Windows และเปิด MT5 เพื่อให้เชื่อมต่อได้ @@ -329,3 +329,16 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\mt5_app\install-autost ``` หากต้องการหยุดเฉพาะการส่งคำสั่ง ให้กด **หยุดส่งอัตโนมัติ** ใน dashboard เพื่อให้เว็บและการอ่านพอร์ตยังทำงานต่อ ส่วนการปิดโปรเซสเว็บโดยตรงขณะที่มี supervisor จะทำให้ supervisor เปิดเว็บกลับ คำสั่งที่โบรกเกอร์รับแล้วไม่ถูกยกเลิกจากการหยุดแอป + +### การแก้เหตุหยุดวันที่ 28 ต.ค. 2026 + +จาก `supervisor.log` เวลา 18:19:42 พบ `PermissionError [WinError 5]` ระหว่าง `os.replace` ไฟล์ `supervisor.json` ตัวดูแลรุ่นเดิมถือว่าการเขียนสถานะล้มเหลวเป็นข้อผิดพลาดร้ายแรงแล้วเรียก `stop_child('supervisor_exception')` จึงปิดแอปที่กำลังตอบ health อยู่ตามไปด้วย Task เดิมจบด้วยรหัส 1 และไม่ได้เปิดกลับ แม้ตั้ง RestartOnFailure ไว้ + +แก้วันที่ 29 ต.ค. ดังนี้: + +- การอ่านสถานะลองซ้ำสั้น ๆ และการเขียนไฟล์สถานะลองซ้ำแบบมีขอบเขต เพื่อรับมือไฟล์ถูกเปิดอ่าน/ล็อกชั่วคราวบน Windows หากยังเขียนไม่ได้ให้บันทึกคำเตือนและทำงานต่อ ไฟล์สถานะไม่ใช่ฐานข้อมูลคำสั่งซื้อขาย +- การ publish สถานะล้มเหลวไม่ทำให้ supervisor หยุด และ supervisor ไม่สั่งปิดแอปเพียงเพราะข้อผิดพลาดภายในตัวดูแลเอง การปิด process tree ยังคงใช้สำหรับคำขอหยุดที่ชัดเจนหรือเว็บไม่ตอบเกินเกณฑ์ +- เพิ่ม trigger อิสระทุก 1 นาทีให้ Task เดิม โดยคงผู้ใช้/สิทธิ์เดิม ถ้าแอปและตัวดูแลทำงานอยู่ trigger จะไม่สร้าง instance ใหม่ ค่า LastTaskResult ของคำขอที่ถูกปฏิเสธขณะ Task กำลังรันต้องดูร่วมกับ State, heartbeat และ `/health` +- ไฟล์ `data/supervisor.stop` เป็นเครื่องหมายหยุดที่คงอยู่ข้ามรอบ Task จึงไม่ถูกล้างเองทุกครั้งที่ตัวดูแลเริ่ม ติดตั้ง/เปิดผ่าน `install-autostart.ps1` จะล้างเครื่องหมายโดยตั้งใจ ส่วน `-Remove` ปิด trigger ก่อนหยุดและถอด Task + +ยังไม่ทราบว่าโปรแกรมใดเปิด/ล็อกไฟล์ในจังหวะนั้น การแก้ไม่เปลี่ยนสิทธิ์ไฟล์หรือใช้ Administrator และไม่ล้างฐานข้อมูลบัญชี/คำสั่งเดิม diff --git a/mt5_app/install-autostart.ps1 b/mt5_app/install-autostart.ps1 index b18a59c..47b46fe 100644 --- a/mt5_app/install-autostart.ps1 +++ b/mt5_app/install-autostart.ps1 @@ -4,6 +4,8 @@ $taskRoot = Split-Path $PSScriptRoot -Parent $taskName = 'PrimeThai-MT5-Desk' $taskUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $taskPython = Join-Path $PSScriptRoot '.venv\Scripts\pythonw.exe' +$taskStateDir = Join-Path $PSScriptRoot 'data' +$taskStopMarker = Join-Path $taskStateDir 'supervisor.stop' if (-not (Test-Path -LiteralPath $taskPython)) { throw 'Run mt5_app/setup.ps1 first. Dedicated pythonw.exe is required.' } @@ -16,7 +18,9 @@ if ($oldTask) { } if ($Remove) { if ($oldTask) { - New-Item -ItemType File -Path (Join-Path $PSScriptRoot 'data\supervisor.stop') -Force | Out-Null + Disable-ScheduledTask -TaskName $taskName | Out-Null + New-Item -ItemType Directory -Path $taskStateDir -Force | Out-Null + New-Item -ItemType File -Path $taskStopMarker -Force | Out-Null Start-Sleep -Seconds 8 Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue Unregister-ScheduledTask -TaskName $taskName -Confirm:$false @@ -26,8 +30,15 @@ if ($Remove) { } $taskAction = New-ScheduledTaskAction -Execute $taskPython -Argument '-m mt5_app supervise' -WorkingDirectory $taskRoot $taskTrigger = New-ScheduledTaskTrigger -AtLogOn -User $taskUser +# Independent retry even when Task Scheduler treats a nonzero process exit as +# a completed action and does not apply RestartOnFailure. IgnoreNew prevents duplicates. +$taskSafetyTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(15) -RepetitionInterval (New-TimeSpan -Minutes 1) $taskPrincipal = New-ScheduledTaskPrincipal -UserId $taskUser -LogonType Interactive -RunLevel Limited $taskSettings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Register-ScheduledTask -TaskName $taskName -Action $taskAction -Trigger $taskTrigger -Principal $taskPrincipal -Settings $taskSettings -Description 'Local Pi MT5 desk supervisor. Runs as the logged-in user; preserves trading authorization and broker state.' -Force | Out-Null +Register-ScheduledTask -TaskName $taskName -Action $taskAction -Trigger @($taskTrigger, $taskSafetyTrigger) -Principal $taskPrincipal -Settings $taskSettings -Description 'Local Pi MT5 desk supervisor. Logon plus independent one-minute recovery; single instance; preserves trading authorization and broker state.' -Force | Out-Null +New-Item -ItemType Directory -Path $taskStateDir -Force | Out-Null +if (Test-Path -LiteralPath $taskStopMarker) { + Remove-Item -LiteralPath $taskStopMarker +} Start-ScheduledTask -TaskName $taskName Write-Output "Installed and started $taskName for $taskUser. Open http://127.0.0.1:18901/" diff --git a/mt5_app/runtime.py b/mt5_app/runtime.py index 45500f5..57fca18 100644 --- a/mt5_app/runtime.py +++ b/mt5_app/runtime.py @@ -2,27 +2,64 @@ from contextlib import contextmanager from datetime import datetime, timezone import json +import logging import os from pathlib import Path +import time import uuid +_last_status_warning = {} + def utc_now(): return datetime.now(timezone.utc).isoformat() def read_status(path): - try: - return json.loads(Path(path).read_text(encoding='utf-8')) - except (OSError, ValueError): - return {} + for attempt in range(3): + try: + value = json.loads(Path(path).read_text(encoding='utf-8')) + return value if isinstance(value, dict) else {} + except FileNotFoundError: + return {} + except (OSError, ValueError): + if attempt < 2: + time.sleep(.02) + return {} def write_status(path, value): + """Best-effort telemetry; Windows readers/scanners may briefly block rename. + + A status-file failure must never terminate a healthy server or supervisor. + Trading intents remain durable in SQLite, independent of these JSON files. + """ path = Path(path) temp = path.with_name(path.name + f'.{os.getpid()}.tmp') - temp.write_text(json.dumps(value, ensure_ascii=False), encoding='utf-8') - os.replace(temp, path) + payload = json.dumps(value, ensure_ascii=False) + error = None + try: + for attempt in range(6): + try: + temp.write_text(payload, encoding='utf-8') + os.replace(temp, path) + return True + except OSError as exc: + error = exc + if attempt < 5: + time.sleep(min(.05 * 2 ** attempt, .4)) + key = str(path) + now = time.monotonic() + if now - _last_status_warning.get(key, -float('inf')) >= 60: + _last_status_warning[key] = now + logging.getLogger('mt5supervisor' if path.name == 'supervisor.json' else 'mt5desk').warning( + 'status_write_failed path=%s; continuing without stopping trading processes: %s', path, error) + return False + finally: + try: + temp.unlink(missing_ok=True) + except OSError: + pass @contextmanager diff --git a/mt5_app/supervisor.py b/mt5_app/supervisor.py index 49a5811..5216197 100644 --- a/mt5_app/supervisor.py +++ b/mt5_app/supervisor.py @@ -15,7 +15,7 @@ import time from urllib.request import ProxyHandler, build_opener from .config import ROOT -from .runtime import process_lock, read_status, utc_now, write_status +from .runtime import process_lock, utc_now, write_status def workspace_id(): @@ -49,10 +49,25 @@ def run(settings): child = None python = Path(sys.executable).with_name('python.exe') if os.name == 'nt' else Path(sys.executable) flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0) + last_publish_warning = -float('inf') def publish(status, **extra): + nonlocal last_publish_warning state.update(state=status, heartbeat_at=utc_now(), **extra) - write_status(path, state) + try: + saved = write_status(path, state) + except Exception: + # Telemetry/serialization cannot own the server's lifetime. + if time.monotonic() - last_publish_warning >= 60: + log.exception('status_publish_failed; keeping server running') + last_publish_warning = time.monotonic() + saved = False + if not saved: + state['status_write_failures'] = state.get('status_write_failures', 0) + 1 + elif state.get('status_write_failures'): + log.info('status_write_recovered after_failures=%s', state['status_write_failures']) + state['status_write_failures'] = 0 + return saved def stop_child(reason): if child is None or child.poll() is not None: @@ -71,7 +86,10 @@ def run(settings): log.warning('owned_child_stopped pid=%s exit_code=%s reason=%s', child.pid, child.returncode, reason) with process_lock(settings.state_dir / 'supervisor.lock'): - stop_file.unlink(missing_ok=True) + if stop_file.exists(): + log.info('supervisor_start_suppressed reason=stop_marker') + publish('stopped', stopped_at=utc_now(), reason='stop_marker') + return log.info('supervisor_started pid=%s parent=%s', os.getpid(), os.getppid()) publish('starting') try: @@ -117,8 +135,15 @@ def run(settings): stop_child('supervisor_stop_requested') publish('stopped', stopped_at=utc_now(), reason='stop_file') log.info('supervisor_stopped reason=stop_file') + except KeyboardInterrupt: + publish('stopping', reason='keyboard_interrupt') + stop_child('keyboard_interrupt') + publish('stopped', stopped_at=utc_now(), reason='keyboard_interrupt') except BaseException as exc: log.exception('supervisor_failed') publish('failed', stopped_at=utc_now(), error=f'{type(exc).__name__}: {exc}') - stop_child('supervisor_exception') + # Never kill a healthy trading server because its observer failed. + # The independent Windows trigger will restart/adopt supervision. + log.error('supervisor_exiting_without_stopping_server launcher_pid=%s', + child.pid if child and child.poll() is None else None) raise