4
0

database.py 19 KB

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