init xiaoxiang project
This commit is contained in:
+414
@@ -0,0 +1,414 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
import urllib3
|
||||
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
|
||||
CHECKPOINT_FILE_ENV = "ELEPHANT_MISSING_CHECKPOINT"
|
||||
MAX_WORKERS_ENV = "ELEPHANT_MISSING_MAX_WORKERS"
|
||||
MAX_ATTEMPTS_ENV = "ELEPHANT_MISSING_MAX_ATTEMPTS"
|
||||
SAVE_EVERY_ENV = "ELEPHANT_MISSING_SAVE_EVERY"
|
||||
|
||||
DB_CONF = {
|
||||
"host": "183.6.7.91",
|
||||
"port": 33016,
|
||||
"user": "root",
|
||||
"password": "Aliyun@7646!",
|
||||
"db": "tk_test",
|
||||
"charset": "utf8mb4",
|
||||
}
|
||||
|
||||
INSERT_PAGE_LOG_SQL = """
|
||||
INSERT INTO category_detail_log
|
||||
(shop_id, category_detail_id, one_id, two_id, req_json, work_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
|
||||
def load_detail_module():
|
||||
module_path = BASE_DIR / "小象超市详情列表请求部分.py"
|
||||
spec = importlib.util.spec_from_file_location("elephant_detail_module", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.print = lambda *args, **kwargs: None
|
||||
return module
|
||||
|
||||
|
||||
DETAIL_MODULE = load_detail_module()
|
||||
|
||||
|
||||
def log(message):
|
||||
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
print(f"[{now}] {message}", flush=True)
|
||||
|
||||
|
||||
def now_iso():
|
||||
return datetime.datetime.now().replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def get_checkpoint_path():
|
||||
return BASE_DIR / os.environ.get(
|
||||
CHECKPOINT_FILE_ENV, "elephant_missing_pages_checkpoint.json"
|
||||
)
|
||||
|
||||
|
||||
def get_max_workers(total_headers):
|
||||
value = os.environ.get(MAX_WORKERS_ENV)
|
||||
if not value:
|
||||
return total_headers
|
||||
try:
|
||||
requested = int(value)
|
||||
except ValueError:
|
||||
requested = total_headers
|
||||
return max(1, min(total_headers, requested))
|
||||
|
||||
|
||||
def get_max_attempts():
|
||||
value = os.environ.get(MAX_ATTEMPTS_ENV, "6")
|
||||
try:
|
||||
return max(1, int(value))
|
||||
except ValueError:
|
||||
return 6
|
||||
|
||||
|
||||
def get_save_every():
|
||||
value = os.environ.get(SAVE_EVERY_ENV, "20")
|
||||
try:
|
||||
return max(1, int(value))
|
||||
except ValueError:
|
||||
return 20
|
||||
|
||||
|
||||
def get_db_connection():
|
||||
return pymysql.connect(**DB_CONF)
|
||||
|
||||
|
||||
def load_checkpoint(checkpoint_path):
|
||||
if not checkpoint_path.exists():
|
||||
raise FileNotFoundError(f"checkpoint 不存在: {checkpoint_path}")
|
||||
with checkpoint_path.open("r", encoding="utf-8") as f:
|
||||
state = json.load(f)
|
||||
tasks = state.get("tasks")
|
||||
if not isinstance(tasks, dict):
|
||||
raise ValueError(f"checkpoint 结构不对: {checkpoint_path}")
|
||||
return state
|
||||
|
||||
|
||||
def save_checkpoint(checkpoint_path, state):
|
||||
state["updated_at"] = now_iso()
|
||||
temp_path = checkpoint_path.with_suffix(checkpoint_path.suffix + ".tmp")
|
||||
with temp_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
temp_path.replace(checkpoint_path)
|
||||
|
||||
|
||||
def summarize_tasks(tasks):
|
||||
summary = {}
|
||||
for task in tasks.values():
|
||||
status = task.get("status", "unknown")
|
||||
summary[status] = summary.get(status, 0) + 1
|
||||
return summary
|
||||
|
||||
|
||||
def format_task(task):
|
||||
return (
|
||||
f"店铺={task['shop_id']} 分类={task['one_name']}/{task['two_name']} "
|
||||
f"页={task['page_no']}"
|
||||
)
|
||||
|
||||
|
||||
def get_retry_task_keys(tasks):
|
||||
retry_keys = []
|
||||
for key, task in tasks.items():
|
||||
if task.get("status") in {"page_replaced", "done"}:
|
||||
continue
|
||||
retry_keys.append(key)
|
||||
retry_keys.sort(
|
||||
key=lambda key: (
|
||||
int(tasks[key].get("line_no", 0)),
|
||||
int(tasks[key].get("shop_id", 0)),
|
||||
int(tasks[key].get("one_id", 0)),
|
||||
int(tasks[key].get("two_id", 0)),
|
||||
int(tasks[key].get("page_no", 0)),
|
||||
)
|
||||
)
|
||||
return retry_keys
|
||||
|
||||
|
||||
class BadHeaderError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class CheckpointState:
|
||||
def __init__(self, state, checkpoint_path, max_attempts, save_every):
|
||||
self.state = state
|
||||
self.checkpoint_path = checkpoint_path
|
||||
self.max_attempts = max_attempts
|
||||
self.save_every = save_every
|
||||
self.lock = threading.Lock()
|
||||
self.dirty_count = 0
|
||||
|
||||
def get_task_copy(self, task_key):
|
||||
with self.lock:
|
||||
task = self.state["tasks"].get(task_key)
|
||||
if task is None:
|
||||
return None
|
||||
return dict(task)
|
||||
|
||||
def summary(self):
|
||||
with self.lock:
|
||||
return summarize_tasks(self.state["tasks"])
|
||||
|
||||
def flush(self, force=False):
|
||||
with self.lock:
|
||||
if not force and self.dirty_count <= 0:
|
||||
return
|
||||
save_checkpoint(self.checkpoint_path, self.state)
|
||||
self.dirty_count = 0
|
||||
|
||||
def _touch_locked(self, force=False):
|
||||
self.dirty_count += 1
|
||||
if force or self.dirty_count >= self.save_every:
|
||||
save_checkpoint(self.checkpoint_path, self.state)
|
||||
self.dirty_count = 0
|
||||
|
||||
def mark_success(self, task_key, hd_id):
|
||||
with self.lock:
|
||||
task = self.state["tasks"][task_key]
|
||||
stamp = now_iso()
|
||||
task["attempts"] = int(task.get("attempts") or 0) + 1
|
||||
task["status"] = "page_replaced"
|
||||
task["last_error"] = ""
|
||||
task["last_header_id"] = hd_id
|
||||
task["page_replaced_at"] = stamp
|
||||
task["updated_at"] = stamp
|
||||
self._touch_locked()
|
||||
|
||||
def mark_error(self, task_key, hd_id, error_text, allow_retry):
|
||||
with self.lock:
|
||||
task = self.state["tasks"][task_key]
|
||||
stamp = now_iso()
|
||||
attempts = int(task.get("attempts") or 0) + 1
|
||||
can_retry = allow_retry and attempts < self.max_attempts
|
||||
task["attempts"] = attempts
|
||||
task["status"] = "pending" if can_retry else "failed"
|
||||
task["last_error"] = str(error_text)
|
||||
task["last_header_id"] = hd_id
|
||||
task["updated_at"] = stamp
|
||||
self._touch_locked(force=not can_retry)
|
||||
return can_retry, attempts
|
||||
|
||||
|
||||
def insert_page_log(conn, task, req_json):
|
||||
req_text = json.dumps(req_json, ensure_ascii=False)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
INSERT_PAGE_LOG_SQL,
|
||||
(
|
||||
task["shop_id"],
|
||||
task["page_no"],
|
||||
task["one_id"],
|
||||
task["two_id"],
|
||||
req_text,
|
||||
task["work_id"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def fetch_missing_page(task, hd):
|
||||
hd_id = hd[0]
|
||||
try:
|
||||
response, _ = DETAIL_MODULE.one_(
|
||||
task["one_id"],
|
||||
task["two_id"],
|
||||
task["page_no"],
|
||||
task["shop_id"],
|
||||
hd,
|
||||
task.get("one_all_num"),
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"header_id={hd_id} 请求异常: {exc}") from exc
|
||||
|
||||
response_text = response.text or ""
|
||||
if "网络访问错误" in response_text or "您的网络好像不太给力" in response_text:
|
||||
DETAIL_MODULE.update_headers(418, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 网络访问错误")
|
||||
|
||||
try:
|
||||
req_json = response.json()
|
||||
except Exception as exc:
|
||||
if "Expecting value: line 1 column 1 (char 0)" in str(exc):
|
||||
DETAIL_MODULE.update_headers(403, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} JSON 解析失败: {exc}") from exc
|
||||
raise RuntimeError(f"header_id={hd_id} JSON 解析失败: {exc}") from exc
|
||||
|
||||
data = req_json.get("data")
|
||||
if not isinstance(data, dict) or not data:
|
||||
DETAIL_MODULE.update_headers(406, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 返回 data 为空")
|
||||
|
||||
try:
|
||||
contents = data["contents"][0]["subModule"]["contents"]
|
||||
one_price = contents[0]["lxInfo"]["sale_price"]
|
||||
except Exception as exc:
|
||||
DETAIL_MODULE.update_headers(406, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 首商品价格读取失败: {exc}") from exc
|
||||
|
||||
if one_price == "?":
|
||||
DETAIL_MODULE.update_headers(406, hd_id)
|
||||
raise BadHeaderError(f"header_id={hd_id} 首商品价格为 ?")
|
||||
|
||||
DETAIL_MODULE.update_headers(1, hd_id)
|
||||
return req_json, hd_id
|
||||
|
||||
|
||||
def worker(worker_no, hd, task_queue, checkpoint_state):
|
||||
worker_name = f"worker-{worker_no}"
|
||||
hd_id = hd[0]
|
||||
conn = get_db_connection()
|
||||
success_count = 0
|
||||
retry_count = 0
|
||||
failed_count = 0
|
||||
|
||||
log(f"[{worker_name}] 启动,header_id={hd_id}")
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
task_key = task_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
task = checkpoint_state.get_task_copy(task_key)
|
||||
if task is None or task.get("status") in {"page_replaced", "done"}:
|
||||
task_queue.task_done()
|
||||
continue
|
||||
|
||||
try:
|
||||
req_json, used_hd_id = fetch_missing_page(task, hd)
|
||||
conn.ping(reconnect=True)
|
||||
insert_page_log(conn, task, req_json)
|
||||
except BadHeaderError as exc:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
can_retry, attempts = checkpoint_state.mark_error(
|
||||
task_key, hd_id, str(exc), allow_retry=True
|
||||
)
|
||||
if can_retry:
|
||||
task_queue.put(task_key)
|
||||
retry_count += 1
|
||||
log(
|
||||
f"[{worker_name}] header_id={hd_id} 失效,任务回队: "
|
||||
f"{format_task(task)},第 {attempts} 次"
|
||||
)
|
||||
else:
|
||||
failed_count += 1
|
||||
log(
|
||||
f"[{worker_name}] header_id={hd_id} 失效且达到重试上限: "
|
||||
f"{format_task(task)}"
|
||||
)
|
||||
task_queue.task_done()
|
||||
break
|
||||
except Exception as exc:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
can_retry, attempts = checkpoint_state.mark_error(
|
||||
task_key, hd_id, str(exc), allow_retry=True
|
||||
)
|
||||
if can_retry:
|
||||
task_queue.put(task_key)
|
||||
retry_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
log(
|
||||
f"[{worker_name}] 任务失败且达到重试上限: "
|
||||
f"{format_task(task)},原因: {exc}"
|
||||
)
|
||||
task_queue.task_done()
|
||||
continue
|
||||
|
||||
checkpoint_state.mark_success(task_key, used_hd_id)
|
||||
success_count += 1
|
||||
task_queue.task_done()
|
||||
if success_count % 10 == 0:
|
||||
log(f"[{worker_name}] 已成功补页 {success_count} 条,header_id={hd_id}")
|
||||
finally:
|
||||
checkpoint_state.flush()
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
log(
|
||||
f"[{worker_name}] 退出,header_id={hd_id},"
|
||||
f"成功 {success_count} 条,回队 {retry_count} 条,失败 {failed_count} 条"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
checkpoint_path = get_checkpoint_path()
|
||||
state = load_checkpoint(checkpoint_path)
|
||||
retry_task_keys = get_retry_task_keys(state["tasks"])
|
||||
|
||||
log(f"checkpoint: {checkpoint_path}")
|
||||
log(f"当前状态分布: {summarize_tasks(state['tasks'])}")
|
||||
log(f"本次待重跑任务数: {len(retry_task_keys)}")
|
||||
|
||||
if not retry_task_keys:
|
||||
log("没有需要重跑的任务")
|
||||
return
|
||||
|
||||
headers = list(DETAIL_MODULE.get_hds())
|
||||
if not headers:
|
||||
raise RuntimeError("没有可用详情 headers")
|
||||
|
||||
worker_count = get_max_workers(10)
|
||||
checkpoint_state = CheckpointState(
|
||||
state,
|
||||
checkpoint_path,
|
||||
max_attempts=get_max_attempts(),
|
||||
save_every=get_save_every(),
|
||||
)
|
||||
task_queue = queue.Queue()
|
||||
for task_key in retry_task_keys:
|
||||
task_queue.put(task_key)
|
||||
|
||||
log(f"可用 headers: {len(headers)},实际并发: {worker_count}")
|
||||
with ThreadPoolExecutor(max_workers=worker_count) as pool:
|
||||
futures = []
|
||||
for worker_no, hd in enumerate(headers[:worker_count], start=1):
|
||||
futures.append(
|
||||
pool.submit(worker, worker_no, hd, task_queue, checkpoint_state)
|
||||
)
|
||||
for future in futures:
|
||||
future.result()
|
||||
|
||||
checkpoint_state.flush(force=True)
|
||||
summary = checkpoint_state.summary()
|
||||
log(f"重跑结束,剩余队列 {task_queue.qsize()},状态分布 {summary}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
log("收到中断信号,已停止")
|
||||
raise
|
||||
Reference in New Issue
Block a user