Noel-Teens commited on
Commit
6069ba8
Β·
1 Parent(s): 2d2d664

feat(env): validate configuration and add MySQL connection test with SQLite fallback

Browse files

- Add environment variable validation and configuration summary display on startup
- Test MySQL database connection if all required variables are set, exit on failure
- Print warning and fallback to SQLite development database if MySQL config is incomplete
- Enhance SSL options for MySQL connection, including certificate handling and verification
- Add runtime warnings when database variables are missing or fallback to SQLite is used
- Reorder and clarify startup steps: validate env, test DB, run migrations, then start server
- Remove unused 'resend' package from requirements.txt to clean dependencies

Files changed (5) hide show
  1. app.py +29 -2
  2. pms_server/settings.py +41 -6
  3. requirements.txt +1 -2
  4. utils/environment.py +125 -0
  5. utils/test_db.py +116 -0
app.py CHANGED
@@ -1,9 +1,36 @@
1
  import os
 
 
 
2
 
3
- # ---- STEP 2: Run migrations to initialize database
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  os.system("python manage.py makemigrations")
5
  os.system("python manage.py migrate")
6
  os.system("python manage.py createsuperadmin --username=Admin --email=admin@gmail.com --password=adminpassword")
7
 
8
- # ---- STEP 3: Start Django dev server on required Hugging Face port
 
 
 
9
  os.system("uvicorn pms_server.asgi:application --host 0.0.0.0 --port 7860")
 
1
  import os
2
+ import sys
3
+ from utils.environment import print_configuration_summary, validate_environment_variables
4
+ from utils.test_db import test_database_connection, check_required_variables
5
 
6
+ # ---- STEP 1: Validate environment configuration
7
+ print_configuration_summary()
8
+ validation_results = validate_environment_variables()
9
+
10
+ # ---- STEP 2: Test database connection (only if MySQL is configured)
11
+ mysql_vars = ['AIVEN_DB_NAME', 'AIVEN_DB_USER', 'AIVEN_DB_PASSWORD', 'AIVEN_DB_HOST']
12
+ if all(os.getenv(var) for var in mysql_vars):
13
+ print("\n" + "=" * 50)
14
+ print("Testing Database Connection...")
15
+ print("=" * 50)
16
+
17
+ if not test_database_connection():
18
+ print("\n❌ Database connection failed. Exiting...")
19
+ print("Please check your database configuration and try again.")
20
+ sys.exit(1)
21
+ else:
22
+ print("\n⚠️ MySQL not configured, using SQLite fallback for development.")
23
+
24
+ # ---- STEP 3: Run migrations to initialize database
25
+ print("\n" + "=" * 50)
26
+ print("Running Database Migrations...")
27
+ print("=" * 50)
28
  os.system("python manage.py makemigrations")
29
  os.system("python manage.py migrate")
30
  os.system("python manage.py createsuperadmin --username=Admin --email=admin@gmail.com --password=adminpassword")
31
 
32
+ # ---- STEP 4: Start Django dev server on required Hugging Face port
33
+ print("\n" + "=" * 50)
34
+ print("Starting Server...")
35
+ print("=" * 50)
36
  os.system("uvicorn pms_server.asgi:application --host 0.0.0.0 --port 7860")
pms_server/settings.py CHANGED
@@ -140,10 +140,32 @@ AIVEN_CA_CERT = os.getenv("AIVEN_CA_CERT")
140
  ssl_options = {}
141
  if AIVEN_CA_CERT:
142
  # Write cert text to a temporary file at runtime
143
- ca_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pem")
144
- ca_file.write(AIVEN_CA_CERT.encode())
145
  ca_file.flush()
146
- ssl_options["ca"] = ca_file.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  DATABASES = {
149
  "default": {
@@ -153,12 +175,25 @@ DATABASES = {
153
  "PASSWORD": os.getenv("AIVEN_DB_PASSWORD"),
154
  "HOST": os.getenv("AIVEN_DB_HOST"),
155
  "PORT": os.getenv("AIVEN_DB_PORT", "16000"),
156
- "OPTIONS": {
157
- "ssl": ssl_options,
158
- },
159
  }
160
  }
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  # Password validation
163
  # https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
164
 
 
140
  ssl_options = {}
141
  if AIVEN_CA_CERT:
142
  # Write cert text to a temporary file at runtime
143
+ ca_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pem")
144
+ ca_file.write(AIVEN_CA_CERT)
145
  ca_file.flush()
146
+ ca_file.close()
147
+ ssl_options = {
148
+ "ca": ca_file.name,
149
+ "check_hostname": False,
150
+ "verify_mode": 2 # ssl.CERT_REQUIRED
151
+ }
152
+ else:
153
+ # If no certificate provided, disable SSL verification (not recommended for production)
154
+ ssl_options = {
155
+ "disabled": True
156
+ }
157
+
158
+ # Validate database configuration
159
+ required_db_vars = ['AIVEN_DB_NAME', 'AIVEN_DB_USER', 'AIVEN_DB_PASSWORD', 'AIVEN_DB_HOST']
160
+ missing_db_vars = [var for var in required_db_vars if not os.getenv(var)]
161
+
162
+ if missing_db_vars:
163
+ import warnings
164
+ warnings.warn(
165
+ f"Aiven MySQL database configuration incomplete. Missing: {', '.join(missing_db_vars)}. "
166
+ "Application may fail to start.",
167
+ RuntimeWarning
168
+ )
169
 
170
  DATABASES = {
171
  "default": {
 
175
  "PASSWORD": os.getenv("AIVEN_DB_PASSWORD"),
176
  "HOST": os.getenv("AIVEN_DB_HOST"),
177
  "PORT": os.getenv("AIVEN_DB_PORT", "16000"),
178
+ "OPTIONS": ssl_options,
 
 
179
  }
180
  }
181
 
182
+ # Fallback to SQLite if MySQL configuration is incomplete (development only)
183
+ if missing_db_vars:
184
+ import warnings
185
+ warnings.warn(
186
+ "MySQL configuration incomplete. Falling back to SQLite for development. "
187
+ "This should not be used in production.",
188
+ RuntimeWarning
189
+ )
190
+ DATABASES = {
191
+ "default": {
192
+ "ENGINE": "django.db.backends.sqlite3",
193
+ "NAME": BASE_DIR / "db.sqlite3",
194
+ }
195
+ }
196
+
197
  # Password validation
198
  # https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
199
 
requirements.txt CHANGED
@@ -11,5 +11,4 @@ django-storages==1.14.3
11
  boto3==1.35.40
12
  botocore==1.35.40
13
  PyMySQL==1.1.0
14
- python-dotenv==1.0.1
15
- resend
 
11
  boto3==1.35.40
12
  botocore==1.35.40
13
  PyMySQL==1.1.0
14
+ python-dotenv==1.0.1
 
utils/environment.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Environment validation utilities for PMS Server
3
+ """
4
+ import os
5
+ import warnings
6
+ from typing import Dict, List, Optional
7
+
8
+
9
+ def validate_environment_variables() -> Dict[str, bool]:
10
+ """
11
+ Validate required environment variables for the application.
12
+
13
+ Returns:
14
+ Dict[str, bool]: Dictionary with validation status for each service
15
+ """
16
+ validation_results = {}
17
+
18
+ # Backblaze B2 Storage
19
+ b2_vars = ['B2_KEY_ID', 'B2_APP_KEY', 'B2_BUCKET_NAME', 'B2_ENDPOINT_URL']
20
+ b2_configured = all(os.getenv(var) for var in b2_vars)
21
+ validation_results['backblaze_b2'] = b2_configured
22
+
23
+ if not b2_configured:
24
+ missing_vars = [var for var in b2_vars if not os.getenv(var)]
25
+ warnings.warn(
26
+ f"Backblaze B2 storage not fully configured. Missing: {', '.join(missing_vars)}. "
27
+ "Files will be stored locally.",
28
+ RuntimeWarning
29
+ )
30
+
31
+ # Aiven MySQL Database
32
+ mysql_vars = ['AIVEN_DB_NAME', 'AIVEN_DB_USER', 'AIVEN_DB_PASSWORD', 'AIVEN_DB_HOST']
33
+ mysql_configured = all(os.getenv(var) for var in mysql_vars)
34
+ validation_results['aiven_mysql'] = mysql_configured
35
+
36
+ if not mysql_configured:
37
+ missing_vars = [var for var in mysql_vars if not os.getenv(var)]
38
+ warnings.warn(
39
+ f"Aiven MySQL database not fully configured. Missing: {', '.join(missing_vars)}. "
40
+ "Application will fall back to SQLite for development.",
41
+ RuntimeWarning
42
+ )
43
+ elif not os.getenv('AIVEN_CA_CERT'):
44
+ warnings.warn(
45
+ "AIVEN_CA_CERT not provided. SSL connection may fail. "
46
+ "For production, please provide the SSL certificate.",
47
+ RuntimeWarning
48
+ )
49
+
50
+ # Email Services (SendGrid)
51
+ sendgrid_vars = ['SENDGRID_API_KEY', 'FROM_EMAIL']
52
+ sendgrid_configured = all(os.getenv(var) for var in sendgrid_vars)
53
+ validation_results['sendgrid'] = sendgrid_configured
54
+
55
+ if not sendgrid_configured:
56
+ missing_vars = [var for var in sendgrid_vars if not os.getenv(var)]
57
+ warnings.warn(
58
+ f"SendGrid email service not configured. Missing: {', '.join(missing_vars)}. "
59
+ "Email invitations will not work.",
60
+ RuntimeWarning
61
+ )
62
+
63
+ # Firebase
64
+ firebase_configured = bool(os.getenv('FIREBASE_SERVICE_KEY'))
65
+ validation_results['firebase'] = firebase_configured
66
+
67
+ if not firebase_configured:
68
+ warnings.warn(
69
+ "Firebase not configured. FIREBASE_SERVICE_KEY missing. "
70
+ "Firebase authentication will not work.",
71
+ RuntimeWarning
72
+ )
73
+
74
+ return validation_results
75
+
76
+
77
+ def get_storage_status() -> str:
78
+ """
79
+ Get current storage configuration status.
80
+
81
+ Returns:
82
+ str: Description of current storage configuration
83
+ """
84
+ b2_vars = ['B2_KEY_ID', 'B2_APP_KEY', 'B2_BUCKET_NAME', 'B2_ENDPOINT_URL']
85
+ if all(os.getenv(var) for var in b2_vars):
86
+ return "Backblaze B2 Cloud Storage (Configured)"
87
+ else:
88
+ return "Local File Storage (Backblaze B2 not configured)"
89
+
90
+
91
+ def get_database_status() -> str:
92
+ """
93
+ Get current database configuration status.
94
+
95
+ Returns:
96
+ str: Description of current database configuration
97
+ """
98
+ mysql_vars = ['AIVEN_DB_NAME', 'AIVEN_DB_USER', 'AIVEN_DB_PASSWORD', 'AIVEN_DB_HOST']
99
+ if all(os.getenv(var) for var in mysql_vars):
100
+ ssl_status = "with SSL" if os.getenv('AIVEN_CA_CERT') else "without SSL"
101
+ return f"Aiven MySQL Database (Configured {ssl_status} using PyMySQL)"
102
+ else:
103
+ return "SQLite Database (Fallback - MySQL not configured)"
104
+
105
+
106
+ def print_configuration_summary():
107
+ """Print a summary of the current configuration."""
108
+ print("=" * 50)
109
+ print("PMS Server Configuration Summary")
110
+ print("=" * 50)
111
+
112
+ validation_results = validate_environment_variables()
113
+
114
+ print(f"Storage: {get_storage_status()}")
115
+ print(f"Database: {get_database_status()}")
116
+ print(f"Email (SendGrid): {'Configured' if validation_results['sendgrid'] else 'Not Configured'}")
117
+ print(f"Firebase: {'Configured' if validation_results['firebase'] else 'Not Configured'}")
118
+
119
+ if not all(validation_results.values()):
120
+ print("\n⚠️ Some services are not fully configured.")
121
+ print("Please check the warnings above and set the missing environment variables.")
122
+ else:
123
+ print("\nβœ… All services are properly configured!")
124
+
125
+ print("=" * 50)
utils/test_db.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database connection testing utilities
3
+ """
4
+ import os
5
+ import sys
6
+ import warnings
7
+
8
+
9
+ def test_database_connection():
10
+ """
11
+ Test database connection before running migrations.
12
+ Returns True if connection is successful, False otherwise.
13
+ """
14
+ try:
15
+ # Set up Django environment
16
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pms_server.settings')
17
+
18
+ import django
19
+ django.setup()
20
+
21
+ from django.db import connection
22
+ from django.db.utils import OperationalError
23
+
24
+ # Test the connection
25
+ with connection.cursor() as cursor:
26
+ cursor.execute("SELECT 1")
27
+ result = cursor.fetchone()
28
+
29
+ print("βœ… Database connection successful!")
30
+ return True
31
+
32
+ except OperationalError as e:
33
+ error_msg = str(e)
34
+
35
+ if "no certificate or crl found" in error_msg:
36
+ print("❌ SSL Certificate error:")
37
+ print(" The AIVEN_CA_CERT environment variable is missing or invalid.")
38
+ print(" Please ensure you have the correct SSL certificate from Aiven.")
39
+ print(" For development, you can temporarily disable SSL, but this is not recommended.")
40
+
41
+ elif "Access denied" in error_msg:
42
+ print("❌ Authentication error:")
43
+ print(" Please check your AIVEN_DB_USER and AIVEN_DB_PASSWORD.")
44
+
45
+ elif "Unknown database" in error_msg:
46
+ print("❌ Database not found:")
47
+ print(" Please check your AIVEN_DB_NAME.")
48
+
49
+ elif "Can't connect" in error_msg or "Connection refused" in error_msg:
50
+ print("❌ Connection error:")
51
+ print(" Please check your AIVEN_DB_HOST and AIVEN_DB_PORT.")
52
+ print(" Make sure your IP is whitelisted in Aiven.")
53
+
54
+ else:
55
+ print(f"❌ Database connection failed: {error_msg}")
56
+
57
+ return False
58
+
59
+ except ImportError as e:
60
+ print(f"❌ Django import error: {e}")
61
+ return False
62
+
63
+ except Exception as e:
64
+ print(f"❌ Unexpected error: {e}")
65
+ return False
66
+
67
+
68
+ def check_required_variables():
69
+ """
70
+ Check if all required database environment variables are set.
71
+ """
72
+ required_vars = [
73
+ 'AIVEN_DB_NAME',
74
+ 'AIVEN_DB_USER',
75
+ 'AIVEN_DB_PASSWORD',
76
+ 'AIVEN_DB_HOST'
77
+ ]
78
+
79
+ missing_vars = []
80
+ for var in required_vars:
81
+ if not os.getenv(var):
82
+ missing_vars.append(var)
83
+
84
+ if missing_vars:
85
+ print("❌ Missing required database environment variables:")
86
+ for var in missing_vars:
87
+ print(f" - {var}")
88
+ print("\nPlease set these variables in your .env file or environment.")
89
+ return False
90
+
91
+ # Check optional SSL certificate
92
+ if not os.getenv('AIVEN_CA_CERT'):
93
+ warnings.warn(
94
+ "AIVEN_CA_CERT not provided. SSL connection may fail in production.",
95
+ RuntimeWarning
96
+ )
97
+
98
+ return True
99
+
100
+
101
+ if __name__ == "__main__":
102
+ print("=" * 50)
103
+ print("Database Connection Test")
104
+ print("=" * 50)
105
+
106
+ # Check environment variables first
107
+ if not check_required_variables():
108
+ sys.exit(1)
109
+
110
+ # Test database connection
111
+ if test_database_connection():
112
+ print("Database is ready for Django migrations!")
113
+ sys.exit(0)
114
+ else:
115
+ print("Database connection failed. Please fix the issues above.")
116
+ sys.exit(1)