Repository navigation
Expand file tree
/
Copy pathdeploy_all.py
More file actions
460 lines (409 loc) · 20.9 KB
/
Copy pathdeploy_all.py
File metadata and controls
460 lines (409 loc) · 20.9 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
import os
import sys
import logging
import importlib
import argparse
import inspect
from dotenv import load_dotenv
from typing import Dict, List, Optional
import subprocess
# CRITICAL: Add the project root to the path for local module imports
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
from agents.app.agent_engine_adk_app import deploy_adk_agent_engine
from common.observability import setup_observability
from google.cloud import aiplatform as vertexai
# --- Logger Initialization ---
logger = logging.getLogger(__name__)
# --- Configuration ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
GCLOUD_COMMON_ARGS = []
class ApiDisabledError(Exception):
"""Custom exception for when a required GCP API is not enabled."""
pass
class DeploymentError(Exception):
"""Custom exception for deployment failures."""
pass
# --- Helper Functions ---
def install_dependencies():
"""Installs dependencies from requirements.txt."""
logging.info("--- Installing/Updating Dependencies from requirements.txt ---")
req_path = os.path.join(PROJECT_ROOT, 'requirements.txt')
if not os.path.exists(req_path):
logging.warning(f"Root requirements.txt not found at {req_path}. Skipping dependency installation.")
return
try:
run_command([sys.executable, "-m", "pip", "install", "--upgrade", "-r", req_path], check=True, capture_output=False)
logging.info("--- Dependencies are up to date. ---")
except subprocess.CalledProcessError as e:
raise DeploymentError("Failed to install dependencies from requirements.txt.") from e
def run_command(command: List[str], check: bool = True, capture_output: bool = True, text: bool = True, timeout: Optional[int] = None, input_str: Optional[str] = None) -> subprocess.CompletedProcess:
"""
Executes a shell command and logs its execution and output.
Raises CalledProcessError on failure if check is True.
"""
cmd_str = ' '.join(command)
logging.info(f"Executing command: {cmd_str}")
try:
result = subprocess.run(command, check=check, capture_output=capture_output, text=text, timeout=timeout, input=input_str)
if result.returncode != 0 and not check:
logging.warning(f"Command failed with code {result.returncode}: {cmd_str}")
if capture_output:
logging.warning(f"STDERR: {result.stderr.strip()}")
logging.warning(f"STDOUT: {result.stdout.strip()}")
return result
except subprocess.CalledProcessError as e:
logging.error(f"Command failed with exit code {e.returncode}: {' '.join(e.cmd)}")
if capture_output:
logging.error(f"STDERR: {e.stderr.strip()}")
logging.error(f"STDOUT: {e.stdout.strip()}")
if check:
raise
else:
return subprocess.CompletedProcess(e.args, e.returncode, e.stdout, e.stderr)
except FileNotFoundError:
logging.error(f"Command not found: {command[0]}. Ensure gcloud SDK is installed and in your PATH.")
raise
except subprocess.TimeoutExpired as e:
logging.error(f"Command timed out after {timeout} seconds: {cmd_str}")
if e.stdout: logging.error(f"STDOUT: {e.stdout}")
if e.stderr: logging.error(f"STDERR: {e.stderr}")
raise
def sanitize_env_var(value: Optional[str]) -> str:
"""Sanitizes an environment variable value."""
if value is None:
return ''
return value.split('#', 1)[0].strip().strip('"').strip("'")
def setup_environment() -> Dict[str, str]:
"""Loads and validates required environment variables."""
load_dotenv()
required_vars = {
"project_id": "COMMON_GOOGLE_CLOUD_PROJECT",
"region": "COMMON_GOOGLE_CLOUD_LOCATION",
"staging_bucket": "COMMON_VERTEX_STAGING_BUCKET",
"spanner_instance": "COMMON_SPANNER_INSTANCE_ID",
"spanner_db": "COMMON_SPANNER_DATABASE_ID",
}
optional_vars = {
"service_account": "SERVICE_ACCOUNT_EMAIL",
}
env_config = {key: sanitize_env_var(os.environ.get(var_name)) for key, var_name in required_vars.items()}
for key, var_name in optional_vars.items():
env_config[key] = sanitize_env_var(os.environ.get(var_name))
missing = [var_name for key, var_name in required_vars.items() if not env_config[key]]
if missing:
raise ValueError(f"Missing critical environment variables: {', '.join(missing)}")
global GCLOUD_COMMON_ARGS
GCLOUD_COMMON_ARGS = ['--project', env_config["project_id"]]
try:
vertexai.init(project=env_config["project_id"], location=env_config["region"], staging_bucket=env_config["staging_bucket"])
logging.info(f"Vertex AI initialized for project '{env_config['project_id']}' in '{env_config['region']}'.")
except Exception as e:
raise DeploymentError(f"Failed to initialize Vertex AI: {e}")
try:
run_command(['gcloud', 'auth', 'print-access-token'] + GCLOUD_COMMON_ARGS, capture_output=True, text=True, check=True)
logging.info("gcloud authentication seems fine.")
except subprocess.CalledProcessError:
raise DeploymentError("gcloud not authenticated. Please run 'gcloud auth login'.")
os.environ['GRPC_DNS_RESOLVER'] = 'native'
logging.info("Set GRPC_DNS_RESOLVER=native")
return env_config
def setup_spanner(project_id: str, instance_id: str, db_id: str, region: str):
"""Ensures the Spanner instance and database exist."""
logging.info("--- Starting Spanner Setup ---")
instance_check_cmd = ['gcloud', 'spanner', 'instances', 'describe', instance_id] + GCLOUD_COMMON_ARGS
instance_result = run_command(instance_check_cmd, check=False)
if instance_result.returncode != 0:
if "NOT_FOUND" in instance_result.stderr:
logging.info(f"Spanner instance '{instance_id}' not found. Creating...")
run_command([
"gcloud", "spanner", "instances", "create", instance_id,
f"--config=regional-{region}", f"--description=Spanner for {project_id}",
"--processing-units=100"
] + GCLOUD_COMMON_ARGS, check=True)
logging.info(f"Spanner instance '{instance_id}' created.")
else:
raise DeploymentError(f"Failed to check for Spanner instance '{instance_id}'.")
db_check_cmd = ['gcloud', 'spanner', 'databases', 'describe', db_id, f'--instance={instance_id}'] + GCLOUD_COMMON_ARGS
db_result = run_command(db_check_cmd, check=False)
if db_result.returncode != 0:
if "NOT_FOUND" in db_result.stderr:
logging.info(f"Spanner database '{db_id}' not found. Creating...")
run_command([
'gcloud', 'spanner', 'databases', 'create', db_id,
f'--instance={instance_id}'
] + GCLOUD_COMMON_ARGS, check=True)
logging.info(f"Spanner database '{db_id}' created.")
else:
raise DeploymentError(f"Failed to check for Spanner database '{db_id}'.")
original_cwd = os.getcwd()
try:
os.chdir("instavibe")
if os.path.exists("setup.py"):
run_command([sys.executable, "setup.py"], check=True)
logging.info("Successfully executed instavibe/setup.py.")
else:
logging.warning("instavibe/setup.py not found, skipping schema setup.")
finally:
os.chdir(original_cwd)
logging.info("--- Spanner Setup Complete ---")
def build_and_deploy_cloud_run_service(
project_id: str,
region: str,
service_name: str,
source_path: str,
env_vars: Optional[Dict[str, str]] = None,
allow_unauthenticated: bool = True,
service_account: Optional[str] = None
) -> Optional[str]:
"""
Builds and deploys a Cloud Run service using a cloudbuild.yaml that
accepts individual substitutions for each environment variable.
"""
logging.info(f"--- Deploying Cloud Run Service: {service_name} from path {source_path} ---")
if not os.path.isdir(source_path):
raise DeploymentError(f"Source path not found: {source_path}")
image_path = f"{region}-docker.pkg.dev/{project_id}/instavibe-images/{service_name}:latest"
substitutions = {
"_IMAGE_PATH": image_path,
"_SERVICE_NAME": service_name,
"_SERVICE_DIR": source_path,
"_REGION": region,
"_SERVICE_ACCOUNT": service_account or "",
}
if env_vars:
for k, v in env_vars.items():
if v is not None:
substitutions[f"_{k}"] = str(v)
substitutions_string = ",".join([f"{k}={v}" for k, v in substitutions.items()])
build_submit_cmd = [
"gcloud", "builds", "submit", ".",
"--config", "cloudbuild.yaml",
f"--substitutions={substitutions_string}",
"--project", project_id,
]
try:
logging.info(f"Submitting build and deploy for {service_name}...")
run_command(build_submit_cmd, timeout=900, check=True)
except subprocess.CalledProcessError as e:
raise DeploymentError(f"Cloud Build submission failed for {service_name}") from e
url_cmd = [
"gcloud", "run", "services", "describe", service_name,
"--platform", "managed", "--region", region, "--project", project_id,
"--format=value(status.url)"
]
try:
result = run_command(url_cmd, check=True)
service_url = result.stdout.strip()
if not service_url:
raise DeploymentError(f"Failed to get URL for Cloud Run service {service_name}")
logging.info(f"Successfully deployed '{service_name}' to {service_url}")
return service_url
except (subprocess.CalledProcessError, DeploymentError) as e:
logging.warning(f"Could not retrieve service URL for {service_name} after deployment. This might be okay. Error: {e}")
return None
def main(args):
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
try:
setup_observability(disable_export=True)
logging.info("Observability setup complete.")
install_dependencies()
env_config = setup_environment()
if not args.skip_spanner:
setup_spanner(env_config["project_id"], env_config["spanner_instance"], env_config["spanner_db"], env_config["region"])
else:
logging.info("Skipping Spanner setup.")
if not args.skip_collector:
otel_collector_url = build_and_deploy_cloud_run_service(
env_config["project_id"],
env_config["region"],
"otel-collector",
"./otel-collector",
env_vars={"COMMON_GOOGLE_CLOUD_PROJECT": env_config["project_id"]},
allow_unauthenticated=False,
service_account=env_config.get("service_account"),
)
if otel_collector_url:
os.environ["OTEL_COLLECTOR_ENDPOINT"] = f"{otel_collector_url}:4317"
else:
logging.info("Skipping OpenTelemetry Collector deployment.")
mcp_tool_server_url = None
if not args.skip_mcp_server:
mcp_tool_server_url = build_and_deploy_cloud_run_service(
env_config["project_id"],
env_config["region"],
"mcp-tool-server",
"./tools/instavibe",
env_vars={
"COMMON_GOOGLE_CLOUD_PROJECT": env_config["project_id"],
"SERVICE_NAME": "mcp-tool-server",
"OTEL_COLLECTOR_ENDPOINT": os.environ.get("OTEL_COLLECTOR_ENDPOINT"),
},
allow_unauthenticated=False,
)
if mcp_tool_server_url:
logging.info(f"Setting MCP_SERVER_URL for agent deployment: {mcp_tool_server_url}")
os.environ["MCP_SERVER_URL"] = mcp_tool_server_url
else:
logging.warning("MCP Tool Server deployment did not return a URL. Platform MCP Client Agent may fail.")
agent_resource_names = {}
if not args.skip_agents:
# Get the model name from the environment
gemini_model = os.getenv("COMMON_GEMINI_MODEL")
if not gemini_model:
logging.error("ERROR: COMMON_GEMINI_MODEL environment variable not set. Please define it in your .env file.")
exit(1)
agents_to_deploy = [
{
"name": "planner_agent",
"gcp_id": "planner-agent",
"display_name": "Planner Agent",
"module": "agents.planner.agent",
"agent_variable": "PlannerAgent",
"requirements_file": "agents/planner/requirements.txt",
"extra_packages": ["./agents/app", "./common", "./agents/planner"],
"tools": []
},
{
"name": "orchestrate_agent",
"gcp_id": "orchestrate-agent",
"display_name": "Orchestrate Agent",
"module": "agents.orchestrate.orchestrate_service_agent",
"agent_variable": "OrchestrateServiceAgent",
"requirements_file": "agents/orchestrate/requirements.txt",
"extra_packages": ["./agents/app", "./common", "./agents/orchestrate"],
},
{
"name": "social_agent",
"gcp_id": "social-agent",
"display_name": "Social Agent",
"module": "agents.social.agent",
"agent_variable": "SocialLoopAgent",
"requirements_file": "agents/social/requirements.txt",
"extra_packages": ["./agents/app", "./common", "./agents/social", "./tools"],
},
{
"name": "platform_mcp_client_agent",
"gcp_id": "platform-mcp-client-agent",
"display_name": "Platform MCP Client Agent",
"module": "agents.platform_mcp_client.agent",
"agent_variable": "PlatformMCPClientAgent",
"requirements_file": "agents/platform_mcp_client/requirements.txt",
"extra_packages": ["./agents/app", "./common", "./agents/platform_mcp_client"],
"tools": []
}
]
otel_collector_endpoint = os.environ.get("OTEL_COLLECTOR_ENDPOINT")
if args.deploy_orchestrate_only:
logging.info("--- Deploying only the Orchestrate Agent ---")
agents_to_deploy = [a for a in agents_to_deploy if a['name'] == 'orchestrate_agent']
project_id = env_config["project_id"]
region = env_config["region"]
for agent_conf in agents_to_deploy:
display_name = agent_conf["display_name"]
adk_agent_name = agent_conf["name"]
agent_gcp_id = agent_conf.get("gcp_id", adk_agent_name)
logging.info(f"--- Deploying/Updating Agent: {display_name} (ADK Name: {adk_agent_name}, GCP ID: {agent_gcp_id}) ---")
try:
module_path = agent_conf["module"]
agent_var = agent_conf["agent_variable"]
module = importlib.import_module(module_path)
agent_class = getattr(module, agent_var)
kwargs = {
"name": adk_agent_name,
"model": gemini_model,
"tools": agent_conf.get("tools", []),
"display_name": agent_conf.get("display_name", adk_agent_name),
"otel_collector_endpoint": os.getenv("OTEL_COLLECTOR_ENDPOINT")
}
if agent_var == "PlatformMCPClientAgent":
kwargs["mcp_server_address"] = os.getenv("MCP_SERVER_URL")
if not kwargs["mcp_server_address"]:
logging.error(f"ERROR: MCP_SERVER_URL must be set in .env for {adk_agent_name}")
continue
if agent_var == "SocialLoopAgent":
# SocialLoopAgent doesn't accept model or tools based on previous errors
if "model" in kwargs: del kwargs["model"]
if "tools" in kwargs: del kwargs["tools"]
logging.info(f"Instantiating {adk_agent_name} with keys: {list(kwargs.keys())}")
agent_to_deploy = agent_class(**kwargs)
remote_agent = deploy_adk_agent_engine(
agent_object=agent_to_deploy,
gcp_agent_id=agent_gcp_id,
project=project_id,
location=region,
requirements_path=agent_conf["requirements_file"],
extra_packages=agent_conf["extra_packages"],
display_name=display_name,
)
agent_resource_names[adk_agent_name] = remote_agent.resource_name
logging.info(f"--- Successfully Deployed/Updated: {display_name} ---")
except Exception as e:
logger.error(f"--- FAILED to Deploy/Update: {display_name}: {e} ---", exc_info=True)
else:
logging.info("--- Skipping all agent deployments. ---")
if not args.skip_app:
app_env_vars = {
"COMMON_GOOGLE_CLOUD_PROJECT": env_config["project_id"],
"COMMON_GOOGLE_CLOUD_LOCATION": env_config["region"],
"COMMON_SPANNER_INSTANCE_ID": env_config["spanner_instance"],
"COMMON_SPANNER_DATABASE_ID": env_config["spanner_db"],
"AGENTS_PLATFORM_MCP_CLIENT_MCP_SERVER_URL": mcp_tool_server_url,
"OTEL_COLLECTOR_ENDPOINT": os.environ.get("OTEL_COLLECTOR_ENDPOINT"),
"ENABLE_TRACING": str(not args.deploy_orchestrate_only),
}
# Pass all deployed agent resource names to the app
for agent_name, resource_name in agent_resource_names.items():
env_key = f"{agent_name.upper()}_RESOURCE_NAME"
app_env_vars[env_key] = resource_name
if "orchestrate_agent" not in agent_resource_names:
logging.warning("Orchestrate agent resource name not found. InstaVibe app may not function correctly.")
build_and_deploy_cloud_run_service(
env_config["project_id"],
env_config["region"],
"instavibe-app",
"./instavibe",
env_vars=app_env_vars,
allow_unauthenticated=True,
service_account=env_config.get("service_account"),
)
else:
logging.info("Skipping InstaVibe App deployment.")
logging.info("--- Deployment script finished successfully! ---")
except ValueError as e:
logging.error(f"Configuration error: {e}")
sys.exit(1)
except Exception as e:
logging.error(f"An unexpected error occurred in deploy_all: {e}", exc_info=True)
sys.exit(1)
finally:
from opentelemetry import trace, metrics
logging.info("--- Shutting down observability ---")
tracer_provider = trace.get_tracer_provider()
if hasattr(tracer_provider, 'shutdown'):
try:
tracer_provider.shutdown()
logging.info("TracerProvider shutdown complete.")
except Exception as e:
logging.error(f"Error shutting down TracerProvider: {e}", exc_info=True)
meter_provider = metrics.get_meter_provider()
if hasattr(meter_provider, 'shutdown'):
try:
meter_provider.shutdown(timeout_millis=10000)
logging.info("MeterProvider shutdown complete.")
except Exception as e:
logging.error(f"Error shutting down MeterProvider: {e}", exc_info=True)
logging.info("--- Observability shutdown process finished ---")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description="Deploy all components of the InstaVibe system.")
parser.add_argument("--skip-agents", action="store_true", help="Skip deploying all reasoning engine agents.")
parser.add_argument("--skip-gateway", action="store_true", help="Skip deploying the Cloud Run gateway.")
parser.add_argument("--skip-mcp-server", action="store_true", help="Skip deploying the MCP Tool Server.")
parser.add_argument("--skip-app", action="store_true", help="Skip deploying the main InstaVibe web app.")
parser.add_argument("--skip-spanner", action="store_true", help="Skip Spanner setup.")
parser.add_argument("--skip-collector", action="store_true", help="Skip deploying the OpenTelemetry Collector.")
parser.add_argument("--deploy-orchestrate-only", action="store_true", help="Deploy only the orchestrate agent.")
args = parser.parse_args()
main(args)