database.py 23 KB

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