Fix launch logic
Have cleaned up redundant logic used for testing it ruined my life today. Port mapping works but it's simply picking it up from a single integer field. We might have to expand on this logic for multi port mappings per instance. Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
This commit is contained in:
parent
77ab980fd4
commit
88f5614cd4
@ -1,7 +1,27 @@
|
||||
from django.contrib import admin
|
||||
from .models import Game, Server
|
||||
from .utils import launch_pod_container, stop_pod_container, remove_pod_container
|
||||
from .utils import stop_pod_container, remove_pod_container
|
||||
import podman
|
||||
from django.contrib import messages
|
||||
|
||||
|
||||
@admin.action(description="Launch selected servers")
|
||||
def launch_servers(modeladmin, request, queryset):
|
||||
for server in queryset:
|
||||
result = server.launch_pod_container()
|
||||
messages.info(request, f"{server.name}: {result}")
|
||||
|
||||
@admin.action(description="Stop selected servers")
|
||||
def stop_servers(modeladmin, request, queryset):
|
||||
for server in queryset:
|
||||
result = server.stop_pod_container()
|
||||
messages.info(request, f"{server.name}: {result}")
|
||||
|
||||
@admin.action(description="Remove selected servers")
|
||||
def remove_servers(modeladmin, request, queryset):
|
||||
for server in queryset:
|
||||
result = server.remove_pod_container()
|
||||
messages.info(request, f"{server.name}: {result}")
|
||||
|
||||
@admin.register(Game)
|
||||
class GameAdmin(admin.ModelAdmin):
|
||||
@ -9,43 +29,6 @@ class GameAdmin(admin.ModelAdmin):
|
||||
search_fields = ('name', 'genre')
|
||||
ordering = ('name',)
|
||||
|
||||
@admin.action(description='Launch Container')
|
||||
def launch_container(modeladmin, request, queryset):
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
for server in queryset:
|
||||
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
|
||||
try:
|
||||
# Ensure the command is passed as a list of strings
|
||||
command = server.get_podman_run_command().split() if server.run_command else []
|
||||
container = client.containers.run(
|
||||
server.image,
|
||||
detach=True,
|
||||
name=container_name,
|
||||
command=command,
|
||||
ports={f"{server.port}/tcp": server.port},
|
||||
remove=True, # Automatically remove on stop
|
||||
)
|
||||
server.sync_status()
|
||||
modeladmin.message_user(request, f"Container launched: {container.id}")
|
||||
except Exception as e:
|
||||
modeladmin.message_user(request, f"Failed to launch {server}: {e}", level="error")
|
||||
|
||||
@admin.action(description='Stop Container')
|
||||
def stop_container(modeladmin, request, queryset):
|
||||
for server in queryset:
|
||||
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
|
||||
result = stop_pod_container(container_name)
|
||||
server.sync_status()
|
||||
modeladmin.message_user(request, f"Stop container result for {server}: {result}")
|
||||
|
||||
@admin.action(description='Remove Container')
|
||||
def remove_container(modeladmin, request, queryset):
|
||||
for server in queryset:
|
||||
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
|
||||
result = remove_pod_container(container_name)
|
||||
server.sync_status()
|
||||
modeladmin.message_user(request, f"Remove container result for {server}: {result}")
|
||||
|
||||
@admin.register(Server)
|
||||
class ServerAdmin(admin.ModelAdmin):
|
||||
list_display = ('game', 'name', 'ip_address', 'port', 'status', 'image', 'run_command', 'command_args')
|
||||
@ -64,4 +47,4 @@ class ServerAdmin(admin.ModelAdmin):
|
||||
list_filter = ('status', 'game')
|
||||
search_fields = ('ip_address', 'game__name', 'image')
|
||||
ordering = ('game', 'ip_address')
|
||||
actions = [launch_container, stop_container, remove_container]
|
||||
actions = [ stop_servers, remove_servers, launch_servers]
|
||||
|
@ -0,0 +1,23 @@
|
||||
# Generated by Django 5.1.5 on 2025-04-16 14:13
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("webpanel", "0008_alter_game_thumbnail"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="server",
|
||||
name="container_id",
|
||||
field=models.CharField(blank=True, max_length=64, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="server",
|
||||
name="last_log",
|
||||
field=models.TextField(blank=True, null=True),
|
||||
),
|
||||
]
|
@ -1,5 +1,8 @@
|
||||
from django.db import models
|
||||
import podman
|
||||
import shlex
|
||||
import re
|
||||
|
||||
|
||||
class Game(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
@ -14,7 +17,7 @@ class Server(models.Model):
|
||||
('online', 'Online'),
|
||||
('offline', 'Offline'),
|
||||
]
|
||||
|
||||
last_log = models.TextField(blank=True, null=True)
|
||||
game = models.ForeignKey(Game, on_delete=models.CASCADE)
|
||||
name = models.CharField(max_length=100)
|
||||
ip_address = models.GenericIPAddressField(null=True)
|
||||
@ -22,6 +25,7 @@ class Server(models.Model):
|
||||
image = models.CharField(max_length=200, null=True)
|
||||
run_command = models.CharField(max_length=500, blank=True, null=True)
|
||||
command_args = models.TextField(blank=True, null=True)
|
||||
container_id = models.CharField(max_length=64, blank=True, null=True)
|
||||
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='offline')
|
||||
|
||||
def __str__(self):
|
||||
@ -29,10 +33,10 @@ class Server(models.Model):
|
||||
|
||||
def sync_status(self):
|
||||
"""Check the real-time status of the container and update the field."""
|
||||
safe_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', self.name)
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
container_name = f"{self.game.name}_{self.ip_address}_{self.port}"
|
||||
try:
|
||||
container = client.containers.get(container_name)
|
||||
container = client.containers.get(safe_name)
|
||||
if container.status == "running":
|
||||
self.status = "online"
|
||||
else:
|
||||
@ -40,17 +44,77 @@ class Server(models.Model):
|
||||
except podman.errors.NotFound:
|
||||
self.status = "offline"
|
||||
except Exception as e:
|
||||
self.status = "offline" # Fallback in case of unexpected errors
|
||||
self.status = "offline"
|
||||
self.save()
|
||||
|
||||
def get_podman_run_command(self):
|
||||
"""Returns the Podman run command, falling back to default image if not set."""
|
||||
if self.run_command:
|
||||
# Return command as a string to be split later
|
||||
return self.run_command
|
||||
else:
|
||||
# Default command with image and arguments
|
||||
base_command = f"{self.image}"
|
||||
if self.command_args:
|
||||
base_command += " " + self.command_args
|
||||
return base_command
|
||||
def launch_pod_container(self):
|
||||
safe_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', self.name) # sanitize name
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.create(
|
||||
name=safe_name,
|
||||
image=self.image,
|
||||
ports={
|
||||
f'{self.port}/udp': ('0.0.0.0', self.port),
|
||||
f'{self.port}/tcp': ('0.0.0.0', self.port),
|
||||
},
|
||||
command=shlex.split(self.run_command),
|
||||
detach=True,
|
||||
)
|
||||
container.start()
|
||||
self.container_id = container.id
|
||||
self.last_log = f"Launched container {container.id}"
|
||||
self.is_running = True
|
||||
self.sync_status()
|
||||
self.save()
|
||||
return f"Container launched successfully: {container.id}"
|
||||
except podman.errors.APIError as e:
|
||||
self.last_log = f"API Error: {str(e)}"
|
||||
self.save()
|
||||
return f"API Error: {e}"
|
||||
except Exception as e:
|
||||
self.last_log = f"Error: {str(e)}"
|
||||
self.save()
|
||||
return f"Error: {e}"
|
||||
|
||||
def stop_pod_container(self):
|
||||
safe_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', self.name)
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.get(safe_name)
|
||||
container.stop()
|
||||
self.status = "offline"
|
||||
self.last_log = f"Stopped container {container.id}"
|
||||
self.sync_status()
|
||||
self.save()
|
||||
return f"Container stopped successfully: {container.id}"
|
||||
except podman.errors.NotFound:
|
||||
self.last_log = f"Container '{safe_name}' not found"
|
||||
self.save()
|
||||
return f"Error: Container '{safe_name}' not found"
|
||||
except Exception as e:
|
||||
self.last_log = f"Error stopping container: {str(e)}"
|
||||
self.save()
|
||||
return f"Error: {e}"
|
||||
|
||||
def remove_pod_container(self):
|
||||
safe_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', self.name)
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.get(safe_name)
|
||||
container.remove(force=True)
|
||||
self.status = "offline"
|
||||
self.container_id = None
|
||||
self.last_log = f"Removed container {safe_name}"
|
||||
self.sync_status()
|
||||
self.save()
|
||||
return f"Container removed successfully: {safe_name}"
|
||||
except podman.errors.NotFound:
|
||||
self.last_log = f"Container '{safe_name}' not found"
|
||||
self.save()
|
||||
return f"Error: Container '{safe_name}' not found"
|
||||
except Exception as e:
|
||||
self.last_log = f"Error removing container: {str(e)}"
|
||||
self.save()
|
||||
return f"Error: {e}"
|
||||
|
||||
|
@ -1,51 +0,0 @@
|
||||
import podman
|
||||
|
||||
def launch_pod_container(image, run_command, name, ports):
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.create(
|
||||
name=name,
|
||||
image=image,
|
||||
# ports=ports,
|
||||
command=run_command,
|
||||
detach=True,
|
||||
network_mode='host'
|
||||
)
|
||||
container.start()
|
||||
return f"Container launched successfully: {container.id}"
|
||||
except podman.errors.APIError as e:
|
||||
return f"API Error: {e}"
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
|
||||
def stop_pod_container(name):
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.get(name)
|
||||
container.stop()
|
||||
return f"Container stopped: {name}"
|
||||
except podman.errors.NotFound:
|
||||
return f"Container not found: {name}"
|
||||
except Exception as e:
|
||||
return f"Error stopping container {name}: {e}"
|
||||
|
||||
def remove_pod_container(name):
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.get(name)
|
||||
container.remove(force=True) # Force removal if the container is running
|
||||
return f"Container removed: {name}"
|
||||
except podman.errors.NotFound:
|
||||
return f"Container not found: {name}"
|
||||
except Exception as e:
|
||||
return f"Error removing container {name}: {e}"
|
||||
|
||||
def is_container_running(name):
|
||||
client = podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
|
||||
try:
|
||||
container = client.containers.get(name)
|
||||
return container.status == "running"
|
||||
except podman.errors.NotFound:
|
||||
return False
|
||||
except Exception as e:
|
||||
return f"Error checking container {name}: {e}"
|
Loading…
x
Reference in New Issue
Block a user