database.py 22 KB

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