database.py 18 KB

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