Compare commits

..

1 Commits

Author SHA1 Message Date
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
22 changed files with 156 additions and 306 deletions

View File

@ -1,14 +0,0 @@
FROM python:3.10-alpine
ARG supervisor_dir="/usr/src/GameServerSupervisor"
RUN mkdir -p $supervisor_dir
WORKDIR $supervisor_dir
COPY . $supervisor_dir
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 80

View File

@ -121,4 +121,4 @@ STATIC_URL = "static/"
# 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

@ -1,23 +1,10 @@
# GibCasa GameServerSupervisor
## Table of Contents
- [Installation using venv](#installation-using-venv)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Installation using Podman](#installation-using-podman)
- [Prerequisites](#prerequisites-1)
- [Installation](#installation-1)
- [Usage](#usage)
- [Contributing](#contributing)
- [License](#license)
## Installation using venv
### Prerequisites
## Prerequisites
Python 3.10 or above
### Installation
## Installation
1. Clone the repository:
```bash
@ -35,80 +22,19 @@ Python 3.10 or above
```bash
pip install -r requirements.txt
```
5. Run tests:
```bash
./manage.py test
```
6. Run migrations:
```bash
./manage.py migrate
```
7. Create admin user:
```bash
./manage.py createsuperuser
```
8. Run server:
```bash
./manage.py runserver
```
## Installation using Podman
### Prerequisites
Podman
### Installation
1. Clone the repository:
```bash
git clone https://git.com.de/GibCasa/GameServerSupervisor
```
2. Build the image:
```bash
podman build . -t supervisor-image
```
3. Run a container in an interactive shell:
```bash
podman run -it --network=host localhost/supervisor-image sh
```
4. Run tests:
```bash
./manage.py test
```
5. Run migrations:
```bash
./manage.py migrate
python manage.py migrate
```
6. Create admin user:
```bash
./manage.py createsuperuser
python manage.py createsuperuser
```
7. Run server:
```bash
./manage.py runserver
python manage.py runserver
```
-------------
To live sync host directory with container folder, in Step 3:
```bash
podman run --network=host -itv /host/src/path:/usr/src/GameServerSupervisor supervisor-image sh
```
`/host/src/path` is the absolute path to the repository in the host machine.
## Usage
* Visit http://localhost:8000 for /public and
* visit http://localhost:8000 for /public and
http://localhost:8000/admin/ to login via the superuser credentials
## Contributing
1. Fork the repository.
2. Create a new branch: `git checkout -b feature-name`.
3. Make your changes.
4. Push your branch: `git push origin feature-name`.
5. Create a pull request.
## License
This project is licensed under the [AGPL](https://www.gnu.org/licenses/agpl-3.0.html).
* will need docker running

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: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -3,7 +3,6 @@ certifi==2024.12.14
charset-normalizer==3.4.1
Django==5.1.5
idna==3.10
pillow==11.2.1
podman==5.2.0
requests==2.32.3
sqlparse==0.5.3

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,13 +1,11 @@
from django.db import models
import podman
import shlex
import re
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='media/game_thumbnails/', null=True, blank=True)
thumbnail = models.ImageField(upload_to='game_thumbnails/', null=True, blank=True)
def __str__(self):
return self.name
@ -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,7 +23,6 @@ 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):
@ -33,10 +30,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(safe_name)
container = client.containers.get(container_name)
if container.status == "running":
self.status = "online"
else:
@ -44,77 +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):
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}"
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

@ -4,7 +4,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}GibCasa{% endblock %}</title>
<title>{% block title %}Game Server Supervisor{% endblock %}</title>
<style>
* {
margin: 0;
@ -165,39 +165,36 @@
font-size: 14px;
}
/* .game-box img {
.game-box img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 5px;
} */
}
</style>
</head>
<body>
<div class="navbar">
<div class="center">
<div class="left">
<pre>
┬ ┌┬┐ ┬─┐ ┌─┐ ┬─┐ ┐─┐ ┬─┐
│ │ │─│ │ │─┤ └─┐ │─┤
┘─┘ └┴┘ │─┘ └─┘ ┘ │ ──┘ ┘ │
</pre>
</div>
<div class="navbar">
<div class="left">
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'games' %}">Games</a>
<a href="#">Mods</a>
</div>
</div>
</div class="navbar">
<!-- <div class="right"> -->
<!-- <div class="search-box">
<!-- <div class="right">
<div class="search-box">
<input type="text" placeholder="Search...">
</div> -->
<!-- <a href="#">Auth / Settings</a> -->
<!-- <div class="profile">Dp</div> -->
<!-- </div> -->
</div>
</div>
<a href="#">Auth / Settings</a> -->
<div class="profile">Dp</div>
</div>
</div>
<div class="content">
{% block content %}{% endblock %}
@ -205,10 +202,10 @@
<footer>
<a href="https://ozFrags.net">Other Communities</a>
<a href="https://liberta.casa/rules.html">Terms of Service WIP</a>
<a href="#">License: AGPLish</a>
<a href="#">Contribute (WIP)</a>
<a href="https://liberta.casa/gamja/#gibcasa">Support</a>
<a href="#">Terms of Service</a>
<a href="#">License: AGPL</a>
<a href="#">Donate</a>
<a href="ircs://irc.casa/#gibcasa">Support</a>
</footer>
</body>

View File

@ -16,30 +16,16 @@
</nav> -->
<div class="game-detail">
<div class="game-box" style="width: 150px; text-align: center;">
<a href="{% url 'game_detail' game.name %}">
<img src="{{ game.thumbnail.url }}" alt="{{ game.name }}" style="width: 100%; height: auto;">
<p>{{ game.name }}</p>
</a>
</div>
<div class="active-servers">
{% if active_servers %}
{% for server in active_servers %}
<fieldset class="server-box">
<legend>Server: {{ game.name }}</legend>
<div class="server-details">
<p><strong>IP Address:</strong> {{ server.ip_address }}</p>
<p><strong>Port:</strong> {{ server.port }}</p>
<p><strong>Status:</strong> Online</p>
</div>
</fieldset>
{% endfor %}
{% else %}
<p>No active servers found for this game.</p>
{% endif %}
<div class="game-image">
<img src="{{ game.image_url }}" alt="{{ game.name }}">
</div>
<div class="game-info">
<p>Pull data from some open API to populate information about the game and render it.</p>
<ul>
<li>🔹 <strong>Active:</strong> Non-full, non-empty servers with connection info, map, and player count</li>
<li>🔹 <strong>All Active:</strong> List of all active servers</li>
<li>🔹 <strong>Stopped:</strong> Available upon request</li>
</ul>
</div>
</div>
{% endblock %}

View File

@ -3,12 +3,12 @@
{% block title %}Games - Game Servers{% endblock %}
{% block content %}
<h2>Games</h2>
<h2>Public Game Servers</h2>
<div class="game-grid" style="display: flex; flex-wrap: wrap; gap: 10px;">
{% for game in games %}
<div class="game-box" style="width: 150px; text-align: center;">
<a href="{% url 'game_detail' game.name %}">
<a href="{% url 'games' %}">
<img src="{{ game.thumbnail.url }}" alt="{{ game.name }}" style="width: 100%; height: auto;">
<p>{{ game.name }}</p>
</a>

View File

@ -1,11 +0,0 @@
from django.test import TestCase
from webpanel.models import Game
class GameTestCase(TestCase):
def setUp(self):
Game.objects.create(name="Assassin's Creed")
def test_game_creation(self):
assassins = Game.objects.get(name="Assassin's Creed")
assert str(assassins) == "Assassin's Creed"

3
webpanel/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

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'),
]
path('games/<str:game>/', 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)

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

View File

@ -11,12 +11,5 @@ def games(request):
return render(request, 'webpanel/games.html', {'games': games})
def game_detail(request, game_name):
print(f"Looking for game: {game_name}")
game = get_object_or_404(Game, name=game_name)
servers = Server.objects.filter(game=game)
for server in servers:
server.sync_status()
dormant_servers = servers.filter(status='offline')
active_servers = servers.filter(status='online')
return render(request, 'webpanel/game_detail.html', {'game': game,
'active_servers': active_servers, 'dormant_servers': dormant_servers})
game = get_object_or_404(Game, id=game_name)
return render(request, 'webpanel/game_detail.html', {'game': game})