Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
199 lines (164 loc) · 7.19 KB
/
Copy pathcli.py
File metadata and controls
199 lines (164 loc) · 7.19 KB
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
"""actor-debugger - launch an Apify Python Actor under debugpy, debuggable from a plain
browser over the run's container URL, with a one-line Dockerfile change:
CMD ["python3", "-m", "actor_debugger"] # auto-detect the Actor's entrypoint
CMD ["python3", "-m", "actor_debugger", "-m", "src"] # explicit module
CMD ["python3", "-m", "actor_debugger", "main.py"] # explicit file
CMD ["python3", "-m", "actor_debugger", "--brk"] # pause on the first line until attached
Running through this command is what enables debugging - revert the CMD to the normal
entrypoint to turn it off.
"""
from __future__ import annotations
import os
import signal
import socket
import subprocess
import sys
import threading
import time
from .debug_server import start_debug_server
ADAPTER_PORT = 5678
TAG = "[actor-debugger]"
def log(message: str) -> None:
print(f"{TAG} {message}", file=sys.stderr, flush=True)
# The apify/actor-python base image ships a placeholder src/ package (default CMD is
# `python -m src`) that only prints a "replace this file" warning - it exists in EVERY
# image built on that base, so auto-detection must never mistake it for the Actor's code.
_PLACEHOLDER_MARKER = b"set up your Docker image correctly"
def _is_placeholder(*paths: str) -> bool:
for path in paths:
try:
with open(path, "rb") as f:
if _PLACEHOLDER_MARKER in f.read(65536):
return True
except OSError:
continue
return False
def _runnable_packages() -> list[str]:
"""Top-level packages that `python -m <name>` can run, excluding placeholders.
Covers every current Apify Python template (`my_actor/`), older ones (`src/`), and
Crawlee-generated projects, whose package is named after the project - so the scan is
by shape (a directory with __main__.py), not by name.
"""
found = []
for name in sorted(os.listdir(".")):
if name.startswith(".") or name in ("__pycache__", "actor_debugger", "node_modules", "storage"):
continue
main_file = os.path.join(name, "__main__.py")
if not os.path.isfile(main_file):
continue
if _is_placeholder(main_file, os.path.join(name, "main.py")):
log(f"ignored -m {name}: it is the apify/actor-python base-image placeholder, not your code.")
continue
found.append(name)
return found
def resolve_entry(args: list[str]) -> list[str] | None:
"""Return the argv tail (["-m", "pkg"] or ["path.py"]) for the Actor's entrypoint."""
if "-m" in args:
module = args[args.index("-m") + 1 :][:1]
if module:
return ["-m", module[0]]
positional = [a for a in args if not a.startswith("-")]
if positional:
return [os.path.abspath(positional[0])]
packages = _runnable_packages()
if len(packages) == 1:
return ["-m", packages[0]]
if len(packages) > 1:
# Prefer the template conventions when a project carries several runnable packages.
for preferred in ("src", "my_actor"):
if preferred in packages:
log(f"multiple runnable packages found ({', '.join(packages)}); picking -m {preferred}.")
return ["-m", preferred]
log(f"multiple runnable packages found: {', '.join(packages)} - pass one explicitly:")
log(f' CMD ["python3", "-m", "actor_debugger", "-m", "{packages[0]}"]')
return None
if os.path.isfile("src/main.py") and not _is_placeholder("src/main.py"):
return ["-m", "src.main"]
for candidate in ("main.py", "__main__.py", "app.py"):
if os.path.isfile(candidate):
if _is_placeholder(candidate):
log(f"ignored {candidate}: it is the apify/actor-python base-image placeholder, not your code.")
continue
return [os.path.abspath(candidate)]
return None
def entry_file_path(entry: list[str]) -> str:
"""Best-effort path of the file that runs first, for the frontend's --brk entry stop."""
if entry[0] != "-m":
return entry[0]
base = entry[1].replace(".", os.sep)
for candidate in (os.path.join(base, "__main__.py"), base + ".py"):
if os.path.isfile(candidate):
return os.path.abspath(candidate)
return ""
def wait_for_adapter(port: int, timeout: float = 30.0) -> bool:
"""Wait until something listens on the adapter port WITHOUT connecting to it.
debugpy treats the first accepted connection as its DAP client and shuts the session
down when it drops, so probing with a real connect would kill the adapter. A bind
attempt failing with EADDRINUSE detects the listener without ever touching it.
"""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
probe.bind(("127.0.0.1", port))
except OSError:
return True
finally:
probe.close()
time.sleep(0.25)
return False
def announce(web_server_url: str) -> None:
if not wait_for_adapter(ADAPTER_PORT):
log(f"debugpy adapter did not come up on 127.0.0.1:{ADAPTER_PORT}.")
return
base = web_server_url.rstrip("/")
log("=" * 64)
log("debugging is ON - reachable over the container URL.")
log("OPEN THIS in your local browser for a full debugger UI (no local setup):")
log(f" {base}/ui/")
host = base.split("://", 1)[-1]
log(f"raw DAP-over-WebSocket channel (one JSON message per frame): wss://{host}/dap")
log("=" * 64)
def main() -> None:
args = sys.argv[1:]
brk = "--brk" in args
entry = resolve_entry([a for a in args if a != "--brk"])
if not entry:
log("could not find an Actor entrypoint. Pass one explicitly, e.g.:")
log(' CMD ["python3", "-m", "actor_debugger", "-m", "src"]')
log(' CMD ["python3", "-m", "actor_debugger", "server.py"]')
sys.exit(1)
log(f"entrypoint: {' '.join(entry)}")
debugpy_argv = [
sys.executable,
"-Xfrozen_modules=off",
"-m",
"debugpy",
"--listen",
f"127.0.0.1:{ADAPTER_PORT}",
*(["--wait-for-client"] if brk else []),
*entry,
]
env = {**os.environ, "PYDEVD_DISABLE_FILE_VALIDATION": "1"}
child = subprocess.Popen(debugpy_argv, env=env)
server = None
port = os.environ.get("ACTOR_WEB_SERVER_PORT")
url = os.environ.get("ACTOR_WEB_SERVER_URL")
if port and url:
frontend_dir = os.path.join(os.path.dirname(__file__), "frontend")
server = start_debug_server(int(port), ADAPTER_PORT, frontend_dir, brk=brk, entry_path=entry_file_path(entry))
threading.Thread(target=announce, args=(url,), daemon=True).start()
if brk:
log("--brk: the Actor is paused on its first line until you attach from the browser.")
else:
log(f"ACTOR_WEB_SERVER_URL/PORT not set - DAP on 127.0.0.1:{ADAPTER_PORT} only (no container-URL bridge).")
def forward(signum, _frame):
child.send_signal(signum)
signal.signal(signal.SIGTERM, forward)
signal.signal(signal.SIGINT, forward)
code = child.wait()
if server:
server.shutdown()
sys.exit(code)
if __name__ == "__main__":
main()