manage_db.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. #!/usr/bin/env python3
  2. """Database management script for SquidStats.
  3. This script provides convenient commands for managing database migrations
  4. using Alembic. It wraps common Alembic operations with simplified commands.
  5. Usage:
  6. python manage_db.py init # Initialize (stamp) database as up-to-date
  7. python manage_db.py upgrade # Apply pending migrations
  8. python manage_db.py downgrade # Revert last migration
  9. python manage_db.py current # Show current migration version
  10. python manage_db.py history # Show migration history
  11. python manage_db.py create # Create a new migration
  12. """
  13. import os
  14. import sys
  15. from pathlib import Path
  16. from alembic.config import Config as AlembicConfig
  17. from dotenv import load_dotenv
  18. from loguru import logger
  19. from sqlalchemy import inspect
  20. from alembic import command
  21. from database.database import get_engine
  22. from database.models.models import BlacklistDomain, SquidConfig
  23. from services.security.blacklist_service import merge_and_save_blacklist
  24. # Delay import of project modules until runtime (project root added to sys.path above)
  25. # Add project root to path
  26. project_root = Path(__file__).parent
  27. sys.path.insert(0, str(project_root))
  28. # Load environment variables
  29. load_dotenv()
  30. def get_alembic_config():
  31. """Get Alembic configuration."""
  32. alembic_ini_path = project_root / "alembic.ini"
  33. if not alembic_ini_path.exists():
  34. logger.error(f"alembic.ini not found at {alembic_ini_path}")
  35. sys.exit(1)
  36. config = AlembicConfig(str(alembic_ini_path))
  37. return config
  38. def init_database():
  39. """Mark database as up-to-date without running migrations.
  40. Use this for existing databases to initialize Alembic tracking.
  41. This stamps the database with the latest migration version without
  42. actually running the migrations (assumes schema already exists).
  43. """
  44. config = get_alembic_config()
  45. logger.info("Initializing database migration tracking...")
  46. logger.info("This will mark your database as up-to-date with the latest migration.")
  47. logger.info("Use this ONLY if your database schema is already correct.")
  48. response = input("Continue? (yes/no): ").lower().strip()
  49. if response != "yes":
  50. logger.info("Operation cancelled.")
  51. return
  52. try:
  53. # Stamp database with the latest revision
  54. command.stamp(config, "head")
  55. logger.info("✓ Database initialized successfully!")
  56. logger.info("Your database is now tracked by Alembic.")
  57. except Exception as e:
  58. logger.error(f"Failed to initialize database: {e}")
  59. sys.exit(1)
  60. def upgrade_database(revision="head"):
  61. """Apply pending migrations to the database.
  62. Args:
  63. revision: Target revision (default: 'head' for latest)
  64. """
  65. config = get_alembic_config()
  66. logger.info(f"Upgrading database to revision: {revision}")
  67. try:
  68. command.upgrade(config, revision)
  69. logger.info("✓ Database upgraded successfully!")
  70. except Exception as e:
  71. logger.error(f"Failed to upgrade database: {e}")
  72. sys.exit(1)
  73. def downgrade_database(revision="-1"):
  74. """Revert database migrations.
  75. Args:
  76. revision: Target revision (default: '-1' for one step back)
  77. """
  78. config = get_alembic_config()
  79. logger.warning(f"Downgrading database to revision: {revision}")
  80. logger.warning("This operation may result in data loss!")
  81. response = input("Continue? (yes/no): ").lower().strip()
  82. if response != "yes":
  83. logger.info("Operation cancelled.")
  84. return
  85. try:
  86. command.downgrade(config, revision)
  87. logger.info("✓ Database downgraded successfully!")
  88. except Exception as e:
  89. logger.error(f"Failed to downgrade database: {e}")
  90. sys.exit(1)
  91. def show_current():
  92. """Show current migration version."""
  93. config = get_alembic_config()
  94. try:
  95. command.current(config, verbose=True)
  96. except Exception as e:
  97. logger.error(f"Failed to show current version: {e}")
  98. sys.exit(1)
  99. def show_history():
  100. """Show migration history."""
  101. config = get_alembic_config()
  102. try:
  103. command.history(config, verbose=True)
  104. except Exception as e:
  105. logger.error(f"Failed to show history: {e}")
  106. sys.exit(1)
  107. def create_migration(message=None):
  108. """Create a new migration.
  109. Args:
  110. message: Migration message/description
  111. """
  112. config = get_alembic_config()
  113. if not message:
  114. message = input("Enter migration message: ").strip()
  115. if not message:
  116. logger.error("Migration message is required!")
  117. sys.exit(1)
  118. try:
  119. command.revision(config, message=message, autogenerate=True)
  120. logger.info("✓ Migration created successfully!")
  121. except Exception as e:
  122. logger.error(f"Failed to create migration: {e}")
  123. sys.exit(1)
  124. def migrate_env_blacklist(auto_confirm: bool = False):
  125. """Migrate domains listed in BLACKLIST_DOMAINS (from .env) into DB table.
  126. - Reads `BLACKLIST_DOMAINS` environment variable (comma separated)
  127. - Checks that the `blacklist_domains` table exists in the DB
  128. - Skips if the env var is empty or not set
  129. - Uses `services.security.blacklist_service.merge_and_save_blacklist` to insert/update rows
  130. """
  131. val = os.getenv("BLACKLIST_DOMAINS")
  132. if not val:
  133. logger.info("No BLACKLIST_DOMAINS found in environment; nothing to migrate.")
  134. return
  135. # Trim surrounding quotes if present
  136. if (val.startswith('"') and val.endswith('"')) or (
  137. val.startswith("'") and val.endswith("'")
  138. ):
  139. val = val[1:-1]
  140. items = [d.strip() for d in val.split(",") if d.strip()]
  141. if not items:
  142. logger.info("BLACKLIST_DOMAINS is empty after parsing; nothing to migrate.")
  143. return
  144. # Verify table exists
  145. engine = get_engine()
  146. inspector = inspect(engine)
  147. table_name = BlacklistDomain.__tablename__
  148. if not inspector.has_table(table_name):
  149. logger.error(
  150. f"Table '{table_name}' does not exist in the database. Run migrations first."
  151. )
  152. return
  153. # Confirm with user (or auto-confirm)
  154. logger.info(f"Found {len(items)} domains to migrate into '{table_name}'.")
  155. if not auto_confirm:
  156. ans = input("Proceed with migration? (yes/no): ").strip().lower()
  157. if ans != "yes":
  158. logger.info("Migration cancelled by user.")
  159. return
  160. # Use merge function which will avoid duplicates and reactivate entries
  161. try:
  162. merge_and_save_blacklist(
  163. set(items), source="env_migration", added_by="migrate_env"
  164. )
  165. logger.info("✓ BLACKLIST_DOMAINS migrated into database successfully.")
  166. except Exception:
  167. logger.exception("Failed migrating BLACKLIST_DOMAINS into DB")
  168. return
  169. def migrate_env_squid_config(auto_confirm: bool = False):
  170. """Migrate Squid environment variables into the squid_config DB table."""
  171. env_values = {}
  172. raw_keys = {
  173. "SQUID_HOST": "squid_host",
  174. "SQUID_PORT": "squid_port",
  175. "LOG_FORMAT": "log_format",
  176. "SQUID_LOG": "squid_log",
  177. "SQUID_CACHE_LOG": "squid_cache_log",
  178. "SQUID_CONFIG_PATH": "squid_config_path",
  179. "ACL_FILES_DIR": "acl_files_dir",
  180. }
  181. for env_key, field_name in raw_keys.items():
  182. value = os.getenv(env_key)
  183. if value is None:
  184. continue
  185. if (value.startswith('"') and value.endswith('"')) or (
  186. value.startswith("'") and value.endswith("'")
  187. ):
  188. value = value[1:-1]
  189. env_values[field_name] = value.strip()
  190. if not env_values:
  191. logger.info("No Squid environment variables found; nothing to migrate.")
  192. return
  193. engine = get_engine()
  194. inspector = inspect(engine)
  195. table_name = SquidConfig.__tablename__
  196. if not inspector.has_table(table_name):
  197. logger.error(
  198. f"Table '{table_name}' does not exist in the database. Run migrations first."
  199. )
  200. return
  201. if not auto_confirm:
  202. logger.info(
  203. "Squid config env values found. This will create a single row in squid_config."
  204. )
  205. ans = input("Proceed with migration? (yes/no): ").strip().lower()
  206. if ans != "yes":
  207. logger.info("Migration cancelled by user.")
  208. return
  209. from sqlalchemy.orm import sessionmaker
  210. Session = sessionmaker(bind=engine)
  211. session = Session()
  212. try:
  213. existing = session.query(SquidConfig).first()
  214. if existing:
  215. logger.info(
  216. "squid_config already exists in the database; skipping migration."
  217. )
  218. return
  219. squid_port = env_values.get("squid_port")
  220. if squid_port is not None:
  221. try:
  222. env_values["squid_port"] = int(squid_port)
  223. except ValueError:
  224. logger.warning(
  225. f"Invalid SQUID_PORT value '{squid_port}'; using default 3128."
  226. )
  227. env_values["squid_port"] = 3128
  228. row = SquidConfig(
  229. squid_host=env_values.get("squid_host", "127.0.0.1"),
  230. squid_port=env_values.get("squid_port", 3128),
  231. log_format=env_values.get("log_format", "DEFAULT"),
  232. squid_log=env_values.get("squid_log", "/var/log/squid/access.log"),
  233. squid_cache_log=env_values.get(
  234. "squid_cache_log", "/var/log/squid/cache.log"
  235. ),
  236. squid_config_path=env_values.get(
  237. "squid_config_path", "/etc/squid/squid.conf"
  238. ),
  239. acl_files_dir=env_values.get("acl_files_dir", ""),
  240. )
  241. session.add(row)
  242. session.commit()
  243. logger.info("✓ SQUID environment config migrated into database successfully.")
  244. except Exception:
  245. session.rollback()
  246. logger.exception("Failed migrating Squid config env values into DB")
  247. finally:
  248. session.close()
  249. def show_help():
  250. """Show help message."""
  251. help_text = """
  252. SquidStats Database Management Tool
  253. Commands:
  254. init Initialize database migration tracking (for existing databases)
  255. upgrade Apply pending migrations to the database
  256. downgrade Revert the last migration (use with caution!)
  257. current Show current database migration version
  258. history Show complete migration history
  259. create Create a new migration file
  260. help Show this help message
  261. Examples:
  262. python manage_db.py init # First time setup for existing database
  263. python manage_db.py upgrade # Apply all pending migrations
  264. python manage_db.py current # Check current version
  265. python manage_db.py create "add user email field" # Create new migration
  266. python manage_db.py migrate-env-blacklist # Migrate BLACKLIST_DOMAINS from .env to DB
  267. python manage_db.py migrate-env-squid-config # Migrate Squid env vars from .env to DB
  268. For more information, see the Alembic documentation:
  269. https://alembic.sqlalchemy.org/
  270. """
  271. print(help_text)
  272. def main():
  273. """Main entry point."""
  274. if len(sys.argv) < 2:
  275. show_help()
  276. sys.exit(1)
  277. command_name = sys.argv[1].lower()
  278. commands = {
  279. "init": init_database,
  280. "upgrade": upgrade_database,
  281. "downgrade": downgrade_database,
  282. "current": show_current,
  283. "history": show_history,
  284. "create": lambda: create_migration(sys.argv[2] if len(sys.argv) > 2 else None),
  285. "migrate-env-blacklist": migrate_env_blacklist,
  286. "migrate-env-squid-config": migrate_env_squid_config,
  287. "help": show_help,
  288. }
  289. if command_name not in commands:
  290. logger.error(f"Unknown command: {command_name}")
  291. show_help()
  292. sys.exit(1)
  293. commands[command_name]()
  294. if __name__ == "__main__":
  295. main()