4
0

database.py 18 KB

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