fetch_logs.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. """
  3. fetch_logs.py — Retrieve workflow execution diagnostics from a ComfyUI server.
  4. When a workflow errors, the server's /history (local) or /jobs (cloud) entry
  5. contains the full Python traceback. This script makes it easy to fetch by
  6. prompt_id, with sensible formatting.
  7. Usage:
  8. python3 fetch_logs.py <prompt_id>
  9. python3 fetch_logs.py <prompt_id> --host https://cloud.comfy.org
  10. python3 fetch_logs.py --tail-queue # show currently queued/running jobs
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import sys
  15. from pathlib import Path
  16. sys.path.insert(0, str(Path(__file__).resolve().parent))
  17. from _common import (
  18. DEFAULT_LOCAL_HOST, ENV_API_KEY, emit_json, http_get, is_cloud_host,
  19. resolve_api_key, resolve_url,
  20. )
  21. def fetch_history_entry(host: str, headers: dict, prompt_id: str, *, is_cloud: bool) -> dict:
  22. if is_cloud:
  23. # Try /jobs/{id} first
  24. url = resolve_url(host, f"/jobs/{prompt_id}", is_cloud=True)
  25. r = http_get(url, headers=headers, retries=2, timeout=30)
  26. if r.status == 200:
  27. try:
  28. return {"ok": True, "entry": r.json(), "source": "/api/jobs"}
  29. except Exception:
  30. pass
  31. # Fallback to history_v2
  32. url = resolve_url(host, f"/history/{prompt_id}", is_cloud=True)
  33. r = http_get(url, headers=headers, retries=2, timeout=30)
  34. try:
  35. data = r.json()
  36. except Exception:
  37. data = None
  38. if r.status == 200 and data:
  39. return {"ok": True, "entry": data, "source": "/api/history_v2"}
  40. return {"ok": False, "http_status": r.status, "body": r.text()[:500]}
  41. url = resolve_url(host, f"/history/{prompt_id}", is_cloud=False)
  42. r = http_get(url, headers=headers, retries=2, timeout=30)
  43. if r.status != 200:
  44. return {"ok": False, "http_status": r.status, "body": r.text()[:500]}
  45. try:
  46. data = r.json()
  47. except Exception:
  48. return {"ok": False, "reason": "non-JSON response"}
  49. if not isinstance(data, dict) or prompt_id not in data:
  50. return {"ok": False, "reason": "prompt_id not found in history",
  51. "history_keys": list(data.keys())[:5] if isinstance(data, dict) else []}
  52. return {"ok": True, "entry": data[prompt_id], "source": "/history"}
  53. def fetch_queue(host: str, headers: dict) -> dict:
  54. url = resolve_url(host, "/queue")
  55. r = http_get(url, headers=headers, retries=2, timeout=15)
  56. try:
  57. data = r.json()
  58. except Exception:
  59. data = {"raw": r.text()[:500]}
  60. return {"http_status": r.status, "data": data}
  61. def extract_diagnostics(entry: dict) -> dict:
  62. """Pull out the parts a human cares about: status, errors, traceback, timing."""
  63. diag: dict = {}
  64. status = entry.get("status") or {}
  65. diag["status_str"] = status.get("status_str")
  66. diag["completed"] = status.get("completed")
  67. messages = status.get("messages") or []
  68. diag["execution_log"] = []
  69. for msg in messages:
  70. if isinstance(msg, list) and len(msg) >= 2:
  71. mtype, mdata = msg[0], msg[1]
  72. diag["execution_log"].append({"type": mtype, "data": mdata})
  73. else:
  74. diag["execution_log"].append(msg)
  75. # Look for execution_error inside messages
  76. errors = []
  77. for msg in messages:
  78. if isinstance(msg, list) and len(msg) >= 2 and msg[0] == "execution_error":
  79. errors.append(msg[1])
  80. if errors:
  81. diag["errors"] = errors
  82. # Cloud's /jobs response shape: top-level outputs / status / etc.
  83. if "outputs" in entry:
  84. out = entry["outputs"] or {}
  85. if isinstance(out, dict):
  86. diag["output_node_ids"] = list(out.keys())
  87. # Count file refs across all output buckets (images / video / etc.)
  88. total = 0
  89. for node_output in out.values():
  90. if not isinstance(node_output, dict):
  91. continue
  92. for v in node_output.values():
  93. if isinstance(v, list):
  94. total += len(v)
  95. diag["output_count"] = total
  96. else:
  97. diag["output_node_ids"] = []
  98. diag["output_count"] = 0
  99. return diag
  100. def main(argv: list[str] | None = None) -> int:
  101. p = argparse.ArgumentParser(description="Fetch workflow execution diagnostics")
  102. p.add_argument("prompt_id", nargs="?", help="prompt_id to look up")
  103. p.add_argument("--host", default=DEFAULT_LOCAL_HOST)
  104. p.add_argument("--api-key", help=f"or set ${ENV_API_KEY}")
  105. p.add_argument("--raw", action="store_true",
  106. help="Print the full history entry instead of the digest")
  107. p.add_argument("--tail-queue", action="store_true",
  108. help="Show currently running/pending jobs instead")
  109. args = p.parse_args(argv)
  110. api_key = resolve_api_key(args.api_key)
  111. headers = {"X-API-Key": api_key} if api_key else {}
  112. is_cloud = is_cloud_host(args.host)
  113. if args.tail_queue:
  114. emit_json(fetch_queue(args.host, headers))
  115. return 0
  116. if not args.prompt_id:
  117. print("Error: prompt_id is required (or use --tail-queue)", file=sys.stderr)
  118. return 1
  119. res = fetch_history_entry(args.host, headers, args.prompt_id, is_cloud=is_cloud)
  120. if not res.get("ok"):
  121. emit_json(res)
  122. return 1
  123. if args.raw:
  124. emit_json(res)
  125. return 0
  126. diag = extract_diagnostics(res["entry"])
  127. diag["source"] = res.get("source")
  128. diag["prompt_id"] = args.prompt_id
  129. emit_json(diag)
  130. return 0 if diag.get("status_str") not in {"error",} else 1
  131. if __name__ == "__main__":
  132. sys.exit(main())