diff --git a/app/modules/db/migrate.py b/app/modules/db/migrate.py index 40c3f48d..0d2cc0b8 100644 --- a/app/modules/db/migrate.py +++ b/app/modules/db/migrate.py @@ -12,26 +12,26 @@ from app.modules.db.migration_manager import create_migrations_table, migrate, r def main(): parser = argparse.ArgumentParser(description='Database migration tool') subparsers = parser.add_subparsers(dest='command', help='Command to run') - + # Create migration command create_parser = subparsers.add_parser('create', help='Create a new migration') create_parser.add_argument('name', help='Name of the migration') - + # Migrate command subparsers.add_parser('migrate', help='Apply pending migrations') - + # Rollback command rollback_parser = subparsers.add_parser('rollback', help='Rollback migrations') rollback_parser.add_argument('--steps', type=int, default=1, help='Number of migrations to roll back') - + # Initialize command subparsers.add_parser('init', help='Initialize the migrations table') # list command subparsers.add_parser('list', help='List all migrations and their status') - + args = parser.parse_args() - + if args.command == 'create': filename = create_migration(args.name) print(f"Created migration file: {filename}") diff --git a/app/modules/db/migration_manager.py b/app/modules/db/migration_manager.py index 03500ad3..930925b6 100644 --- a/app/modules/db/migration_manager.py +++ b/app/modules/db/migration_manager.py @@ -28,12 +28,12 @@ def get_migration_files(): """Get all migration files from the migrations directory.""" migrations_dir = os.path.join(os.path.dirname(__file__), 'migrations') migration_files = [] - + for filename in os.listdir(migrations_dir): if filename.endswith('.py') and not filename.startswith('__'): migration_name = filename[:-3] # Remove .py extension migration_files.append(migration_name) - + # Sort migrations by name (which should include a timestamp) migration_files.sort() return migration_files @@ -49,11 +49,11 @@ def apply_migration(migration_name): try: # Import the migration module module = importlib.import_module(f'app.modules.db.migrations.{migration_name}') - + # Apply the migration print(f"Applying migration: {migration_name}") module.up() - + # Record the migration as applied Migration.create(name=migration_name) print(f"Migration applied: {migration_name}") @@ -68,11 +68,11 @@ def rollback_migration(migration_name): try: # Import the migration module module = importlib.import_module(f'app.modules.db.migrations.{migration_name}') - + # Rollback the migration print(f"Rolling back migration: {migration_name}") module.down() - + # Remove the migration record Migration.delete().where(Migration.name == migration_name).execute() print(f"Migration rolled back: {migration_name}") @@ -85,49 +85,49 @@ def rollback_migration(migration_name): def migrate(): """Apply all pending migrations.""" create_migrations_table() - + # Get all migration files and applied migrations migration_files = get_migration_files() applied_migrations = get_applied_migrations() - + # Determine which migrations need to be applied pending_migrations = [m for m in migration_files if m not in applied_migrations] - + if not pending_migrations: print("No pending migrations to apply.") return True - + # Apply pending migrations success = True for migration_name in pending_migrations: if not apply_migration(migration_name): success = False break - + return success def rollback(steps=1): """Rollback the specified number of migrations.""" create_migrations_table() - + # Get applied migrations in reverse order (most recent first) applied_migrations = Migration.select().order_by(Migration.applied_at.desc()) - + if not applied_migrations: print("No migrations to roll back.") return True - + # Rollback the specified number of migrations success = True for i, migration in enumerate(applied_migrations): if i >= steps: break - + if not rollback_migration(migration.name): success = False break - + return success @@ -136,7 +136,7 @@ def create_migration(name): timestamp = datetime.now().strftime('%Y%m%d%H%M%S') filename = f"{timestamp}_{name}.py" filepath = os.path.join(os.path.dirname(__file__), 'migrations', filename) - + template = """from playhouse.migrate import * from app.modules.db.db_model import connect, mysql_enable @@ -158,10 +158,10 @@ def down(): # ) pass """ - + with open(filepath, 'w') as f: f.write(template) - + print(f"Created migration file: {filename}") return filename diff --git a/app/modules/db/migrations/20230101000006_delete_prometheus_tools.py b/app/modules/db/migrations/20230101000006_delete_prometheus_tools.py index 9ffa1a99..db2618d5 100644 --- a/app/modules/db/migrations/20230101000006_delete_prometheus_tools.py +++ b/app/modules/db/migrations/20230101000006_delete_prometheus_tools.py @@ -26,7 +26,7 @@ def down(): is_roxy=0, desc='Prometheus monitoring system' ).on_conflict_ignore().execute() - + RoxyTool.insert( name='grafana-server', current_version='1.0', diff --git a/app/modules/db/migrations/__init__.py b/app/modules/db/migrations/__init__.py index 82723f26..c4696eb1 100644 --- a/app/modules/db/migrations/__init__.py +++ b/app/modules/db/migrations/__init__.py @@ -1 +1 @@ -# This file makes the migrations directory a Python package \ No newline at end of file +# This file makes the migrations directory a Python package diff --git a/app/views/service/nginx_section_views.py b/app/views/service/nginx_section_views.py index 9605a8c2..2e81ef15 100644 --- a/app/views/service/nginx_section_views.py +++ b/app/views/service/nginx_section_views.py @@ -118,7 +118,7 @@ class NginxSectionView(MethodView): return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot find a server') try: - output = self._edit_config(service, server, body, 'create') + output = self._edit_config(service, server, body, 'update') except Exception as e: return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot create HAProxy section') @@ -162,20 +162,17 @@ class NginxSectionView(MethodView): config_file_name = f'{service_dir}/sites-enabled/proxy-pass_{name}.conf' return config_file_name - def _edit_config(self, service, server: Server, body: NginxUpstreamRequest, action: Literal['create', 'delete'], **kwargs) -> str: + def _edit_config(self, service, server: Server, body: NginxUpstreamRequest, action: Literal['create', 'update', 'delete'], **kwargs) -> str: cfg = config_common.generate_config_path(service, server.ip) - print('cfg', cfg) config_file_name = self._create_config_path(service, body.type, body.name) - if action == 'create': + if action in ('create', 'update'): inv = service_mod.generate_section_inv(body.model_dump(mode='json'), cfg, service) else: inv = service_mod.generate_section_inv_for_del(cfg, kwargs.get('section_type'), kwargs.get('section_name')) - try: + if action == 'update': config_mod.get_config(server.ip, cfg, service=service, config_file_name=config_file_name) - except Exception as e: - raise e os.system(f'mv {cfg} {cfg}.old')