-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-dev.py
More file actions
304 lines (245 loc) · 10 KB
/
Copy pathdocker-dev.py
File metadata and controls
304 lines (245 loc) · 10 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
#!/usr/bin/env python3
"""
ProScrape Docker Development Manager
Simplified Docker management for development workflow
"""
import subprocess
import sys
import time
import argparse
import os
from pathlib import Path
class DockerDevManager:
def __init__(self):
self.compose_files = [
"docker-compose.yml",
"docker-compose.dev.yml"
]
self.project_name = "proscrape"
def run_command(self, cmd, check=True, capture_output=False):
"""Run a command and handle output."""
print(f"Running: {' '.join(cmd)}")
if capture_output:
result = subprocess.run(cmd, capture_output=True, text=True)
return result
else:
result = subprocess.run(cmd, check=check)
return result
def get_compose_cmd(self, *args):
"""Build docker-compose command with proper files."""
cmd = ["docker-compose"]
for file in self.compose_files:
cmd.extend(["-f", file])
cmd.extend(["-p", self.project_name])
cmd.extend(args)
return cmd
def check_prerequisites(self):
"""Check if Docker and required files exist."""
print("==> Checking prerequisites...")
# Check Docker
try:
result = self.run_command(["docker", "--version"], capture_output=True)
if result.returncode == 0:
print(f"[OK] {result.stdout.strip()}")
else:
print("[ERROR] Docker not found")
return False
except FileNotFoundError:
print("[ERROR] Docker not found. Please install Docker Desktop.")
return False
# Check docker-compose files
for file in self.compose_files:
if not Path(file).exists():
print(f"[ERROR] Missing {file}")
return False
print(f"[OK] Found {file}")
# Check .env file
if not Path(".env").exists():
print("[WARNING] .env file not found. Using defaults.")
else:
print("[OK] Found .env file")
return True
def build_services(self, services=None):
"""Build Docker services."""
print("\n==> Building services...")
cmd = self.get_compose_cmd("build")
if services:
cmd.extend(services)
try:
self.run_command(cmd)
print("[OK] Build completed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Build failed: {e}")
return False
def start_services(self, services=None):
"""Start Docker services."""
print("\n==> Starting services...")
# Default services for development
if not services:
services = ["redis", "api", "celery_worker", "flower"]
cmd = self.get_compose_cmd("up", "-d") + services
try:
self.run_command(cmd)
print("\n==> Waiting for services to be ready...")
time.sleep(5)
self.check_services()
print("\n[OK] Services started successfully!")
self.show_endpoints()
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to start services: {e}")
return False
def stop_services(self):
"""Stop Docker services."""
print("\n==> Stopping services...")
try:
self.run_command(self.get_compose_cmd("down"))
print("[OK] Services stopped successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to stop services: {e}")
return False
def restart_services(self, services=None):
"""Restart specific services or all."""
print("\n==> Restarting services...")
if services:
cmd = self.get_compose_cmd("restart") + services
else:
cmd = self.get_compose_cmd("restart")
try:
self.run_command(cmd)
print("[OK] Services restarted successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to restart services: {e}")
return False
def check_services(self):
"""Check service health."""
print("\n==> Checking service health...")
# Check API
try:
import requests
response = requests.get("http://localhost:8000/health", timeout=5)
if response.status_code == 200:
print(" [OK] API: Healthy")
data = response.json()
print(f" Status: {data.get('status')}")
print(f" Database: {data.get('database')}")
else:
print(f" [ERROR] API: HTTP {response.status_code}")
except Exception as e:
print(f" [WARNING] API: Not responding ({e})")
# Check Flower
try:
import requests
response = requests.get("http://localhost:5555", timeout=5)
if response.status_code == 200:
print(" [OK] Flower: Accessible")
else:
print(f" [WARNING] Flower: HTTP {response.status_code}")
except Exception as e:
print(f" [WARNING] Flower: Not responding ({e})")
def show_logs(self, service=None, follow=False):
"""Show service logs."""
print(f"\n==> Showing logs {'(following)' if follow else ''}...")
cmd = self.get_compose_cmd("logs")
if follow:
cmd.append("-f")
if service:
cmd.append(service)
try:
self.run_command(cmd, check=False)
except KeyboardInterrupt:
print("\n[INFO] Logs stopped")
def show_status(self):
"""Show service status."""
print("\n==> Service status:")
try:
self.run_command(self.get_compose_cmd("ps"))
except subprocess.CalledProcessError:
print("[ERROR] Failed to get service status")
def show_endpoints(self):
"""Show available endpoints."""
print("\n==> Available endpoints:")
print(" - API: http://localhost:8000")
print(" - API Health: http://localhost:8000/health")
print(" - API Docs: http://localhost:8000/docs")
print(" - Flower: http://localhost:5555 (admin:dev)")
print("\n==> Frontend setup:")
print(" 1. Open new terminal")
print(" 2. cd frontend")
print(" 3. npm run dev")
print(" 4. Open http://localhost:5174")
def cleanup(self):
"""Clean up Docker resources."""
print("\n==> Cleaning up Docker resources...")
try:
# Stop and remove containers
self.run_command(self.get_compose_cmd("down", "-v"))
# Remove unused images
self.run_command(["docker", "image", "prune", "-f"])
# Remove unused volumes
self.run_command(["docker", "volume", "prune", "-f"])
print("[OK] Cleanup completed!")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Cleanup failed: {e}")
return False
def main():
"""Main entry point."""
manager = DockerDevManager()
parser = argparse.ArgumentParser(description="ProScrape Docker Development Manager")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Start command
start_parser = subparsers.add_parser("start", help="Start services")
start_parser.add_argument("--build", action="store_true", help="Build before starting")
start_parser.add_argument("--services", nargs="+", help="Specific services to start")
# Other commands
subparsers.add_parser("stop", help="Stop services")
subparsers.add_parser("restart", help="Restart services")
subparsers.add_parser("status", help="Show service status")
subparsers.add_parser("health", help="Check service health")
subparsers.add_parser("endpoints", help="Show available endpoints")
subparsers.add_parser("cleanup", help="Clean up Docker resources")
# Build command
build_parser = subparsers.add_parser("build", help="Build services")
build_parser.add_argument("services", nargs="*", help="Specific services to build")
# Logs command
logs_parser = subparsers.add_parser("logs", help="Show service logs")
logs_parser.add_argument("service", nargs="?", help="Specific service name")
logs_parser.add_argument("-f", "--follow", action="store_true", help="Follow log output")
args = parser.parse_args()
if not args.command:
parser.print_help()
return
# Check prerequisites for most commands
if args.command not in ["cleanup"] and not manager.check_prerequisites():
sys.exit(1)
if args.command == "start":
if args.build:
if not manager.build_services(args.services):
sys.exit(1)
success = manager.start_services(args.services)
if not success:
sys.exit(1)
elif args.command == "stop":
manager.stop_services()
elif args.command == "restart":
manager.restart_services()
elif args.command == "build":
success = manager.build_services(args.services if args.services else None)
if not success:
sys.exit(1)
elif args.command == "status":
manager.show_status()
elif args.command == "health":
manager.check_services()
elif args.command == "logs":
manager.show_logs(args.service, args.follow)
elif args.command == "endpoints":
manager.show_endpoints()
elif args.command == "cleanup":
manager.cleanup()
if __name__ == "__main__":
main()