-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud_utility-deploy_cloud_run_job.py
More file actions
157 lines (131 loc) · 4.48 KB
/
Copy pathcloud_utility-deploy_cloud_run_job.py
File metadata and controls
157 lines (131 loc) · 4.48 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
"""
Google Cloud Run Job Deployment Script for Milhas WhatsApp Agent
This script automates deployment of the agent as a Cloud Run Job (batch),
staying within the free tier.
"""
import os
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Tuple
GOOGLE_CLOUD_PROJECT_ID = "GOOGLE_CLOUD_PROJECT_ID" #! Set your project ID
JOB_NAME = "job-name" #! Set your job name
REGION = "us-central1"
MEMORY = "512Mi"
CPU = "1"
TIMEOUT = "600s"
TASKS = 1
MAX_RETRIES = 3
def run_command(command: List[str], cwd: str = None) -> Tuple[bool, str]:
try:
result = subprocess.run(
command,
check=True,
cwd=cwd,
capture_output=True,
text=True,
shell=sys.platform == "win32",
)
return True, result.stdout
except subprocess.CalledProcessError as e:
print(f"Command failed: {' '.join(e.cmd)}")
print(f"Error: {e.stderr}")
return False, f"Error: {e.stderr}"
def check_gcloud_installed() -> bool:
success, _ = run_command(["gcloud", "--version"])
if not success:
print("gcloud CLI is not installed or not in PATH.")
return False
success, output = run_command(["gcloud", "auth", "list", "--filter=status:ACTIVE", "--format=value(account)"])
if not success or not output.strip():
print("You need to authenticate with Google Cloud (gcloud auth login).")
return False
return True
def build_and_push_image(project_id: str, job_name: str) -> bool:
image_name = f"gcr.io/{project_id}/{job_name}"
print(f"Building Docker image: {image_name}")
success, output = run_command(["docker", "build", "-t", job_name, "."])
if not success:
print(f"Failed to build Docker image: {output}")
return False
print("✓ Docker image built successfully")
print("Tagging image...")
success, output = run_command(["docker", "tag", job_name, image_name])
if not success:
print(f"Failed to tag image: {output}")
return False
print("✓ Image tagged successfully")
print("Pushing image to Google Container Registry...")
success, output = run_command(["docker", "push", image_name])
if not success:
print(f"Failed to push image: {output}")
return False
print("✓ Image pushed successfully")
return True
def deploy_cloud_run_job(
project_id: str,
job_name: str,
region: str,
memory: str,
cpu: str,
timeout: str,
tasks: int,
max_retries: int,
env_file: str = ".env"
) -> bool:
from dotenv import dotenv_values
image_name = f"gcr.io/{project_id}/{job_name}"
env_vars = {}
if os.path.exists(env_file):
env_vars = dotenv_values(env_file)
env_vars = {k: v for k, v in env_vars.items() if v is not None}
env_vars_str = ",".join(f"{k}={v}" for k, v in env_vars.items())
cmd = [
"gcloud", "beta", "run", "jobs", "deploy", job_name,
f"--image={image_name}",
f"--region={region}",
f"--memory={memory}",
f"--cpu={cpu}",
f"--max-retries={max_retries}",
f"--task-timeout={timeout}",
f"--tasks={tasks}",
# "--platform=managed"
]
if env_vars:
cmd.append(f"--set-env-vars={env_vars_str}")
print("Deploying Cloud Run Job...")
success, output = run_command(cmd)
if success:
print("\n✓ Job deployed successfully!")
print(output)
return True
else:
print("\n✗ Job deployment failed!")
print(output)
return False
def main():
print("=== Milhas WhatsApp Agent Cloud Run Job Deployment ===\n")
if not check_gcloud_installed():
sys.exit(1)
if not build_and_push_image(GOOGLE_CLOUD_PROJECT_ID, JOB_NAME):
print("\n✗ Failed to build and push Docker image")
sys.exit(1)
print("\n=== Deploying Cloud Run Job ===")
success = deploy_cloud_run_job(
project_id=GOOGLE_CLOUD_PROJECT_ID,
job_name=JOB_NAME,
region=REGION,
memory=MEMORY,
cpu=CPU,
timeout=TIMEOUT,
tasks=TASKS,
max_retries=MAX_RETRIES
)
if success:
print(f"\n✓ Job deployment completed successfully!")
print(f"Job URL: https://console.cloud.google.com/run/jobs/details/{REGION}/{JOB_NAME}?project={GOOGLE_CLOUD_PROJECT_ID}")
else:
print("\n✗ Job deployment failed. Check the error messages above.")
sys.exit(1)
if __name__ == "__main__":
main()