Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
164 lines (133 loc) · 5.55 KB
/
Copy pathrun.py
File metadata and controls
164 lines (133 loc) · 5.55 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
import os
import sys
import importlib
import uvicorn
import subprocess
import signal
import argparse
import platform
def load_env_variables():
"""
Load environment variables from a .env file.
The .env file is expected to be in the same directory as this script.
The file should contain lines of the form "VARIABLE_NAME=VALUE".
Lines that start with "#" are ignored.
If the .env file is not found, the function simply prints a warning message.
"""
env_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(env_path):
with open(env_path, 'r') as f:
for line in f:
# Ignore blank lines and lines that start with "#"
if line.strip() and not line.startswith('#'):
key, value = line.strip().split('=', 1)
os.environ[key] = value
print("Loaded environment variables from .env file.")
else:
print("Warning: .env file not found.")
def check_environment_variables():
"""
Check that all required environment variables are set.
"""
# The list of environment variables that must be set
required_vars = ['METACAT_SERVER_URL', 'METACAT_AUTH_SERVER_URL']
# Check if any of the required environment variables are missing
missing_vars = [var for var in required_vars if not os.getenv(var)]
# If any required environment variables are missing, print an error message and exit
if missing_vars:
print(f"Error: Missing environment variables: {', '.join(missing_vars)}")
sys.exit(1)
def check_required_packages():
"""
Check if all required packages are installed.
The function checks if the packages in the required_packages list are installed.
If any of the packages are missing, the function prints an error message and exits.
"""
required_packages = ['fastapi', 'uvicorn', 'metacat']
for package in required_packages:
try:
# Try to import the package
importlib.import_module(package)
except ImportError:
# If the import fails, print an error message and exit
print(f"Error: Required package '{package}' is not installed.")
sys.exit(1)
def check_metacat_connection():
"""
Check that we can connect to MetaCat.
This function is called before starting the server. If the connection
check fails, the function prints an error message and exits the program.
"""
from src.lib.mcatapi import MetaCatAPI
try:
api = MetaCatAPI()
# Perform a simple query to check the connection
api.list_datasets()
print("MetaCat connection successful.")
except Exception as e:
# If the connection check fails, print an error message and exit
print(f"Error: Unable to connect to MetaCat. {str(e)}")
sys.exit(1)
def get_npm_command():
"""Get the correct npm command based on the operating system."""
if platform.system() == "Windows":
return "npm.cmd"
return "npm"
def start_frontend(production_mode=False):
"""
Start the Next.js frontend server.
Args:
production_mode (bool): If True, builds and runs in production mode.
If False, runs in development mode.
"""
npm_cmd = get_npm_command()
# Set up environment with node_modules/.bin in PATH
env = os.environ.copy()
project_dir = os.path.dirname(__file__)
node_bin_path = os.path.join(project_dir, 'node_modules', '.bin')
env['PATH'] = f"{node_bin_path}:{env.get('PATH', '')}"
if production_mode:
print("Building frontend for production...")
build_process = subprocess.Popen([npm_cmd, "run", "build"], cwd=project_dir, env=env)
build_process.wait() # Wait for build to complete
print("Starting frontend in production mode...")
return subprocess.Popen([npm_cmd, "run", "start"], cwd=project_dir, env=env)
else:
print("Starting frontend in development mode...")
return subprocess.Popen([npm_cmd, "run", "dev"], cwd=project_dir, env=env)
def start_server(production_mode=False):
"""
Start the FastAPI server.
This function is called at the end of the run.py script. It starts the
FastAPI server using the uvicorn.run() function.
Parameters:
None
Returns:
None
"""
print("Starting backend server...")
uvicorn.run("src.backend.main:app", host="0.0.0.0", port=8080, reload=not production_mode)
def signal_handler(sig, frame):
"""Handle Ctrl+C gracefully"""
print("\nShutting down servers...")
sys.exit(0)
if __name__ == "__main__":
# Set up argument parser
parser = argparse.ArgumentParser(description='Run the DUNE Catalog application')
parser.add_argument('-start', '--production', action='store_true',
help='Run in production mode (npm run build + npm run start)')
args = parser.parse_args()
signal.signal(signal.SIGINT, signal_handler)
print("Performing pre-start checks...")
load_env_variables()
if args.production:
os.environ["ENVIRONMENT"] = "production"
from src.backend.auth import validate_security_configuration
validate_security_configuration()
check_environment_variables()
check_required_packages()
check_metacat_connection()
print("All checks passed. Starting the servers...")
frontend_process = start_frontend(production_mode=args.production)
start_server(production_mode=args.production) # Blocks until the backend stops
frontend_process.terminate() # Clean up frontend when backend stops