Initial Commit

Base Functionality added. Adding a Server with
the image port  ip and other params specified
will spawn a container and one can manage the
lifecycle in the admin panel and the game server
detail view updates based on container status.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
This commit is contained in:
Pratyush Desai 2025-01-20 05:02:25 +05:30
commit 5da520bc9d
Signed by: pratyush
GPG Key ID: DBA5BB7505946FAD
25 changed files with 700 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
__pycache__
db.sqlite3

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for GameServerSupervisor project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GameServerSupervisor.settings")
application = get_asgi_application()

View File

@ -0,0 +1,124 @@
"""
Django settings for GameServerSupervisor project.
Generated by 'django-admin startproject' using Django 5.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-m$gupec&ocf99t^v%ahb)8-_trcl(sajxz-_7%(66*wh)fnmk-"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"webpanel",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "GameServerSupervisor.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "GameServerSupervisor.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
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"

View File

@ -0,0 +1,24 @@
"""
URL configuration for GameServerSupervisor project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webpanel.urls')),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for GameServerSupervisor project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GameServerSupervisor.settings")
application = get_wsgi_application()

0
README.md Normal file
View File

22
manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GameServerSupervisor.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
asgiref==3.8.1
certifi==2024.12.14
charset-normalizer==3.4.1
Django==5.1.5
docker==7.1.0
idna==3.10
requests==2.32.3
sqlparse==0.5.3
urllib3==2.3.0

0
webpanel/__init__.py Normal file
View File

53
webpanel/admin.py Normal file
View File

@ -0,0 +1,53 @@
from django.contrib import admin
from .models import Game, Server
from .utils import launch_docker_container, stop_docker_container, remove_docker_container
@admin.register(Game)
class GameAdmin(admin.ModelAdmin):
list_display = ('name', 'genre')
search_fields = ('name', 'genre')
ordering = ('name',)
@admin.action(description='Launch Docker Container')
def launch_container(modeladmin, request, queryset):
for server in queryset:
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
result = launch_docker_container(
image=server.docker_image,
name=container_name,
ports={f"{server.port}/tcp": server.port},
)
server.sync_status()
modeladmin.message_user(request, f"Container launch result for {server}: {result}")
@admin.action(description='Stop Docker Container')
def stop_container(modeladmin, request, queryset):
for server in queryset:
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
result = stop_docker_container(container_name)
server.sync_status()
modeladmin.message_user(request, f"Stop container result for {server}: {result}")
@admin.action(description='Remove Docker Container')
def remove_container(modeladmin, request, queryset):
for server in queryset:
container_name = f"{server.game.name}_{server.ip_address}_{server.port}"
result = remove_docker_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', 'ip_address', 'port', 'status', 'docker_image')
def get_queryset(self, request):
"""Sync status of all servers before rendering the admin list view."""
queryset = super().get_queryset(request)
for server in queryset:
server.sync_status()
return queryset
list_filter = ('status', 'game')
search_fields = ('ip_address', 'game__name', 'docker_image')
ordering = ('game', 'ip_address')
actions = [launch_container, stop_container, remove_container]

6
webpanel/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class WebpanelConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "webpanel"

View File

@ -0,0 +1,62 @@
# Generated by Django 5.1.5 on 2025-01-19 21:03
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Game",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=100)),
("genre", models.CharField(blank=True, max_length=50, null=True)),
("description", models.TextField(blank=True, null=True)),
],
),
migrations.CreateModel(
name="Server",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("ip_address", models.GenericIPAddressField()),
("port", models.PositiveIntegerField()),
(
"status",
models.CharField(
choices=[("online", "Online"), ("offline", "Offline")],
max_length=50,
),
),
(
"game",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="servers",
to="webpanel.game",
),
),
],
),
]

View File

@ -0,0 +1,22 @@
# Generated by Django 5.1.5 on 2025-01-19 21:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("webpanel", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="server",
name="docker_image",
field=models.CharField(
help_text="Enter the Docker image name (e.g., lacledeslan/gamesvr-hl2dm)",
max_length=200,
null=True,
),
),
]

View File

@ -0,0 +1,39 @@
# Generated by Django 5.1.5 on 2025-01-19 22:01
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("webpanel", "0002_server_docker_image"),
]
operations = [
migrations.RemoveField(
model_name="game",
name="description",
),
migrations.AlterField(
model_name="server",
name="docker_image",
field=models.CharField(max_length=200, null=True),
),
migrations.AlterField(
model_name="server",
name="game",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="webpanel.game"
),
),
migrations.AlterField(
model_name="server",
name="status",
field=models.CharField(
choices=[("online", "Online"), ("offline", "Offline")],
default="offline",
max_length=10,
),
),
]

View File

40
webpanel/models.py Normal file
View File

@ -0,0 +1,40 @@
from django.db import models
import docker
class Game(models.Model):
name = models.CharField(max_length=100)
genre = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.name
class Server(models.Model):
STATUS_CHOICES = [
('online', 'Online'),
('offline', 'Offline'),
]
game = models.ForeignKey(Game, on_delete=models.CASCADE)
ip_address = models.GenericIPAddressField()
port = models.PositiveIntegerField()
docker_image = models.CharField(max_length=200, null=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='offline')
def __str__(self):
return f"{self.game.name} Server at {self.ip_address}:{self.port}"
def sync_status(self):
"""Check the real-time status of the Docker container and update the field."""
client = docker.from_env()
container_name = f"{self.game.name}_{self.ip_address}_{self.port}"
try:
container = client.containers.get(container_name)
if container.status == "running":
self.status = "online"
else:
self.status = "offline"
except docker.errors.NotFound:
self.status = "offline"
except Exception as e:
self.status = "offline" # Fallback in case of unexpected errors
self.save()

View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Active Servers</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.server-box {
border: 2px solid #007BFF;
border-radius: 5px;
padding: 10px;
margin-bottom: 15px;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
}
legend {
font-weight: bold;
color: #007BFF;
}
.server-details {
margin-left: 15px;
}
</style>
</head>
<body>
<h1>Active Servers</h1>
{% if servers %}
{% for server in servers %}
<fieldset class="server-box">
<legend>Server: {{ server.game.name }}</legend>
<div class="server-details">
<p><strong>Genre:</strong> {{ server.game.genre }}</p>
<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.</p>
{% endif %}
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head><title>{{ game.name }}</title></head>
<body>
<h1>{{ game.name }}</h1>
<p>{{ game.description }}</p>
<h2>Servers</h2>
<ul>
{% for server in game.servers.all %}
<li>{{ server.ip_address }}:{{ server.port }} - {{ server.status }}</li>
{% endfor %}
</ul>
<a href="/">Back to Games</a>
</body>
</html>

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Active Servers for {{ game.name }}</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #007BFF;
}
.server-box {
border: 2px solid #007BFF;
border-radius: 5px;
padding: 10px;
margin-bottom: 15px;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
}
legend {
font-weight: bold;
color: #007BFF;
}
.server-details {
margin-left: 15px;
}
</style>
</head>
<body>
<h1>Active Servers for {{ game.name }}</h1>
<h3>Genre: {{ game.genre }}</h3>
{% if servers %}
{% for server in 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 %}
</body>
</html>

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Hosting Panel</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #007BFF;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
a {
text-decoration: none;
color: #007BFF;
font-weight: bold;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Game Hosting Panel</h1>
<h2>Quick Links</h2>
<ul>
<li><a href="{% url 'active-servers' %}">View All Active Servers</a></li>
</ul>
<h2>Games</h2>
<ul>
{% for game in games %}
<li>
<a href="{% url 'game-servers' game.name %}">
View Active Servers for {{ game.name }}
</a>
</li>
{% empty %}
<li>No games available.</li>
{% endfor %}
</ul>
</body>
</html>

3
webpanel/tests.py Normal file
View File

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

9
webpanel/urls.py Normal file
View File

@ -0,0 +1,9 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.home_view, name='home'),
path('<int:pk>/', 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'),
]

49
webpanel/utils.py Normal file
View File

@ -0,0 +1,49 @@
import docker
def launch_docker_container(image, name, ports=None, environment=None):
client = docker.from_env()
try:
container = client.containers.run(
image,
name=name,
ports=ports,
environment=environment,
detach=True
)
return f"Container launched successfully: {container.id}"
except docker.errors.APIError as e:
return f"API Error: {e}"
except Exception as e:
return f"Error: {e}"
def stop_docker_container(name):
client = docker.from_env()
try:
container = client.containers.get(name)
container.stop()
return f"Container stopped: {name}"
except docker.errors.NotFound:
return f"Container not found: {name}"
except Exception as e:
return f"Error stopping container {name}: {e}"
def remove_docker_container(name):
client = docker.from_env()
try:
container = client.containers.get(name)
container.remove(force=True) # Force removal if the container is running
return f"Container removed: {name}"
except docker.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 = docker.from_env()
try:
container = client.containers.get(name)
return container.status == "running"
except docker.errors.NotFound:
return False
except Exception as e:
return f"Error checking container {name}: {e}"

41
webpanel/views.py Normal file
View File

@ -0,0 +1,41 @@
from django.shortcuts import render, get_object_or_404
from .models import Game, Server
def home_view(request):
"""Display the home page with links to other views."""
games = Game.objects.all() # Fetch all games
return render(request, 'webpanel/home.html', {'games': games})
# def game_list(request):
# games = Game.objects.all()
# return render(request, 'webpanel/game_list.html', {'games': games})
def game_detail(request, pk):
game = get_object_or_404(Game, pk=pk)
return render(request, 'webpanel/game_detail.html', {'game': game})
def active_servers_view(request):
"""Fetch and display all active servers."""
# Sync server status before fetching
servers = Server.objects.all()
for server in servers:
server.sync_status()
# Fetch only servers with status 'online'
active_servers = Server.objects.filter(status='online')
return render(request, 'webpanel/active_servers.html', {'servers': active_servers})
def game_servers_view(request, game_name):
"""Fetch and display active servers for a specific game."""
game = get_object_or_404(Game, name=game_name)
# Sync server status before fetching
servers = Server.objects.filter(game=game)
for server in servers:
server.sync_status()
# Fetch only active servers for the game
active_servers = servers.filter(status='online')
return render(request, 'webpanel/game_servers.html', {'game': game, 'servers': active_servers})