Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,280 +1,159 @@
|
|
| 1 |
-
import os
|
| 2 |
import subprocess
|
| 3 |
import threading
|
| 4 |
import time
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
from datetime import datetime
|
| 9 |
-
from fastapi import FastAPI
|
| 10 |
-
from fastapi.responses import HTMLResponse, JSONResponse
|
| 11 |
-
import uvicorn
|
| 12 |
-
|
| 13 |
-
app = FastAPI()
|
| 14 |
|
| 15 |
-
|
| 16 |
-
SERVER_VERSION = os.getenv("SERVER_VERSION", "1.20.4")
|
| 17 |
-
MAX_RAM = os.getenv("MAX_RAM", "10G")
|
| 18 |
-
MIN_RAM = os.getenv("MIN_RAM", "2G")
|
| 19 |
-
PORT = int(os.getenv("PORT", "7860"))
|
| 20 |
-
SERVER_PORT = int(os.getenv("SERVER_PORT", "25565"))
|
| 21 |
-
RCON_PASSWORD = os.getenv("RCON_PASSWORD", "minecraft")
|
| 22 |
-
MC_PATH = os.getenv("MINECRAFT_PATH", "/data/minecraft")
|
| 23 |
-
BACKUP_PATH = os.getenv("BACKUP_PATH", "/data/backups")
|
| 24 |
-
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 25 |
-
HF_DATASET_REPO = os.getenv("HF_DATASET_REPO", "") # e.g. "username/mc-world-backup"
|
| 26 |
-
SPACE_URL = os.getenv("SPACE_URL", "") # e.g. "https://yourname-spacename.hf.space"
|
| 27 |
|
|
|
|
| 28 |
mc_process = None
|
| 29 |
-
|
| 30 |
-
start_time = None
|
| 31 |
-
|
| 32 |
-
# โโ helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
|
| 36 |
-
entry = f"[{ts}] {msg}"
|
| 37 |
-
server_log.append(entry)
|
| 38 |
-
if len(server_log) > 500:
|
| 39 |
-
server_log.pop(0)
|
| 40 |
-
print(entry)
|
| 41 |
-
|
| 42 |
-
def setup_dirs():
|
| 43 |
-
os.makedirs(MC_PATH, exist_ok=True)
|
| 44 |
-
os.makedirs(BACKUP_PATH, exist_ok=True)
|
| 45 |
-
|
| 46 |
-
def download_paper():
|
| 47 |
-
jar = os.path.join(MC_PATH, "server.jar")
|
| 48 |
-
if os.path.exists(jar):
|
| 49 |
-
log("server.jar already present, skipping download")
|
| 50 |
-
return
|
| 51 |
-
log(f"Downloading Paper {SERVER_VERSION}...")
|
| 52 |
-
url = f"https://api.papermc.io/v2/projects/paper/versions/{SERVER_VERSION}/builds"
|
| 53 |
-
try:
|
| 54 |
-
builds = requests.get(url, timeout=30).json()["builds"]
|
| 55 |
-
latest = builds[-1]
|
| 56 |
-
build_num = latest["build"]
|
| 57 |
-
jar_name = latest["downloads"]["application"]["name"]
|
| 58 |
-
dl_url = (f"https://api.papermc.io/v2/projects/paper/versions/{SERVER_VERSION}"
|
| 59 |
-
f"/builds/{build_num}/downloads/{jar_name}")
|
| 60 |
-
r = requests.get(dl_url, stream=True, timeout=120)
|
| 61 |
-
with open(jar, "wb") as f:
|
| 62 |
-
for chunk in r.iter_content(8192):
|
| 63 |
-
f.write(chunk)
|
| 64 |
-
log("Paper downloaded successfully")
|
| 65 |
-
except Exception as e:
|
| 66 |
-
log(f"Download failed: {e}")
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
if not os.path.exists(props_path):
|
| 75 |
-
with open(props_path, "w") as f:
|
| 76 |
-
f.write(f"""server-port={SERVER_PORT}
|
| 77 |
-
online-mode=false
|
| 78 |
-
difficulty=normal
|
| 79 |
-
gamemode=survival
|
| 80 |
-
max-players=20
|
| 81 |
-
enable-rcon=true
|
| 82 |
-
rcon.port=25575
|
| 83 |
-
rcon.password={RCON_PASSWORD}
|
| 84 |
-
view-distance=8
|
| 85 |
-
simulation-distance=6
|
| 86 |
-
""")
|
| 87 |
|
| 88 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
setup_dirs()
|
| 93 |
-
download_paper()
|
| 94 |
-
write_configs()
|
| 95 |
-
jar = os.path.join(MC_PATH, "server.jar")
|
| 96 |
-
cmd = [
|
| 97 |
-
"java",
|
| 98 |
-
f"-Xms{MIN_RAM}", f"-Xmx{MAX_RAM}",
|
| 99 |
-
"-XX:+UseG1GC",
|
| 100 |
-
"-XX:+ParallelRefProcEnabled",
|
| 101 |
-
"-XX:MaxGCPauseMillis=200",
|
| 102 |
-
"-jar", jar, "nogui"
|
| 103 |
-
]
|
| 104 |
-
log("Starting Minecraft server...")
|
| 105 |
mc_process = subprocess.Popen(
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
)
|
| 110 |
-
start_time = datetime.now()
|
| 111 |
-
# stream stdout
|
| 112 |
-
def read_output():
|
| 113 |
-
for line in mc_process.stdout:
|
| 114 |
-
server_log.append(line.rstrip())
|
| 115 |
-
if len(server_log) > 500:
|
| 116 |
-
server_log.pop(0)
|
| 117 |
-
threading.Thread(target=read_output, daemon=True).start()
|
| 118 |
-
|
| 119 |
-
def stop_server():
|
| 120 |
-
global mc_process
|
| 121 |
-
if mc_process and mc_process.poll() is None:
|
| 122 |
-
mc_process.terminate()
|
| 123 |
-
mc_process.wait(timeout=30)
|
| 124 |
-
mc_process = None
|
| 125 |
-
log("Server stopped")
|
| 126 |
-
|
| 127 |
-
def is_running():
|
| 128 |
-
return mc_process is not None and mc_process.poll() is None
|
| 129 |
-
|
| 130 |
-
# โโ watchdog โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 131 |
-
|
| 132 |
-
def watchdog():
|
| 133 |
-
"""Restart the server if it crashes."""
|
| 134 |
-
time.sleep(60) # give initial start time
|
| 135 |
-
while True:
|
| 136 |
-
time.sleep(30)
|
| 137 |
-
if not is_running() and start_time is not None:
|
| 138 |
-
log("โ ๏ธ Server not running โ auto-restarting...")
|
| 139 |
-
start_server()
|
| 140 |
-
|
| 141 |
-
# โโ self-ping keepalive โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 142 |
|
| 143 |
-
def keepalive():
|
| 144 |
-
"""Ping our own /health every 25 min to prevent HF sleep."""
|
| 145 |
-
time.sleep(120)
|
| 146 |
-
while True:
|
| 147 |
-
if SPACE_URL:
|
| 148 |
-
try:
|
| 149 |
-
requests.get(f"{SPACE_URL}/health", timeout=10)
|
| 150 |
-
log("keepalive ping sent")
|
| 151 |
-
except Exception:
|
| 152 |
-
pass
|
| 153 |
-
time.sleep(25 * 60)
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
#
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
<
|
| 216 |
-
<
|
| 217 |
-
<
|
| 218 |
-
<
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
<div class="card">
|
| 245 |
-
<b>Server Logs</b>
|
| 246 |
-
<pre>{logs_html}</pre>
|
| 247 |
-
</div>
|
| 248 |
-
</body></html>"""
|
| 249 |
-
|
| 250 |
-
@app.get("/health")
|
| 251 |
-
async def health():
|
| 252 |
-
return JSONResponse({"status": "running" if is_running() else "stopped", "uptime_ok": True})
|
| 253 |
-
|
| 254 |
-
@app.post("/start")
|
| 255 |
-
async def api_start():
|
| 256 |
-
if not is_running():
|
| 257 |
-
threading.Thread(target=start_server, daemon=True).start()
|
| 258 |
-
from fastapi.responses import RedirectResponse
|
| 259 |
-
return RedirectResponse("/", status_code=303)
|
| 260 |
-
|
| 261 |
-
@app.post("/stop")
|
| 262 |
-
async def api_stop():
|
| 263 |
-
stop_server()
|
| 264 |
-
from fastapi.responses import RedirectResponse
|
| 265 |
-
return RedirectResponse("/", status_code=303)
|
| 266 |
-
|
| 267 |
-
@app.post("/backup")
|
| 268 |
-
async def api_backup():
|
| 269 |
-
threading.Thread(target=backup_world, daemon=True).start()
|
| 270 |
-
from fastapi.responses import RedirectResponse
|
| 271 |
-
return RedirectResponse("/", status_code=303)
|
| 272 |
-
|
| 273 |
-
@app.get("/logs")
|
| 274 |
-
async def api_logs():
|
| 275 |
-
return JSONResponse({"logs": server_log[-100:]})
|
| 276 |
-
|
| 277 |
-
# โโ main โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 278 |
|
| 279 |
if __name__ == "__main__":
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import subprocess
|
| 2 |
import threading
|
| 3 |
import time
|
| 4 |
+
import os
|
| 5 |
+
import socket
|
| 6 |
+
from flask import Flask, jsonify
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# โโ Minecraft process handle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 11 |
mc_process = None
|
| 12 |
+
mc_start_time = None
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
def start_minecraft():
|
| 15 |
+
global mc_process, mc_start_time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Start Tailscale daemon
|
| 18 |
+
subprocess.Popen(
|
| 19 |
+
["tailscaled", "--tun=userspace-networking", "--socks5-server=localhost:1055"],
|
| 20 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
| 21 |
+
)
|
| 22 |
+
time.sleep(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# Authenticate Tailscale (only if authkey provided)
|
| 25 |
+
authkey = os.environ.get("TAILSCALE_AUTHKEY", "")
|
| 26 |
+
if authkey:
|
| 27 |
+
subprocess.run(["tailscale", "up", "--authkey", authkey],
|
| 28 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 29 |
|
| 30 |
+
# Launch Minecraft with Aikar's flags
|
| 31 |
+
mc_start_time = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
mc_process = subprocess.Popen(
|
| 33 |
+
[
|
| 34 |
+
"java",
|
| 35 |
+
"-Xmx4G", "-Xms4G",
|
| 36 |
+
"-XX:+UseG1GC",
|
| 37 |
+
"-XX:+ParallelRefProcEnabled",
|
| 38 |
+
"-XX:MaxGCPauseMillis=200",
|
| 39 |
+
"-XX:+UnlockExperimentalVMOptions",
|
| 40 |
+
"-XX:+DisableExplicitGC",
|
| 41 |
+
"-XX:+AlwaysPreTouch",
|
| 42 |
+
"-XX:G1NewSizePercent=30",
|
| 43 |
+
"-XX:G1MaxNewSizePercent=40",
|
| 44 |
+
"-XX:G1HeapRegionSize=8M",
|
| 45 |
+
"-XX:G1ReservePercent=20",
|
| 46 |
+
"-XX:G1HeapWastePercent=5",
|
| 47 |
+
"-XX:G1MixedGCCountTarget=4",
|
| 48 |
+
"-XX:InitiatingHeapOccupancyPercent=15",
|
| 49 |
+
"-XX:G1MixedGCLiveThresholdPercent=90",
|
| 50 |
+
"-XX:G1RSetUpdatingPauseTimePercent=5",
|
| 51 |
+
"-XX:SurvivorRatio=32",
|
| 52 |
+
"-XX:+PerfDisableSharedMem",
|
| 53 |
+
"-XX:MaxTenuringThreshold=1",
|
| 54 |
+
"-Dusing.aikars.flags=https://mcflags.emc.gs",
|
| 55 |
+
"-Daikars.new.flags=true",
|
| 56 |
+
"-jar", "paper.jar", "nogui"
|
| 57 |
+
],
|
| 58 |
+
cwd="/minecraft",
|
| 59 |
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
|
| 60 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
def is_minecraft_port_open():
|
| 64 |
+
"""Check if Minecraft port 25565 is accepting connections."""
|
| 65 |
+
try:
|
| 66 |
+
with socket.create_connection(("127.0.0.1", 25565), timeout=2):
|
| 67 |
+
return True
|
| 68 |
+
except OSError:
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_uptime():
|
| 73 |
+
if mc_start_time is None:
|
| 74 |
+
return "Not started"
|
| 75 |
+
elapsed = int(time.time() - mc_start_time)
|
| 76 |
+
h, m, s = elapsed // 3600, (elapsed % 3600) // 60, elapsed % 60
|
| 77 |
+
return f"{h}h {m}m {s}s"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# โโ Routes โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 81 |
+
|
| 82 |
+
@app.route("/")
|
| 83 |
+
def index():
|
| 84 |
+
mc_alive = mc_process is not None and mc_process.poll() is None
|
| 85 |
+
port_open = is_minecraft_port_open()
|
| 86 |
+
status = "๐ข Running" if mc_alive else "๐ด Stopped"
|
| 87 |
+
port_status = "๐ข Open" if port_open else "๐ก Startingโฆ"
|
| 88 |
+
|
| 89 |
+
html = f"""<!DOCTYPE html>
|
| 90 |
+
<html lang="en">
|
| 91 |
+
<head>
|
| 92 |
+
<meta charset="UTF-8">
|
| 93 |
+
<meta http-equiv="refresh" content="30">
|
| 94 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 95 |
+
<title>Minecraft Server Status</title>
|
| 96 |
+
<style>
|
| 97 |
+
body {{
|
| 98 |
+
font-family: 'Segoe UI', sans-serif;
|
| 99 |
+
background: #1a1a2e; color: #eee;
|
| 100 |
+
display: flex; align-items: center; justify-content: center;
|
| 101 |
+
min-height: 100vh; margin: 0;
|
| 102 |
+
}}
|
| 103 |
+
.card {{
|
| 104 |
+
background: #16213e; border-radius: 16px;
|
| 105 |
+
padding: 40px 50px; text-align: center;
|
| 106 |
+
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
| 107 |
+
max-width: 480px; width: 90%;
|
| 108 |
+
}}
|
| 109 |
+
h1 {{ margin: 0 0 8px; font-size: 1.8rem; color: #e94560; }}
|
| 110 |
+
.subtitle {{ color: #888; margin-bottom: 28px; font-size: 0.95rem; }}
|
| 111 |
+
.row {{ display: flex; justify-content: space-between;
|
| 112 |
+
padding: 12px 0; border-bottom: 1px solid #0f3460; }}
|
| 113 |
+
.row:last-child {{ border-bottom: none; }}
|
| 114 |
+
.label {{ color: #aaa; }}
|
| 115 |
+
.value {{ font-weight: 600; }}
|
| 116 |
+
.footer {{ margin-top: 24px; font-size: 0.8rem; color: #555; }}
|
| 117 |
+
</style>
|
| 118 |
+
</head>
|
| 119 |
+
<body>
|
| 120 |
+
<div class="card">
|
| 121 |
+
<h1>โ Minecraft Server</h1>
|
| 122 |
+
<p class="subtitle">Paper 1.21.11 | Auto-refreshes every 30s</p>
|
| 123 |
+
<div class="row"><span class="label">Process</span><span class="value">{status}</span></div>
|
| 124 |
+
<div class="row"><span class="label">Port 25565</span><span class="value">{port_status}</span></div>
|
| 125 |
+
<div class="row"><span class="label">Uptime</span><span class="value">{get_uptime()}</span></div>
|
| 126 |
+
<div class="row"><span class="label">Version</span><span class="value">Paper 1.21.11</span></div>
|
| 127 |
+
<p class="footer">Connect via your Tailscale IP on port 25565</p>
|
| 128 |
+
</div>
|
| 129 |
+
</body>
|
| 130 |
+
</html>"""
|
| 131 |
+
return html
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@app.route("/health")
|
| 135 |
+
def health():
|
| 136 |
+
"""Hugging Face health-check endpoint โ always returns 200."""
|
| 137 |
+
return jsonify({"status": "ok"}), 200
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@app.route("/api/status")
|
| 141 |
+
def api_status():
|
| 142 |
+
mc_alive = mc_process is not None and mc_process.poll() is None
|
| 143 |
+
return jsonify({
|
| 144 |
+
"minecraft_running": mc_alive,
|
| 145 |
+
"port_open": is_minecraft_port_open(),
|
| 146 |
+
"uptime": get_uptime(),
|
| 147 |
+
"version": "Paper 1.21.11"
|
| 148 |
+
})
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# โโ Entry point โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
| 154 |
+
# Start Minecraft in a background thread so Flask starts immediately
|
| 155 |
+
t = threading.Thread(target=start_minecraft, daemon=True)
|
| 156 |
+
t.start()
|
| 157 |
+
|
| 158 |
+
# Flask must bind 0.0.0.0:7860 for Hugging Face Spaces
|
| 159 |
+
app.run(host="0.0.0.0", port=7860, threaded=True)
|