-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.py
More file actions
446 lines (375 loc) · 15.1 KB
/
dev.py
File metadata and controls
446 lines (375 loc) · 15.1 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
#!/usr/bin/env python3
"""
DSMS Unified Development Server
"""
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
# Colors for output
class Colors:
CYAN = "\033[0;36m"
GREEN = "\033[0;32m"
YELLOW = "\033[0;33m"
RED = "\033[0;31m"
NC = "\033[0m" # No Color
def print_colored(message, color):
print(f"{color}{message}{Colors.NC}")
def check_python_dependencies():
"""Check and install Python dependencies if needed"""
print_colored("Checking Python dependencies...", Colors.CYAN)
# Find or create virtual environment
venv_paths = [
os.path.join("src", "dsms", "venv"),
os.path.join("src", "dsms", ".venv"),
]
venv_path = None
venv_python = None
# Check if any venv exists
for path in venv_paths:
python_exe = (
os.path.join(path, "Scripts", "python.exe")
if sys.platform == "win32"
else os.path.join(path, "bin", "python")
)
if os.path.exists(python_exe):
venv_path = path
venv_python = python_exe
break
# Create venv if it doesn't exist
if venv_python is None:
print_colored(
"[INFO] Virtual environment not found, creating one...", Colors.YELLOW
)
venv_path = venv_paths[0] # Use first path (venv)
try:
subprocess.run([sys.executable, "-m", "venv", venv_path], check=True)
venv_python = (
os.path.join(venv_path, "Scripts", "python.exe")
if sys.platform == "win32"
else os.path.join(venv_path, "bin", "python")
)
print_colored(
f"[OK] Virtual environment created at {venv_path}", Colors.GREEN
)
except Exception as e:
print_colored(
f"[ERROR] Failed to create virtual environment: {e}", Colors.RED
)
print_colored("[INFO] Falling back to system Python", Colors.YELLOW)
venv_python = sys.executable
requirements_file = os.path.join("src", "dsms", "requirements.txt")
try:
result = subprocess.run(
[
venv_python,
"-c",
'import django, mongoengine, channels, rest_framework, celery; print("OK")',
],
capture_output=True,
text=True,
cwd=os.path.join("src", "dsms"),
)
if result.returncode == 0:
print_colored("[OK] Python dependencies are up to date", Colors.GREEN)
return True
else:
print_colored("[INFO] Installing Python dependencies...", Colors.YELLOW)
# Install dependencies
install_result = subprocess.run(
[venv_python, "-m", "pip", "install", "-r", requirements_file],
capture_output=False,
text=True,
)
if install_result.returncode == 0:
print_colored(
"[OK] Python dependencies installed successfully", Colors.GREEN
)
return True
else:
print_colored(
"[ERROR] Failed to install Python dependencies", Colors.RED
)
return False
except Exception as e:
print_colored(f"[ERROR] Error with Python dependencies: {e}", Colors.RED)
return False
def check_mongodb():
"""Check if MongoDB is running"""
print_colored("Checking MongoDB connection...", Colors.CYAN)
# If using cloud MongoDB, skip local check
if "MONGODB_URI" in os.environ:
print_colored("[OK] Using cloud MongoDB (MONGODB_URI is set)", Colors.GREEN)
return True
try:
import pymongo
from pymongo import MongoClient
# Check local MongoDB
mongodb_uri = "mongodb://localhost:27017/"
client = MongoClient(mongodb_uri, serverSelectionTimeoutMS=5000)
client.admin.command("ping")
print_colored("[OK] MongoDB is running", Colors.GREEN)
return True
except Exception as e:
print_colored(f"[WARNING] Local MongoDB not found: {e}", Colors.YELLOW)
print_colored(
"[TIP] Set MONGODB_URI environment variable for cloud MongoDB or start local MongoDB",
Colors.YELLOW,
)
return False
def check_redis():
"""Check if Redis is running"""
print_colored("Checking Redis connection...", Colors.CYAN)
# If using cloud Redis, skip local check
if "REDIS_URL" in os.environ:
print_colored("[OK] Using cloud Redis (REDIS_URL is set)", Colors.GREEN)
return True
try:
import redis
# Check local Redis
r = redis.Redis(host="localhost", port=6379, db=0, socket_timeout=5)
r.ping()
print_colored("[OK] Redis is running", Colors.GREEN)
return True
except Exception as e:
print_colored(f"[WARNING] Local Redis not found: {e}", Colors.YELLOW)
print_colored(
"[TIP] Set REDIS_URL environment variable for cloud Redis or start local Redis",
Colors.YELLOW,
)
return False
def check_frontend_dependencies():
"""Check and install frontend dependencies if needed"""
print_colored("Checking frontend dependencies...", Colors.CYAN)
node_modules = Path("node_modules")
package_json = Path("package.json")
if not package_json.exists():
print_colored("[ERROR] package.json not found", Colors.RED)
return False
needs_install = False
if not node_modules.exists() or not any(node_modules.iterdir()):
print_colored("[INFO] Frontend dependencies not installed", Colors.YELLOW)
needs_install = True
else:
# Check if package-lock.json is newer than node_modules (dependencies changed)
package_lock = Path("package-lock.json")
if package_lock.exists():
if package_lock.stat().st_mtime > node_modules.stat().st_mtime:
print_colored(
"[INFO] Dependencies updated, reinstalling...", Colors.YELLOW
)
needs_install = True
if needs_install:
print_colored("Installing frontend dependencies...", Colors.CYAN)
try:
npm_cmd = "npm.cmd" if sys.platform == "win32" else "npm"
result = subprocess.run(
[npm_cmd, "install"],
shell=True,
capture_output=False,
text=True,
)
if result.returncode == 0:
print_colored(
"[OK] Frontend dependencies installed successfully", Colors.GREEN
)
return True
else:
print_colored(
"[ERROR] Failed to install frontend dependencies", Colors.RED
)
return False
except Exception as e:
print_colored(
f"[ERROR] Failed to install frontend dependencies: {e}", Colors.RED
)
return False
print_colored("[OK] Frontend dependencies are up to date", Colors.GREEN)
return True
def start_django_server():
"""Start Django development server"""
print_colored("Starting Django server...", Colors.GREEN)
# Find virtual environment Python
venv_paths = [
(
os.path.join("src", "dsms", "venv", "Scripts", "python.exe"),
os.path.join("src", "dsms", "venv", "bin", "python"),
),
(
os.path.join("src", "dsms", ".venv", "Scripts", "python.exe"),
os.path.join("src", "dsms", ".venv", "bin", "python"),
),
]
venv_python = None
for win_path, unix_path in venv_paths:
if sys.platform == "win32" and os.path.exists(win_path):
venv_python = win_path
break
elif sys.platform != "win32" and os.path.exists(unix_path):
venv_python = unix_path
break
if venv_python is None:
venv_python = sys.executable # Fallback to system Python
print_colored("[WARNING] Using system Python (venv not found)", Colors.YELLOW)
# manage.py is now at root
return subprocess.Popen([venv_python, "manage.py", "runserver", "0.0.0.0:8000"])
def start_webpack_dev_server():
"""Start Webpack dev server for frontend"""
print_colored("Starting Webpack dev server...", Colors.GREEN)
try:
# On Windows, use npm.cmd, on Unix use npm
npm_cmd = "npm.cmd" if sys.platform == "win32" else "npm"
return subprocess.Popen([npm_cmd, "run", "dev:frontend"], shell=True)
except FileNotFoundError:
print_colored(
"[WARNING] npm not found. Install Node.js to run frontend.", Colors.YELLOW
)
return None
def main():
parser = argparse.ArgumentParser(description="DSMS Unified Development Server")
parser.add_argument(
"--skip-checks", action="store_true", help="Skip dependency checks"
)
parser.add_argument(
"--django-only", action="store_true", help="Run Django only (backend)"
)
parser.add_argument(
"--frontend-only", action="store_true", help="Run frontend only"
)
args = parser.parse_args()
print_colored("DSMS Django Development Server", Colors.CYAN)
print_colored("==============================", Colors.CYAN)
# Change to project root
os.chdir(Path(__file__).parent)
# Check dependencies unless skipped
if not args.skip_checks:
checks_passed = True
frontend_checks_passed = True
# Backend checks
checks_passed &= check_python_dependencies()
# Frontend checks (only if not running django-only)
if not args.django_only:
frontend_checks_passed = check_frontend_dependencies()
# MongoDB and Redis checks are now warnings only for cloud setups
mongodb_ok = check_mongodb()
redis_ok = check_redis()
# Exit if dependencies failed to install
if not checks_passed:
print_colored(
"\n[ERROR] Failed to setup Python dependencies",
Colors.RED,
)
sys.exit(1)
if not args.django_only and not frontend_checks_passed:
print_colored(
"\n[ERROR] Failed to setup frontend dependencies",
Colors.RED,
)
sys.exit(1)
# Warn but don't fail for MongoDB/Redis
if not mongodb_ok or not redis_ok:
print_colored(
"\n[WARNING] Some services are not running locally. Make sure environment variables are set.",
Colors.YELLOW,
)
print_colored(" Continuing anyway...\n", Colors.YELLOW)
# Start servers based on flags
processes = []
try:
if args.frontend_only:
# Start only Webpack dev server
print_colored("\nStarting Webpack dev server...", Colors.CYAN)
webpack_process = start_webpack_dev_server()
if webpack_process:
processes.append(("Webpack", webpack_process))
print_colored("\nDSMS Frontend is running!", Colors.GREEN)
print_colored("==========================", Colors.GREEN)
print_colored("Frontend: http://localhost:3000", Colors.GREEN)
print_colored("\nPress Ctrl+C to stop the server", Colors.YELLOW)
else:
print_colored(
"\n[ERROR] Failed to start Webpack dev server", Colors.RED
)
sys.exit(1)
elif args.django_only:
# Start only Django server
print_colored("\nStarting Django server...", Colors.CYAN)
django_process = start_django_server()
if django_process:
processes.append(("Django", django_process))
print_colored("\nDSMS Django API is running!", Colors.GREEN)
print_colored("============================", Colors.GREEN)
print_colored("Django API: http://localhost:8000", Colors.GREEN)
print_colored("API Docs: http://localhost:8000/api/", Colors.GREEN)
print_colored(
"Health Check: http://localhost:8000/health/", Colors.GREEN
)
print_colored("\nPress Ctrl+C to stop the server", Colors.YELLOW)
else:
print_colored("\n[ERROR] Failed to start Django server", Colors.RED)
sys.exit(1)
else:
# Start both Django and Webpack dev servers
print_colored("\nStarting Django server...", Colors.CYAN)
django_process = start_django_server()
if django_process:
processes.append(("Django", django_process))
else:
print_colored("\n[ERROR] Failed to start Django server", Colors.RED)
sys.exit(1)
print_colored("Starting Webpack dev server...", Colors.CYAN)
webpack_process = start_webpack_dev_server()
if webpack_process:
processes.append(("Webpack", webpack_process))
else:
print_colored(
"\n[ERROR] Failed to start Webpack dev server", Colors.RED
)
# Cleanup already started processes
for name, process in processes:
print_colored(f"Stopping {name}...", Colors.YELLOW)
if process:
process.terminate()
process.wait()
sys.exit(1)
print_colored("\nDSMS is running!", Colors.GREEN)
print_colored("=================", Colors.GREEN)
print_colored("Django API: http://localhost:8000", Colors.GREEN)
print_colored("Frontend: http://localhost:3000", Colors.GREEN)
print_colored("API Docs: http://localhost:8000/api/", Colors.GREEN)
print_colored("Health Check: http://localhost:8000/health/", Colors.GREEN)
print_colored("\nPress Ctrl+C to stop all servers", Colors.YELLOW)
# Wait for processes
for name, process in processes:
if process:
process.wait()
except KeyboardInterrupt:
print_colored("\nStopping servers...", Colors.YELLOW)
for name, process in processes:
if process:
print_colored(f"Stopping {name}...", Colors.YELLOW)
try:
process.terminate()
process.wait(timeout=5)
except Exception:
# Force kill if terminate doesn't work
try:
process.kill()
except Exception:
pass
print_colored("[OK] Servers stopped", Colors.GREEN)
except Exception as e:
print_colored(f"[ERROR] Error: {e}", Colors.RED)
# Cleanup processes
for name, process in processes:
if process:
try:
process.terminate()
process.wait(timeout=5)
except Exception:
pass
sys.exit(1)
if __name__ == "__main__":
main()