-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtarget.py
More file actions
executable file
·788 lines (667 loc) · 26.2 KB
/
Copy pathtarget.py
File metadata and controls
executable file
·788 lines (667 loc) · 26.2 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
#!/usr/bin/env python3
import os
import sys
import subprocess
import tempfile
import shutil
import json
import urllib.request
import signal
import argparse
import random
import shlex
import string
import time
from pathlib import Path
from typing import ClassVar, Dict, List, Optional
from dataclasses import dataclass
import ssl
import platform
ssl._create_default_https_context = ssl._create_unverified_context
@dataclass
class Config:
"""Constants and runtime configuration for the script.
Instance fields are populated by `Config.from_args(args)` with precedence:
CLI flag > env var > default. ClassVar fields are true constants.
"""
# CLI/env-driven values
host_data_path: str # JAM_FUZZ_DATA_PATH
docker_cpu_set: str # JAM_FUZZ_DOCKER_CPU_SET
targets_dir: str # JAM_FUZZ_TARGETS_DIR
targets_file: str # JAM_FUZZ_TARGETS_FILE, --targets-file
spec: str # JAM_FUZZ_SPEC, --spec
log_level: str # JAM_FUZZ_LOG_LEVEL
# True constants
DEFAULT_DOCKER_IMAGE: ClassVar[str] = "debian:stable-slim"
DOCKER_PLATFORM: ClassVar[str] = "linux/amd64"
# Standard JAM fuzz packaging paths inside the container (see fuzz-proto/README.md).
CONTAINER_DATA_PATH: ClassVar[str] = "/tmp/jam_fuzz"
CONTAINER_SOCK_PATH: ClassVar[str] = "/tmp/jam_fuzz/fuzz.sock"
CURRENT_DIR: ClassVar[str] = os.getcwd()
SCRIPT_DIR: ClassVar[str] = os.path.dirname(os.path.abspath(__file__))
@classmethod
def from_args(cls, args) -> "Config":
cpu_default = f"0-{os.cpu_count() - 1}"
spec = os.environ.get("JAM_FUZZ_SPEC", "tiny")
if args.action == "run" and args.spec:
spec = args.spec
return cls(
host_data_path=os.environ.get("JAM_FUZZ_DATA_PATH", "/tmp/jam_fuzz"),
docker_cpu_set=os.environ.get("JAM_FUZZ_DOCKER_CPU_SET", cpu_default),
targets_dir=os.environ.get("JAM_FUZZ_TARGETS_DIR", f"{cls.CURRENT_DIR}/targets"),
targets_file=args.targets_file or os.environ.get(
"JAM_FUZZ_TARGETS_FILE", f"{cls.SCRIPT_DIR}/targets.json"
),
spec=spec,
log_level=os.environ.get("JAM_FUZZ_LOG_LEVEL", "info"),
)
CONFIG: Optional[Config] = None
@dataclass
class Target:
name: str
repo: Optional[str] = None
image: Optional[str] = None
file: Optional[str] = None
cmd: Optional[str] = None
args: Optional[str] = None
env: Optional[str] = None
gp_version: Optional[str] = None
def is_docker_target(self) -> bool:
"""Check if this is a Docker target."""
return self.image is not None
def is_repo_target(self) -> bool:
"""Check if this is a repository target."""
return self.repo is not None
def load_targets() -> Dict[str, Target]:
"""Load target configuration from JSON file and convert to Target instances."""
try:
with open(CONFIG.targets_file, "r") as f:
text = f.read().replace("{SOCK_PATH}", CONFIG.CONTAINER_SOCK_PATH)
except FileNotFoundError:
print(f"Error: targets.json not found at {CONFIG.targets_file}")
sys.exit(1)
try:
targets_data = json.loads(text)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in targets.json: {e}")
sys.exit(1)
return {name: Target(name=name, **cfg) for name, cfg in targets_data.items()}
def create_parser() -> argparse.ArgumentParser:
"""Create and configure the argument parser."""
parser = argparse.ArgumentParser(
description="JAM conformance target manager - download and run JAM implementation targets",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s list # List all available targets
%(prog)s get jamzig # Download jamzig target
%(prog)s run boka # Run boka target
%(prog)s info boka # Show info for boka target
Environment variables (all overridable via CLI flags listed above):
JAM_FUZZ_TARGETS_FILE Path to targets JSON file (default: <script>/targets.json)
JAM_FUZZ_TARGETS_DIR Where downloaded targets are stored (default: ./targets)
JAM_FUZZ_DATA_PATH Host data directory (default: /tmp/jam_fuzz)
JAM_FUZZ_DOCKER_CPU_SET CPU set for Docker containers (default: all cores)
JAM_FUZZ_SPEC Specification: tiny or full (default: tiny)
JAM_FUZZ_LOG_LEVEL Log level forwarded to the target (default: info)
GITHUB_TOKEN Optional bearer token for GitHub release lookups
""",
)
parser.add_argument(
"--spec",
choices=["tiny", "full"],
default=None,
help="Specification to use (tiny or full, overrides JAM_FUZZ_SPEC env var)"
)
parser.add_argument(
"--targets-file",
type=str,
default=None,
help="Path to targets JSON file (overrides JAM_FUZZ_TARGETS_FILE env var)",
)
subparsers = parser.add_subparsers(
dest="action", help="Action to perform", required=True
)
# Get subcommand
get_parser = subparsers.add_parser("get", help="Download target")
get_parser.add_argument(
"target",
metavar="TARGET",
help="Target to download",
)
# Run subcommand
run_parser = subparsers.add_parser("run", help="Run target")
run_parser.add_argument(
"target", metavar="TARGET", help="Target to run"
)
run_parser.add_argument(
"--target-args",
type=str,
default="",
help="Extra target args to append to the ones found in target.json"
)
run_parser.add_argument(
"--target-env",
type=str,
default="",
help="Extra environment variables (space-separated KEY=VALUE pairs) to extend target env"
)
run_parser.add_argument(
"--container-name",
type=str,
help="Specify custom Docker container name (default: auto-generated with random suffix)",
)
run_parser.add_argument(
"--docker-elevate-priority",
action="store_true",
help="Elevate Docker container priority (Linux only, requires sudo)",
)
# Info subcommand
info_parser = subparsers.add_parser("info", help="Show target information")
info_parser.add_argument(
"target",
metavar="TARGET",
help="Target to show info for",
)
# Clean subcommand
clean_parser = subparsers.add_parser("clean", help="Clean target files")
clean_parser.add_argument(
"target",
metavar="TARGET",
help="Target to clean",
)
# List subcommand
list_parser = subparsers.add_parser("list", help="List all available targets")
list_parser.add_argument(
"--gp-version",
type=str,
help="Filter targets by gp-version (e.g., 0.7.0, 0.7.1)",
)
return parser
def _clean_host_data() -> None:
try:
shutil.rmtree(CONFIG.host_data_path)
except FileNotFoundError:
pass
# Trailing suffixes -> extractor command. Multi-suffix entries must come first
# so e.g. .tar.gz isn't peeled as just .tar.
ARCHIVE_EXTRACTORS = [
((".tar", ".gz"), ["tar", "-xzf"]),
((".tar", ".bz2"), ["tar", "-xjf"]),
((".tar", ".xz"), ["tar", "-xJf"]),
((".zip",), ["unzip"]),
((".tgz",), ["tar", "-xzf"]),
((".tbz2",), ["tar", "-xjf"]),
((".txz",), ["tar", "-xJf"]),
((".tar",), ["tar", "-xf"]),
]
def post_actions(target: Target) -> bool:
if not target.file:
return False
print(f"Performing post actions for {target.file}")
target_dir = Path(f"{CONFIG.targets_dir}/{target.name}/latest")
# Extract nested archives by peeling off extensions
current_file = target_dir / target.file
while current_file.exists():
for suffixes, cmd in ARCHIVE_EXTRACTORS:
if tuple(current_file.suffixes[-len(suffixes):]) == suffixes:
ext = "".join(suffixes).lstrip(".")
print(f"Extracting {ext} archive: {current_file}")
subprocess.run(cmd + [str(current_file)], check=True, cwd=target_dir)
current_file.unlink()
for _ in suffixes:
current_file = current_file.with_suffix("")
break
else:
# No archive matched: treat as the final binary
print(f"Making file executable: {current_file}")
current_file.chmod(0o755)
break
return True
def get_docker_image(target: Target) -> bool:
if not target.image:
print(f"Error: No Docker image specified for {target.name}")
return False
print(f"Pulling Docker image: {target.image}")
if not shutil.which("docker"):
print("Error: Docker is not installed or not in PATH")
return False
try:
subprocess.run(["docker", "info"], check=True, capture_output=True)
except subprocess.CalledProcessError:
print("Error: Docker daemon is not running or not accessible")
print("Please start Docker and try again")
return False
try:
subprocess.run(["docker", "pull", "--platform", CONFIG.DOCKER_PLATFORM, target.image], check=True)
print(f"Successfully pulled Docker image: {target.image}")
return True
except subprocess.CalledProcessError:
print(f"Error: Failed to pull Docker image {target.image}")
return False
def get_github_release(target: Target) -> bool:
if not target.repo:
print(f"Error: missing repository information for {target.name}")
return False
# Get the latest release tag from GitHub API
print("Fetching latest release information...")
try:
url = f"https://api.github.com/repos/{target.repo}/releases/latest"
req = urllib.request.Request(url)
github_token = os.environ.get("GITHUB_TOKEN")
if github_token:
req.add_header("Authorization", f"token {github_token}")
with urllib.request.urlopen(req) as response:
data = json.loads(response.read().decode())
latest_tag = data["tag_name"]
except Exception as e:
print(f"Error: Could not fetch latest release tag: {e}")
return False
print(f"Latest version: {latest_tag}")
# Construct download URL
download_url = f"https://github.com/{target.repo}/releases/download/{latest_tag}/{target.file}"
print(f"Downloading from: {download_url}")
# Download to a temporary file to avoid race conditions when
# multiple targets share the same filename (e.g., jamzilla and jamzilla-int)
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=f"_{target.file}") as tmp:
tmp_path = tmp.name
urllib.request.urlretrieve(download_url, tmp_path)
except Exception as e:
print(f"Error: Download failed: {e}")
return False
print(f"Downloaded target to: {tmp_path}")
target_dir = Path(f"{CONFIG.targets_dir}/{target.name}")
target_dir_rev = target_dir / latest_tag
target_dir_rev.mkdir(parents=True, exist_ok=True)
shutil.move(tmp_path, target_dir_rev / target.file)
print(f"* Target downloaded to: {target_dir_rev}")
latest_link = target_dir / "latest"
if latest_link.exists() or latest_link.is_symlink():
latest_link.unlink()
latest_link.symlink_to(target_dir_rev.resolve())
return post_actions(target)
def print_docker_image_info(image):
result = subprocess.run(
["docker", "inspect", image, "--format", "{{.Id}}\n{{.Created}}"],
capture_output=True,
text=True,
check=True
)
lines = result.stdout.strip().split('\n')
image_id = lines[0]
created = lines[1] if len(lines) > 1 else "Unknown"
# Strip "sha256:" prefix if present
if image_id.startswith("sha256:"):
image_id = image_id[7:]
image_id = image_id[:12] # Short ID
print(f"Image: {image}")
print(f"Image ID: {image_id}")
print(f"Created: {created}")
def is_rootless_docker() -> bool:
"""Detect if Docker is running in rootless mode."""
try:
result = subprocess.run(
["docker", "info", "--format", "{{.SecurityOptions}}"],
capture_output=True, text=True, check=True,
)
return "rootless" in result.stdout
except (subprocess.CalledProcessError, FileNotFoundError):
return False
def _chmod_socket_when_ready(
container_name: str,
host_sock_path: str,
container_sock_path: str,
process: subprocess.Popen,
timeout_s: float = 60.0,
) -> None:
# On rootless Docker, the unix socket created by the container is owned
# by the rootlesskit-mapped subordinate uid (e.g. host 100999 for
# container 1000), and the host-side fuzzer cannot connect() to it
# without world-rw on the socket file. We chmod from inside the
# container because only the owning uid (or root) can chmod it, and
# the host is not that uid. On rootful this is a harmless no-op.
#
# We wait for the socket to appear by polling the host side of the
# bind mount, not by `docker exec`-ing into the container. Calling
# docker exec while the daemon is still finalizing the container's
# bind mounts races mount setup and can flip the host data dir to
# root ownership, which then makes the in-container bind() fail
# with EACCES. Once the socket exists the mount has settled and a
# single docker exec for the chmod is safe.
#
# Raises RuntimeError on timeout, container exit, or chmod failure.
deadline = time.monotonic() + timeout_s
sock = Path(host_sock_path)
while time.monotonic() < deadline:
rc = process.poll()
if rc is not None:
raise RuntimeError(
f"container {container_name} exited (status {rc}) before socket {host_sock_path} appeared"
)
if sock.is_socket():
chmod = subprocess.run(
["docker", "exec", container_name, "chmod", "0666", container_sock_path],
capture_output=True,
)
if chmod.returncode != 0:
stderr = chmod.stderr.decode(errors="replace").strip()
raise RuntimeError(
f"chmod {container_sock_path} inside {container_name} failed: {stderr}"
)
print(f"chmod 0666 {container_sock_path} (inside {container_name})")
return
time.sleep(0.2)
raise RuntimeError(
f"socket {host_sock_path} did not appear within {timeout_s}s"
)
def run_docker_image(target: Target, args) -> None:
if not target.image:
print(f"Error: No Docker image specified for {target.name}")
sys.exit(1)
# Use custom container name if provided, otherwise generate unique name with random suffix
if args.container_name:
container_name = args.container_name
else:
# Generate unique container name with random suffix to allow parallel instances
random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
container_name = f"{target.name}-{random_suffix}"
print(f"Running '{target.name}' on docker image")
print(f"Command: '{target.cmd}'")
print(f"Container: '{container_name}'")
try:
print_docker_image_info(target.image)
except (subprocess.CalledProcessError, IndexError, ValueError):
print(f"Error: Docker image '{target.image}' not found locally.")
print(f"Please run: {sys.argv[0]} get {target.name}")
sys.exit(1)
# Clean start: remove any leftover data directory from previous runs
# This ensures the socket and other runtime files are fresh
_clean_host_data()
# Create host data directory
os.makedirs(CONFIG.host_data_path, exist_ok=True)
# Ensure the directory is world-writable so the container user can create files
# (needed for rootless Docker where the mapped user may differ from the host user)
os.chmod(CONFIG.host_data_path, 0o777)
print(f"Host data path: {CONFIG.host_data_path}")
def cleanup():
print(f"Cleaning up Docker container {container_name}...")
subprocess.run(["docker", "kill", container_name], capture_output=True)
subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)
_clean_host_data()
def signal_handler(signum, frame):
cleanup()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Pre-flight cleanup: remove any existing container with the same name
print(f"Ensuring no leftover container with name {container_name}...")
subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)
docker_cmd = [
"docker",
"run",
"--rm",
"--name",
container_name,
"--init",
"--platform",
CONFIG.DOCKER_PLATFORM,
"--cpuset-cpus",
f"{CONFIG.docker_cpu_set}",
"--cpu-shares",
"2048",
"--cpu-quota",
"-1",
"--memory",
"16g",
"--memory-swap",
"16g",
"--shm-size",
"1g",
"--ulimit",
"nofile=65536:65536",
"--ulimit",
"nproc=32768:32768",
"--sysctl",
"net.core.somaxconn=65535",
"--sysctl",
"net.ipv4.tcp_tw_reuse=1",
"--security-opt",
"seccomp=unconfined",
"--security-opt",
"apparmor=unconfined",
"--cap-add",
"SYS_NICE",
"--cap-add",
"SYS_RESOURCE",
"--cap-add",
"IPC_LOCK",
"-v",
f"{CONFIG.host_data_path}:{CONFIG.CONTAINER_DATA_PATH}",
]
# In rootful Docker, run as the host user so files are owned correctly.
# In rootless Docker, container root already maps to the host user,
# so --user would cause double UID remapping and permission errors.
rootless = is_rootless_docker()
if rootless:
print("Detected rootless Docker, skipping --user flag")
else:
docker_cmd.extend(["--user", f"{os.getuid()}:{os.getgid()}"])
# Standard JAM fuzz packaging environment variables (see fuzz-proto/README.md).
# Set first so target.json `env` and --target-env can still override them.
docker_cmd.extend([
"-e", "JAM_FUZZ=1",
"-e", f"JAM_FUZZ_SPEC={CONFIG.spec}",
"-e", f"JAM_FUZZ_DATA_PATH={CONFIG.CONTAINER_DATA_PATH}",
"-e", f"JAM_FUZZ_SOCK_PATH={CONFIG.CONTAINER_SOCK_PATH}",
"-e", f"JAM_FUZZ_LOG_LEVEL={CONFIG.log_level}",
])
for var in f"{target.env or ''} {args.target_env}".split():
docker_cmd.extend(["-e", var])
if target.is_repo_target():
# The target's image/cmd were overwritten upstream to wrap a host
# binary; mount its downloaded directory at /jam so it's executable.
docker_cmd.extend(["-w", "/jam"])
docker_cmd.extend(["-e", "HOME=/jam"])
docker_cmd.extend(["-v", f"{CONFIG.targets_dir}/{target.name}/latest:/jam"])
docker_cmd.append(target.image)
# Handle cmd as string
if target.cmd:
docker_cmd.extend(shlex.split(target.cmd))
# Add priority args for Linux if requested
if args.docker_elevate_priority and platform.system().lower() == "linux":
priority_cmd = [
"sudo",
"chrt",
"-f",
"99",
"nice",
"-n",
"-20",
"ionice",
"-c1",
"-n0",
"taskset",
"-c",
f"{CONFIG.docker_cpu_set}",
]
docker_cmd = priority_cmd + docker_cmd
host_sock_path = os.path.join(
CONFIG.host_data_path,
os.path.relpath(CONFIG.CONTAINER_SOCK_PATH, CONFIG.CONTAINER_DATA_PATH),
)
try:
process = subprocess.Popen(docker_cmd)
# Block until the in-container socket is chmod'd so the host-side
# fuzzer cannot race ahead and hit EACCES on connect().
try:
_chmod_socket_when_ready(
container_name,
host_sock_path,
CONFIG.CONTAINER_SOCK_PATH,
process,
)
except RuntimeError as e:
print(f"Error preparing fuzz socket: {e}")
sys.exit(1)
print(f"Waiting for target termination (pid={process.pid})")
exit_code = process.wait()
print(f"Target process exited with status: {exit_code}")
finally:
cleanup()
def run_target(target: Target, args) -> None:
if not target.cmd:
print(f"Error: No run command specified for {target.name}")
return
target_dir = Path(f"{CONFIG.targets_dir}/{target.name}/latest")
if not target_dir.exists():
print(f"Error: Target dir not found: {target_dir}")
print(f"Get the target first with: get {target.name}")
sys.exit(1)
full_command = f"./{target.cmd}"
if target.args is not None:
full_command += f" {target.args}"
if args.target_args:
full_command += f" {args.target_args}"
# Ensure the default Docker image is available locally
try:
subprocess.run(
["docker", "image", "inspect", CONFIG.DEFAULT_DOCKER_IMAGE],
check=True, capture_output=True,
)
except subprocess.CalledProcessError:
print(f"Docker image '{CONFIG.DEFAULT_DOCKER_IMAGE}' not found locally. Pulling...")
subprocess.run(
["docker", "pull", "--platform", CONFIG.DOCKER_PLATFORM, CONFIG.DEFAULT_DOCKER_IMAGE],
check=True,
)
# Wrap the host binary in a dedicated default Docker image.
# `target.repo` is left intact, which run_docker_image uses as the
# signal to mount the downloaded host-binary directory into /jam.
target.image = CONFIG.DEFAULT_DOCKER_IMAGE
target.cmd = full_command
run_docker_image(target, args)
def print_target_info(target: Target) -> None:
"""Print detailed information about a target."""
print(f"Name: {target.name}")
if target.gp_version:
print(f"GP Version: {target.gp_version}")
target_type = []
if target.is_docker_target():
target_type.append("Docker")
if target.is_repo_target():
target_type.append("Repository")
print(f"Type: {', '.join(target_type)}")
if target.is_repo_target():
print(f"Repository: https://github.com/{target.repo}")
target_dir = Path(f"{CONFIG.targets_dir}/{target.name}/latest")
if target_dir.exists():
print(f"Downloaded: {target_dir}")
elif target.is_docker_target():
try:
print_docker_image_info(target.image)
except (subprocess.CalledProcessError, FileNotFoundError):
print("Status: Not downloaded (Docker image not found locally)")
else:
print("Status: Not downloaded")
if target.file:
print(f"File: {target.file}")
if target.cmd:
print(f"Command: {target.cmd}")
if target.args:
print(f"Arguments: {target.args}")
if target.env:
print(f"Environment: {target.env}")
def handle_info_action(target: Target) -> bool:
"""Handle the info action for a target."""
print_target_info(target)
return True
def handle_get_action(target: Target) -> bool:
"""Handle the get action for a target."""
print(f"Downloading {target.name}...")
if target.is_repo_target():
return get_github_release(target)
return get_docker_image(target)
def handle_list_action(all_targets: Dict[str, Target], gp_version: Optional[str]) -> bool:
"""Handle the list action to show all available targets."""
names = sorted(all_targets)
if gp_version:
filtered = [n for n in names if all_targets[n].gp_version == gp_version]
if not filtered:
print(f"No targets found for gp-version: {gp_version}")
return True
for name in filtered:
print(name)
return True
# Group by gp_version, most recent first
groups: Dict[str, List[str]] = {}
for name in names:
v = all_targets[name].gp_version or "unknown"
groups.setdefault(v, []).append(name)
for i, gp_ver in enumerate(sorted(groups, reverse=True)):
if i > 0:
print()
print(gp_ver)
print("=" * len(gp_ver))
for name in sorted(groups[gp_ver]):
print(name)
return True
def handle_clean_action(target: Target) -> bool:
"""Handle the clean action for a target."""
cleaned = False
target_dir = Path(f"{CONFIG.targets_dir}/{target.name}")
if target_dir.exists():
print(f"Cleaning target dir {target_dir}...")
shutil.rmtree(target_dir)
cleaned = True
if target.is_docker_target():
result = subprocess.run(
["docker", "image", "inspect", target.image],
capture_output=True,
)
if result.returncode == 0:
print(f"Removing Docker image {target.image}...")
subprocess.run(["docker", "rmi", "-f", target.image], check=False)
cleaned = True
if cleaned:
print(f"Target {target.name} cleaned successfully!")
else:
print(f"Target {target.name} not found or already clean.")
return True
def handle_run_action(target: Target, args) -> bool:
"""Handle the run action for a target."""
if target.is_docker_target():
run_docker_image(target, args)
else:
run_target(target, args)
return True
def main():
global CONFIG
parser = create_parser()
args = parser.parse_args()
CONFIG = Config.from_args(args)
all_targets = load_targets()
action = args.action
target = getattr(args, 'target', None)
success = False
if action == "list":
success = handle_list_action(all_targets, args.gp_version)
else:
# info / get / run / clean all need a single resolved Target
target_obj = all_targets.get(target)
if target_obj is None:
print(f"Unknown target '{target}'")
print(f"Available targets: {' '.join(sorted(all_targets))}")
sys.exit(1)
if action == "info":
success = handle_info_action(target_obj)
elif action == "get":
success = handle_get_action(target_obj)
elif action == "run":
success = handle_run_action(target_obj, args)
elif action == "clean":
success = handle_clean_action(target_obj)
if not success:
sys.exit(1)
if __name__ == "__main__":
main()