v8.2.0: Fix action type in Nginx config update and clean up spacing.

Changed action type from 'create' to 'update' in `_edit_config` for proper handling of updates. Added 'update' as a valid action in `_edit_config` logic. Also removed unnecessary print statements and standardized whitespace across migration-related files for better readability.
pull/403/merge
Aidaho 2025-05-17 11:37:01 +03:00
parent c20f3f8ee9
commit 0d022c57e5
5 changed files with 31 additions and 34 deletions

View File

@ -12,26 +12,26 @@ from app.modules.db.migration_manager import create_migrations_table, migrate, r
def main(): def main():
parser = argparse.ArgumentParser(description='Database migration tool') parser = argparse.ArgumentParser(description='Database migration tool')
subparsers = parser.add_subparsers(dest='command', help='Command to run') subparsers = parser.add_subparsers(dest='command', help='Command to run')
# Create migration command # Create migration command
create_parser = subparsers.add_parser('create', help='Create a new migration') create_parser = subparsers.add_parser('create', help='Create a new migration')
create_parser.add_argument('name', help='Name of the migration') create_parser.add_argument('name', help='Name of the migration')
# Migrate command # Migrate command
subparsers.add_parser('migrate', help='Apply pending migrations') subparsers.add_parser('migrate', help='Apply pending migrations')
# Rollback command # Rollback command
rollback_parser = subparsers.add_parser('rollback', help='Rollback migrations') 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') rollback_parser.add_argument('--steps', type=int, default=1, help='Number of migrations to roll back')
# Initialize command # Initialize command
subparsers.add_parser('init', help='Initialize the migrations table') subparsers.add_parser('init', help='Initialize the migrations table')
# list command # list command
subparsers.add_parser('list', help='List all migrations and their status') subparsers.add_parser('list', help='List all migrations and their status')
args = parser.parse_args() args = parser.parse_args()
if args.command == 'create': if args.command == 'create':
filename = create_migration(args.name) filename = create_migration(args.name)
print(f"Created migration file: {filename}") print(f"Created migration file: {filename}")

View File

@ -28,12 +28,12 @@ def get_migration_files():
"""Get all migration files from the migrations directory.""" """Get all migration files from the migrations directory."""
migrations_dir = os.path.join(os.path.dirname(__file__), 'migrations') migrations_dir = os.path.join(os.path.dirname(__file__), 'migrations')
migration_files = [] migration_files = []
for filename in os.listdir(migrations_dir): for filename in os.listdir(migrations_dir):
if filename.endswith('.py') and not filename.startswith('__'): if filename.endswith('.py') and not filename.startswith('__'):
migration_name = filename[:-3] # Remove .py extension migration_name = filename[:-3] # Remove .py extension
migration_files.append(migration_name) migration_files.append(migration_name)
# Sort migrations by name (which should include a timestamp) # Sort migrations by name (which should include a timestamp)
migration_files.sort() migration_files.sort()
return migration_files return migration_files
@ -49,11 +49,11 @@ def apply_migration(migration_name):
try: try:
# Import the migration module # Import the migration module
module = importlib.import_module(f'app.modules.db.migrations.{migration_name}') module = importlib.import_module(f'app.modules.db.migrations.{migration_name}')
# Apply the migration # Apply the migration
print(f"Applying migration: {migration_name}") print(f"Applying migration: {migration_name}")
module.up() module.up()
# Record the migration as applied # Record the migration as applied
Migration.create(name=migration_name) Migration.create(name=migration_name)
print(f"Migration applied: {migration_name}") print(f"Migration applied: {migration_name}")
@ -68,11 +68,11 @@ def rollback_migration(migration_name):
try: try:
# Import the migration module # Import the migration module
module = importlib.import_module(f'app.modules.db.migrations.{migration_name}') module = importlib.import_module(f'app.modules.db.migrations.{migration_name}')
# Rollback the migration # Rollback the migration
print(f"Rolling back migration: {migration_name}") print(f"Rolling back migration: {migration_name}")
module.down() module.down()
# Remove the migration record # Remove the migration record
Migration.delete().where(Migration.name == migration_name).execute() Migration.delete().where(Migration.name == migration_name).execute()
print(f"Migration rolled back: {migration_name}") print(f"Migration rolled back: {migration_name}")
@ -85,49 +85,49 @@ def rollback_migration(migration_name):
def migrate(): def migrate():
"""Apply all pending migrations.""" """Apply all pending migrations."""
create_migrations_table() create_migrations_table()
# Get all migration files and applied migrations # Get all migration files and applied migrations
migration_files = get_migration_files() migration_files = get_migration_files()
applied_migrations = get_applied_migrations() applied_migrations = get_applied_migrations()
# Determine which migrations need to be applied # Determine which migrations need to be applied
pending_migrations = [m for m in migration_files if m not in applied_migrations] pending_migrations = [m for m in migration_files if m not in applied_migrations]
if not pending_migrations: if not pending_migrations:
print("No pending migrations to apply.") print("No pending migrations to apply.")
return True return True
# Apply pending migrations # Apply pending migrations
success = True success = True
for migration_name in pending_migrations: for migration_name in pending_migrations:
if not apply_migration(migration_name): if not apply_migration(migration_name):
success = False success = False
break break
return success return success
def rollback(steps=1): def rollback(steps=1):
"""Rollback the specified number of migrations.""" """Rollback the specified number of migrations."""
create_migrations_table() create_migrations_table()
# Get applied migrations in reverse order (most recent first) # Get applied migrations in reverse order (most recent first)
applied_migrations = Migration.select().order_by(Migration.applied_at.desc()) applied_migrations = Migration.select().order_by(Migration.applied_at.desc())
if not applied_migrations: if not applied_migrations:
print("No migrations to roll back.") print("No migrations to roll back.")
return True return True
# Rollback the specified number of migrations # Rollback the specified number of migrations
success = True success = True
for i, migration in enumerate(applied_migrations): for i, migration in enumerate(applied_migrations):
if i >= steps: if i >= steps:
break break
if not rollback_migration(migration.name): if not rollback_migration(migration.name):
success = False success = False
break break
return success return success
@ -136,7 +136,7 @@ def create_migration(name):
timestamp = datetime.now().strftime('%Y%m%d%H%M%S') timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
filename = f"{timestamp}_{name}.py" filename = f"{timestamp}_{name}.py"
filepath = os.path.join(os.path.dirname(__file__), 'migrations', filename) filepath = os.path.join(os.path.dirname(__file__), 'migrations', filename)
template = """from playhouse.migrate import * template = """from playhouse.migrate import *
from app.modules.db.db_model import connect, mysql_enable from app.modules.db.db_model import connect, mysql_enable
@ -158,10 +158,10 @@ def down():
# ) # )
pass pass
""" """
with open(filepath, 'w') as f: with open(filepath, 'w') as f:
f.write(template) f.write(template)
print(f"Created migration file: {filename}") print(f"Created migration file: {filename}")
return filename return filename

View File

@ -26,7 +26,7 @@ def down():
is_roxy=0, is_roxy=0,
desc='Prometheus monitoring system' desc='Prometheus monitoring system'
).on_conflict_ignore().execute() ).on_conflict_ignore().execute()
RoxyTool.insert( RoxyTool.insert(
name='grafana-server', name='grafana-server',
current_version='1.0', current_version='1.0',

View File

@ -1 +1 @@
# This file makes the migrations directory a Python package # This file makes the migrations directory a Python package

View File

@ -118,7 +118,7 @@ class NginxSectionView(MethodView):
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot find a server') return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot find a server')
try: try:
output = self._edit_config(service, server, body, 'create') output = self._edit_config(service, server, body, 'update')
except Exception as e: except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot create HAProxy section') 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' config_file_name = f'{service_dir}/sites-enabled/proxy-pass_{name}.conf'
return config_file_name 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) cfg = config_common.generate_config_path(service, server.ip)
print('cfg', cfg)
config_file_name = self._create_config_path(service, body.type, body.name) 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) inv = service_mod.generate_section_inv(body.model_dump(mode='json'), cfg, service)
else: else:
inv = service_mod.generate_section_inv_for_del(cfg, kwargs.get('section_type'), kwargs.get('section_name')) 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) 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') os.system(f'mv {cfg} {cfg}.old')