database.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. import logging
  2. import os
  3. import re
  4. from datetime import date, datetime
  5. from typing import Any
  6. from urllib.parse import urlparse
  7. from dotenv import load_dotenv
  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. # Cargar variables de entorno desde .env
  23. load_dotenv()
  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(String(64), nullable=False, index=True) # SHA256 hash for deduplication
  87. icon = Column(String(100), nullable=True)
  88. source = Column(String(50), nullable=False, index=True) # 'squid', 'system', 'security', 'users', 'git'
  89. read = Column(Integer, default=0) # 0 = unread, 1 = read
  90. created_at = Column(DateTime, default=datetime.now, nullable=False, index=True)
  91. updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
  92. expires_at = Column(DateTime, nullable=True) # Optional expiration date
  93. count = Column(Integer, default=1) # Number of times this notification was triggered
  94. def get_database_url() -> str:
  95. db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
  96. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "squidstats.db")
  97. if db_type == "SQLITE":
  98. if not conn_str.startswith("sqlite:///"):
  99. return f"sqlite:///{conn_str}"
  100. return conn_str
  101. elif db_type in ("MYSQL", "MARIADB"):
  102. # Ejemplo: mysql+pymysql://user:password@host/dbname
  103. # El usuario debe poner el string completo en el .env
  104. if (
  105. conn_str.startswith("mysql://")
  106. or conn_str.startswith("mariadb://")
  107. or conn_str.startswith("mysql+pymysql://")
  108. ):
  109. return conn_str
  110. raise ValueError(
  111. "DATABASE_STRING_CONNECTION must start with 'mysql://' or 'mariadb://'."
  112. )
  113. elif db_type in ("POSTGRESQL", "POSTGRES"):
  114. # Ejemplo: postgresql://user:password@host:port/dbname
  115. # o postgresql+psycopg2://user:password@host:port/dbname
  116. if (
  117. conn_str.startswith("postgresql://")
  118. or conn_str.startswith("postgres://")
  119. or conn_str.startswith("postgresql+psycopg2://")
  120. or conn_str.startswith("postgresql+psycopg://")
  121. ):
  122. return conn_str
  123. raise ValueError(
  124. "DATABASE_STRING_CONNECTION must start with 'postgresql://', 'postgres://', 'postgresql+psycopg2://', or 'postgresql+psycopg://'."
  125. )
  126. else:
  127. raise ValueError(f"Database type not supported: {db_type}")
  128. def create_database_if_not_exists():
  129. db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
  130. if db_type == "SQLITE":
  131. # SQLite crea el archivo automáticamente, no necesitamos hacer nada
  132. logger.info("SQLite database will be created automatically if it doesn't exist")
  133. return
  134. elif db_type in ("MYSQL", "MARIADB"):
  135. try:
  136. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  137. parsed_url = urlparse(conn_str)
  138. database_name = parsed_url.path.lstrip("/")
  139. if not database_name:
  140. logger.warning("No database name found in connection string")
  141. return
  142. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  143. server_engine = create_engine(server_url, echo=False)
  144. with server_engine.connect() as conn:
  145. # Verificar si la base de datos existe
  146. result = conn.execute(
  147. text(
  148. f"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{database_name}'"
  149. )
  150. )
  151. if not result.fetchone():
  152. conn.execute(
  153. text(
  154. f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
  155. )
  156. )
  157. conn.commit()
  158. logger.info(f"Database '{database_name}' created successfully")
  159. else:
  160. logger.info(f"Database '{database_name}' already exists")
  161. server_engine.dispose()
  162. except Exception as e:
  163. logger.error(f"Error creating MySQL/MariaDB database: {e}")
  164. raise
  165. elif db_type in ("POSTGRESQL", "POSTGRES"):
  166. try:
  167. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  168. parsed_url = urlparse(conn_str)
  169. database_name = parsed_url.path.lstrip("/")
  170. if not database_name:
  171. logger.warning("No database name found in PostgreSQL connection string")
  172. return
  173. # Crear URL para conectarse a la base de datos 'postgres' (default)
  174. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/postgres"
  175. # Crear engine con autocommit para evitar transacciones automáticas
  176. server_engine = create_engine(
  177. server_url, echo=False, isolation_level="AUTOCOMMIT"
  178. )
  179. try:
  180. with server_engine.connect() as conn:
  181. # Verificar si la base de datos existe
  182. result = conn.execute(
  183. text(
  184. f"SELECT 1 FROM pg_database WHERE datname = '{database_name}'"
  185. )
  186. )
  187. if not result.fetchone():
  188. # La base de datos no existe, crearla
  189. # Usar una versión más simple que sea compatible con la mayoría de configuraciones
  190. try:
  191. # Primero intentar con template0 para evitar problemas de collation
  192. conn.execute(
  193. text(
  194. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8' TEMPLATE = template0"
  195. )
  196. )
  197. logger.info(
  198. f"PostgreSQL database '{database_name}' created successfully with template0"
  199. )
  200. except Exception:
  201. # Si falla con template0, intentar sin especificar collation
  202. try:
  203. conn.execute(
  204. text(
  205. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8'"
  206. )
  207. )
  208. logger.info(
  209. f"PostgreSQL database '{database_name}' created successfully without collation"
  210. )
  211. except Exception:
  212. # Como último recurso, crear la base de datos sin especificar encoding
  213. conn.execute(text(f'CREATE DATABASE "{database_name}"'))
  214. logger.info(
  215. f"PostgreSQL database '{database_name}' created successfully with default settings"
  216. )
  217. else:
  218. logger.info(
  219. f"PostgreSQL database '{database_name}' already exists"
  220. )
  221. finally:
  222. server_engine.dispose()
  223. except Exception as e:
  224. logger.error(f"Error creating PostgreSQL database: {e}")
  225. raise
  226. def get_engine():
  227. global _engine
  228. if _engine is not None:
  229. return _engine
  230. create_database_if_not_exists()
  231. db_url = get_database_url()
  232. _engine = create_engine(db_url, echo=False, future=True)
  233. return _engine
  234. def get_session():
  235. global _Session
  236. engine = get_engine()
  237. if _Session is None:
  238. create_dynamic_tables(engine)
  239. _Session = sessionmaker(bind=engine)
  240. return _Session()
  241. def table_exists(engine, table_name: str) -> bool:
  242. inspector = inspect(engine)
  243. return inspector.has_table(table_name)
  244. def create_dynamic_tables(engine, date_suffix: str = None):
  245. LogMetadata.__table__.create(engine, checkfirst=True)
  246. DeniedLog.__table__.create(engine, checkfirst=True)
  247. SystemMetrics.__table__.create(engine, checkfirst=True)
  248. Notification.__table__.create(engine, checkfirst=True) # Add notifications table
  249. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  250. creation_logger = logging.getLogger(f"CreateTable_{date_suffix or 'today'}")
  251. creation_logger.propagate = False # Evita que el log suba al logger raíz
  252. if not creation_logger.handlers:
  253. handler = logging.StreamHandler()
  254. formatter = logging.Formatter(
  255. "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  256. )
  257. handler.setFormatter(formatter)
  258. creation_logger.addHandler(handler)
  259. if not table_exists(engine, user_table_name) or not table_exists(
  260. engine, log_table_name
  261. ):
  262. creation_logger.info(
  263. f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
  264. )
  265. DynamicBase = declarative_base()
  266. class DynamicUser(DynamicBase):
  267. __tablename__ = user_table_name
  268. id = Column(Integer, primary_key=True)
  269. username = Column(String(255), nullable=False)
  270. ip = Column(String(255), nullable=False)
  271. created_at = Column(DateTime, default=datetime.now)
  272. class DynamicLog(DynamicBase):
  273. __tablename__ = log_table_name
  274. id = Column(Integer, primary_key=True)
  275. user_id = Column(Integer, nullable=False)
  276. url = Column(Text, nullable=False)
  277. response = Column(Integer, nullable=False)
  278. request_count = Column(Integer, default=1)
  279. data_transmitted = Column(BigInteger, default=0)
  280. created_at = Column(DateTime, default=datetime.now)
  281. DynamicBase.metadata.create_all(engine, checkfirst=True)
  282. def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
  283. if date_suffix is None:
  284. date_suffix = get_table_suffix()
  285. return f"user_{date_suffix}", f"log_{date_suffix}"
  286. def get_dynamic_models(date_suffix: str):
  287. cache_key = f"user_log_{date_suffix}"
  288. if cache_key in dynamic_model_cache:
  289. return dynamic_model_cache[cache_key]
  290. engine = get_engine()
  291. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  292. user_exists = table_exists(engine, user_table_name)
  293. log_exists = table_exists(engine, log_table_name)
  294. if not user_exists or not log_exists:
  295. logger.warning(
  296. f"User/log tables for date suffix '{date_suffix}' do not exist. Attempting to recreate..."
  297. )
  298. create_dynamic_tables(engine, date_suffix=date_suffix)
  299. user_exists = table_exists(engine, user_table_name)
  300. log_exists = table_exists(engine, log_table_name)
  301. if not user_exists or not log_exists:
  302. logger.error(
  303. f"User/log tables for date suffix '{date_suffix}' could not be created or found."
  304. )
  305. return None, None
  306. DynamicBase = declarative_base()
  307. class DynamicUser(DynamicBase):
  308. __tablename__ = user_table_name
  309. id = Column(Integer, primary_key=True, autoincrement=True)
  310. username = Column(String(255), nullable=False)
  311. ip = Column(String(255), nullable=False)
  312. created_at = Column(DateTime, default=datetime.now)
  313. class DynamicLog(DynamicBase):
  314. __tablename__ = log_table_name
  315. id = Column(Integer, primary_key=True, autoincrement=True)
  316. user_id = Column(Integer, nullable=False)
  317. url = Column(Text, nullable=False)
  318. response = Column(Integer, nullable=False)
  319. request_count = Column(Integer, default=1)
  320. data_transmitted = Column(BigInteger, default=0)
  321. created_at = Column(DateTime, default=datetime.now)
  322. dynamic_model_cache[cache_key] = (DynamicUser, DynamicLog)
  323. return DynamicUser, DynamicLog
  324. def get_concat_function(column, separator=", "):
  325. db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
  326. if db_type in ("POSTGRESQL", "POSTGRES"):
  327. # PostgreSQL usa STRING_AGG
  328. return func.string_agg(column, separator)
  329. else:
  330. # MySQL, MariaDB y SQLite usan GROUP_CONCAT
  331. if separator != ", ":
  332. # Si hay separador personalizado, usarlo
  333. return func.group_concat(column, separator)
  334. else:
  335. # Separador por defecto
  336. return func.group_concat(column)
  337. def migrate_database():
  338. engine = get_engine()
  339. db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
  340. inspector = inspect(engine)
  341. original_level = logger.level
  342. logger.setLevel(logging.DEBUG)
  343. try:
  344. with engine.connect() as conn:
  345. # Define expected schema for all tables
  346. expected_schemas = {
  347. "user_base": {
  348. "username": {"type": "VARCHAR(255)", "nullable": False},
  349. "ip": {"type": "VARCHAR(255)", "nullable": False},
  350. },
  351. "log_base": {"url": {"type": "TEXT", "nullable": False}},
  352. "denied_logs": {
  353. "username": {"type": "VARCHAR(255)", "nullable": False},
  354. "ip": {"type": "VARCHAR(255)", "nullable": False},
  355. "url": {"type": "TEXT", "nullable": False},
  356. "method": {"type": "VARCHAR(255)", "nullable": False},
  357. "status": {"type": "VARCHAR(255)", "nullable": False},
  358. },
  359. "system_metrics": {
  360. "cpu_usage": {"type": "VARCHAR(255)", "nullable": False}
  361. },
  362. }
  363. for table_name, expected_columns in expected_schemas.items():
  364. if not inspector.has_table(table_name):
  365. logger.info(f"Table {table_name} doesn't exist, skipping migration")
  366. continue
  367. logger.info(f"Checking schema for table: {table_name}")
  368. current_columns = inspector.get_columns(table_name)
  369. for column_name, expected_spec in expected_columns.items():
  370. # Find current column info
  371. current_column = next(
  372. (col for col in current_columns if col["name"] == column_name),
  373. None,
  374. )
  375. if not current_column:
  376. logger.warning(
  377. f"Column {column_name} not found in {table_name}"
  378. )
  379. continue
  380. logger.info(
  381. f"Checking {table_name}.{column_name}: current type = {current_column['type']}"
  382. )
  383. # Check if migration is needed
  384. needs_migration = _column_needs_migration(
  385. current_column, expected_spec, db_type
  386. )
  387. if needs_migration:
  388. logger.info(
  389. f"Migrating {table_name}.{column_name} to {expected_spec['type']}"
  390. )
  391. _migrate_column(
  392. conn, table_name, column_name, expected_spec, db_type
  393. )
  394. else:
  395. logger.info(
  396. f"No migration needed for {table_name}.{column_name}"
  397. )
  398. # Also check dynamic tables (user_YYYYMMDD, log_YYYYMMDD)
  399. _migrate_dynamic_tables(conn, inspector, db_type)
  400. conn.commit()
  401. logger.info("Database migration completed successfully")
  402. except Exception as e:
  403. logger.warning(
  404. f"Migration warning (this might be expected if already migrated): {e}"
  405. )
  406. finally:
  407. logger.setLevel(original_level)
  408. def _column_needs_migration(current_column, expected_spec, db_type):
  409. current_type = str(current_column["type"]).upper()
  410. expected_type = expected_spec["type"].upper()
  411. logger.debug(
  412. f"Checking migration: current='{current_type}' vs expected='{expected_type}'"
  413. )
  414. # Normalize type representations across different databases
  415. if db_type in ("MYSQL", "MARIADB"):
  416. # MySQL type mapping
  417. if "VARCHAR(255)" in expected_type and (
  418. "VARCHAR" in current_type or "CHAR" in current_type
  419. ):
  420. # Extract current length
  421. import re
  422. match = re.search(r"VARCHAR\((\d+)\)", current_type)
  423. if match:
  424. current_length = int(match.group(1))
  425. logger.debug(
  426. f"MySQL VARCHAR: current length={current_length}, expected=255"
  427. )
  428. return current_length != 255 # Changed from < to != for exact match
  429. else:
  430. # If no length found, assume it needs migration
  431. return True
  432. elif "TEXT" in expected_type and "TEXT" not in current_type:
  433. return True
  434. elif db_type in ("POSTGRESQL", "POSTGRES"):
  435. # PostgreSQL type mapping
  436. if "VARCHAR(255)" in expected_type:
  437. if "CHARACTER VARYING" in current_type or "VARCHAR" in current_type:
  438. import re
  439. match = re.search(
  440. r"(?:CHARACTER VARYING|VARCHAR)\((\d+)\)", current_type
  441. )
  442. if match:
  443. current_length = int(match.group(1))
  444. logger.debug(
  445. f"PostgreSQL VARCHAR: current length={current_length}, expected=255"
  446. )
  447. return current_length != 255 # Changed from < to != for exact match
  448. # If no length specified, it might need migration
  449. return "(" not in current_type
  450. else:
  451. # Different type entirely, needs migration
  452. return True
  453. elif "TEXT" in expected_type and "TEXT" not in current_type:
  454. return True
  455. elif db_type == "SQLITE":
  456. # SQLite is more flexible with types, but let's still check for obvious differences
  457. if "VARCHAR(255)" in expected_type and (
  458. "VARCHAR" in current_type or "CHAR" in current_type
  459. ):
  460. import re
  461. match = re.search(r"VARCHAR\((\d+)\)", current_type)
  462. if match:
  463. current_length = int(match.group(1))
  464. logger.debug(
  465. f"SQLite VARCHAR: current length={current_length}, expected=255"
  466. )
  467. return current_length != 255
  468. # For SQLite, generally don't migrate unless there's a significant type difference
  469. return False
  470. return False
  471. def _migrate_column(conn, table_name, column_name, expected_spec, db_type):
  472. try:
  473. if db_type in ("MYSQL", "MARIADB"):
  474. nullable_clause = "" if expected_spec["nullable"] else "NOT NULL"
  475. sql = f"ALTER TABLE {table_name} MODIFY COLUMN {column_name} {expected_spec['type']} {nullable_clause}"
  476. conn.execute(text(sql))
  477. logger.info(
  478. f"Migrated {table_name}.{column_name} to {expected_spec['type']}"
  479. )
  480. elif db_type in ("POSTGRESQL", "POSTGRES"):
  481. sql = f"ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {expected_spec['type']}"
  482. conn.execute(text(sql))
  483. logger.info(
  484. f"Migrated {table_name}.{column_name} to {expected_spec['type']}"
  485. )
  486. elif db_type == "SQLITE":
  487. logger.info(
  488. f"SQLite migration skipped for {table_name}.{column_name} (flexible typing)"
  489. )
  490. except Exception as e:
  491. logger.error(f"Failed to migrate {table_name}.{column_name}: {e}")
  492. def _migrate_dynamic_tables(conn, inspector, db_type):
  493. # Get all table names that match the dynamic pattern
  494. all_tables = inspector.get_table_names()
  495. user_tables = [t for t in all_tables if re.match(r"user_\d{8}$", t)]
  496. logger.info(f"Found {len(user_tables)} dynamic user tables: {user_tables}")
  497. # Define expected schema for dynamic tables
  498. user_schema = {
  499. "username": {"type": "VARCHAR(255)", "nullable": False},
  500. "ip": {
  501. "type": "VARCHAR(255)",
  502. "nullable": False,
  503. },
  504. }
  505. # Migrate user tables
  506. for table_name in user_tables:
  507. logger.info(f"Checking dynamic table: {table_name}")
  508. current_columns = inspector.get_columns(table_name)
  509. for column_name, expected_spec in user_schema.items():
  510. current_column = next(
  511. (col for col in current_columns if col["name"] == column_name), None
  512. )
  513. if current_column:
  514. logger.info(
  515. f"Checking {table_name}.{column_name}: current type = {current_column['type']}"
  516. )
  517. if _column_needs_migration(current_column, expected_spec, db_type):
  518. logger.info(
  519. f"Migrating dynamic table {table_name}.{column_name} to {expected_spec['type']}"
  520. )
  521. _migrate_column(
  522. conn, table_name, column_name, expected_spec, db_type
  523. )
  524. else:
  525. logger.info(f"No migration needed for {table_name}.{column_name}")