-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgenerate_compose.py
More file actions
308 lines (247 loc) · 9.13 KB
/
generate_compose.py
File metadata and controls
308 lines (247 loc) · 9.13 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
"""Generate Docker Compose configuration from scenario.toml"""
import argparse
import os
import re
import sys
from pathlib import Path
from typing import Any
try:
import tomli
except ImportError:
try:
import tomllib as tomli
except ImportError:
print("Error: tomli required. Install with: pip install tomli")
sys.exit(1)
try:
import tomli_w
except ImportError:
print("Error: tomli-w required. Install with: pip install tomli-w")
sys.exit(1)
try:
import requests
except ImportError:
print("Error: requests required. Install with: pip install requests")
sys.exit(1)
AGENTBEATS_API_URL = "https://agentbeats.dev/api/agents"
def fetch_agent_info(agentbeats_id: str) -> dict:
"""Fetch agent info from agentbeats.dev API."""
url = f"{AGENTBEATS_API_URL}/{agentbeats_id}"
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
print(f"Error: Failed to fetch agent {agentbeats_id}: {e}")
sys.exit(1)
except requests.exceptions.JSONDecodeError:
print(f"Error: Invalid JSON response for agent {agentbeats_id}")
sys.exit(1)
except requests.exceptions.RequestException as e:
print(f"Error: Request failed for agent {agentbeats_id}: {e}")
sys.exit(1)
COMPOSE_PATH = "docker-compose.yml"
A2A_SCENARIO_PATH = "a2a-scenario.toml"
ENV_PATH = ".env.example"
DEFAULT_PORT = 9009
DEFAULT_ENV_VARS = {"PYTHONUNBUFFERED": "1"}
COMPOSE_TEMPLATE = """# Auto-generated from scenario.toml
services:
green-agent:
image: {green_image}
platform: linux/amd64
container_name: green-agent
privileged: {privileged} # Needed for route-agent (to run Mininet).
command: ["--host", "0.0.0.0", "--port", "{green_port}", "--card-url", "http://green-agent:{green_port}"]
environment:{green_env}
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:{green_port}/.well-known/agent-card.json"]
interval: 5s
timeout: 3s
retries: 10
start_period: 30s
depends_on:{green_depends}
networks:
- agent-network
{extra_options}
{participant_services}
agentbeats-client:
image: ghcr.io/agentbeats/agentbeats-client:v1.0.0
platform: linux/amd64
container_name: agentbeats-client
volumes:
- ./a2a-scenario.toml:/app/scenario.toml
- ./output:/app/output
command: ["scenario.toml", "output/results.json"]
depends_on:{client_depends}
networks:
- agent-network
networks:
agent-network:
driver: bridge
"""
PARTICIPANT_TEMPLATE = """ {name}:
image: {image}
platform: linux/amd64
container_name: {name}
command: ["--host", "0.0.0.0", "--port", "{port}", "--card-url", "http://{name}:{port}"]
environment:{env}
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:{port}/.well-known/agent-card.json"]
interval: 5s
timeout: 3s
retries: 10
start_period: 30s
networks:
- agent-network
"""
A2A_SCENARIO_TEMPLATE = """[green_agent]
endpoint = "http://green-agent:{green_port}"
{participants}
{config}"""
def resolve_image(agent: dict, name: str) -> None:
"""Resolve docker image for an agent, either from 'image' field or agentbeats API."""
has_image = "image" in agent
has_id = "agentbeats_id" in agent
if has_image and has_id:
print(f"Error: {name} has both 'image' and 'agentbeats_id' - use one or the other")
sys.exit(1)
elif has_image:
if os.environ.get("GITHUB_ACTIONS"):
print(f"Error: {name} requires 'agentbeats_id' for GitHub Actions (use 'image' for local testing only)")
sys.exit(1)
print(f"Using {name} image: {agent['image']}")
elif has_id:
info = fetch_agent_info(agent["agentbeats_id"])
agent["image"] = info["docker_image"]
print(f"Resolved {name} image: {agent['image']}")
else:
print(f"Error: {name} must have either 'image' or 'agentbeats_id' field")
sys.exit(1)
def parse_scenario(scenario_path: Path) -> dict[str, Any]:
toml_data = scenario_path.read_text()
data = tomli.loads(toml_data)
green = data.get("green_agent", {})
resolve_image(green, "green_agent")
participants = data.get("participants", [])
# Check for duplicate participant names
names = [p.get("name") for p in participants]
duplicates = [name for name in set(names) if names.count(name) > 1]
if duplicates:
print(f"Error: Duplicate participant names found: {', '.join(duplicates)}")
print("Each participant must have a unique name.")
sys.exit(1)
for participant in participants:
name = participant.get("name", "unknown")
resolve_image(participant, f"participant '{name}'")
return data
def format_env_vars(env_dict: dict[str, Any]) -> str:
env_vars = {**DEFAULT_ENV_VARS, **env_dict}
lines = [f" - {key}={value}" for key, value in env_vars.items()]
return "\n" + "\n".join(lines)
def format_depends_on(services: list) -> str:
lines = []
for service in services:
lines.append(f" {service}:")
lines.append(f" condition: service_healthy")
return "\n" + "\n".join(lines)
def generate_docker_compose(scenario: dict[str, Any], app: str) -> str:
green = scenario["green_agent"]
participants = scenario.get("participants", [])
participant_names = [p["name"] for p in participants]
# Expose kubeconfig and localhost for k8s app to allow communication with kind cluster
extra_options = ""
if app == "k8s":
extra_options = """volumes:
- ./kubeconfig:/root/.kube/:ro
extra_hosts:
- "host.docker.internal:host-gateway"
"""
elif app == "route":
extra_options = """volumes:
- /lib/modules:/lib/modules
"""
participant_services = "\n".join([
PARTICIPANT_TEMPLATE.format(
name=p["name"],
image=p["image"],
port=DEFAULT_PORT,
env=format_env_vars(p.get("env", {}))
)
for p in participants
])
all_services = ["green-agent"] + participant_names
green_env = green.get("env", {})
if app == "k8s":
# For k8s app, set KUBECONFIG env var for green agent
green_env["KUBECONFIG"] = "/root/.kube/config"
return COMPOSE_TEMPLATE.format(
green_image=green["image"],
green_port=DEFAULT_PORT,
green_env=format_env_vars(green_env),
green_depends=format_depends_on(participant_names),
participant_services=participant_services,
client_depends=format_depends_on(all_services),
privileged=str(app == "route").lower(),
extra_options=extra_options
)
def generate_a2a_scenario(scenario: dict[str, Any]) -> str:
green = scenario["green_agent"]
participants = scenario.get("participants", [])
participant_lines = []
for p in participants:
lines = [
f"[[participants]]",
f"role = \"{p['name']}\"",
f"endpoint = \"http://{p['name']}:{DEFAULT_PORT}\"",
]
if "agentbeats_id" in p:
lines.append(f"agentbeats_id = \"{p['agentbeats_id']}\"")
participant_lines.append("\n".join(lines) + "\n")
config_section = scenario.get("config", {})
config_lines = [tomli_w.dumps({"config": config_section})]
return A2A_SCENARIO_TEMPLATE.format(
green_port=DEFAULT_PORT,
participants="\n".join(participant_lines),
config="\n".join(config_lines)
)
def generate_env_file(scenario: dict[str, Any]) -> str:
green = scenario["green_agent"]
participants = scenario.get("participants", [])
secrets = set()
# Extract secrets from ${VAR} patterns in env values
env_var_pattern = re.compile(r'\$\{([^}]+)\}')
for value in green.get("env", {}).values():
for match in env_var_pattern.findall(str(value)):
secrets.add(match)
for p in participants:
for value in p.get("env", {}).values():
for match in env_var_pattern.findall(str(value)):
secrets.add(match)
if not secrets:
return ""
lines = []
for secret in sorted(secrets):
lines.append(f"{secret}=")
return "\n".join(lines) + "\n"
def main():
parser = argparse.ArgumentParser(description="Generate Docker Compose from scenario.toml")
parser.add_argument("--scenario", type=Path)
parser.add_argument("--app", type=str, choices=["malt", "route", "k8s"], default="malt", help="What app to generate for.")
args = parser.parse_args()
if not args.scenario.exists():
print(f"Error: {args.scenario} not found")
sys.exit(1)
scenario = parse_scenario(args.scenario)
with open(COMPOSE_PATH, "w") as f:
f.write(generate_docker_compose(scenario, args.app))
with open(A2A_SCENARIO_PATH, "w") as f:
f.write(generate_a2a_scenario(scenario))
env_content = generate_env_file(scenario)
if env_content:
with open(ENV_PATH, "w") as f:
f.write(env_content)
print(f"Generated {ENV_PATH}")
print(f"Generated {COMPOSE_PATH} and {A2A_SCENARIO_PATH}")
if __name__ == "__main__":
main()