database.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import os
  2. from datetime import date, datetime
  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.exc import IntegrityError
  17. from sqlalchemy.orm import sessionmaker
  18. from alembic import command
  19. from config import Config
  20. from database.base import Base # noqa: F401
  21. from database.models import (
  22. AdminUser,
  23. DeniedLog,
  24. LogMetadata,
  25. Notification,
  26. SystemMetrics,
  27. )
  28. from database.models.models import BlacklistDomain, create_dynamic_models
  29. _engine = None
  30. _Session = None
  31. dynamic_model_cache: dict[str, Any] = {}
  32. def get_table_suffix() -> str:
  33. return date.today().strftime("%Y%m%d")
  34. def _normalize_sqlite_path(path_str: str) -> Path:
  35. path_str = path_str.strip()
  36. if path_str in ("", "."):
  37. raise ValueError(
  38. "DATABASE_STRING_CONNECTION for SQLITE must contain a database path"
  39. )
  40. if path_str == ":memory:" or path_str == "sqlite:///:memory:":
  41. return Path(":memory:")
  42. if path_str.startswith("sqlite:///"):
  43. path_str = path_str[len("sqlite:///") :]
  44. if not path_str:
  45. raise ValueError(
  46. "DATABASE_STRING_CONNECTION for SQLITE must contain a database path"
  47. )
  48. project_root = Path(__file__).resolve().parents[1]
  49. db_path = Path(path_str)
  50. if not db_path.is_absolute():
  51. db_path = project_root / db_path
  52. if path_str.endswith("/") or db_path.is_dir():
  53. db_path = db_path / "squidstats.db"
  54. return db_path
  55. def get_database_url() -> str:
  56. db_type = Config.DATABASE_TYPE
  57. conn_str = Config.DATABASE_STRING_CONNECTION
  58. if db_type == "SQLITE":
  59. db_path = _normalize_sqlite_path(conn_str)
  60. if str(db_path) == ":memory:":
  61. return "sqlite:///:memory:"
  62. return f"sqlite:///{db_path}"
  63. elif db_type in ("MYSQL", "MARIADB"):
  64. # Ejemplo: mysql+pymysql://user:password@host/dbname
  65. # El usuario debe poner el string completo en el .env
  66. if (
  67. conn_str.startswith("mysql://")
  68. or conn_str.startswith("mariadb://")
  69. or conn_str.startswith("mysql+pymysql://")
  70. ):
  71. return conn_str
  72. raise ValueError(
  73. "DATABASE_STRING_CONNECTION must start with 'mysql://' or 'mariadb://'."
  74. )
  75. elif db_type in ("POSTGRESQL", "POSTGRES"):
  76. # Ejemplo: postgresql://user:password@host:port/dbname
  77. # o postgresql+psycopg2://user:password@host:port/dbname
  78. if (
  79. conn_str.startswith("postgresql://")
  80. or conn_str.startswith("postgres://")
  81. or conn_str.startswith("postgresql+psycopg2://")
  82. or conn_str.startswith("postgresql+psycopg://")
  83. ):
  84. return conn_str
  85. raise ValueError(
  86. "DATABASE_STRING_CONNECTION must start with 'postgresql://', 'postgres://', 'postgresql+psycopg2://', or 'postgresql+psycopg://'."
  87. )
  88. else:
  89. raise ValueError(f"Database type not supported: {db_type}")
  90. def create_database_if_not_exists():
  91. db_type = Config.DATABASE_TYPE
  92. if db_type == "SQLITE":
  93. # SQLite crea el archivo automáticamente, no necesitamos hacer nada
  94. logger.info("SQLite database will be created automatically if it doesn't exist")
  95. return
  96. elif db_type in ("MYSQL", "MARIADB"):
  97. try:
  98. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  99. parsed_url = urlparse(conn_str)
  100. database_name = parsed_url.path.lstrip("/")
  101. if not database_name:
  102. logger.warning("No database name found in connection string")
  103. return
  104. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  105. server_engine = create_engine(server_url, echo=False)
  106. with server_engine.connect() as conn:
  107. # Verificar si la base de datos existe
  108. result = conn.execute(
  109. text(
  110. "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :dbname"
  111. ),
  112. {"dbname": database_name},
  113. )
  114. if not result.fetchone():
  115. conn.execute(
  116. text(
  117. f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
  118. )
  119. )
  120. conn.commit()
  121. logger.info(f"Database '{database_name}' created successfully")
  122. else:
  123. logger.info(f"Database '{database_name}' already exists")
  124. server_engine.dispose()
  125. except Exception as e:
  126. logger.error(f"Error creating MySQL/MariaDB database: {e}")
  127. raise
  128. elif db_type in ("POSTGRESQL", "POSTGRES"):
  129. try:
  130. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  131. parsed_url = urlparse(conn_str)
  132. database_name = parsed_url.path.lstrip("/")
  133. if not database_name:
  134. logger.warning("No database name found in PostgreSQL connection string")
  135. return
  136. # Crear URL para conectarse a la base de datos 'postgres' (default)
  137. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/postgres"
  138. # Crear engine con autocommit para evitar transacciones automáticas
  139. server_engine = create_engine(
  140. server_url, echo=False, isolation_level="AUTOCOMMIT"
  141. )
  142. try:
  143. with server_engine.connect() as conn:
  144. # Verificar si la base de datos existe
  145. result = conn.execute(
  146. text("SELECT 1 FROM pg_database WHERE datname = :dbname"),
  147. {"dbname": database_name},
  148. )
  149. if not result.fetchone():
  150. # La base de datos no existe, crearla
  151. # Usar una versión más simple que sea compatible con la mayoría de configuraciones
  152. try:
  153. # Primero intentar con template0 para evitar problemas de collation
  154. conn.execute(
  155. text(
  156. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8' TEMPLATE = template0"
  157. )
  158. )
  159. logger.info(
  160. f"PostgreSQL database '{database_name}' created successfully with template0"
  161. )
  162. except Exception:
  163. # Si falla con template0, intentar sin especificar collation
  164. try:
  165. conn.execute(
  166. text(
  167. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8'"
  168. )
  169. )
  170. logger.info(
  171. f"PostgreSQL database '{database_name}' created successfully without collation"
  172. )
  173. except Exception:
  174. # Como último recurso, crear la base de datos sin especificar encoding
  175. conn.execute(text(f'CREATE DATABASE "{database_name}"'))
  176. logger.info(
  177. f"PostgreSQL database '{database_name}' created successfully with default settings"
  178. )
  179. else:
  180. logger.info(
  181. f"PostgreSQL database '{database_name}' already exists"
  182. )
  183. finally:
  184. server_engine.dispose()
  185. except Exception as e:
  186. logger.error(f"Error creating PostgreSQL database: {e}")
  187. raise
  188. def get_engine():
  189. global _engine
  190. if _engine is not None:
  191. return _engine
  192. create_database_if_not_exists()
  193. db_url = get_database_url()
  194. db_type = Config.DATABASE_TYPE
  195. if db_type == "SQLITE":
  196. _engine = create_engine(
  197. db_url,
  198. echo=False,
  199. future=True,
  200. connect_args={"timeout": 30, "check_same_thread": False},
  201. )
  202. # Enable WAL journal mode and set synchronous=NORMAL for the connection.
  203. # WAL allows concurrent reads while a write is in progress and dramatically
  204. # reduces "database is locked" errors in multi-threaded apps.
  205. @event.listens_for(_engine, "connect")
  206. def set_sqlite_pragmas(dbapi_conn, _connection_record):
  207. cursor = dbapi_conn.cursor()
  208. cursor.execute("PRAGMA journal_mode=WAL")
  209. cursor.execute("PRAGMA synchronous=NORMAL")
  210. cursor.execute("PRAGMA busy_timeout=30000")
  211. cursor.close()
  212. else:
  213. _engine = create_engine(db_url, echo=False, future=True)
  214. return _engine
  215. def get_session():
  216. global _Session
  217. engine = get_engine()
  218. if _Session is None:
  219. create_dynamic_tables(engine)
  220. _Session = sessionmaker(bind=engine)
  221. return _Session()
  222. def table_exists(engine, table_name: str) -> bool:
  223. inspector = inspect(engine)
  224. return inspector.has_table(table_name)
  225. def create_dynamic_tables(engine, date_suffix: str = None):
  226. """Create every static table and the dynamic tables for one day.
  227. ``create_all(checkfirst=True)`` is intentionally used here in addition to
  228. Alembic. Alembic tracks *schema versions*, but a table can be deleted
  229. manually while the version remains at ``head``; in that case Alembic has
  230. no pending migration to run. SQLAlchemy creates only tables that are
  231. absent and leaves existing tables and their data untouched.
  232. """
  233. existing_tables = set(inspect(engine).get_table_names())
  234. # All models that inherit from database.base.Base are registered in this
  235. # metadata, including tables added in later migrations.
  236. Base.metadata.create_all(engine, checkfirst=True)
  237. LogMetadata.__table__.create(engine, checkfirst=True)
  238. DeniedLog.__table__.create(engine, checkfirst=True)
  239. SystemMetrics.__table__.create(engine, checkfirst=True)
  240. Notification.__table__.create(engine, checkfirst=True) # Add notifications table
  241. BlacklistDomain.__table__.create(engine, checkfirst=True)
  242. # New quota tables for the admin quota feature
  243. from database.models.models import QuotaEvent, QuotaGroup, QuotaRule, QuotaUser
  244. QuotaUser.__table__.create(engine, checkfirst=True)
  245. QuotaGroup.__table__.create(engine, checkfirst=True)
  246. QuotaRule.__table__.create(engine, checkfirst=True)
  247. QuotaEvent.__table__.create(engine, checkfirst=True)
  248. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  249. logger.info(f"CreateTable_{date_suffix or 'today'}")
  250. if not table_exists(engine, user_table_name) or not table_exists(
  251. engine, log_table_name
  252. ):
  253. logger.info(
  254. f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
  255. )
  256. # Use create_dynamic_models to define and create the per-day user/log tables
  257. try:
  258. create_dynamic_models(engine, user_table_name, log_table_name)
  259. except Exception as e:
  260. logger.error(f"Error creating dynamic user/log tables: {e}")
  261. raise
  262. created_tables = sorted(
  263. set(inspect(engine).get_table_names()).difference(existing_tables)
  264. )
  265. if created_tables:
  266. logger.warning(
  267. "Database schema repair created missing tables: {}",
  268. ", ".join(created_tables),
  269. )
  270. def repair_database_schema(engine, date_suffix: str = None) -> list[str]:
  271. """Repair missing application tables without deleting or altering data.
  272. Returns the names of tables created during this repair. Rows that were
  273. previously deleted cannot be recovered by recreating an empty table; a
  274. database backup is required for data recovery.
  275. """
  276. before = set(inspect(engine).get_table_names())
  277. current_suffix = date_suffix or get_table_suffix()
  278. create_dynamic_tables(engine, date_suffix=current_suffix)
  279. # Keep historical user/log pairs consistent as well. If one side of a
  280. # known pair was removed, recreate only that side and preserve the other.
  281. known_suffixes = {current_suffix}
  282. for table_name in inspect(engine).get_table_names():
  283. if table_name.startswith(("user_", "log_")):
  284. _, suffix = table_name.split("_", 1)
  285. if suffix.isdigit() and len(suffix) == 8:
  286. known_suffixes.add(suffix)
  287. for historical_suffix in sorted(known_suffixes):
  288. user_table_name, log_table_name = get_dynamic_table_names(historical_suffix)
  289. current_tables = set(inspect(engine).get_table_names())
  290. if (
  291. user_table_name not in current_tables
  292. or log_table_name not in current_tables
  293. ):
  294. create_dynamic_tables(engine, date_suffix=historical_suffix)
  295. after = set(inspect(engine).get_table_names())
  296. created_tables = sorted(after.difference(before))
  297. missing_static_tables = set(Base.metadata.tables).difference(after)
  298. if missing_static_tables:
  299. raise RuntimeError(
  300. "Database schema repair could not create tables: "
  301. + ", ".join(sorted(missing_static_tables))
  302. )
  303. return created_tables
  304. def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
  305. if date_suffix is None:
  306. date_suffix = get_table_suffix()
  307. return f"user_{date_suffix}", f"log_{date_suffix}"
  308. def get_dynamic_models(date_suffix: str):
  309. cache_key = f"user_log_{date_suffix}"
  310. if cache_key in dynamic_model_cache:
  311. return dynamic_model_cache[cache_key]
  312. engine = get_engine()
  313. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  314. user_exists = table_exists(engine, user_table_name)
  315. log_exists = table_exists(engine, log_table_name)
  316. if not user_exists or not log_exists:
  317. logger.warning(
  318. f"User/log tables for date suffix '{date_suffix}' do not exist. Attempting to recreate..."
  319. )
  320. create_dynamic_tables(engine, date_suffix=date_suffix)
  321. user_exists = table_exists(engine, user_table_name)
  322. log_exists = table_exists(engine, log_table_name)
  323. if not user_exists or not log_exists:
  324. logger.error(
  325. f"User/log tables for date suffix '{date_suffix}' could not be created or found."
  326. )
  327. return None, None
  328. DynamicUser, DynamicLog = create_dynamic_models(
  329. engine, user_table_name, log_table_name
  330. )
  331. dynamic_model_cache[cache_key] = (DynamicUser, DynamicLog)
  332. return DynamicUser, DynamicLog
  333. def get_concat_function(column, separator=", "):
  334. db_type = Config.DATABASE_TYPE
  335. if db_type in ("POSTGRESQL", "POSTGRES"):
  336. # PostgreSQL usa STRING_AGG
  337. return func.string_agg(column, separator)
  338. else:
  339. # MySQL, MariaDB y SQLite usan GROUP_CONCAT
  340. if separator != ", ":
  341. # Si hay separador personalizado, usarlo
  342. return func.group_concat(column, separator)
  343. else:
  344. # Separador por defecto
  345. return func.group_concat(column)
  346. def migrate_database():
  347. """Run Alembic migrations to update the database schema."""
  348. try:
  349. # Get Alembic configuration
  350. alembic_ini_path = os.path.join(
  351. os.path.dirname(os.path.dirname(__file__)), "alembic.ini"
  352. )
  353. if not os.path.exists(alembic_ini_path):
  354. logger.warning("alembic.ini not found. Skipping Alembic migrations.")
  355. logger.warning(
  356. "Running model-based schema repair instead; "
  357. "please restore alembic.ini for future migrations."
  358. )
  359. engine = get_engine()
  360. repaired_tables = repair_database_schema(engine)
  361. if repaired_tables:
  362. logger.warning(
  363. "Startup database repair recreated: {}",
  364. ", ".join(repaired_tables),
  365. )
  366. _ensure_admin_user(engine)
  367. return
  368. alembic_cfg = AlembicConfig(alembic_ini_path)
  369. engine = get_engine()
  370. with engine.connect() as conn:
  371. context = MigrationContext.configure(conn)
  372. current_rev = context.get_current_revision()
  373. existing_tables = set(inspect(conn).get_table_names())
  374. # If the version table is missing but there is an existing schema,
  375. # preserve that schema and repair it before recording its migration
  376. # state. Running the initial migration against a partially existing
  377. # schema would try to recreate tables that are already there.
  378. application_tables = existing_tables.difference({"alembic_version"})
  379. if current_rev is None:
  380. logger.info("Database is not currently tracked by Alembic.")
  381. if application_tables:
  382. logger.info(
  383. "Existing schema detected without migration tracking; "
  384. "repairing missing tables before marking it as current."
  385. )
  386. repair_database_schema(engine)
  387. command.stamp(alembic_cfg, "head")
  388. logger.info("✓ Existing database marked as up-to-date with migrations.")
  389. else:
  390. logger.info("No existing schema found. Running initial migrations...")
  391. command.upgrade(alembic_cfg, "head")
  392. logger.info("✓ Database schema created successfully.")
  393. else:
  394. logger.info(f"Current database version: {current_rev}")
  395. logger.info("Checking for pending migrations...")
  396. command.upgrade(alembic_cfg, "head")
  397. logger.info("✓ Database migrations completed successfully.")
  398. # Alembic does not rerun a migration when a table is removed after the
  399. # migration reached head. Always perform this idempotent repair at
  400. # startup, including after an entirely new database was migrated.
  401. repaired_tables = repair_database_schema(engine)
  402. if repaired_tables:
  403. logger.warning(
  404. "Startup database repair recreated: {}",
  405. ", ".join(repaired_tables),
  406. )
  407. _ensure_admin_user(engine)
  408. except ImportError as e:
  409. logger.error(f"Alembic not installed: {e}")
  410. logger.error("Please install: pip install alembic")
  411. raise
  412. except Exception as e:
  413. logger.error(f"Migration error: {e}")
  414. logger.error(
  415. "If you have an existing database, please run: python manage_db.py init"
  416. )
  417. raise
  418. def _ensure_admin_user(engine):
  419. """Ensure admin user exists, create if not."""
  420. try:
  421. inspector = inspect(engine)
  422. if not inspector.has_table("admin_users"):
  423. logger.warning("admin_users table not found. Cannot create admin user.")
  424. return False
  425. Session = sessionmaker(bind=engine)
  426. session = Session()
  427. try:
  428. existing_admin = (
  429. session.query(AdminUser).filter_by(username="admin").first()
  430. )
  431. if not existing_admin:
  432. logger.info("Admin user not found, creating default admin user...")
  433. return _create_default_admin_user(session)
  434. return False
  435. finally:
  436. session.close()
  437. except IntegrityError:
  438. # Another process may have created the default user between the query
  439. # and the insert. The unique username constraint makes this harmless.
  440. logger.info("Admin user was created concurrently by another process.")
  441. return False
  442. except Exception as e:
  443. logger.warning(f"Could not check/create admin user: {e}")
  444. return False
  445. def _create_default_admin_user(session):
  446. """Create the default admin user using FIRST_PASSWORD from environment."""
  447. try:
  448. import bcrypt
  449. # Get FIRST_PASSWORD from environment
  450. first_password = Config.FIRST_PASSWORD
  451. if not first_password:
  452. logger.warning(
  453. "FIRST_PASSWORD not set in .env file. Skipping admin user creation."
  454. )
  455. logger.warning(
  456. "Set FIRST_PASSWORD in your .env file to create the admin user."
  457. )
  458. return False
  459. # Hash the password
  460. salt = bcrypt.gensalt()
  461. password_hash = bcrypt.hashpw(first_password.encode("utf-8"), salt)
  462. now = datetime.now()
  463. session.add(
  464. AdminUser(
  465. username="admin",
  466. password_hash=password_hash.decode("utf-8"),
  467. salt=salt.decode("utf-8"),
  468. role="admin",
  469. is_active=1,
  470. created_at=now,
  471. updated_at=now,
  472. )
  473. )
  474. session.commit()
  475. logger.info("✓ Default admin user created successfully with FIRST_PASSWORD")
  476. return True
  477. except ImportError:
  478. logger.error("bcrypt module not available. Cannot create admin user.")
  479. session.rollback()
  480. except IntegrityError:
  481. # Another process may have created the default user after the lookup.
  482. session.rollback()
  483. logger.info("Admin user was created concurrently by another process.")
  484. except Exception as e:
  485. logger.error(f"Error creating default admin user: {e}")
  486. session.rollback()
  487. return False