Compare commits

..

11 Commits

Author SHA1 Message Date
8dc855548e Merge pull request 'Fix botched fix' (#28) from misc_fixes_2 into master
Reviewed-on: #28
2025-04-20 21:30:58 +02:00
f251b97b4d
Fix botched fix
Fix the botched fix for thumbnails

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-21 00:59:45 +05:30
66954eb634 Merge pull request 'misc-fixes' (#27) from misc-fixes into master
Reviewed-on: #27
2025-04-20 21:12:55 +02:00
2fbf160920
Fix thumbnails
Repaired media upload thumbnails giving 404

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-21 00:32:49 +05:30
0be9090981
DRY
Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-20 23:21:28 +05:30
b120c6904e Merge pull request 'Overhauls several things' (#26) from match_data into master
Reviewed-on: #26
2025-04-17 16:12:15 +02:00
851496a0af
Rm commented code
Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-17 19:37:59 +05:30
88f5614cd4
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>
2025-04-16 21:01:58 +05:30
77ab980fd4
Create Frontend
Create views and templates to render the views for a list of games
And for it to show if server is running for the game selected.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-16 14:30:51 +05:30
195a11e07d Merge pull request 'Added pillow to handle the thumbnails for the games' (#25) from add_req_pillow into master
Reviewed-on: #25
2025-04-15 20:57:09 +02:00
35d8549a38
Added pillow to handle the thumbnails for the games
Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-16 00:25:35 +05:30
14 changed files with 175 additions and 120 deletions

View File

@ -118,7 +118,10 @@ USE_TZ = True
STATIC_URL = "static/"
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

View File

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

View File

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -1,51 +1,31 @@
from django.contrib import admin
from django.contrib import admin, messages
from .models import Game, Server
from .utils import launch_pod_container, stop_pod_container, remove_pod_container
import podman
@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):
list_display = ('name', 'genre', 'thumbnail')
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 +44,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]

View File

@ -1,4 +1,4 @@
# Generated by Django 5.1.5 on 2025-02-11 01:27
# Generated by Django 5.1.5 on 2025-04-15 19:28
from django.db import migrations, models

View File

@ -0,0 +1,20 @@
# Generated by Django 5.1.5 on 2025-04-16 08:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("webpanel", "0007_game_thumbnail"),
]
operations = [
migrations.AlterField(
model_name="game",
name="thumbnail",
field=models.ImageField(
blank=True, null=True, upload_to="media/game_thumbnails/"
),
),
]

View File

@ -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),
),
]

View File

@ -0,0 +1,20 @@
# Generated by Django 5.1.5 on 2025-04-20 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("webpanel", "0009_server_container_id_server_last_log"),
]
operations = [
migrations.AlterField(
model_name="game",
name="thumbnail",
field=models.ImageField(
blank=True, null=True, upload_to="game_thumbnails/"
),
),
]

View File

@ -1,13 +1,15 @@
from django.db import models
import podman
import shlex
import re
from typing import Optional,List
class Game(models.Model):
name = models.CharField(max_length=100)
genre = models.CharField(max_length=50, blank=True, null=True)
thumbnail = models.ImageField(upload_to='game_thumbnails/', null=True, blank=True)
def __str__(self):
def __str__(self) -> str:
return self.name
class Server(models.Model):
@ -15,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)
@ -23,17 +25,28 @@ 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):
def __str__(self)-> str:
return f"{self.game.name} Server at {self.ip_address}:{self.port}"
def sync_status(self):
@property
def safe_name(self) -> str:
"""Return a container-safe version of the server name"""
return re.sub(r'[^a-zA-Z0-9_.-]', '_', self.name)
def _log_error(self, msg):
self.last_log = msg
self.save(update_fields=["status", "last_log"])
def _get_podman_client(self) -> podman.PodmanClient:
"""Get a configured Podman client instance."""
return podman.PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock")
def sync_status(self) -> None:
"""Check the real-time status of the container and update the field."""
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 = self._get_podman_client().containers.get(self.safe_name)
if container.status == "running":
self.status = "online"
else:
@ -41,17 +54,70 @@ 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) -> str:
try:
container = self._get_podman_client().containers.create(
name=self.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) -> str:
try:
container = self._get_podman_client().containers.get(self.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 '{self.safe_name}' not found"
self.save()
return f"Error: Container '{self.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) -> str:
try:
container = self._get_podman_client().containers.get(self.safe_name)
container.remove(force=True)
self.status = "offline"
self.container_id = None
self.last_log = f"Removed container {self.safe_name}"
self.sync_status()
self.save()
return f"Container removed successfully: {self.safe_name}"
except podman.errors.NotFound:
self.last_log = f"Container '{self.safe_name}' not found"
self.save()
return f"Error: Container '{self.safe_name}' not found"
except Exception as e:
self.last_log = f"Error removing container: {str(e)}"
self.save()
return f"Error: {e}"

View File

@ -3,14 +3,8 @@ from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('games/', views.games, name='games'),
path('games/<str:game_name>/', views.game_detail, name='game_detail'),
# path('active-servers/', views.active_servers_view, name='active-servers'),
# path('games/<str:game_name>/', views.game_servers_view, name='game-servers'),
]
if settings.DEBUG: # Only serve media files in development
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View File

@ -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}"