Files
.gitignore
bot.py
requirements.txt
Code
3 455
bot.py
import asyncio
import hashlib
import json
import logging
import os
import re
import shutil
import urllib.request
from pathlib import Path
from xml.sax.saxutils import escape
import discord
import psutil
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("kodari-vps-bot")
DATA_DIR = Path(os.getenv("DATA_DIR", "data"))
VPS_FILE = DATA_DIR / "vps.json"
ADMINS_FILE = DATA_DIR / "admins.json"
DEFAULT_RAM_GIB = 128
DEFAULT_VCPU = 64
DEFAULT_STORAGE_GIB = 528
DEFAULT_OWNER_ID = 1320732831424450561
OWNER_IDS = {int(value.strip()) for value in os.getenv("BOT_OWNER_IDS", "").split(",") if value.strip().isdigit()} or {DEFAULT_OWNER_ID}
SSH_LINK_RE = re.compile(r"https://sshx\.io/[^\s\x1b<>]+")
UBUNTU_IMAGE_NAME = "noble-server-cloudimg-amd64.img"
UBUNTU_IMAGE_URL = f"https://cloud-images.ubuntu.com/noble/current/{UBUNTU_IMAGE_NAME}"
UBUNTU_SHA256_URL = "https://cloud-images.ubuntu.com/noble/current/SHA256SUMS"
def read_json(path: Path, fallback):
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return fallback
def write_json(path: Path, value) -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(json.dumps(value, indent=2), encoding="utf-8")
temporary.replace(path)
class LocalKVM:
def __init__(self):
self.uri = os.getenv("LIBVIRT_URI", "qemu:///system")
base_image = os.getenv("LOCAL_BASE_IMAGE", "").strip()
if base_image == "/absolute/path/to/cloud-init-enabled-linux-image.img":
base_image = ""
self.use_default_image = not base_image
self.base_image = (
Path(base_image).expanduser().resolve()
if base_image
else (DATA_DIR / "cloud-images" / UBUNTU_IMAGE_NAME).resolve()
)
self.vm_dir = Path(os.getenv("LOCAL_VM_DIR", "./vps-data")).expanduser().resolve()
self.network = os.getenv("LOCAL_NETWORK", "default")
self.username = os.getenv("SSH_USERNAME", "ubuntu")
async def ensure_base_image(self) -> None:
if self.base_image.is_file():
return
if not self.use_default_image:
raise RuntimeError(f"Configured LOCAL_BASE_IMAGE file nahi mili: {self.base_image}")
log.info("Downloading verified Ubuntu 24.04 cloud image to %s", self.base_image)
await asyncio.to_thread(self.download_default_image)
def download_default_image(self) -> None:
self.base_image.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(UBUNTU_SHA256_URL, timeout=60) as response:
checksums = response.read().decode("utf-8")
expected = next(
(line.split()[0] for line in checksums.splitlines()
if len(line.split()) >= 2 and line.split()[-1].lstrip("*") == UBUNTU_IMAGE_NAME),
None,
)
if not expected:
raise RuntimeError("Ubuntu image ke liye SHA256 checksum nahi mila.")
temporary = self.base_image.with_suffix(self.base_image.suffix + ".part")
digest = hashlib.sha256()
try:
with urllib.request.urlopen(UBUNTU_IMAGE_URL, timeout=60) as response, temporary.open("wb") as image:
while chunk := response.read(1024 * 1024):
digest.update(chunk)
image.write(chunk)
if digest.hexdigest() != expected:
raise RuntimeError("Downloaded Ubuntu image ka SHA256 checksum match nahi hua.")
temporary.replace(self.base_image)
finally:
temporary.unlink(missing_ok=True)
async def run(self, *args: str, timeout: int = 120) -> str:
try:
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
except FileNotFoundError as exc:
if args[0] == "qemu-img":
raise RuntimeError(
"qemu-img install nahi hai ya PATH mein nahi mila. Ubuntu/Debian par "
"`sudo apt update && sudo apt install -y qemu-utils` chalayein, "
"phir bot restart karein."
) from exc
raise RuntimeError(f"Required command `{args[0]}` install nahi hai ya PATH mein nahi mila.") from exc
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except TimeoutError:
process.kill()
await process.wait()
raise TimeoutError(f"Command timed out: {args[0]}")
if process.returncode:
detail = stderr.decode(errors="replace").strip() or stdout.decode(errors="replace").strip()
raise RuntimeError(f"{args[0]} failed: {detail[:800]}")
return stdout.decode(errors="replace").strip()
async def virsh(self, *args: str, timeout: int = 120) -> str:
return await self.run("virsh", "-c", self.uri, *args, timeout=timeout)
def check_capacity(self, ram_gib: int, vcpu: int, storage_gib: int, state: dict) -> None:
entries = list(state.values())
used_ram = sum(int(entry.get("ram_gib", 0)) for entry in entries)
used_storage = sum(int(entry.get("storage_gib", 0)) for entry in entries)
host_ram_gib = psutil.virtual_memory().total // (1024 ** 3)
self.vm_dir.mkdir(parents=True, exist_ok=True)
free_disk_gib = shutil.disk_usage(self.vm_dir).free // (1024 ** 3)
if used_ram + ram_gib > max(0, host_ram_gib - 2):
raise RuntimeError(f"Local node par enough RAM nahi hai. Host RAM: {host_ram_gib} GiB; 2 GiB host reserve rakha gaya hai.")
if used_storage + storage_gib > free_disk_gib:
raise RuntimeError(f"Local node par requested storage ke liye enough free disk nahi hai ({free_disk_gib} GiB free).")
async def create_vm(self, vmid: int, name: str, ram_gib: int, vcpu: int, storage_gib: int) -> str:
if not self.base_image.is_file():
raise RuntimeError(f"Base cloud image nahi mili: {self.base_image}")
public_key = os.getenv("SSH_PUBLIC_KEY", "").strip()
if not public_key:
raise RuntimeError("VM banane ke liye .env mein SSH_PUBLIC_KEY configure karein.")
self.vm_dir.mkdir(parents=True, exist_ok=True)
slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", name).strip("-_").lower()[:24] or "server"
domain = f"kodari-{vmid}-{slug}"
disk_path = self.vm_dir / f"{domain}.qcow2"
seed_path = self.vm_dir / f"{domain}-seed.iso"
user_data_path = self.vm_dir / f"{domain}-user-data"
meta_data_path = self.vm_dir / f"{domain}-meta-data"
xml_path = self.vm_dir / f"{domain}.xml"
defined = False
try:
image_info = json.loads(await self.run("qemu-img", "info", "--output=json", str(self.base_image)))
await self.run(
"qemu-img", "create", "-f", "qcow2", "-F", image_info["format"],
"-b", str(self.base_image), str(disk_path), f"{storage_gib}G",
)
user_data_path.write_text(
"#cloud-config\n"
f"hostname: {json.dumps(domain)}\n"
"users:\n - default\n"
f" - name: {json.dumps(self.username)}\n"
" groups: [sudo]\n shell: /bin/bash\n"
" sudo: [\"ALL=(ALL) NOPASSWD:ALL\"]\n"
" lock_passwd: true\n ssh_authorized_keys:\n"
f" - {json.dumps(public_key)}\n"
"ssh_pwauth: false\n",
encoding="utf-8",
)
meta_data_path.write_text(
f"instance-id: kodari-{vmid}\nlocal-hostname: {domain}\n", encoding="utf-8"
)
await self.run("cloud-localds", str(seed_path), str(user_data_path), str(meta_data_path))
self.vm_dir.mkdir(parents=True, exist_ok=True)
disk_xml = escape(str(disk_path))
seed_xml = escape(str(seed_path))
network_xml = escape(self.network)
xml_path.write_text(
f"<domain type='kvm'><name>{domain}</name>"
f"<memory unit='MiB'>{ram_gib * 1024}</memory>"
f"<currentMemory unit='MiB'>{ram_gib * 1024}</currentMemory>"
f"<vcpu placement='static'>{vcpu}</vcpu>"
"<os><type arch='x86_64' machine='q35'>hvm</type><boot dev='hd'/></os>"
"<features><acpi/><apic/></features><cpu mode='host-passthrough'/>"
"<devices>"
f"<disk type='file' device='disk'><driver name='qemu' type='qcow2'/>"
f"<source file='{disk_xml}'/><target dev='vda' bus='virtio'/></disk>"
f"<disk type='file' device='cdrom'><driver name='qemu' type='raw'/>"
f"<source file='{seed_xml}'/><target dev='sda' bus='sata'/><readonly/></disk>"
f"<interface type='network'><source network='{network_xml}'/><model type='virtio'/></interface>"
"<graphics type='none'/><console type='pty'><target type='serial' port='0'/></console>"
"<serial type='pty'><target port='0'/></serial></devices></domain>",
encoding="utf-8",
)
await self.virsh("define", str(xml_path))
defined = True
await self.virsh("start", domain)