oncolab 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
oncolab/__init__.py ADDED
File without changes
oncolab/cli.py ADDED
@@ -0,0 +1,528 @@
1
+ import argparse
2
+ import base64
3
+ import inspect
4
+ import json
5
+ import os
6
+ import re
7
+ import secrets
8
+ import shlex
9
+ import socket
10
+ import subprocess as sp
11
+ import sys
12
+ import termios
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from contextlib import contextmanager
15
+ from importlib.metadata import version
16
+ from importlib.resources import files
17
+ from pathlib import Path
18
+ from signal import SIGINT, SIG_IGN, signal
19
+ from tempfile import TemporaryDirectory, TemporaryFile
20
+ from threading import Event
21
+
22
+ from .config import plan, read_rclone_config
23
+ from .copy import ARCHIVE_WORKERS, COPY_FAILED, INPUT_CLOSED, copy_plan, send_archive, send_input
24
+ from .env import parse_env
25
+ from .progress import progress, run_step
26
+
27
+
28
+ @contextmanager
29
+ def without_echo(enabled):
30
+ if not (enabled and sys.stdin.isatty()):
31
+ yield False
32
+ return
33
+ fd = sys.stdin.fileno()
34
+ original = termios.tcgetattr(fd)
35
+ quiet = original.copy()
36
+ quiet[3] &= ~(termios.ECHO | termios.ECHONL)
37
+ termios.tcsetattr(fd, termios.TCSANOW, quiet)
38
+ try:
39
+ yield bool(original[3] & termios.ECHO)
40
+ finally:
41
+ termios.tcsetattr(fd, termios.TCSANOW, original)
42
+
43
+
44
+ def release(name, terminal, color):
45
+ with without_echo(terminal):
46
+ result = run_step("Releasing Colab VM…", lambda: sp.run(
47
+ ["colab", "stop", "-s", name], capture_output=True, stdin=sp.DEVNULL,
48
+ ), terminal, color)
49
+ if result.returncode:
50
+ print(f"oncolab: could not confirm release of {name!r}; check colab sessions", file=sys.stderr)
51
+
52
+
53
+ def allocate(flags, terminal, color):
54
+ cancelled = False
55
+
56
+ def cancel(*_):
57
+ nonlocal cancelled
58
+ if not cancelled and not terminal:
59
+ print("Cancelling: waiting for Colab…", file=sys.stderr, flush=True)
60
+ cancelled = True
61
+
62
+ def label():
63
+ return "Cancelling: waiting for Colab…" if cancelled else "Creating Colab VM…"
64
+
65
+ previous = signal(SIGINT, cancel)
66
+ try:
67
+ with without_echo(terminal) as echo_was_on:
68
+ result = run_step(label, lambda: sp.run(
69
+ ["colab", "new", *flags], capture_output=True, start_new_session=True,
70
+ ), terminal, color)
71
+ finally:
72
+ signal(SIGINT, previous)
73
+ match = re.search(rb"^\[colab\] Creating session '([A-Za-z0-9_-]+)'", result.stdout, re.MULTILINE)
74
+ name = match[1].decode() if match and not result.returncode else None
75
+ if cancelled:
76
+ signal(SIGINT, SIG_IGN)
77
+ try:
78
+ if name:
79
+ release(name, terminal, color)
80
+ else:
81
+ print("oncolab: could not confirm allocation; check colab sessions", file=sys.stderr)
82
+ cancel_footer(echo_was_on, color)
83
+ finally:
84
+ signal(SIGINT, previous)
85
+ return None, 130
86
+ if name:
87
+ return name, 0
88
+ error = re.sub(rb"\x1b\[[0-?]*[ -/]*[@-~]", b"", result.stderr)
89
+ if allocation_unavailable(error):
90
+ print("oncolab: Google Colab could not allocate a VM (503 Service Unavailable). "
91
+ "Try again in a moment.", file=sys.stderr)
92
+ else:
93
+ sys.stderr.buffer.write(result.stdout + result.stderr)
94
+ return None, result.returncode or 1
95
+
96
+
97
+
98
+ def allocation_unavailable(stderr):
99
+ # Rich may wrap the URL in the final exception across terminal lines.
100
+ _, found, message = stderr.rpartition(b"ColabRequestError:")
101
+ return bool(found and re.fullmatch(
102
+ rb"\s*Failed to issue request POST\s+"
103
+ rb"https://colab\.research\.google\.com/tun/m/assign\?[^:]*:"
104
+ rb"\s*Service Unavailable\s*",
105
+ message,
106
+ ))
107
+
108
+ def cancel_footer(echo, color):
109
+ tty = sys.stderr.isatty() and os.environ.get("TERM", "dumb") != "dumb"
110
+ prefix = "^C\n" if echo and tty else ""
111
+ if tty and color:
112
+ from prompt_toolkit import print_formatted_text
113
+ from prompt_toolkit.formatted_text import FormattedText
114
+
115
+ print_formatted_text(FormattedText([("", prefix), ("class:aborting", "[cancelled]")]),
116
+ file=sys.stderr, flush=True)
117
+ else:
118
+ print(prefix + "[cancelled]", file=sys.stderr, flush=True)
119
+
120
+
121
+ def ssh_options(name):
122
+ proxy = ["colab", "ssh", "--proxy-mode", "-s", name]
123
+ for filename in ("id_ed25519.pub", "id_ecdsa.pub"):
124
+ public = Path.home() / ".ssh" / filename
125
+ if public.is_file():
126
+ proxy += ["--identity", str(public)]
127
+ private = public.with_suffix("")
128
+ return proxy, ["-o", "IdentitiesOnly=yes", "-i", str(private if private.is_file() else public)], public
129
+ return proxy, [], None
130
+
131
+
132
+ # File contents and runtime environment values travel via SSH stdin, not argv.
133
+ STAGE = """import base64, json, os, sys
134
+ from pathlib import Path
135
+ os.umask(0o077)
136
+ for directory, entries in json.load(sys.stdin).items():
137
+ path = Path(directory)
138
+ path.mkdir(mode=0o700)
139
+ for name, encoded in entries.items():
140
+ with (path / name).open("xb") as file:
141
+ file.write(base64.b64decode(encoded))
142
+ """
143
+
144
+
145
+ def upload(ssh, target, result, sources=(), targets=(), modes=None):
146
+ helper = files("oncolab").joinpath("copy.py").read_text()
147
+ channel = [*ssh, "-T", "-o", "ProxyCommand=false", "-o", "ControlMaster=no", target]
148
+ args = [json.dumps(targets)]
149
+ if modes is not None:
150
+ args.append(json.dumps(modes))
151
+ command = shlex.join(["python3", "-c", helper, result, *args])
152
+ try:
153
+ with TemporaryFile() as diagnostic, sp.Popen(
154
+ [*channel, command], stdin=sp.PIPE, stdout=sp.DEVNULL, stderr=diagnostic,
155
+ ) as process:
156
+ try:
157
+ with process.stdin:
158
+ send_archive(process.stdin, sources)
159
+ except (OSError, ValueError) as exc:
160
+ local_error = exc
161
+ else:
162
+ local_error = None
163
+ status = process.wait()
164
+ diagnostic.seek(0)
165
+ detail = diagnostic.read().decode(errors="replace").strip()
166
+ if not status and not local_error:
167
+ return None, True
168
+ # A closed pipe is usually a symptom of the receiver's error.
169
+ if isinstance(local_error, BrokenPipeError) and detail:
170
+ local_error = None
171
+ error = (str(local_error) if local_error is not None else detail) or f"copy channel exited with status {status}"
172
+ if status in (0, COPY_FAILED):
173
+ return error, True
174
+ except OSError as exc:
175
+ error = str(exc)
176
+ # If the receiver never launched, wake the remote runner as a failure.
177
+ mark = shlex.join(["python3", "-c", helper, result, "--failed"])
178
+ notified = sp.run([*channel, mark], stdin=sp.DEVNULL, stdout=sp.DEVNULL,
179
+ stderr=sp.DEVNULL).returncode == 0
180
+ return error, notified
181
+
182
+
183
+ def call_with_upload(argv, transfer):
184
+ process = sp.Popen(argv)
185
+ try:
186
+ while not transfer.done():
187
+ try:
188
+ status = process.wait(timeout=.2)
189
+ except sp.TimeoutExpired:
190
+ continue
191
+ return status
192
+ _, notified = transfer.result()
193
+ # Otherwise the remote runner could wait for a marker that cannot arrive.
194
+ if not notified and process.poll() is None:
195
+ return 255
196
+ return process.wait()
197
+ finally:
198
+ if process.poll() is None:
199
+ process.terminate()
200
+ process.wait()
201
+
202
+
203
+ def upload_stream(endpoint, key, source):
204
+ # Unlike an SSH exec channel, each streamlocal forward is not counted
205
+ # against MaxSessions. Keep data off the control channel and payload stdin.
206
+ local_error = None
207
+ try:
208
+ with socket.socket(socket.AF_UNIX) as link:
209
+ link.connect(str(endpoint))
210
+ link.sendall(key.encode("ascii") + b"\n")
211
+ try:
212
+ with link.makefile("wb") as stream:
213
+ send_input(stream, source)
214
+ except (OSError, ValueError) as exc:
215
+ local_error = exc
216
+ try:
217
+ link.shutdown(socket.SHUT_WR)
218
+ except OSError:
219
+ pass
220
+ reply = link.recv(1)
221
+ except OSError as exc:
222
+ return f"could not open task stdin for {source.name}: {exc}", False
223
+ status = reply[0] if reply else None
224
+ if status == 0 and local_error is None:
225
+ return None, True
226
+ if status == INPUT_CLOSED and (local_error is None or isinstance(local_error, BrokenPipeError)):
227
+ return None, True
228
+ notified = status in (0, COPY_FAILED, INPUT_CLOSED)
229
+ detail = str(local_error) if local_error else ("stream interrupted" if notified else "connection lost")
230
+ return f"could not stream {source.name} to task stdin: {detail}", notified
231
+
232
+
233
+ def upload_tasks(ssh, target, jobdir, groups, endpoint=None):
234
+ channel = [*ssh, "-T", "-o", "ProxyCommand=false", "-o", "ControlMaster=no", target]
235
+ helper = files("oncolab").joinpath("copy.py").read_text()
236
+ types = {key: source is not None for key, (_, source) in groups.items()}
237
+ command = shlex.join(["python3", "-c", helper, "--broker", jobdir, json.dumps(types)])
238
+ jobs, errors = [], []
239
+ with (
240
+ ThreadPoolExecutor(max_workers=ARCHIVE_WORKERS) as archives,
241
+ ThreadPoolExecutor(max_workers=max(1, sum(types.values()))) as streams,
242
+ TemporaryFile() as diagnostic,
243
+ sp.Popen([*channel, command], stdin=sp.DEVNULL, stdout=sp.PIPE,
244
+ stderr=diagnostic, text=True) as broker,
245
+ ):
246
+ def report_result(job):
247
+ if job.cancelled():
248
+ return
249
+ if job.exception() is not None:
250
+ notified = False
251
+ else:
252
+ error, notified = job.result()
253
+ if error:
254
+ # Ready services can finish receiving stdin after the command starts.
255
+ # Report late failures now, without cutting off SSH or teardown.
256
+ print(f"oncolab: {error}", file=sys.stderr, flush=True)
257
+ if not notified and broker.poll() is None:
258
+ # Dropping only the broker wakes the remote copy waiters.
259
+ broker.terminate()
260
+
261
+ for line in broker.stdout:
262
+ key = line.rstrip("\n")
263
+ if key not in groups:
264
+ continue
265
+ entries, input_source = groups.pop(key)
266
+ if input_source is None:
267
+ sources, targets, modes = zip(*entries)
268
+ job = archives.submit(upload, ssh, target, f"{jobdir}/{key}/copy-result", sources, targets, modes)
269
+ else:
270
+ job = streams.submit(upload_stream, endpoint, key, input_source)
271
+ jobs.append(job)
272
+ job.add_done_callback(report_result)
273
+ if broker.wait():
274
+ diagnostic.seek(0)
275
+ error = diagnostic.read().decode(errors="replace").strip() or "task copy channel disconnected"
276
+ print(f"oncolab: {error}", file=sys.stderr, flush=True)
277
+ errors.append(error)
278
+ for job in jobs:
279
+ job.cancel()
280
+ for job in jobs:
281
+ if job.cancelled():
282
+ continue
283
+ error, _ = job.result()
284
+ if error:
285
+ errors.append(error)
286
+ return errors
287
+
288
+
289
+ def prepare_copies(config, specs, explicit):
290
+ mounts = [Path(mount["target"]) for mount in config["mounts"].values()]
291
+ workdir = config["workdir"]
292
+ cli_copies = copy_plan(specs, workdir, mounts, explicit=explicit)
293
+ task_groups = {}
294
+ targets = [Path(target) for _, target in cli_copies]
295
+ for name, step in config.get("setup", {}).items():
296
+ entries = step.pop("copies", ())
297
+ group = []
298
+ for local, target, mode in entries:
299
+ if target == "-":
300
+ source = Path(local)
301
+ if source.is_symlink() or not source.is_file():
302
+ raise ValueError(f"setup.{name}.copy: stdin source must be a regular file: {local}")
303
+ group.append((source.resolve(), "-", 0o600))
304
+ step["input"] = True
305
+ continue
306
+ [(source, destination)] = copy_plan([], workdir, mounts, explicit=[(local, target)])
307
+ dest = Path(destination)
308
+ if Path(workdir).is_relative_to(dest):
309
+ raise ValueError(f"setup.{name}.copy: destination cannot contain workdir: {destination}")
310
+ if any(dest.is_relative_to(other) or other.is_relative_to(dest) for other in targets):
311
+ raise ValueError(f"Overlapping --copy destination: {destination}")
312
+ targets.append(dest)
313
+ group.append((source, destination, mode))
314
+ if group:
315
+ task_groups[name] = group
316
+ return cli_copies, task_groups
317
+
318
+
319
+ def run_session(name, config, rclone_ini, known_hosts, command, forward, terminal, color, attempted, *,
320
+ copies=(), task_copies=None):
321
+ proxy, identity, public = ssh_options(name)
322
+ target = "root@colab-runtime"
323
+ drive_stage = "/dev/shm/oncolab-" + secrets.token_hex(12)
324
+ remote = inspect.getsource(progress) + "\n" + files("oncolab").joinpath("remote.py").read_text()
325
+ jobdir = drive_stage + "-job"
326
+ result = jobdir + "/copy-result"
327
+ config = dict(config)
328
+ env = config.pop("env", {})
329
+ command_env = config.pop("command_env", {})
330
+ ports = config.pop("ports", ())
331
+ task_copies = task_copies or {}
332
+ groups = {}
333
+ config["setup"] = {name: dict(step) for name, step in config["setup"].items()}
334
+ markers = {"copy-result": "", "copy-ok": "ok", "copy-failed": "failed"}
335
+ sources, targets = zip(*copies) if copies else ((), ())
336
+ if env or command_env or sources or task_copies:
337
+ config["jobdir"] = jobdir
338
+ if env or command_env:
339
+ config["has_env"] = True
340
+ if sources:
341
+ config["copy_result"] = result
342
+ config["copy_supplies_workdir"] = any(Path(config["workdir"]).is_relative_to(path) for path in targets)
343
+ staging = {}
344
+ if rclone_ini is not None:
345
+ staging[drive_stage] = {"rclone.conf": rclone_ini}
346
+ if env or command_env or sources or task_copies:
347
+ staging[jobdir] = {"env.json": json.dumps([env, command_env])} if env or command_env else {}
348
+ if sources:
349
+ staging[jobdir].update(markers)
350
+ for number, (task, entries) in enumerate(task_copies.items()):
351
+ key = f"task-{number}"
352
+ copies_in_task = [entry for entry in entries if entry[1] != "-"]
353
+ if copies_in_task:
354
+ directory = f"{jobdir}/{key}"
355
+ staging[directory] = markers
356
+ config["setup"][task]["copy_result"] = f"{directory}/copy-result"
357
+ groups[key] = (copies_in_task, None)
358
+ source = next((source for source, destination, _ in entries if destination == "-"), None)
359
+ config["setup"][task].pop("input", None)
360
+ if source is not None:
361
+ key += "-input"
362
+ directory = f"{jobdir}/{key}"
363
+ staging[directory] = {**markers, "copy-short": "short"}
364
+ config["setup"][task]["stdin_result"] = f"{directory}/copy-result"
365
+ groups[key] = ((), source)
366
+ # The bootstrap channel must never read the command's stdin.
367
+ staged_input = json.dumps({
368
+ directory: {name: base64.b64encode(value.encode() if isinstance(value, str) else value).decode("ascii")
369
+ for name, value in entries.items()}
370
+ for directory, entries in staging.items()
371
+ }).encode() if staging else b""
372
+ payload = shlex.join(["uv", "run", "--no-project", "python3", "-c", remote, drive_stage,
373
+ str(int(color)), json.dumps(config), *command])
374
+ trust = (["-o", "StrictHostKeyChecking=yes", "-o", f"UserKnownHostsFile={known_hosts}"]
375
+ if known_hosts else ["-o", "StrictHostKeyChecking=no", "-o", f"UserKnownHostsFile={os.devnull}"])
376
+ with TemporaryDirectory(prefix="oc-", dir="/tmp") as tmp, ThreadPoolExecutor(2) as transfers:
377
+ ssh = ["ssh", "-F", os.devnull, "-S", f"{tmp}/ssh", "-o", "LogLevel=ERROR", "-A" if forward else "-a"]
378
+ connect_options = [*identity, "-M", "-T", "-o", "ControlPersist=60",
379
+ "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3",
380
+ "-o", "ProxyCommand=" + shlex.join(proxy), *trust]
381
+ endpoint = f"{tmp}/stdin.sock" if any(source is not None for _, source in groups.values()) else None
382
+ if ports or endpoint:
383
+ connect_options.extend(("-o", "ExitOnForwardFailure=yes"))
384
+ if endpoint:
385
+ connect_options.extend(("-L", f"{endpoint}:{jobdir}/stdin.sock"))
386
+ for local, remote_port in ports:
387
+ connect_options.extend(("-L", f"127.0.0.1:{local}:127.0.0.1:{remote_port}"))
388
+ terminal_connect = False
389
+ if terminal and public:
390
+ keys = sp.run(["ssh-add", "-L"], capture_output=True).stdout.splitlines()
391
+ advertised = public.read_bytes().split()[:2]
392
+ terminal_connect = any(key.split()[:2] == advertised for key in keys)
393
+ pending = [f"{directory}/{file}" for directory, file in
394
+ ((drive_stage, "rclone.conf"), (jobdir, "env.json")) if file in staging.get(directory, {})]
395
+ master_closed = False
396
+
397
+ def close_master():
398
+ nonlocal master_closed
399
+ if master_closed:
400
+ return
401
+ master_closed = True
402
+ try:
403
+ if pending:
404
+ # The runner claims these names by rename; never remove active files.
405
+ command = shlex.join(["rm", "-f", "--", *pending])
406
+ try:
407
+ cleanup = sp.run(
408
+ [*ssh, "-T", "-o", "ProxyCommand=false", "-o", "ControlMaster=no", target, command],
409
+ stdin=sp.DEVNULL, stdout=sp.DEVNULL, stderr=sp.DEVNULL, timeout=5,
410
+ )
411
+ confirmed = cleanup.returncode == 0
412
+ except (OSError, sp.TimeoutExpired):
413
+ confirmed = False
414
+ if not confirmed:
415
+ print(f"oncolab: could not confirm cleanup of unclaimed credentials for {name!r}",
416
+ file=sys.stderr)
417
+ finally:
418
+ sp.run([*ssh, "-O", "exit", target], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
419
+
420
+ stage = shlex.join(["python3", "-c", STAGE]) if staging else "true"
421
+ try:
422
+ with without_echo(terminal_connect):
423
+ connected = run_step("Connecting via SSH…", lambda: sp.run(
424
+ [*ssh, *connect_options, target, stage],
425
+ input=staged_input, capture_output=terminal_connect,
426
+ ), terminal_connect, color)
427
+ if terminal_connect:
428
+ # Setup diagnostics must not mix with payload stdout.
429
+ sys.stderr.buffer.write(connected.stderr)
430
+ sys.stderr.flush()
431
+ if connected.returncode:
432
+ return connected.returncode, True
433
+ tty = "-t" if sys.stdin.isatty() and sys.stdout.isatty() else "-T"
434
+ attempted.set()
435
+ transfer = transfers.submit(upload, ssh, target, result, sources, targets) if sources else None
436
+ task_upload = transfers.submit(upload_tasks, ssh, target, jobdir, groups, endpoint) if groups else None
437
+ argv = [*ssh, "-o", "ProxyCommand=false", "-o", "ControlMaster=no", tty, target, payload]
438
+ status = call_with_upload(argv, transfer) if transfer else sp.call(argv)
439
+ if status == 0:
440
+ pending.clear()
441
+ if status and ((transfer and not transfer.done()) or (task_upload and not task_upload.done())):
442
+ close_master()
443
+ if transfer:
444
+ error, _ = transfer.result()
445
+ if error:
446
+ print(f"oncolab: {error}", file=sys.stderr)
447
+ status = status or 1
448
+ if task_upload:
449
+ try:
450
+ transfer_errors = task_upload.result(timeout=3)
451
+ except TimeoutError:
452
+ # The payload has exited; no remote teardown can still be waiting on this broker.
453
+ close_master()
454
+ transfer_errors = task_upload.result()
455
+ if transfer_errors:
456
+ status = status or 1
457
+ return status, False
458
+ finally:
459
+ close_master()
460
+
461
+
462
+ def main():
463
+ parser = argparse.ArgumentParser(description="Run a terminal command on a fresh Google Colab VM.")
464
+ parser.add_argument("--version", action="version", version=f"oncolab {version('oncolab')}")
465
+ parser.add_argument("--copy", action="append", default=[], metavar="LOCAL[:REMOTE]",
466
+ help="Copy a file or directory to the VM before running; repeatable")
467
+ parser.add_argument("--copy-to", action="append", nargs=2, default=[], metavar=("LOCAL", "REMOTE"),
468
+ help="Copy using separate literal paths; repeatable")
469
+ parser.add_argument("--mount", action="append", default=[], metavar="source=REMOTE:PATH,target=PATH[,readonly]",
470
+ help="Mount an rclone remote path; read/write by default, add ,readonly for read-only; repeatable")
471
+ parser.add_argument("-p", "--publish", action="append", default=[], metavar="LOCAL_PORT:REMOTE_PORT",
472
+ help="Forward a local loopback TCP port to the VM; repeatable")
473
+ parser.add_argument("-e", "--env", action="append", default=[], metavar="NAME[=VALUE]",
474
+ help="Set a value or forward a named local variable; repeatable")
475
+ parser.add_argument("--config", type=Path, help="Use an explicit local TOML configuration")
476
+ hardware = parser.add_mutually_exclusive_group()
477
+ hardware.add_argument("--gpu", metavar="MODEL",
478
+ help="Request a GPU: T4, L4, G4, A100, H100 (subject to availability)")
479
+ hardware.add_argument("--tpu", metavar="MODEL",
480
+ help="Request a TPU: V5E1, V6E1 (subject to availability)")
481
+ parser.add_argument("--high-mem", action="store_true", help="Request a high-memory VM")
482
+ parser.add_argument("-A", "--forward-agent", action="store_true", help="Forward the local SSH agent")
483
+ parser.add_argument("command", nargs=argparse.REMAINDER, metavar="COMMAND")
484
+ args = parser.parse_args()
485
+ command = args.command[1:] if args.command[:1] == ["--"] else args.command
486
+ if not command:
487
+ parser.error("a command is required")
488
+ try:
489
+ config, rclone_path, known_hosts = plan(args.config, cli_mounts=args.mount, cli_ports=args.publish)
490
+ config["command_env"] = parse_env(args.env)
491
+ copies, task_groups = prepare_copies(config, args.copy, args.copy_to)
492
+ ini = read_rclone_config(rclone_path) if rclone_path is not None else None
493
+ except (ValueError, OSError) as exc:
494
+ parser.error(str(exc))
495
+ flags = ["--gpu", args.gpu] if args.gpu else ["--tpu", args.tpu] if args.tpu else []
496
+ if args.high_mem:
497
+ flags.append("--high-mem")
498
+ color = not os.environ.get("NO_COLOR")
499
+ terminal = sys.stdout.isatty() and os.environ.get("TERM", "dumb") != "dumb"
500
+ name = None
501
+ attempted = Event()
502
+ try:
503
+ name, status = allocate(flags, terminal, color)
504
+ if not name:
505
+ return status
506
+ status, fallback = run_session(name, config, ini, known_hosts, command,
507
+ args.forward_agent, terminal, color, attempted, copies=copies,
508
+ **({"task_copies": task_groups} if task_groups else {}))
509
+ if fallback:
510
+ release(name, terminal, color)
511
+ if attempted.is_set() and (status == 255 or status < 0):
512
+ print(f"oncolab: SSH status is ambiguous; check Colab session {name!r}", file=sys.stderr)
513
+ return status if status >= 0 else 128 - status
514
+ except KeyboardInterrupt:
515
+ # After allocation, an interrupted SSH connection may leave the mount
516
+ # running. Do not force-stop a VM with potentially pending writes.
517
+ if name and not attempted.is_set():
518
+ signal(SIGINT, SIG_IGN)
519
+ release(name, terminal, color)
520
+ elif name:
521
+ print(f"oncolab: check colab sessions for {name!r} if it is still running", file=sys.stderr)
522
+ cancel_footer(False, color)
523
+ return 130
524
+ except OSError as exc:
525
+ print(f"oncolab: {exc}", file=sys.stderr)
526
+ if name and not attempted.is_set():
527
+ release(name, terminal, color)
528
+ return 1