Spaces:
Paused
Paused
Update app/services/maintenance.py
Browse files- app/services/maintenance.py +216 -201
app/services/maintenance.py
CHANGED
|
@@ -1,202 +1,217 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import shutil
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
-
from
|
| 6 |
-
from
|
| 7 |
-
from ..
|
| 8 |
-
from ..
|
| 9 |
-
from ..
|
| 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 |
-
for directory in
|
| 188 |
-
if os.path.exists(directory):
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
maintenance = MaintenanceService()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import psutil
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
from typing import Dict, Any, Optional
|
| 6 |
+
from sqlalchemy import select, delete, update, func
|
| 7 |
+
from ..db.database import db
|
| 8 |
+
from ..utils.logger import logger
|
| 9 |
+
from ..core.config import settings
|
| 10 |
+
from ..services.websocket import create_and_broadcast_notification
|
| 11 |
+
from ..db.models import User, Order, Notification, Session
|
| 12 |
+
|
| 13 |
+
class MaintenanceService:
|
| 14 |
+
async def cleanup_expired_sessions(self) -> int:
|
| 15 |
+
"""Clean up expired sessions"""
|
| 16 |
+
try:
|
| 17 |
+
cutoff = datetime.utcnow() - timedelta(days=7)
|
| 18 |
+
async with db.session() as session:
|
| 19 |
+
stmt = delete(Session).where(Session.last_activity < cutoff)
|
| 20 |
+
result = await session.execute(stmt)
|
| 21 |
+
await session.commit()
|
| 22 |
+
return result.rowcount
|
| 23 |
+
except Exception as e:
|
| 24 |
+
logger.error(f"Error cleaning up sessions: {str(e)}")
|
| 25 |
+
return 0
|
| 26 |
+
|
| 27 |
+
async def archive_old_data(self) -> Dict[str, int]:
|
| 28 |
+
"""Archive old data"""
|
| 29 |
+
try:
|
| 30 |
+
cutoff = datetime.utcnow() - timedelta(days=365)
|
| 31 |
+
archived = {}
|
| 32 |
+
|
| 33 |
+
async with db.session() as session:
|
| 34 |
+
# Archive old orders
|
| 35 |
+
order_stmt = update(Order).where(
|
| 36 |
+
Order.created_at < cutoff,
|
| 37 |
+
Order.status.in_(["completed", "cancelled"])
|
| 38 |
+
).values(archived=True)
|
| 39 |
+
order_result = await session.execute(order_stmt)
|
| 40 |
+
archived["orders"] = order_result.rowcount
|
| 41 |
+
|
| 42 |
+
# Archive old notifications
|
| 43 |
+
notif_stmt = update(Notification).where(
|
| 44 |
+
Notification.created_at < cutoff,
|
| 45 |
+
Notification.read == True
|
| 46 |
+
).values(archived=True)
|
| 47 |
+
notif_result = await session.execute(notif_stmt)
|
| 48 |
+
archived["notifications"] = notif_result.rowcount
|
| 49 |
+
|
| 50 |
+
await session.commit()
|
| 51 |
+
return archived
|
| 52 |
+
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error(f"Error archiving old data: {str(e)}")
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
async def check_system_health(self) -> Dict[str, Any]:
|
| 58 |
+
"""Check system health"""
|
| 59 |
+
try:
|
| 60 |
+
async with db.session() as session:
|
| 61 |
+
# Check database connection by running a simple query
|
| 62 |
+
await session.execute(select(func.now()))
|
| 63 |
+
|
| 64 |
+
# Get database size (using psutil for disk stats)
|
| 65 |
+
disk = psutil.disk_usage('/')
|
| 66 |
+
total_space = disk.total / (1024 * 1024 * 1024) # GB
|
| 67 |
+
free_space = disk.free / (1024 * 1024 * 1024) # GB
|
| 68 |
+
|
| 69 |
+
health_data = {
|
| 70 |
+
"status": "healthy",
|
| 71 |
+
"database": {
|
| 72 |
+
"connected": True
|
| 73 |
+
},
|
| 74 |
+
"disk": {
|
| 75 |
+
"total_gb": total_space,
|
| 76 |
+
"free_gb": free_space,
|
| 77 |
+
"usage_percent": disk.percent
|
| 78 |
+
},
|
| 79 |
+
"timestamp": datetime.utcnow()
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# Send alert if disk space is low
|
| 83 |
+
if free_space < 5: # Less than 5GB free
|
| 84 |
+
await create_and_broadcast_notification(
|
| 85 |
+
user_id="admin",
|
| 86 |
+
title="Low Disk Space Alert",
|
| 87 |
+
message=f"Server is running low on disk space. Only {free_space:.2f}GB remaining.",
|
| 88 |
+
notification_type="system_alert",
|
| 89 |
+
data={"free_space_gb": free_space}
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
return health_data
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
logger.error(f"Health check error: {str(e)}")
|
| 96 |
+
return {"status": "unhealthy", "error": str(e)}
|
| 97 |
+
|
| 98 |
+
async def monitor_system_resources(self) -> Dict[str, Any]:
|
| 99 |
+
"""Monitor system resources"""
|
| 100 |
+
try:
|
| 101 |
+
async with db.session() as session:
|
| 102 |
+
# Get current active connections (using psutil for process stats)
|
| 103 |
+
process = psutil.Process()
|
| 104 |
+
open_files = process.open_files()
|
| 105 |
+
connections = len([f for f in open_files if 'socket' in str(f.path)])
|
| 106 |
+
|
| 107 |
+
resources = {
|
| 108 |
+
"database": {
|
| 109 |
+
"connections": connections,
|
| 110 |
+
},
|
| 111 |
+
"system": {
|
| 112 |
+
"cpu_percent": psutil.cpu_percent(),
|
| 113 |
+
"memory_percent": psutil.virtual_memory().percent
|
| 114 |
+
},
|
| 115 |
+
"timestamp": datetime.utcnow()
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
# Alert if too many connections or high resource usage
|
| 119 |
+
if connections > settings.MAX_DB_CONNECTIONS * 0.9:
|
| 120 |
+
await create_and_broadcast_notification(
|
| 121 |
+
user_id="admin",
|
| 122 |
+
title="High Database Connections",
|
| 123 |
+
message=f"Database has {connections} active connections",
|
| 124 |
+
notification_type="system_alert",
|
| 125 |
+
data={"connections": connections}
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return resources
|
| 129 |
+
|
| 130 |
+
except Exception as e:
|
| 131 |
+
logger.error(f"Resource monitoring error: {str(e)}")
|
| 132 |
+
return {"error": str(e)}
|
| 133 |
+
|
| 134 |
+
async def perform_database_maintenance(self) -> Dict[str, Any]:
|
| 135 |
+
"""Perform database maintenance tasks"""
|
| 136 |
+
try:
|
| 137 |
+
async with db.session() as session:
|
| 138 |
+
# Run ANALYZE on major tables
|
| 139 |
+
for table in [User, Order, Notification]:
|
| 140 |
+
await session.execute(f"ANALYZE {table.__tablename__}")
|
| 141 |
+
|
| 142 |
+
# Clean up any orphaned records
|
| 143 |
+
# For example, delete notifications for non-existent users
|
| 144 |
+
stmt = delete(Notification).where(
|
| 145 |
+
~Notification.user_id.in_(
|
| 146 |
+
select(User.id)
|
| 147 |
+
)
|
| 148 |
+
)
|
| 149 |
+
await session.execute(stmt)
|
| 150 |
+
await session.commit()
|
| 151 |
+
|
| 152 |
+
return {"status": "success"}
|
| 153 |
+
|
| 154 |
+
except Exception as e:
|
| 155 |
+
logger.error(f"Database maintenance error: {str(e)}")
|
| 156 |
+
return {"error": str(e)}
|
| 157 |
+
|
| 158 |
+
async def rotate_log_files(self) -> None:
|
| 159 |
+
"""Rotate log files"""
|
| 160 |
+
log_dir = "logs"
|
| 161 |
+
max_log_size = 10 * 1024 * 1024 # 10MB
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
for filename in os.listdir(log_dir):
|
| 165 |
+
filepath = os.path.join(log_dir, filename)
|
| 166 |
+
if os.path.getsize(filepath) > max_log_size:
|
| 167 |
+
# Archive old log
|
| 168 |
+
archive_name = f"{filename}.{datetime.now().strftime('%Y%m%d')}"
|
| 169 |
+
shutil.move(filepath, os.path.join(log_dir, archive_name))
|
| 170 |
+
|
| 171 |
+
# Create new log file
|
| 172 |
+
open(filepath, 'a').close()
|
| 173 |
+
logger.info(f"Rotated log file: {filename}")
|
| 174 |
+
except Exception as e:
|
| 175 |
+
logger.error(f"Log rotation error: {str(e)}")
|
| 176 |
+
|
| 177 |
+
async def manage_storage_quotas(self) -> Dict[str, Any]:
|
| 178 |
+
"""Manage storage quotas and cleanup"""
|
| 179 |
+
try:
|
| 180 |
+
results = {
|
| 181 |
+
"warnings": [],
|
| 182 |
+
"cleaned": 0
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
# Check and clean upload directories
|
| 186 |
+
upload_dirs = ["uploads/documents", "uploads/images"]
|
| 187 |
+
for directory in upload_dirs:
|
| 188 |
+
if os.path.exists(directory):
|
| 189 |
+
total_size = sum(
|
| 190 |
+
os.path.getsize(os.path.join(directory, f))
|
| 191 |
+
for f in os.listdir(directory)
|
| 192 |
+
if os.path.isfile(os.path.join(directory, f))
|
| 193 |
+
) / (1024 * 1024) # Convert to MB
|
| 194 |
+
|
| 195 |
+
if total_size > settings.MAX_UPLOAD_DIR_SIZE_MB:
|
| 196 |
+
results["warnings"].append(
|
| 197 |
+
f"Upload directory {directory} exceeds size limit"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Clean up temporary files
|
| 201 |
+
temp_dirs = ["uploads/temp", "backups/temp"]
|
| 202 |
+
for directory in temp_dirs:
|
| 203 |
+
if os.path.exists(directory):
|
| 204 |
+
# Remove files older than 24 hours
|
| 205 |
+
cutoff = datetime.now() - timedelta(days=1)
|
| 206 |
+
for filename in os.listdir(directory):
|
| 207 |
+
filepath = os.path.join(directory, filename)
|
| 208 |
+
if os.path.getctime(filepath) < cutoff.timestamp():
|
| 209 |
+
os.remove(filepath)
|
| 210 |
+
results["cleaned"] += 1
|
| 211 |
+
|
| 212 |
+
return results
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.error(f"Storage quota management error: {str(e)}")
|
| 215 |
+
return {"error": str(e)}
|
| 216 |
+
|
| 217 |
maintenance = MaintenanceService()
|