Initial commit — Server_Monitorizare_v2
This commit is contained in:
0
config/__init__.py
Normal file
0
config/__init__.py
Normal file
106
config/config.py
Normal file
106
config/config.py
Normal file
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
Application configuration management
|
||||
"""
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
class Config:
|
||||
"""Base configuration"""
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-in-production'
|
||||
|
||||
# Database
|
||||
DATABASE_URL = os.environ.get('DATABASE_URL') or 'sqlite:///data/enhanced_monitoring.db'
|
||||
|
||||
# File Upload Settings
|
||||
UPLOAD_FOLDER = 'data/uploads'
|
||||
MAX_CONTENT_LENGTH = 50 * 1024 * 1024 # 50MB max file size
|
||||
ALLOWED_EXTENSIONS = {'txt', 'log', 'conf', 'cfg', 'json', 'yml', 'yaml'}
|
||||
|
||||
# Message Compression Settings
|
||||
ENABLE_MESSAGE_COMPRESSION = True
|
||||
COMPRESSION_THRESHOLD = 100 # Compress messages longer than 100 chars
|
||||
MAX_TEMPLATE_CACHE_SIZE = 1000
|
||||
|
||||
# Ansible Settings
|
||||
ANSIBLE_INVENTORY_PATH = 'ansible/inventory/dynamic_inventory.yaml'
|
||||
ANSIBLE_PLAYBOOK_PATH = 'ansible/playbooks'
|
||||
SSH_KEY_PATH = os.path.expanduser('~/.ssh/ansible_key')
|
||||
|
||||
# SSH Settings
|
||||
SSH_USERNAME = 'pi'
|
||||
SSH_PORT = 22
|
||||
SSH_TIMEOUT = 10
|
||||
|
||||
# Performance Settings
|
||||
DATABASE_POOL_SIZE = 20
|
||||
DATABASE_POOL_TIMEOUT = 30
|
||||
LOG_RETENTION_DAYS = 90
|
||||
|
||||
# Security Settings
|
||||
BCRYPT_LOG_ROUNDS = 12
|
||||
SESSION_COOKIE_SECURE = False # Set to True in production with HTTPS
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||
PERMANENT_SESSION_LIFETIME = timedelta(days=7)
|
||||
|
||||
# API Settings
|
||||
API_RATE_LIMIT = '1000 per hour'
|
||||
API_PAGINATION_DEFAULT = 100
|
||||
API_PAGINATION_MAX = 1000
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
"""Development configuration"""
|
||||
DEBUG = True
|
||||
TESTING = False
|
||||
|
||||
# More verbose logging in development
|
||||
LOG_LEVEL = 'DEBUG'
|
||||
|
||||
# Disable some security features for development
|
||||
SESSION_COOKIE_SECURE = False
|
||||
WTF_CSRF_ENABLED = False # Disable CSRF for API testing
|
||||
|
||||
class ProductionConfig(Config):
|
||||
"""Production configuration"""
|
||||
DEBUG = False
|
||||
TESTING = False
|
||||
|
||||
# Security settings for production
|
||||
SESSION_COOKIE_SECURE = True
|
||||
WTF_CSRF_ENABLED = True
|
||||
|
||||
# Production database (if using PostgreSQL)
|
||||
DATABASE_URL = os.environ.get('DATABASE_URL') or 'sqlite:///data/enhanced_monitoring.db'
|
||||
|
||||
# Logging
|
||||
LOG_LEVEL = 'INFO'
|
||||
LOG_FILE = 'logs/app.log'
|
||||
|
||||
# Performance
|
||||
DATABASE_POOL_SIZE = 50
|
||||
|
||||
class TestingConfig(Config):
|
||||
"""Testing configuration"""
|
||||
TESTING = True
|
||||
DEBUG = True
|
||||
|
||||
# Use in-memory database for testing
|
||||
DATABASE_URL = 'sqlite:///:memory:'
|
||||
|
||||
# Disable CSRF for testing
|
||||
WTF_CSRF_ENABLED = False
|
||||
|
||||
# Configuration dictionary
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
'testing': TestingConfig,
|
||||
'default': DevelopmentConfig
|
||||
}
|
||||
|
||||
def get_config(config_name=None):
|
||||
"""Get configuration class"""
|
||||
if config_name is None:
|
||||
config_name = os.environ.get('FLASK_ENV', 'default')
|
||||
|
||||
return config.get(config_name, config['default'])
|
||||
120
config/database_config.py
Normal file
120
config/database_config.py
Normal file
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
Database configuration and connection management
|
||||
"""
|
||||
import os
|
||||
from sqlalchemy import create_engine, MetaData
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from contextlib import contextmanager
|
||||
from app.models import Base
|
||||
import logging
|
||||
|
||||
class DatabaseConfig:
|
||||
"""Database configuration and connection management"""
|
||||
|
||||
def __init__(self, database_url=None):
|
||||
if database_url is None:
|
||||
# Default to SQLite with improved path
|
||||
self.database_url = f"sqlite:///data/enhanced_monitoring.db"
|
||||
else:
|
||||
self.database_url = database_url
|
||||
|
||||
self.engine = None
|
||||
self.Session = None
|
||||
self._setup_database()
|
||||
|
||||
def _setup_database(self):
|
||||
"""Initialize database connection and session factory"""
|
||||
# Create data directory if it doesn't exist
|
||||
os.makedirs('data', exist_ok=True)
|
||||
|
||||
# Create engine with connection pooling for SQLite
|
||||
self.engine = create_engine(
|
||||
self.database_url,
|
||||
echo=False, # Set to True for SQL debugging
|
||||
pool_pre_ping=True,
|
||||
connect_args={"check_same_thread": False} # For SQLite
|
||||
)
|
||||
|
||||
# Create session factory
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
|
||||
def create_tables(self):
|
||||
"""Create all database tables"""
|
||||
try:
|
||||
Base.metadata.create_all(self.engine)
|
||||
logging.info("Database tables created successfully")
|
||||
return True
|
||||
except Exception as e:
|
||||
logging.error(f"Error creating database tables: {e}")
|
||||
return False
|
||||
|
||||
def drop_tables(self):
|
||||
"""Drop all database tables (use with caution!)"""
|
||||
try:
|
||||
Base.metadata.drop_all(self.engine)
|
||||
logging.info("Database tables dropped successfully")
|
||||
return True
|
||||
except Exception as e:
|
||||
logging.error(f"Error dropping database tables: {e}")
|
||||
return False
|
||||
|
||||
@contextmanager
|
||||
def get_session(self):
|
||||
"""Context manager for database sessions"""
|
||||
session = self.Session()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
logging.error(f"Database session error: {e}")
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def get_session_direct(self):
|
||||
"""Get session directly (remember to close it)"""
|
||||
return self.Session()
|
||||
|
||||
def backup_database(self, backup_path=None):
|
||||
"""Create database backup"""
|
||||
if backup_path is None:
|
||||
from datetime import datetime
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
backup_path = f"data/backups/backup_{timestamp}.db"
|
||||
|
||||
try:
|
||||
# Create backups directory
|
||||
os.makedirs('data/backups', exist_ok=True)
|
||||
|
||||
# For SQLite, simple file copy
|
||||
if self.database_url.startswith('sqlite'):
|
||||
import shutil
|
||||
db_file = self.database_url.replace('sqlite:///', '')
|
||||
shutil.copy2(db_file, backup_path)
|
||||
logging.info(f"Database backup created: {backup_path}")
|
||||
return backup_path
|
||||
else:
|
||||
# For other databases, implement proper backup
|
||||
logging.warning("Backup not implemented for non-SQLite databases")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Database backup failed: {e}")
|
||||
return None
|
||||
|
||||
# Global database instance
|
||||
db_config = None
|
||||
|
||||
def init_database(database_url=None):
|
||||
"""Initialize global database configuration"""
|
||||
global db_config
|
||||
db_config = DatabaseConfig(database_url)
|
||||
return db_config.create_tables()
|
||||
|
||||
def get_db():
|
||||
"""Get database configuration instance"""
|
||||
global db_config
|
||||
if db_config is None:
|
||||
init_database()
|
||||
return db_config
|
||||
Reference in New Issue
Block a user