database.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import os
  2. from datetime import date
  3. from pathlib import Path
  4. from typing import Any
  5. from urllib.parse import urlparse
  6. from alembic.config import Config as AlembicConfig
  7. from alembic.runtime.migration import MigrationContext
  8. from loguru import logger
  9. from sqlalchemy import (
  10. create_engine,
  11. event,
  12. func,
  13. inspect,
  14. text,
  15. )
  16. from sqlalchemy.orm import sessionmaker
  17. from alembic import command
  18. from config import Config
  19. from database.base import Base # noqa: F401
  20. from database.models import (
  21. AdminUser,
  22. DeniedLog,
  23. LogMetadata,
  24. Notification,
  25. SystemMetrics,
  26. )
  27. from database.models.models import BlacklistDomain, create_dynamic_models
  28. _engine = None
  29. _Session = None
  30. dynamic_model_cache: dict[str, Any] = {}
  31. def get_table_suffix() -> str:
  32. return date.today().strftime("%Y%m%d")
  33. def _normalize_sqlite_path(path_str: str) -> Path:
  34. path_str = path_str.strip()
  35. if path_str in ("", "."):
  36. raise ValueError("DATABASE_STRING_CONNECTION for SQLITE must contain a database path")
  37. if path_str == ":memory:" or path_str == "sqlite:///:memory:":
  38. return Path(":memory:")
  39. if path_str.startswith("sqlite:///"):
  40. path_str = path_str[len("sqlite:///"):]
  41. if not path_str:
  42. raise ValueError("DATABASE_STRING_CONNECTION for SQLITE must contain a database path")
  43. project_root = Path(__file__).resolve().parents[1]
  44. db_path = Path(path_str)
  45. if not db_path.is_absolute():
  46. db_path = project_root / db_path
  47. if path_str.endswith("/") or db_path.is_dir():
  48. db_path = db_path / "squidstats.db"
  49. return db_path
  50. def get_database_url() -> str:
  51. db_type = Config.DATABASE_TYPE
  52. conn_str = Config.DATABASE_STRING_CONNECTION
  53. if db_type == "SQLITE":
  54. db_path = _normalize_sqlite_path(conn_str)
  55. if str(db_path) == ":memory:":
  56. return "sqlite:///:memory:"
  57. return f"sqlite:///{db_path}"
  58. elif db_type in ("MYSQL", "MARIADB"):
  59. # Ejemplo: mysql+pymysql://user:password@host/dbname
  60. # El usuario debe poner el string completo en el .env
  61. if (
  62. conn_str.startswith("mysql://")
  63. or conn_str.startswith("mariadb://")
  64. or conn_str.startswith("mysql+pymysql://")
  65. ):
  66. return conn_str
  67. raise ValueError(
  68. "DATABASE_STRING_CONNECTION must start with 'mysql://' or 'mariadb://'."
  69. )
  70. elif db_type in ("POSTGRESQL", "POSTGRES"):
  71. # Ejemplo: postgresql://user:password@host:port/dbname
  72. # o postgresql+psycopg2://user:password@host:port/dbname
  73. if (
  74. conn_str.startswith("postgresql://")
  75. or conn_str.startswith("postgres://")
  76. or conn_str.startswith("postgresql+psycopg2://")
  77. or conn_str.startswith("postgresql+psycopg://")
  78. ):
  79. return conn_str
  80. raise ValueError(
  81. "DATABASE_STRING_CONNECTION must start with 'postgresql://', 'postgres://', 'postgresql+psycopg2://', or 'postgresql+psycopg://'."
  82. )
  83. else:
  84. raise ValueError(f"Database type not supported: {db_type}")
  85. def create_database_if_not_exists():
  86. db_type = Config.DATABASE_TYPE
  87. if db_type == "SQLITE":
  88. # SQLite crea el archivo automáticamente, no necesitamos hacer nada
  89. logger.info("SQLite database will be created automatically if it doesn't exist")
  90. return
  91. elif db_type in ("MYSQL", "MARIADB"):
  92. try:
  93. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  94. parsed_url = urlparse(conn_str)
  95. database_name = parsed_url.path.lstrip("/")
  96. if not database_name:
  97. logger.warning("No database name found in connection string")
  98. return
  99. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  100. server_engine = create_engine(server_url, echo=False)
  101. with server_engine.connect() as conn:
  102. # Verificar si la base de datos existe
  103. result = conn.execute(
  104. text(
  105. "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :dbname"
  106. ),
  107. {"dbname": database_name},
  108. )
  109. if not result.fetchone():
  110. conn.execute(
  111. text(
  112. f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
  113. )
  114. )
  115. conn.commit()
  116. logger.info(f"Database '{database_name}' created successfully")
  117. else:
  118. logger.info(f"Database '{database_name}' already exists")
  119. server_engine.dispose()
  120. except Exception as e:
  121. logger.error(f"Error creating MySQL/MariaDB database: {e}")
  122. raise
  123. elif db_type in ("POSTGRESQL", "POSTGRES"):
  124. try:
  125. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  126. parsed_url = urlparse(conn_str)
  127. database_name = parsed_url.path.lstrip("/")
  128. if not database_name:
  129. logger.warning("No database name found in PostgreSQL connection string")
  130. return
  131. # Crear URL para conectarse a la base de datos 'postgres' (default)
  132. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/postgres"
  133. # Crear engine con autocommit para evitar transacciones automáticas
  134. server_engine = create_engine(
  135. server_url, echo=False, isolation_level="AUTOCOMMIT"
  136. )
  137. try:
  138. with server_engine.connect() as conn:
  139. # Verificar si la base de datos existe
  140. result = conn.execute(
  141. text("SELECT 1 FROM pg_database WHERE datname = :dbname"),
  142. {"dbname": database_name},
  143. )
  144. if not result.fetchone():
  145. # La base de datos no existe, crearla
  146. # Usar una versión más simple que sea compatible con la mayoría de configuraciones
  147. try:
  148. # Primero intentar con template0 para evitar problemas de collation
  149. conn.execute(
  150. text(
  151. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8' TEMPLATE = template0"
  152. )
  153. )
  154. logger.info(
  155. f"PostgreSQL database '{database_name}' created successfully with template0"
  156. )
  157. except Exception:
  158. # Si falla con template0, intentar sin especificar collation
  159. try:
  160. conn.execute(
  161. text(
  162. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8'"
  163. )
  164. )
  165. logger.info(
  166. f"PostgreSQL database '{database_name}' created successfully without collation"
  167. )
  168. except Exception:
  169. # Como último recurso, crear la base de datos sin especificar encoding
  170. conn.execute(text(f'CREATE DATABASE "{database_name}"'))
  171. logger.info(
  172. f"PostgreSQL database '{database_name}' created successfully with default settings"
  173. )
  174. else:
  175. logger.info(
  176. f"PostgreSQL database '{database_name}' already exists"
  177. )
  178. finally:
  179. server_engine.dispose()
  180. except Exception as e:
  181. logger.error(f"Error creating PostgreSQL database: {e}")
  182. raise
  183. def get_engine():
  184. global _engine
  185. if _engine is not None:
  186. return _engine
  187. create_database_if_not_exists()
  188. db_url = get_database_url()
  189. db_type = Config.DATABASE_TYPE
  190. if db_type == "SQLITE":
  191. _engine = create_engine(
  192. db_url,
  193. echo=False,
  194. future=True,
  195. connect_args={"timeout": 30, "check_same_thread": False},
  196. )
  197. # Enable WAL journal mode and set synchronous=NORMAL for the connection.
  198. # WAL allows concurrent reads while a write is in progress and dramatically
  199. # reduces "database is locked" errors in multi-threaded apps.
  200. @event.listens_for(_engine, "connect")
  201. def set_sqlite_pragmas(dbapi_conn, _connection_record):
  202. cursor = dbapi_conn.cursor()
  203. cursor.execute("PRAGMA journal_mode=WAL")
  204. cursor.execute("PRAGMA synchronous=NORMAL")
  205. cursor.execute("PRAGMA busy_timeout=30000")
  206. cursor.close()
  207. else:
  208. _engine = create_engine(db_url, echo=False, future=True)
  209. return _engine
  210. def get_session():
  211. global _Session
  212. engine = get_engine()
  213. if _Session is None:
  214. create_dynamic_tables(engine)
  215. _Session = sessionmaker(bind=engine)
  216. return _Session()
  217. def table_exists(engine, table_name: str) -> bool:
  218. inspector = inspect(engine)
  219. return inspector.has_table(table_name)
  220. def create_dynamic_tables(engine, date_suffix: str = None):
  221. LogMetadata.__table__.create(engine, checkfirst=True)
  222. DeniedLog.__table__.create(engine, checkfirst=True)
  223. SystemMetrics.__table__.create(engine, checkfirst=True)
  224. Notification.__table__.create(engine, checkfirst=True) # Add notifications table
  225. BlacklistDomain.__table__.create(engine, checkfirst=True)
  226. # New quota tables for the admin quota feature
  227. from database.models.models import QuotaEvent, QuotaGroup, QuotaRule, QuotaUser
  228. QuotaUser.__table__.create(engine, checkfirst=True)
  229. QuotaGroup.__table__.create(engine, checkfirst=True)
  230. QuotaRule.__table__.create(engine, checkfirst=True)
  231. QuotaEvent.__table__.create(engine, checkfirst=True)
  232. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  233. logger.info(f"CreateTable_{date_suffix or 'today'}")
  234. if not table_exists(engine, user_table_name) or not table_exists(
  235. engine, log_table_name
  236. ):
  237. logger.info(
  238. f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
  239. )
  240. # Use create_dynamic_models to define and create the per-day user/log tables
  241. try:
  242. create_dynamic_models(engine, user_table_name, log_table_name)
  243. except Exception as e:
  244. logger.error(f"Error creating dynamic user/log tables: {e}")
  245. raise
  246. def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
  247. if date_suffix is None:
  248. date_suffix = get_table_suffix()
  249. return f"user_{date_suffix}", f"log_{date_suffix}"
  250. def get_dynamic_models(date_suffix: str):
  251. cache_key = f"user_log_{date_suffix}"
  252. if cache_key in dynamic_model_cache:
  253. return dynamic_model_cache[cache_key]
  254. engine = get_engine()
  255. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  256. user_exists = table_exists(engine, user_table_name)
  257. log_exists = table_exists(engine, log_table_name)
  258. if not user_exists or not log_exists:
  259. logger.warning(
  260. f"User/log tables for date suffix '{date_suffix}' do not exist. Attempting to recreate..."
  261. )
  262. create_dynamic_tables(engine, date_suffix=date_suffix)
  263. user_exists = table_exists(engine, user_table_name)
  264. log_exists = table_exists(engine, log_table_name)
  265. if not user_exists or not log_exists:
  266. logger.error(
  267. f"User/log tables for date suffix '{date_suffix}' could not be created or found."
  268. )
  269. return None, None
  270. DynamicUser, DynamicLog = create_dynamic_models(
  271. engine, user_table_name, log_table_name
  272. )
  273. dynamic_model_cache[cache_key] = (DynamicUser, DynamicLog)
  274. return DynamicUser, DynamicLog
  275. def get_concat_function(column, separator=", "):
  276. db_type = Config.DATABASE_TYPE
  277. if db_type in ("POSTGRESQL", "POSTGRES"):
  278. # PostgreSQL usa STRING_AGG
  279. return func.string_agg(column, separator)
  280. else:
  281. # MySQL, MariaDB y SQLite usan GROUP_CONCAT
  282. if separator != ", ":
  283. # Si hay separador personalizado, usarlo
  284. return func.group_concat(column, separator)
  285. else:
  286. # Separador por defecto
  287. return func.group_concat(column)
  288. def migrate_database():
  289. """Run Alembic migrations to update the database schema."""
  290. try:
  291. # Get Alembic configuration
  292. alembic_ini_path = os.path.join(
  293. os.path.dirname(os.path.dirname(__file__)), "alembic.ini"
  294. )
  295. if not os.path.exists(alembic_ini_path):
  296. logger.warning("alembic.ini not found. Skipping Alembic migrations.")
  297. logger.warning("Please run: python manage_db.py init")
  298. return
  299. alembic_cfg = AlembicConfig(alembic_ini_path)
  300. # Check if database has been initialized with Alembic
  301. engine = get_engine()
  302. with engine.connect() as conn:
  303. context = MigrationContext.configure(conn)
  304. current_rev = context.get_current_revision()
  305. if current_rev is None:
  306. # Database not initialized with Alembic yet
  307. logger.info("Database not yet initialized with Alembic.")
  308. logger.info("Checking if schema already exists...")
  309. inspector = inspect(engine)
  310. # Check if core tables exist
  311. core_tables_exist = (
  312. inspector.has_table("log_metadata")
  313. and inspector.has_table("denied_logs")
  314. and inspector.has_table("system_metrics")
  315. and inspector.has_table("notifications")
  316. and inspector.has_table("admin_users")
  317. and inspector.has_table("blacklist_domains")
  318. and inspector.has_table("quota_users")
  319. and inspector.has_table("quota_groups")
  320. and inspector.has_table("quota_rules")
  321. and inspector.has_table("quota_events")
  322. )
  323. if core_tables_exist:
  324. # Schema exists, stamp as current version
  325. logger.info(
  326. "Existing schema detected. Marking database as up-to-date..."
  327. )
  328. command.stamp(alembic_cfg, "head")
  329. logger.info("✓ Database marked as up-to-date with migrations.")
  330. # Ensure admin user exists
  331. _ensure_admin_user(conn, engine)
  332. else:
  333. # No schema exists, run all migrations
  334. logger.info(
  335. "No existing schema found. Running initial migrations..."
  336. )
  337. command.upgrade(alembic_cfg, "head")
  338. logger.info("✓ Database schema created successfully.")
  339. # Create admin user after migrations
  340. _ensure_admin_user(conn, engine)
  341. else:
  342. # Database already initialized, run pending migrations
  343. logger.info(f"Current database version: {current_rev}")
  344. logger.info("Checking for pending migrations...")
  345. # Run pending migrations
  346. command.upgrade(alembic_cfg, "head")
  347. logger.info("✓ Database migrations completed successfully.")
  348. # Ensure admin user exists
  349. _ensure_admin_user(conn, engine)
  350. except ImportError as e:
  351. logger.error(f"Alembic not installed: {e}")
  352. logger.error("Please install: pip install alembic")
  353. raise
  354. except Exception as e:
  355. logger.error(f"Migration error: {e}")
  356. logger.error(
  357. "If you have an existing database, please run: python manage_db.py init"
  358. )
  359. raise
  360. def _ensure_admin_user(conn, engine):
  361. """Ensure admin user exists, create if not."""
  362. try:
  363. inspector = inspect(engine)
  364. if not inspector.has_table("admin_users"):
  365. logger.warning("admin_users table not found. Cannot create admin user.")
  366. return
  367. # Check if admin user exists
  368. session = get_session()
  369. try:
  370. existing_admin = (
  371. session.query(AdminUser).filter_by(username="admin").first()
  372. )
  373. if not existing_admin:
  374. logger.info("Admin user not found, creating default admin user...")
  375. _create_default_admin_user(conn, engine)
  376. # else:
  377. # logger.debug("Admin user already exists.")
  378. finally:
  379. session.close()
  380. except Exception as e:
  381. logger.warning(f"Could not check/create admin user: {e}")
  382. def _create_default_admin_user(conn, engine):
  383. """Create the default admin user using FIRST_PASSWORD from environment."""
  384. try:
  385. import bcrypt
  386. # Get FIRST_PASSWORD from environment
  387. first_password = Config.FIRST_PASSWORD
  388. if not first_password:
  389. logger.warning(
  390. "FIRST_PASSWORD not set in .env file. Skipping admin user creation."
  391. )
  392. logger.warning(
  393. "Set FIRST_PASSWORD in your .env file to create the admin user."
  394. )
  395. return
  396. # Hash the password
  397. salt = bcrypt.gensalt()
  398. password_hash = bcrypt.hashpw(first_password.encode("utf-8"), salt)
  399. # Insert admin user
  400. from sqlalchemy import text
  401. insert_query = text("""
  402. INSERT INTO admin_users (username, password_hash, salt, role, is_active, created_at, updated_at)
  403. VALUES (:username, :password_hash, :salt, :role, :is_active, :created_at, :updated_at)
  404. """)
  405. from datetime import datetime
  406. now = datetime.now()
  407. conn.execute(
  408. insert_query,
  409. {
  410. "username": "admin",
  411. "password_hash": password_hash.decode("utf-8"),
  412. "salt": salt.decode("utf-8"),
  413. "role": "admin",
  414. "is_active": 1,
  415. "created_at": now,
  416. "updated_at": now,
  417. },
  418. )
  419. conn.commit()
  420. logger.info("✓ Default admin user created successfully with FIRST_PASSWORD")
  421. except ImportError:
  422. logger.error("bcrypt module not available. Cannot create admin user.")
  423. except Exception as e:
  424. logger.error(f"Error creating default admin user: {e}")
  425. conn.rollback()