Compare commits

..

4 Commits

Author SHA1 Message Date
d8d38e0908
dude wtf
Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-04-16 00:21:07 +05:30
0c44136f1a Merge remote-tracking branch 'origin/master' into website 2025-04-16 00:13:42 +05:30
fc6593329b
Redirect to game_detail
The redirect works now. So if you click on a game,
 it wilk take you there

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-02-11 19:38:01 +05:30
180900c752
add dynamic games/ page
home/ doesnt contian much
the games in games/ should be generated dyamically
needs testing, potential pagination ahead

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2025-02-11 16:47:30 +05:30
14 changed files with 120 additions and 175 deletions

View File

@ -118,10 +118,7 @@ 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

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

View File

@ -1,31 +1,51 @@
from django.contrib import admin, messages
from django.contrib import admin
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')
@ -44,4 +64,4 @@ class ServerAdmin(admin.ModelAdmin):
list_filter = ('status', 'game')
search_fields = ('ip_address', 'game__name', 'image')
ordering = ('game', 'ip_address')
actions = [ stop_servers, remove_servers, launch_servers]
actions = [launch_container, stop_container, remove_container]

View File

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

View File

@ -1,20 +0,0 @@
# 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

@ -1,23 +0,0 @@
# 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

@ -1,20 +0,0 @@
# 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,15 +1,13 @@
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) -> str:
def __str__(self):
return self.name
class Server(models.Model):
@ -17,7 +15,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)
@ -25,28 +23,17 @@ 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)-> str:
def __str__(self):
return f"{self.game.name} Server at {self.ip_address}:{self.port}"
@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:
def sync_status(self):
"""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 = self._get_podman_client().containers.get(self.safe_name)
container = client.containers.get(container_name)
if container.status == "running":
self.status = "online"
else:
@ -54,70 +41,17 @@ class Server(models.Model):
except podman.errors.NotFound:
self.status = "offline"
except Exception as e:
self.status = "offline"
self.status = "offline" # Fallback in case of unexpected errors
self.save()
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}"
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

View File

@ -3,8 +3,14 @@ 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'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# 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)

View File

@ -0,0 +1,51 @@
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}"