database.py 24 KB

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