{ "cells": [ { "id": "md-intro", "cell_type": "markdown", "metadata": {}, "source": [ "# 🎮 GPU Cloud Server — Cloud Gaming + Treo Bot trên Kaggle / Google Colab\n", "\n", "\"Open\n", "\"Open\n", "\"GitHub\"/\n", "\n", "Biến notebook thành **máy chủ GPU đám mây hoàn chỉnh trong trình duyệt**: desktop ảo chơi game (noVNC), web terminal, dashboard realtime (GPU/CPU/RAM), treo bot Discord/Telegram/… — kết nối internet qua **Cloudflare Tunnel**, không cần domain.\n", "\n", "## ⚡ Bắt đầu — chỉ 2 ô code\n", "\n", "| Ô | Làm gì | Thời gian |\n", "|---|---|---|\n", "| **Bước 1** · Auto Setup | Cài desktop XFCE + x11vnc + noVNC + ttyd + cloudflared + aiohttp | ~2–4 phút |\n", "| **Bước 2** · Khởi động | Chạy server, tạo 3 tunnel Cloudflare, in URL public → **giữ ô chạy** | ~30 giây |\n", "\n", "**Yêu cầu:**\n", "- ✅ Colab: `Runtime → Change runtime type → GPU`\n", "- ✅ Kaggle: `Settings → Accelerator → GPU` **và** `Internet → ON`\n", "\n", "**Sau khi Bước 2 chạy xong** bạn sẽ thấy:\n", "\n", "```\n", "══════════════════════════════════════════════════════════\n", " 🎮 GPU CLOUD SERVER ĐANG CHẠY — GIỮ Ô NÀY CHẠY LIÊN TỤC!\n", " 📊 Dashboard https://xxx.trycloudflare.com/?key=…\n", " 🖥️ Cloud Desktop https://yyy.trycloudflare.com/vnc.html?…\n", " ⌨️ Web Terminal https://zzz.trycloudflare.com\n", "══════════════════════════════════════════════════════════\n", "```\n", "\n", "Mở **Dashboard URL** trên bất kỳ thiết bị nào → gặp giao diện quản trị đẹp: Tổng quan · Cloud Gaming · Bots · Files · Hướng dẫn.\n", "\n", "> ⚠️ **Disclaimer:** dùng cho mục đích học tập/thử nghiệm. Chạy game / remote desktop / bot nền dài hạn có thể vi phạm ToS của Colab & Kaggle — tự chịu rủi ro tài khoản.\n" ] }, { "id": "cell-setup", "cell_type": "code", "metadata": {}, "source": [ "#@title 🚀 Bước 1 · Tự động cài đặt môi trường (Desktop + VNC + Tunnel) { display-mode: \"form\" }\n", "# ⚠️ Colab : Runtime → Change runtime type → GPU (T4 / L4)\n", "# ⚠️ Kaggle: Settings → Accelerator → GPU và Internet → ON\n", "import os, sys, json, time, platform, shutil, subprocess, urllib.request, pathlib\n", "\n", "W = \"─\" * 56\n", "def head(t): print(f\"\\n┌{W}\\n {t}\\n└{W}\")\n", "def sh(cmd, timeout=None):\n", " p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)\n", " return p.returncode, ((p.stdout or \"\") + (p.stderr or \"\"))\n", "def have(c): return shutil.which(c) is not None\n", "\n", "# ── Phát hiện môi trường ──────────────────────────────────────────────\n", "IS_KAGGLE = bool(os.environ.get(\"KAGGLE_KERNEL_RUN_TYPE\")) or os.path.exists(\"/kaggle\")\n", "try:\n", " import google.colab # noqa\n", " IS_COLAB = True\n", "except Exception:\n", " IS_COLAB = os.path.exists(\"/content\") and not IS_KAGGLE\n", "ENV_NAME = \"Google Colab\" if IS_COLAB else (\"Kaggle\" if IS_KAGGLE else \"Local\")\n", "\n", "head(f\"🖥️ Môi trường: {ENV_NAME} · Python {platform.python_version()} · {platform.machine()}\")\n", "\n", "# ── Kiểm tra GPU ──────────────────────────────────────────────────────\n", "head(\"🎮 Kiểm tra GPU\")\n", "if have(\"nvidia-smi\"):\n", " rc, out = sh(\"nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader\")\n", " print(\" ✅ GPU:\", out.strip().replace(\"\\n\", \" | \") or \"n/a\")\n", "else:\n", " print(\" ⚠️ Không thấy NVIDIA GPU!\")\n", " print(\" • Colab : Runtime → Change runtime type → GPU (T4 / L4)\")\n", " print(\" • Kaggle: Settings → Accelerator → GPU T4 x2 / P100\")\n", " print(\" (vẫn chạy tiếp — nhưng gaming sẽ không có tăng tốc GPU)\")\n", "\n", "# ── Kiểm tra Internet ─────────────────────────────────────────────────\n", "head(\"🌐 Kiểm tra Internet\")\n", "try:\n", " urllib.request.urlopen(\"https://api.github.com\", timeout=10)\n", " print(\" ✅ Online\")\n", "except Exception as e:\n", " print(\" ❌ Offline! Trên Kaggle hãy bật: Settings → Internet → ON, rồi chạy lại ô này.\")\n", " raise SystemExit(1)\n", "\n", "root = os.geteuid() == 0\n", "SUDO = \"\" if (root or not have(\"sudo\")) else \"sudo -n \"\n", "LOCAL_BIN = str(pathlib.Path.home() / \".local\" / \"bin\")\n", "pathlib.Path(LOCAL_BIN).mkdir(parents=True, exist_ok=True)\n", "if LOCAL_BIN not in os.environ.get(\"PATH\", \"\"):\n", " os.environ[\"PATH\"] += os.pathsep + LOCAL_BIN\n", "\n", "# ── apt: desktop + vnc ────────────────────────────────────────────────\n", "APT = (\"xvfb x11vnc novnc websockify dbus-x11 x11-xserver-utils xterm xfonts-base \"\n", " \"xfce4 xfce4-terminal net-tools\")\n", "head(\"📦 Cài Desktop XFCE + x11vnc + noVNC (apt) — mất 1–3 phút, đừng tắt\")\n", "if have(\"apt-get\"):\n", " rc, out = sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get update -y\", timeout=300)\n", " rc2, out2 = sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends {APT}\", timeout=1200)\n", " ok = rc2 == 0 and have(\"x11vnc\") and have(\"websockify\") and have(\"Xvfb\")\n", " print(\" ✅ Desktop + VNC OK\" if ok else f\" ⚠️ apt exit={rc2} (một số gói thiếu — có thể vẫn chạy được)\")\n", " if not ok:\n", " print(\"\\n\".join(\" \" + l for l in out2.strip().splitlines()[-12:]))\n", "else:\n", " print(\" ⚠️ Không có apt-get — sẽ chỉ chạy Dashboard / Bots / Terminal\")\n", "\n", "# ── pip: aiohttp ──────────────────────────────────────────────────────\n", "head(\"🐍 pip: aiohttp (server dashboard)\")\n", "rc, out = sh(f\"{sys.executable} -m pip install -q aiohttp\", timeout=300)\n", "print(\" ✅ aiohttp OK\" if rc == 0 else f\" ❌ pip lỗi:\\n{out[-400:]}\")\n", "\n", "# ── cloudflared ───────────────────────────────────────────────────────\n", "head(\"☁️ cloudflared (Cloudflare Tunnel — tạo URL public)\")\n", "CF = shutil.which(\"cloudflared\")\n", "if not CF:\n", " arch = {\"x86_64\": \"amd64\", \"aarch64\": \"arm64\", \"armv7l\": \"arm\"}.get(platform.machine(), \"amd64\")\n", " url = f\"https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-{arch}\"\n", " dst = \"/usr/local/bin/cloudflared\" if root else (pathlib.Path.home() / \".local/bin/cloudflared\").as_posix()\n", " try:\n", " print(f\" ⬇️ tải {url}\")\n", " urllib.request.urlretrieve(url, dst)\n", " os.chmod(dst, 0o755)\n", " CF = dst\n", " except Exception as e:\n", " print(\" ❌ Tải cloudflared thất bại:\", e)\n", "if CF:\n", " rc, out = sh(f\"{CF} --version\")\n", " print(f\" ✅ {out.strip()} → {CF}\")\n", "else:\n", " print(\" ⚠️ Không có cloudflared — Bước 2 vẫn chạy nhưng không có URL public\")\n", "\n", "# ── ttyd (web terminal) ───────────────────────────────────────────────\n", "head(\"⌨️ ttyd (Web Terminal trong trình duyệt)\")\n", "if have(\"ttyd\"):\n", " print(\" ✅ ttyd sẵn sàng\")\n", "else:\n", " if have(\"apt-get\"):\n", " sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get install -y ttyd\", timeout=300)\n", " if not have(\"ttyd\"):\n", " arch = {\"x86_64\": \"x86_64\", \"aarch64\": \"aarch64\"}.get(platform.machine())\n", " if arch:\n", " url = f\"https://github.com/tsl0922/ttyd/releases/download/1.7.7/ttyd.{arch}\"\n", " dst = \"/usr/local/bin/ttyd\" if root else (pathlib.Path.home() / \".local/bin/ttyd\").as_posix()\n", " try:\n", " print(f\" ⬇️ tải {url}\")\n", " urllib.request.urlretrieve(url, dst)\n", " os.chmod(dst, 0o755)\n", " except Exception as e:\n", " print(\" ❌ Tải ttyd thất bại:\", e)\n", " print(\" ✅ ttyd OK\" if have(\"ttyd\") else \" ⚠️ ttyd thiếu — Web Terminal sẽ bị tắt\")\n", "\n", "# ── thư mục làm việc ──────────────────────────────────────────────────\n", "HOME = pathlib.Path.home()\n", "for d in (\"gpu_server\", \"bots\", \"bot_logs\"):\n", " (HOME / d).mkdir(exist_ok=True)\n", "pathlib.Path(\"/tmp/tunnels.json\").write_text(\"{}\")\n", "\n", "head(\"✅ BƯỚC 1 HOÀN TẤT — giờ chạy ô 『Bước 2 · Khởi động Server + Tunnel』\")\n", "print(\" 💡 Giữ notebook đang chạy (không đóng tab) để server luôn online.\")\n" ], "execution_count": null, "outputs": [] }, { "id": "cell-dashboard", "cell_type": "code", "metadata": {}, "source": [ "%%writefile dashboard.py\n", "#!/usr/bin/env python3\n", "# -*- coding: utf-8 -*-\n", "# ═══════════════════════════════════════════════════════════════════\n", "# 🎮 GPU CLOUD SERVER · Dashboard Web (aiohttp, không cần framework khác)\n", "# Tab: Tổng quan · Cloud Gaming · Bots · Files · Hướng dẫn\n", "# Chạy được trên Google Colab / Kaggle / máy Linux bất kỳ.\n", "# Bảo mật bằng Access Key (biến môi trường DASH_TOKEN).\n", "# ═══════════════════════════════════════════════════════════════════\n", "import asyncio\n", "import json\n", "import os\n", "import pathlib\n", "import re\n", "import shutil\n", "import socket\n", "import subprocess\n", "import sys\n", "import threading\n", "import time\n", "from aiohttp import web\n", "\n", "HOME = pathlib.Path.home()\n", "BOTS_DIR = HOME / \"bots\"; BOTS_DIR.mkdir(parents=True, exist_ok=True)\n", "LOGS_DIR = HOME / \"bot_logs\"; LOGS_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "PORT = int(os.environ.get(\"DASH_PORT\", \"8080\"))\n", "TOKEN = os.environ.get(\"DASH_TOKEN\") or \"\"\n", "AUTH_ENABLED = bool(os.environ.get(\"DASH_TOKEN\"))\n", "TUNNELS_FILE = pathlib.Path(os.environ.get(\"TUNNELS_FILE\", \"/tmp/tunnels.json\"))\n", "\n", "BOTS = {} # name -> {\"proc\": Popen, \"started\": ts, \"log\": path, \"fh\": file}\n", "ACTIONS = {} # id -> {\"cmd\",\"out\",\"done\",\"rc\",\"t\"}\n", "GDIR = pathlib.Path(os.environ.get(\"GSERVER_DIR\", str(HOME / \"gpu_server\")))\n", "\n", "# ─────────────────────────── helpers ───────────────────────────\n", "def detect_env():\n", " if os.environ.get(\"KAGGLE_KERNEL_RUN_TYPE\") or os.path.exists(\"/kaggle\"):\n", " return \"Kaggle\"\n", " try:\n", " import google.colab # noqa\n", " return \"Google Colab\"\n", " except Exception:\n", " if os.path.exists(\"/content\"):\n", " return \"Google Colab\"\n", " return \"Local\"\n", "\n", "def human_time(s):\n", " s = int(s); h, r = divmod(s, 3600); m, _ = divmod(r, 60)\n", " return (f\"{h}h {m}m\" if h else f\"{m}m {s % 60}s\")\n", "\n", "def _read_cpu():\n", " with open(\"/proc/stat\") as f:\n", " parts = f.readline().split()\n", " vals = list(map(int, parts[1:8]))\n", " idle = vals[3] + (vals[4] if len(vals) > 4 else 0)\n", " return sum(vals), idle\n", "\n", "_cpu_prev = None\n", "def cpu_percent():\n", " global _cpu_prev\n", " if _cpu_prev is None:\n", " _cpu_prev = _read_cpu()\n", " time.sleep(0.15)\n", " cur = _read_cpu()\n", " dt = cur[0] - _cpu_prev[0]\n", " di = cur[1] - _cpu_prev[1]\n", " _cpu_prev = cur\n", " return round(100 * (1 - di / max(dt, 1)), 1)\n", "\n", "def mem_info():\n", " d = {}\n", " for line in open(\"/proc/meminfo\"):\n", " k, v = line.split(\":\")\n", " d[k.strip()] = int(v.strip().split()[0])\n", " total = d.get(\"MemTotal\", 0); avail = d.get(\"MemAvailable\", total)\n", " used = total - avail\n", " return {\"total_gb\": round(total / 1048576, 2),\n", " \"used_gb\": round(used / 1048576, 2),\n", " \"percent\": round(100 * used / max(total, 1), 1)}\n", "\n", "def gpu_info():\n", " if not shutil.which(\"nvidia-smi\"):\n", " return None\n", " try:\n", " out = subprocess.check_output(\n", " [\"nvidia-smi\", \"--query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu\",\n", " \"--format=csv,noheader,nounits\"], text=True, timeout=5)\n", " name, util, mu, mt, temp = [x.strip() for x in out.strip().splitlines()[0].split(\",\")]\n", " return {\"name\": name, \"util\": int(util or 0),\n", " \"mem_used_mb\": int(mu or 0), \"mem_total_mb\": int(mt or 0),\n", " \"temp\": int(temp or 0)}\n", " except Exception:\n", " return None\n", "\n", "def read_tunnels():\n", " try:\n", " return json.loads(TUNNELS_FILE.read_text())\n", " except Exception:\n", " return {}\n", "\n", "# ─────────────────────────── services status ───────────────────────────\n", "def _port_open(port, timeout=0.4):\n", " try:\n", " with socket.create_connection((\"127.0.0.1\", port), timeout=timeout):\n", " return True\n", " except OSError:\n", " return False\n", "\n", "def _proc_running(needle):\n", " me = os.getpid()\n", " for d in pathlib.Path(\"/proc\").iterdir():\n", " if not d.name.isdigit() or int(d.name) == me:\n", " continue\n", " try:\n", " cmd = (d / \"cmdline\").read_bytes().decode(\"utf-8\", \"ignore\").replace(\"\\x00\", \" \")\n", " except Exception:\n", " continue\n", " if needle in cmd:\n", " return True\n", " return False\n", "\n", "def _log_tail(fname, lines=12):\n", " f = GDIR / fname\n", " if not f.exists():\n", " return []\n", " try:\n", " return f.read_bytes()[-4096:].decode(\"utf-8\", \"ignore\").splitlines()[-lines:]\n", " except Exception:\n", " return []\n", "\n", "SERVICE_DEFS = [\n", " (\"xvfb\", \"🖥️ Desktop ảo (Xvfb)\", \"Xvfb\", None, \"xvfb.log\"),\n", " (\"xfce\", \"🪟 XFCE session\", \"xfce\", None, \"xfce4.log\"),\n", " (\"x11vnc\", \"🔗 VNC (x11vnc)\", \"x11vnc\", 5901, \"x11vnc.log\"),\n", " (\"websockify\", \"🌐 noVNC (websockify)\", \"websockify\", 6080, \"websockify.log\"),\n", " (\"ttyd\", \"⌨️ Terminal (ttyd)\", \"ttyd\", 7681, \"ttyd.log\"),\n", " (\"cloudflared\",\"☁️ Tunnel (cloudflared)\", \"cloudflared\", None, None),\n", "]\n", "\n", "def services_status():\n", " out = []\n", " for key, name, proc, port, logf in SERVICE_DEFS:\n", " out.append({\n", " \"key\": key, \"name\": name,\n", " \"running\": _proc_running(proc),\n", " \"port\": port,\n", " \"port_open\": _port_open(port) if port else None,\n", " \"log\": _log_tail(logf) if logf else [],\n", " })\n", " return out\n", "\n", "async def api_services(request):\n", " svcs = await asyncio.get_running_loop().run_in_executor(None, services_status)\n", " return web.json_response({\"services\": svcs})\n", "\n", "# ─────────────────────────── auth ───────────────────────────\n", "@web.middleware\n", "async def auth_mw(request, handler):\n", " if AUTH_ENABLED:\n", " key = request.query.get(\"key\") or request.cookies.get(\"gpu_key\") or request.headers.get(\"X-Key\")\n", " if key != TOKEN:\n", " return web.json_response({\"error\": \"unauthorized — thêm ?key= vào URL\"}, status=401)\n", " resp = await handler(request)\n", " if AUTH_ENABLED:\n", " try:\n", " resp.set_cookie(\"gpu_key\", TOKEN, httponly=True, samesite=\"Lax\", max_age=86400 * 7)\n", " except Exception:\n", " pass\n", " return resp\n", "\n", "# ─────────────────────────── API: stats / tunnels ───────────────────────────\n", "async def api_stats(request):\n", " disk = shutil.disk_usage(HOME)\n", " running = sum(1 for b in BOTS.values() if b[\"proc\"].poll() is None)\n", " return web.json_response({\n", " \"cpu\": cpu_percent(),\n", " \"load\": [round(x, 2) for x in os.getloadavg()],\n", " \"mem\": mem_info(),\n", " \"gpu\": await asyncio.get_running_loop().run_in_executor(None, gpu_info),\n", " \"disk\": {\"total_gb\": round(disk.total / 1e9, 1),\n", " \"used_gb\": round(disk.used / 1e9, 1),\n", " \"percent\": round(100 * disk.used / max(disk.total, 1), 1)},\n", " \"uptime_h\": human_time(float(open(\"/proc/uptime\").read().split()[0]) if os.path.exists(\"/proc/uptime\") else 0),\n", " \"python\": sys.version.split()[0],\n", " \"env\": detect_env(),\n", " \"bots_running\": running,\n", " })\n", "\n", "async def api_tunnels(request):\n", " t = read_tunnels()\n", " return web.json_response({\n", " \"tunnels\": t,\n", " \"local\": {\"dashboard\": f\"http://localhost:{PORT}\",\n", " \"desktop\": \"http://localhost:6080\",\n", " \"terminal\": \"http://localhost:7681\"},\n", " \"auth\": AUTH_ENABLED,\n", " })\n", "\n", "# ─────────────────────────── API: bots ───────────────────────────\n", "def bot_status(name):\n", " b = BOTS.get(name)\n", " if not b:\n", " return \"stopped\"\n", " rc = b[\"proc\"].poll()\n", " if rc is None:\n", " return \"running\"\n", " return f\"exited({rc})\"\n", "\n", "async def api_bots(request):\n", " items = []\n", " for p in sorted(BOTS_DIR.glob(\"*.py\")):\n", " name = p.stem\n", " b = BOTS.get(name)\n", " alive = b is not None and b[\"proc\"].poll() is None\n", " items.append({\n", " \"name\": name,\n", " \"status\": bot_status(name),\n", " \"pid\": b[\"proc\"].pid if alive else None,\n", " \"uptime\": human_time(time.time() - b[\"started\"]) if alive else \"\",\n", " \"size\": p.stat().st_size,\n", " \"has_env\": (BOTS_DIR / f\"{name}.env\").exists(),\n", " })\n", " return web.json_response({\"bots\": items})\n", "\n", "async def api_bots_upload(request):\n", " reader = await request.multipart()\n", " name, env_text, saved_name = None, \"\", None\n", " while True:\n", " part = await reader.next()\n", " if part is None:\n", " break\n", " if part.name == \"file\":\n", " fname = pathlib.Path(part.filename or \"bot.py\").name\n", " if not fname.endswith(\".py\"):\n", " fname += \".py\"\n", " data = b\"\"\n", " while True:\n", " chunk = await part.read_chunk(65536)\n", " if not chunk:\n", " break\n", " data += chunk\n", " (BOTS_DIR / fname).write_bytes(data)\n", " saved_name = fname[:-3]\n", " if not name:\n", " name = saved_name\n", " elif part.name == \"name\":\n", " requested = (await part.read()).decode().strip()\n", " if requested:\n", " name = re.sub(r\"[^A-Za-z0-9_.-]\", \"_\", requested)[:64]\n", " elif part.name == \"env\":\n", " env_text = (await part.read()).decode()\n", " if not saved_name or not name:\n", " return web.json_response({\"error\": \"thiếu file .py\"}, status=400)\n", " src = BOTS_DIR / f\"{saved_name}.py\"\n", " dst = BOTS_DIR / f\"{name}.py\"\n", " if src != dst:\n", " src.rename(dst)\n", " if env_text.strip():\n", " (BOTS_DIR / f\"{name}.env\").write_text(env_text)\n", " return web.json_response({\"ok\": True, \"name\": name})\n", "\n", "async def api_bot_start(request):\n", " name = request.match_info[\"name\"]\n", " script = BOTS_DIR / f\"{name}.py\"\n", " if not re.fullmatch(r\"[A-Za-z0-9_.-]+\", name) or not script.exists():\n", " return web.json_response({\"error\": \"bot không tồn tại\"}, status=404)\n", " if name in BOTS and BOTS[name][\"proc\"].poll() is None:\n", " return web.json_response({\"ok\": True, \"already\": True})\n", " env = dict(os.environ)\n", " envf = BOTS_DIR / f\"{name}.env\"\n", " if envf.exists():\n", " for line in envf.read_text().splitlines():\n", " line = line.strip()\n", " if line and not line.startswith(\"#\") and \"=\" in line:\n", " k, v = line.split(\"=\", 1)\n", " env[k.strip()] = v.strip().strip('\"').strip(\"'\")\n", " logf = LOGS_DIR / f\"{name}.log\"\n", " fh = open(logf, \"ab\", buffering=0)\n", " fh.write(f\"\\n══════ ▶ start {time.strftime('%Y-%m-%d %H:%M:%S')} ══════\\n\".encode())\n", " proc = subprocess.Popen([sys.executable, str(script)], stdout=fh, stderr=subprocess.STDOUT,\n", " stdin=subprocess.DEVNULL, env=env, cwd=str(BOTS_DIR),\n", " start_new_session=True)\n", " BOTS[name] = {\"proc\": proc, \"started\": time.time(), \"log\": logf, \"fh\": fh}\n", " return web.json_response({\"ok\": True, \"pid\": proc.pid})\n", "\n", "async def api_bot_stop(request):\n", " name = request.match_info[\"name\"]\n", " b = BOTS.get(name)\n", " if not b or b[\"proc\"].poll() is not None:\n", " return web.json_response({\"ok\": True, \"note\": \"không đang chạy\"})\n", " b[\"proc\"].terminate()\n", " try:\n", " b[\"proc\"].wait(timeout=4)\n", " except Exception:\n", " b[\"proc\"].kill()\n", " try:\n", " b[\"fh\"].close()\n", " except Exception:\n", " pass\n", " return web.json_response({\"ok\": True})\n", "\n", "async def api_bot_logs(request):\n", " name = request.match_info[\"name\"]\n", " lines = int(request.query.get(\"lines\", \"200\"))\n", " logf = LOGS_DIR / f\"{name}.log\"\n", " data = []\n", " if logf.exists():\n", " raw = logf.read_bytes()[-16384:].decode(\"utf-8\", \"replace\")\n", " data = raw.splitlines()[-lines:]\n", " return web.json_response({\"lines\": data, \"running\": bot_status(name) == \"running\"})\n", "\n", "async def api_bot_delete(request):\n", " name = request.match_info[\"name\"]\n", " if not re.fullmatch(r\"[A-Za-z0-9_.-]+\", name):\n", " return web.json_response({\"error\": \"tên không hợp lệ\"}, status=400)\n", " b = BOTS.pop(name, None)\n", " if b and b[\"proc\"].poll() is None:\n", " b[\"proc\"].terminate()\n", " for f in (BOTS_DIR / f\"{name}.py\", BOTS_DIR / f\"{name}.env\", LOGS_DIR / f\"{name}.log\"):\n", " try:\n", " f.unlink()\n", " except Exception:\n", " pass\n", " return web.json_response({\"ok\": True})\n", "\n", "# ─────────────────────────── API: files ───────────────────────────\n", "def safe_join(rel):\n", " home = HOME.resolve()\n", " if not rel:\n", " return home\n", " p = pathlib.Path(rel)\n", " q = p.resolve() if p.is_absolute() else (home / p).resolve()\n", " try:\n", " q.relative_to(home)\n", " except ValueError:\n", " raise web.HTTPForbidden(text=\"Đường dẫn nằm ngoài thư mục home\")\n", " return q\n", "\n", "async def api_files(request):\n", " p = safe_join(request.query.get(\"path\", \".\"))\n", " items = []\n", " for c in sorted(p.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):\n", " if c.name.startswith(\".\"):\n", " continue\n", " try:\n", " st = c.stat()\n", " items.append({\"name\": c.name, \"is_dir\": c.is_dir(), \"size\": st.st_size})\n", " except Exception:\n", " pass\n", " rel = str(p.relative_to(HOME))\n", " return web.json_response({\"path\": \"\" if rel == \".\" else rel, \"items\": items})\n", "\n", "async def api_files_download(request):\n", " p = safe_join(request.query.get(\"path\", \"\"))\n", " if not p.exists():\n", " return web.json_response({\"error\": \"file không tồn tại\"}, status=404)\n", " if p.is_dir():\n", " return web.json_response({\"error\": \"là thư mục — hãy nén trước\"}, status=400)\n", " return web.FileResponse(p, headers={\"Content-Disposition\": f'attachment; filename=\"{p.name}\"'})\n", "\n", "async def api_files_upload(request):\n", " reader = await request.multipart()\n", " dest, saved = \".\", None\n", " while True:\n", " part = await reader.next()\n", " if part is None:\n", " break\n", " if part.name == \"path\":\n", " dest = (await part.read()).decode().strip()\n", " elif part.name == \"file\":\n", " fname = pathlib.Path(part.filename or \"file.bin\").name\n", " data = b\"\"\n", " while True:\n", " chunk = await part.read_chunk(65536)\n", " if not chunk:\n", " break\n", " data += chunk\n", " saved = (fname, data)\n", " if not saved:\n", " return web.json_response({\"error\": \"thiếu file\"}, status=400)\n", " d = safe_join(dest)\n", " d.mkdir(parents=True, exist_ok=True)\n", " (d / saved[0]).write_bytes(saved[1])\n", " return web.json_response({\"ok\": True})\n", "\n", "async def api_files_delete(request):\n", " body = await request.json()\n", " p = safe_join(body.get(\"path\", \"\"))\n", " if p == HOME.resolve():\n", " return web.json_response({\"error\": \"không thể xóa home\"}, status=400)\n", " if p.is_dir():\n", " shutil.rmtree(p)\n", " else:\n", " p.unlink(missing_ok=True)\n", " return web.json_response({\"ok\": True})\n", "\n", "async def api_files_mkdir(request):\n", " body = await request.json()\n", " p = safe_join(body.get(\"path\", \"\"))\n", " p.mkdir(parents=True, exist_ok=True)\n", " return web.json_response({\"ok\": True})\n", "\n", "# ─────────────────────────── API: actions (quick commands) ───────────────────────────\n", "WHITELIST = {\n", " \"install_steam\": (\"dpkg --add-architecture i386 && apt-get update -y && \"\n", " \"DEBIAN_FRONTEND=noninteractive apt-get install -y steam || \"\n", " \"DEBIAN_FRONTEND=noninteractive apt-get install -y steam-installer\"),\n", " \"install_wine\": (\"dpkg --add-architecture i386 && apt-get update -y && \"\n", " \"DEBIAN_FRONTEND=noninteractive apt-get install -y wine wine64 winbind || \"\n", " \"DEBIAN_FRONTEND=noninteractive apt-get install -y wine\"),\n", " \"install_discord_py\": \"python3 -m pip install -U discord.py\",\n", " \"install_telegram\": \"python3 -m pip install -U pyTelegramBotAPI python-telegram-bot\",\n", " \"install_firefox\": \"DEBIAN_FRONTEND=noninteractive apt-get install -y firefox || \"\n", " \"DEBIAN_FRONTEND=noninteractive apt-get install -y firefox-esr chromium-browser\",\n", "}\n", "\n", "async def api_action(request):\n", " body = await request.json()\n", " act = body.get(\"action\")\n", " cmd = WHITELIST.get(act) or (body.get(\"cmd\") or \"\").strip()\n", " if not cmd:\n", " return web.json_response({\"error\": \"thiếu action/cmd\"}, status=400)\n", " aid = f\"{int(time.time() * 1000)}\"\n", " ACTIONS[aid] = {\"id\": aid, \"cmd\": cmd, \"out\": [], \"done\": False, \"rc\": None,\n", " \"t\": time.strftime(\"%H:%M:%S\")}\n", " def worker():\n", " try:\n", " env = dict(os.environ)\n", " env.setdefault(\"DISPLAY\", \":1\")\n", " env[\"DEBIAN_FRONTEND\"] = \"noninteractive\"\n", " proc = subprocess.Popen([\"bash\", \"-lc\", cmd], stdout=subprocess.PIPE,\n", " stderr=subprocess.STDOUT, text=True, bufsize=1, env=env)\n", " for line in proc.stdout:\n", " a = ACTIONS.get(aid)\n", " if a is not None:\n", " a[\"out\"].append(line.rstrip(\"\\n\"))\n", " a[\"out\"] = a[\"out\"][-400:]\n", " ACTIONS[aid][\"rc\"] = proc.wait()\n", " except Exception as e:\n", " ACTIONS[aid][\"out\"].append(f\"error: {e}\")\n", " ACTIONS[aid][\"done\"] = True\n", " threading.Thread(target=worker, daemon=True).start()\n", " return web.json_response({\"ok\": True, \"id\": aid})\n", "\n", "async def api_action_logs(request):\n", " out = []\n", " for aid in sorted(ACTIONS, reverse=True)[:12]:\n", " a = ACTIONS[aid]\n", " out.append({\"id\": aid, \"cmd\": a[\"cmd\"], \"t\": a[\"t\"], \"done\": a[\"done\"],\n", " \"rc\": a[\"rc\"], \"out\": a[\"out\"][-200:]})\n", " return web.json_response({\"actions\": out})\n", "\n", "# ─────────────────────────── HTML ───────────────────────────\n", "DASH_HTML = r'''\n", "\n", "\n", "🎮 GPU Cloud Server\n", "\n", "\n", "
\n", "
🎮 GPU CLOUD SERVER
\n", " \n", "
🔐 protected
\n", "
\n", "
\n", "\n", "
\n", "

📊 Tổng quan hệ thống

\n", "
\n", "

🎮 GPU

…
\n", "
util —
\n", "
vram —
\n", "
\n", "

🧠 CPU

—
\n", "

💾 RAM

—
\n", "

🗄️ Disk

—
\n", "
\n", "
…
\n", "

🌐 Public URLs (Cloudflare Tunnel)

\n", "
Dịch vụURL
\n", "

💡 URL tunnel là tạm thời — mỗi lần chạy lại notebook sẽ có URL mới.

\n", "
\n", "

⚙️ Dịch vụ nền

\n", " \n", "
Dịch vụTrạng tháiCổng
\n", "

❌ = chưa chạy. Nếu Cloud Desktop không vào được, bấm 📜 xem log từng dịch vụ để tìm nguyên nhân.

\n", "
\n", "
\n", "\n", "
\n", "
\n", "

🎮 Cloud Gaming — Desktop ảo trong trình duyệt

\n", "

Desktop XFCE chạy trên GPU VM, xem/điều khiển qua noVNC. Cài Steam/Wine rồi mở game ngay trong desktop.

\n", "
\n", " \n", " \n", " \n", "
\n", "
\n", "
\n", "

⚡ Hành động nhanh

\n", "
\n", " \n", " \n", " \n", " \n", " \n", "
\n", "
\n", " \n", " \n", "
\n", "
(log hành động…)
\n", "
\n", "

📈 Mẹo gaming mượt hơn

\n", "
    \n", "
  • Chơi game nhẹ / game cũ / emulator — noVNC truyền ảnh qua mạng nên game AAA sẽ lag.
  • \n", "
  • Trong desktop, giảm độ phân giải xuống 1280×720 sẽ mượt hơn đáng kể.
  • \n", "
  • Cài game bằng Steam trong Desktop (tab này chỉ cài phần mềm, mở game trong Desktop).
  • \n", "
  • Audio không truyền qua noVNC — dùng game không cần âm thanh hoặc cắm tai nghe tâm lý 🙂.
  • \n", "
\n", "
\n", "
\n", "\n", "
\n", "

🤖 Treo bot (Discord / Telegram / …)

\n", "
\n", " \n", "
BotTrạng tháiUptimeEnvHành động
\n", "
\n", "
\n", "

⬆️ Upload bot mới (.py + biến môi trường)

\n", "
\n", "
\n", " \n", " \n", "
\n", " \n", "
\n", " \n", " Sau khi lưu, bấm ▶ Start để chạy. Token nằm trong file .env, không in ra log.\n", "
\n", "
\n", "
\n", "
\n", "\n", "
\n", "

📁 Quản lý file

\n", "
\n", "
\n", " \n", " \n", " \n", " \n", " \n", "
\n", "
TênKích thước
\n", "

Home = thư mục user của VM (Colab: /root, Kaggle: /root). File bot nằm trong ~/bots.

\n", "
\n", "
\n", "\n", "
\n", "

❓ Hướng dẫn nhanh

\n", "
    \n", "
  • Cloud Gaming: tab 🎮 → Mở Cloud Desktop → trong desktop cài Steam (bấm nút Cài Steam trước) → đăng nhập → chơi game. Điều khiển bằng chuột/bàn phím của bạn.
  • \n", "
  • Treo bot: tab 🤖 → upload file .py + đặt token vào ô Env (KEY=VALUE) → Start. Xem log realtime bằng nút 📜.
  • \n", "
  • Web Terminal: tab 🎮 → Mở Web Terminal — bash đầy đủ trên VM (cài gì cũng được).
  • \n", "
  • Files: tab 📁 — upload/download/xoá file trong VM.
  • \n", "
  • Bảo mật: Dashboard yêu cầu access key trong URL (?key=…). Desktop/Terminal dùng tunnel riêng không có key — đừng chia sẻ URL công khai.
  • \n", "
  • Giữ server sống: không đóng tab notebook; Colab/Kaggle sẽ ngắt nếu bạn đóng hoặc quá idle quá lâu.
  • \n", "
\n", "
\n", "\n", "
\n", "\n", "
\n", "
Logs
\n", "
\n",
    "
\n", "
\n", "\n", "\n", "\n", "'''\n", "\n", "_index_cache = None\n", "async def index(request):\n", " global _index_cache\n", " if _index_cache is None:\n", " _index_cache = DASH_HTML.replace(\"__TOKEN__\", TOKEN)\n", " return web.Response(text=_index_cache, content_type=\"text/html\")\n", "\n", "async def api_health(request):\n", " return web.json_response({\"ok\": True, \"env\": detect_env(), \"port\": PORT})\n", "\n", "def build_app():\n", " app = web.Application(middlewares=[auth_mw], client_max_size=1024 ** 3)\n", " app.router.add_get(\"/\", index)\n", " app.router.add_get(\"/api/health\", api_health)\n", " app.router.add_get(\"/api/stats\", api_stats)\n", " app.router.add_get(\"/api/tunnels\", api_tunnels)\n", " app.router.add_get(\"/api/services\", api_services)\n", " app.router.add_get(\"/api/bots\", api_bots)\n", " app.router.add_post(\"/api/bots/upload\", api_bots_upload)\n", " app.router.add_post(\"/api/bots/{name}/start\", api_bot_start)\n", " app.router.add_post(\"/api/bots/{name}/stop\", api_bot_stop)\n", " app.router.add_get(\"/api/bots/{name}/logs\", api_bot_logs)\n", " app.router.add_post(\"/api/bots/{name}/delete\", api_bot_delete)\n", " app.router.add_get(\"/api/files\", api_files)\n", " app.router.add_get(\"/api/files/download\", api_files_download)\n", " app.router.add_post(\"/api/files/upload\", api_files_upload)\n", " app.router.add_post(\"/api/files/delete\", api_files_delete)\n", " app.router.add_post(\"/api/files/mkdir\", api_files_mkdir)\n", " app.router.add_post(\"/api/action\", api_action)\n", " app.router.add_get(\"/api/action/logs\", api_action_logs)\n", " return app\n", "\n", "if __name__ == \"__main__\":\n", " print(f\"🎮 GPU Cloud Server dashboard · port {PORT} · auth={'ON' if AUTH_ENABLED else 'OFF'} · env={detect_env()}\")\n", " web.run_app(build_app(), host=\"0.0.0.0\", port=PORT, print=lambda *a: None, access_log=None)\n" ], "execution_count": null, "outputs": [] }, { "id": "cell-run", "cell_type": "code", "metadata": {}, "source": [ "#@title 🎮 Bước 2 · Khởi động GPU Web Server + Cloudflare Tunnel { display-mode: \"form\" }\n", "# ▶ GIỮ Ô NÀY CHẠY LIÊN TỤC — đây là nơi server sống. URL public sẽ in ra dưới đây.\n", "# ✅ Chạy lại được nhiều lần (tự dọn tiến trình cũ). Nếu thiếu Desktop: chạy ô 🩺 Sửa nhanh rồi chạy lại ô này.\n", "import os, sys, json, time, re, shutil, socket, subprocess, threading, secrets, pathlib, importlib.util\n", "\n", "HOME = pathlib.Path.home()\n", "GDIR, BDIR, LDIR = HOME / \"gpu_server\", HOME / \"bots\", HOME / \"bot_logs\"\n", "for d in (GDIR, BDIR, LDIR):\n", " d.mkdir(parents=True, exist_ok=True)\n", "LOCAL_BIN = str(HOME / \".local\" / \"bin\")\n", "pathlib.Path(LOCAL_BIN).mkdir(parents=True, exist_ok=True)\n", "os.environ[\"PATH\"] = LOCAL_BIN + os.pathsep + os.environ.get(\"PATH\", \"\")\n", "\n", "TOKEN = None\n", "try:\n", " TOKEN = json.loads((GDIR / \"server_info.json\").read_text()).get(\"token\")\n", "except Exception:\n", " pass\n", "TOKEN = TOKEN or secrets.token_hex(8)\n", "\n", "PORT_DASH, PORT_NOVNC, PORT_TTYD, DISPLAY = 8080, 6080, 7681, \":1\"\n", "TUNNELS_FILE = pathlib.Path(\"/tmp/tunnels.json\")\n", "TUNNELS, PROCS = {}, []\n", "TL = threading.Lock()\n", "\n", "def have(c): return shutil.which(c) is not None\n", "\n", "def port_open(port, timeout=0.5):\n", " try:\n", " with socket.create_connection((\"127.0.0.1\", port), timeout=timeout):\n", " return True\n", " except OSError:\n", " return False\n", "\n", "def wait_port(port, timeout=25):\n", " t0 = time.time()\n", " while time.time() - t0 < timeout:\n", " if port_open(port):\n", " return True\n", " time.sleep(0.4)\n", " return False\n", "\n", "def kill_matching(needles):\n", " me = os.getpid()\n", " for d in pathlib.Path(\"/proc\").iterdir():\n", " if not d.name.isdigit() or int(d.name) == me:\n", " continue\n", " try:\n", " cmd = (d / \"cmdline\").read_bytes().decode(\"utf-8\", \"ignore\").replace(\"\\x00\", \" \")\n", " except Exception:\n", " continue\n", " if any(n in cmd for n in needles):\n", " try:\n", " os.kill(int(d.name), 15)\n", " except Exception:\n", " pass\n", "\n", "def save_tunnels():\n", " try:\n", " with TL:\n", " TUNNELS_FILE.write_text(json.dumps(TUNNELS))\n", " except Exception:\n", " pass\n", "\n", "def spawn(args, name, gui=False, extra_env=None):\n", " env = dict(os.environ)\n", " if gui:\n", " env[\"DISPLAY\"] = DISPLAY\n", " if extra_env:\n", " env.update(extra_env)\n", " logf = GDIR / f\"{name}.log\"\n", " lf = open(logf, \"ab\", buffering=0)\n", " lf.write(f\"\\n══════ ▶ {name} · {time.strftime('%H:%M:%S')} ══════\\n\".encode())\n", " p = subprocess.Popen([str(a) for a in args], stdout=lf, stderr=subprocess.STDOUT,\n", " stdin=subprocess.DEVNULL, env=env, start_new_session=True)\n", " PROCS.append(p)\n", " print(f\" ▶ {name:<11} pid={p.pid:<6} log={logf}\")\n", " return p\n", "\n", "def start_tunnel(label, port, attempts=2):\n", " cf = shutil.which(\"cloudflared\")\n", " if not cf:\n", " print(f\" ⚠️ [{label}] thiếu cloudflared → không tạo tunnel\")\n", " return\n", " tail = deque(maxlen=10)\n", " for attempt in range(1, attempts + 1):\n", " found = threading.Event()\n", " p = subprocess.Popen([cf, \"tunnel\", \"--url\", f\"http://localhost:{port}\",\n", " \"--no-autoupdate\", \"--protocol\", \"http2\"],\n", " stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n", " text=True, bufsize=1, start_new_session=True)\n", " PROCS.append(p)\n", " def reader(p=p, found=found, tail=tail):\n", " for line in p.stdout:\n", " tail.append(line.rstrip())\n", " m = re.search(r\"https://[a-zA-Z0-9-]+\\.trycloudflare\\.com\", line)\n", " if m:\n", " with TL:\n", " TUNNELS[label] = m.group(0)\n", " save_tunnels()\n", " found.set()\n", " threading.Thread(target=reader, daemon=True).start()\n", " if found.wait(25) and TUNNELS.get(label):\n", " print(f\" 🌐 [{label}] {TUNNELS[label]}\")\n", " return\n", " try:\n", " p.terminate()\n", " except Exception:\n", " pass\n", " if attempt < attempts:\n", " print(f\" ⚠️ [{label}] lần {attempt} chưa tạo được URL — thử lại…\")\n", " time.sleep(2)\n", " print(f\" ❌ [{label}] không tạo được tunnel sau {attempts} lần. Log cuối:\")\n", " for l in list(tail)[-6:]:\n", " print(\" \" + l[:150])\n", "\n", "print(\"🧹 Dọn tiến trình cũ (nếu có)…\")\n", "kill_matching([\"Xvfb\", \"x11vnc\", \"websockify\", \"ttyd\", \"cloudflared\", \"dashboard.py\"])\n", "time.sleep(1.5)\n", "TUNNELS_FILE.write_text(\"{}\")\n", "\n", "# ── thành phần desktop ──\n", "WS_CMD = [\"websockify\"] if have(\"websockify\") else (\n", " [sys.executable, \"-m\", \"websockify\"] if importlib.util.find_spec(\"websockify\") else None)\n", "NOVNC_WEB = (\"/usr/share/novnc\" if os.path.isdir(\"/usr/share/novnc\")\n", " else (str(HOME / \"novnc\") if (HOME / \"novnc\").is_dir() else None))\n", "DESKTOP_OK = (have(\"Xvfb\") and have(\"x11vnc\") and bool(WS_CMD) and bool(NOVNC_WEB)\n", " and (have(\"startxfce4\") or have(\"xterm\")))\n", "\n", "print(\"🧩 Thành phần:\")\n", "for label, ok in [(\"Xvfb (desktop ảo)\", have(\"Xvfb\")), (\"x11vnc\", have(\"x11vnc\")),\n", " (\"websockify\", bool(WS_CMD)), (\"noVNC web\", bool(NOVNC_WEB)),\n", " (\"XFCE/xterm\", have(\"startxfce4\") or have(\"xterm\")),\n", " (\"ttyd\", have(\"ttyd\")), (\"cloudflared\", have(\"cloudflared\"))]:\n", " print(f\" {'✅' if ok else '❌'} {label}\")\n", "if not DESKTOP_OK:\n", " print(\" ⚠️ Thiếu thành phần Desktop → chạy ô 『🩺 SỬA NHANH』 rồi chạy lại ô này.\")\n", " print(\" (Vẫn tiếp tục với Dashboard / Bots / Terminal)\")\n", "\n", "print(\"🎬 Khởi động dịch vụ…\")\n", "if DESKTOP_OK:\n", " spawn([\"Xvfb\", DISPLAY, \"-screen\", \"0\", \"1600x900x24\", \"-nolisten\", \"tcp\"], \"xvfb\")\n", " for _ in range(20):\n", " if os.path.exists(\"/tmp/.X11-unix/X1\"):\n", " break\n", " time.sleep(0.5)\n", " if have(\"xsetroot\"):\n", " spawn([\"xsetroot\", \"-solid\", \"#131022\"], \"xsetroot\", gui=True)\n", " if have(\"dbus-run-session\") and have(\"startxfce4\"):\n", " spawn([\"dbus-run-session\", \"--\", \"startxfce4\"], \"xfce4\", gui=True)\n", " elif have(\"xterm\"):\n", " spawn([\"xterm\", \"-maximized\"], \"xterm\", gui=True)\n", " spawn([\"x11vnc\", \"-display\", DISPLAY, \"-rfbport\", \"5901\", \"-forever\", \"-shared\",\n", " \"-nopw\", \"-noxrecord\", \"-noxfixes\", \"-noxdamage\"], \"x11vnc\")\n", " spawn(WS_CMD + [\"--web\", NOVNC_WEB, PORT_NOVNC, \"localhost:5901\"], \"websockify\")\n", "else:\n", " print(\" ⚠️ bỏ qua Desktop\")\n", "\n", "if have(\"ttyd\"):\n", " spawn([\"ttyd\", \"-W\", \"-p\", PORT_TTYD, \"bash\", \"-l\"], \"ttyd\")\n", "else:\n", " print(\" ⚠️ thiếu ttyd → không có Web Terminal\")\n", "\n", "dash_py = next((c for c in [pathlib.Path.cwd() / \"dashboard.py\", HOME / \"dashboard.py\",\n", " GDIR / \"dashboard.py\"] if c.exists()), None)\n", "if dash_py:\n", " spawn([sys.executable, str(dash_py)], \"dashboard\",\n", " extra_env={\"DASH_PORT\": str(PORT_DASH), \"DASH_TOKEN\": TOKEN,\n", " \"TUNNELS_FILE\": str(TUNNELS_FILE), \"PYTHONUNBUFFERED\": \"1\"})\n", "else:\n", " print(\" ⚠️ không tìm thấy dashboard.py — chạy lại ô %%writefile dashboard.py rồi chạy ô này\")\n", "\n", "if not wait_port(PORT_DASH, 25):\n", " print(\" ⚠️ Dashboard chưa mở cổng — xem log:\", GDIR / \"dashboard.log\")\n", "start_tunnel(\"dashboard\", PORT_DASH)\n", "\n", "if DESKTOP_OK:\n", " if wait_port(PORT_NOVNC, 25):\n", " start_tunnel(\"desktop\", PORT_NOVNC)\n", " else:\n", " print(f\" ❌ noVNC không mở cổng {PORT_NOVNC} — xem {GDIR}/websockify.log, x11vnc.log, xfce4.log\")\n", "if have(\"ttyd\"):\n", " if wait_port(PORT_TTYD, 15):\n", " start_tunnel(\"terminal\", PORT_TTYD)\n", " else:\n", " print(f\" ❌ ttyd không mở cổng {PORT_TTYD} — xem {GDIR}/ttyd.log\")\n", "\n", "demo = BDIR / \"demo_bot.py\"\n", "if not demo.exists():\n", " demo.write_text(\"\"\"import time\n", "print(\"🤖 Demo bot đã khởi động!\", flush=True)\n", "while True:\n", " print(f\"💓 demo bot alive · {time.strftime('%H:%M:%S')}\", flush=True)\n", " time.sleep(60)\n", "\"\"\")\n", "\n", "for _ in range(45):\n", " if TUNNELS.get(\"dashboard\") and (TUNNELS.get(\"desktop\") or not DESKTOP_OK):\n", " break\n", " time.sleep(1)\n", "\n", "dash = TUNNELS.get(\"dashboard\")\n", "desk = TUNNELS.get(\"desktop\")\n", "term = TUNNELS.get(\"terminal\")\n", "dash_url = f\"{dash}/?key={TOKEN}\" if dash else f\"(thất bại — chạy lại ô này)\"\n", "desk_url = f\"{desk}/vnc.html?autoconnect=1&resize=scale&reconnect=1\" if desk else \"(thất bại — xem log bên trên)\"\n", "term_url = term or \"(thất bại — xem log bên trên)\"\n", "\n", "(GDIR / \"server_info.json\").write_text(json.dumps(\n", " {\"token\": TOKEN, \"tunnels\": dict(TUNNELS),\n", " \"ports\": {\"dashboard\": PORT_DASH, \"desktop\": PORT_NOVNC, \"terminal\": PORT_TTYD}}, indent=2))\n", "\n", "print()\n", "print(\"═\" * 66)\n", "print(\" 🎮 GPU CLOUD SERVER ĐANG CHẠY — GIỮ Ô NÀY CHẠY LIÊN TỤC!\")\n", "print(\"═\" * 66)\n", "print(f\" 📊 Dashboard {dash_url}\")\n", "print(f\" 🖥️ Cloud Desktop {desk_url}\")\n", "print(f\" ⌨️ Web Terminal {term_url}\")\n", "print(f\" 🔑 Access Key {TOKEN}\")\n", "print(\"═\" * 66)\n", "print(\" 💡 URL MỚI khác URL cũ — cập nhật lại bookmark/tab đang mở!\")\n", "print(\" 💡 Kiểm tra trạng thái từng dịch vụ: Dashboard → tab Tổng quan → ⚙️ Dịch vụ nền\")\n", "\n", "n = 0\n", "try:\n", " while True:\n", " time.sleep(30)\n", " n += 1\n", " if n % 40 == 0:\n", " print(f\"💓 [{time.strftime('%H:%M:%S')}] server vẫn đang chạy — {dash_url}\")\n", "except KeyboardInterrupt:\n", " print(\"🛑 Đang dừng toàn bộ dịch vụ…\")\n", " for p in PROCS:\n", " try:\n", " p.terminate()\n", " except Exception:\n", " pass\n" ], "execution_count": null, "outputs": [] }, { "id": "cell-fix", "cell_type": "code", "metadata": {}, "source": [ "#@title 🩺 SỬA NHANH · Chẩn đoán + cài thiếu + khởi động lại toàn bộ server { display-mode: \"form\" }\n", "# ══ Dùng khi: Cloud Gaming không có tunnel / Desktop đen / thiếu dịch vụ ══\n", "# CÁCH DÙNG: ① Interrupt (■) ô Bước 2 đang chạy → ② chạy ô này → ③ dùng URL MỚI in ra dưới đây.\n", "import os, sys, json, time, re, shutil, socket, subprocess, threading, secrets, pathlib\n", "import importlib.util, platform, urllib.request, zipfile\n", "from collections import deque\n", "\n", "HOME = pathlib.Path.home()\n", "GDIR, BDIR, LDIR = HOME / \"gpu_server\", HOME / \"bots\", HOME / \"bot_logs\"\n", "for d in (GDIR, BDIR, LDIR):\n", " d.mkdir(parents=True, exist_ok=True)\n", "LOCAL_BIN = str(HOME / \".local\" / \"bin\")\n", "pathlib.Path(LOCAL_BIN).mkdir(parents=True, exist_ok=True)\n", "os.environ[\"PATH\"] = LOCAL_BIN + os.pathsep + os.environ.get(\"PATH\", \"\")\n", "root = os.geteuid() == 0\n", "SUDO = \"\" if (root or not shutil.which(\"sudo\")) else \"sudo -n \"\n", "\n", "PORT_DASH, PORT_NOVNC, PORT_TTYD, DISPLAY = 8080, 6080, 7681, \":1\"\n", "TUNNELS_FILE = pathlib.Path(\"/tmp/tunnels.json\")\n", "TUNNELS, PROCS = {}, []\n", "TL = threading.Lock()\n", "\n", "def sh(cmd, timeout=None):\n", " p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)\n", " return p.returncode, ((p.stdout or \"\") + (p.stderr or \"\"))\n", "\n", "def have(c): return shutil.which(c) is not None\n", "\n", "def port_open(port, timeout=0.5):\n", " try:\n", " with socket.create_connection((\"127.0.0.1\", port), timeout=timeout):\n", " return True\n", " except OSError:\n", " return False\n", "\n", "def wait_port(port, timeout=25):\n", " t0 = time.time()\n", " while time.time() - t0 < timeout:\n", " if port_open(port):\n", " return True\n", " time.sleep(0.4)\n", " return False\n", "\n", "def kill_matching(needles):\n", " me = os.getpid()\n", " for d in pathlib.Path(\"/proc\").iterdir():\n", " if not d.name.isdigit() or int(d.name) == me:\n", " continue\n", " try:\n", " cmd = (d / \"cmdline\").read_bytes().decode(\"utf-8\", \"ignore\").replace(\"\\x00\", \" \")\n", " except Exception:\n", " continue\n", " if any(n in cmd for n in needles):\n", " try:\n", " os.kill(int(d.name), 15)\n", " except Exception:\n", " pass\n", "\n", "def comp(label, ok, extra=\"\"):\n", " print(f\" {'✅' if ok else '❌'} {label}\" + (f\" — {extra}\" if extra else \"\"))\n", "\n", "def spawn(args, name, gui=False, extra_env=None):\n", " env = dict(os.environ)\n", " if gui:\n", " env[\"DISPLAY\"] = DISPLAY\n", " if extra_env:\n", " env.update(extra_env)\n", " logf = GDIR / f\"{name}.log\"\n", " lf = open(logf, \"ab\", buffering=0)\n", " lf.write(f\"\\n══════ ▶ {name} · {time.strftime('%H:%M:%S')} ══════\\n\".encode())\n", " p = subprocess.Popen([str(a) for a in args], stdout=lf, stderr=subprocess.STDOUT,\n", " stdin=subprocess.DEVNULL, env=env, start_new_session=True)\n", " PROCS.append(p)\n", " print(f\" ▶ {name:<11} pid={p.pid:<6} log={logf}\")\n", " return p\n", "\n", "def save_tunnels():\n", " try:\n", " with TL:\n", " TUNNELS_FILE.write_text(json.dumps(TUNNELS))\n", " except Exception:\n", " pass\n", "\n", "def start_tunnel(label, port, attempts=2):\n", " cf = shutil.which(\"cloudflared\")\n", " if not cf:\n", " print(f\" ⚠️ [{label}] thiếu cloudflared\")\n", " return\n", " tail = deque(maxlen=10)\n", " for attempt in range(1, attempts + 1):\n", " found = threading.Event()\n", " p = subprocess.Popen([cf, \"tunnel\", \"--url\", f\"http://localhost:{port}\",\n", " \"--no-autoupdate\", \"--protocol\", \"http2\"],\n", " stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n", " text=True, bufsize=1, start_new_session=True)\n", " PROCS.append(p)\n", " def reader(p=p, found=found, tail=tail):\n", " for line in p.stdout:\n", " tail.append(line.rstrip())\n", " m = re.search(r\"https://[a-zA-Z0-9-]+\\.trycloudflare\\.com\", line)\n", " if m:\n", " with TL:\n", " TUNNELS[label] = m.group(0)\n", " save_tunnels()\n", " found.set()\n", " threading.Thread(target=reader, daemon=True).start()\n", " if found.wait(25) and TUNNELS.get(label):\n", " print(f\" 🌐 [{label}] {TUNNELS[label]}\")\n", " return\n", " try:\n", " p.terminate()\n", " except Exception:\n", " pass\n", " if attempt < attempts:\n", " print(f\" ⚠️ [{label}] lần {attempt} chưa tạo được URL — thử lại…\")\n", " time.sleep(2)\n", " print(f\" ❌ [{label}] không tạo được tunnel sau {attempts} lần. Log cuối:\")\n", " for l in list(tail)[-6:]:\n", " print(\" \" + l[:150])\n", "\n", "TOKEN = None\n", "try:\n", " TOKEN = json.loads((GDIR / \"server_info.json\").read_text()).get(\"token\")\n", "except Exception:\n", " pass\n", "TOKEN = TOKEN or secrets.token_hex(8)\n", "\n", "# ═══════════ 1. CHẨN ĐOÁN ═══════════\n", "print(\"🔍 CHẨN ĐOÁN THÀNH PHẦN\")\n", "WS_BIN = have(\"websockify\")\n", "WS_MOD = importlib.util.find_spec(\"websockify\") is not None\n", "NOVNC_WEB = (\"/usr/share/novnc\" if os.path.isdir(\"/usr/share/novnc\")\n", " else (str(HOME / \"novnc\") if (HOME / \"novnc\").is_dir() else None))\n", "ok_xvfb, ok_vnc = have(\"Xvfb\"), have(\"x11vnc\")\n", "ok_gui = have(\"startxfce4\") or have(\"xterm\")\n", "comp(\"Xvfb (desktop ảo)\", ok_xvfb)\n", "comp(\"x11vnc (VNC server)\", ok_vnc)\n", "comp(\"websockify (VNC → web)\", WS_BIN or WS_MOD,\n", " \"\" if WS_BIN else (\"module pip (không có binary)\" if WS_MOD else \"thiếu hoàn toàn\"))\n", "comp(\"noVNC (web client)\", NOVNC_WEB is not None, NOVNC_WEB or \"\")\n", "comp(\"XFCE / xterm\", ok_gui)\n", "comp(\"ttyd (web terminal)\", have(\"ttyd\"))\n", "comp(\"cloudflared (tunnel)\", have(\"cloudflared\"))\n", "\n", "# ═══════════ 2. CÀI THIẾU ═══════════\n", "need_apt = not (ok_xvfb and ok_vnc and ok_gui and NOVNC_WEB and (WS_BIN or WS_MOD))\n", "if need_apt and have(\"apt-get\"):\n", " pkgs = [n for n, ok in [(\"xvfb\", ok_xvfb), (\"x11vnc\", ok_vnc), (\"novnc\", NOVNC_WEB is None),\n", " (\"websockify\", not (WS_BIN or WS_MOD)),\n", " (\"dbus-x11\", not have(\"dbus-run-session\")),\n", " (\"x11-xserver-utils\", not have(\"xsetroot\")),\n", " (\"xterm\", not have(\"xterm\")), (\"xfce4\", not have(\"startxfce4\")),\n", " (\"xfce4-terminal\", not have(\"xfce4-terminal\"))] if not ok]\n", " print(f\"\\n📦 apt cài: {' '.join(pkgs)} (có thể mất vài phút)\")\n", " rc, out = sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get update -y\", timeout=300)\n", " if rc != 0:\n", " print(\" ⚠️ apt-get update lỗi (log cuối):\\n\" +\n", " \"\\n\".join(\" \" + l for l in out.strip().splitlines()[-8:]))\n", " rc, out = sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends {' '.join(pkgs)}\",\n", " timeout=1500)\n", " if rc != 0:\n", " print(\" ⚠️ Cài cả list bị lỗi — thử từng gói để tìm thủ phạm:\")\n", " for pkg in pkgs:\n", " rc2, out2 = sh(f\"{SUDO}DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends {pkg}\",\n", " timeout=600)\n", " print(f\" {'✅' if rc2 == 0 else '❌'} {pkg}\")\n", " if rc2 != 0:\n", " print(\"\\n\".join(\" \" + l for l in out2.strip().splitlines()[-5:]))\n", "\n", "if not have(\"websockify\") and not WS_MOD:\n", " print(\"\\n🐍 pip fallback: websockify\")\n", " sh(f\"{sys.executable} -m pip install -q websockify\", timeout=300)\n", " WS_MOD = importlib.util.find_spec(\"websockify\") is not None\n", " print(f\" {'✅' if WS_MOD else '❌'} websockify module pip\")\n", "\n", "if not os.path.isdir(\"/usr/share/novnc\") and not (HOME / \"novnc\").is_dir():\n", " print(\"\\n⬇️ Fallback: tải noVNC từ GitHub → ~/novnc\")\n", " for zurl in (\"https://github.com/novnc/noVNC/archive/refs/tags/v1.5.0.zip\",\n", " \"https://github.com/novnc/noVNC/archive/refs/heads/master.zip\"):\n", " try:\n", " ztmp = pathlib.Path(\"/tmp/novnc.zip\")\n", " urllib.request.urlretrieve(zurl, ztmp)\n", " with zipfile.ZipFile(ztmp) as z:\n", " z.extractall(\"/tmp/_novnc_extract\")\n", " src = next(pathlib.Path(\"/tmp/_novnc_extract\").iterdir())\n", " dst = HOME / \"novnc\"\n", " if dst.exists():\n", " shutil.rmtree(dst)\n", " shutil.move(str(src), str(dst))\n", " NOVNC_WEB = str(dst)\n", " print(f\" ✅ {NOVNC_WEB}\")\n", " break\n", " except Exception as e:\n", " print(f\" ⚠️ {zurl} → {e}\")\n", "\n", "if not have(\"ttyd\"):\n", " arch = {\"x86_64\": \"x86_64\", \"aarch64\": \"aarch64\"}.get(platform.machine())\n", " if arch:\n", " dst = pathlib.Path(LOCAL_BIN) / \"ttyd\"\n", " try:\n", " urllib.request.urlretrieve(\n", " f\"https://github.com/tsl0922/ttyd/releases/download/1.7.7/ttyd.{arch}\", dst)\n", " os.chmod(dst, 0o755)\n", " print(f\"\\n✅ ttyd binary → {dst}\")\n", " except Exception as e:\n", " print(\"\\n❌ tải ttyd:\", e)\n", "if not have(\"cloudflared\"):\n", " arch = {\"x86_64\": \"amd64\", \"aarch64\": \"arm64\"}.get(platform.machine(), \"amd64\")\n", " dst = \"/usr/local/bin/cloudflared\" if root else pathlib.Path(LOCAL_BIN) / \"cloudflared\"\n", " try:\n", " urllib.request.urlretrieve(\n", " f\"https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-{arch}\", dst)\n", " os.chmod(dst, 0o755)\n", " print(f\"\\n✅ cloudflared → {dst}\")\n", " except Exception as e:\n", " print(\"\\n❌ tải cloudflared:\", e)\n", "\n", "# tổng kết sau cài đặt\n", "WS_CMD = [\"websockify\"] if have(\"websockify\") else (\n", " [sys.executable, \"-m\", \"websockify\"] if WS_MOD else None)\n", "NOVNC_WEB = (\"/usr/share/novnc\" if os.path.isdir(\"/usr/share/novnc\")\n", " else (str(HOME / \"novnc\") if (HOME / \"novnc\").is_dir() else None))\n", "DESKTOP_OK = (have(\"Xvfb\") and have(\"x11vnc\") and bool(WS_CMD) and bool(NOVNC_WEB)\n", " and (have(\"startxfce4\") or have(\"xterm\")))\n", "print(\"\\n🧩 KẾT QUẢ:\", \"Desktop sẵn sàng ✅\" if DESKTOP_OK\n", " else \"Desktop vẫn thiếu ⚠️ — xem ❌ ở trên (Dashboard/Bots/Terminal vẫn chạy)\")\n", "\n", "# ═══════════ 3. DỌN + KHỞI ĐỘNG LẠI ═══════════\n", "print(\"\\n🧹 Dọn tiến trình cũ…\")\n", "kill_matching([\"Xvfb\", \"x11vnc\", \"websockify\", \"ttyd\", \"cloudflared\", \"dashboard.py\"])\n", "time.sleep(2)\n", "TUNNELS_FILE.write_text(\"{}\")\n", "\n", "print(\"🎬 Khởi động lại toàn bộ…\")\n", "if DESKTOP_OK:\n", " spawn([\"Xvfb\", DISPLAY, \"-screen\", \"0\", \"1600x900x24\", \"-nolisten\", \"tcp\"], \"xvfb\")\n", " for _ in range(20):\n", " if os.path.exists(\"/tmp/.X11-unix/X1\"):\n", " break\n", " time.sleep(0.5)\n", " if have(\"xsetroot\"):\n", " spawn([\"xsetroot\", \"-solid\", \"#131022\"], \"xsetroot\", gui=True)\n", " if have(\"dbus-run-session\") and have(\"startxfce4\"):\n", " spawn([\"dbus-run-session\", \"--\", \"startxfce4\"], \"xfce4\", gui=True)\n", " elif have(\"xterm\"):\n", " spawn([\"xterm\", \"-maximized\"], \"xterm\", gui=True)\n", " spawn([\"x11vnc\", \"-display\", DISPLAY, \"-rfbport\", \"5901\", \"-forever\", \"-shared\",\n", " \"-nopw\", \"-noxrecord\", \"-noxfixes\", \"-noxdamage\"], \"x11vnc\")\n", " spawn(WS_CMD + [\"--web\", NOVNC_WEB, PORT_NOVNC, \"localhost:5901\"], \"websockify\")\n", "else:\n", " print(\" ⚠️ bỏ qua Desktop\")\n", "if have(\"ttyd\"):\n", " spawn([\"ttyd\", \"-W\", \"-p\", PORT_TTYD, \"bash\", \"-l\"], \"ttyd\")\n", "dash_py = next((c for c in [pathlib.Path.cwd() / \"dashboard.py\", HOME / \"dashboard.py\",\n", " GDIR / \"dashboard.py\"] if c.exists()), None)\n", "if dash_py:\n", " spawn([sys.executable, str(dash_py)], \"dashboard\",\n", " extra_env={\"DASH_PORT\": str(PORT_DASH), \"DASH_TOKEN\": TOKEN,\n", " \"TUNNELS_FILE\": str(TUNNELS_FILE), \"PYTHONUNBUFFERED\": \"1\"})\n", "else:\n", " print(\" ⚠️ không tìm thấy dashboard.py — chạy lại ô %%writefile dashboard.py rồi chạy ô này\")\n", "\n", "if wait_port(PORT_DASH, 25):\n", " start_tunnel(\"dashboard\", PORT_DASH)\n", "else:\n", " print(f\" ❌ Dashboard không mở cổng {PORT_DASH} — xem {GDIR}/dashboard.log\")\n", "if DESKTOP_OK:\n", " if wait_port(PORT_NOVNC, 25):\n", " start_tunnel(\"desktop\", PORT_NOVNC)\n", " else:\n", " print(f\" ❌ noVNC không mở cổng {PORT_NOVNC} — xem {GDIR}/websockify.log, x11vnc.log, xfce4.log\")\n", "if have(\"ttyd\"):\n", " if wait_port(PORT_TTYD, 15):\n", " start_tunnel(\"terminal\", PORT_TTYD)\n", " else:\n", " print(f\" ❌ ttyd không mở cổng {PORT_TTYD} — xem {GDIR}/ttyd.log\")\n", "\n", "demo = BDIR / \"demo_bot.py\"\n", "if not demo.exists():\n", " demo.write_text(\"\"\"import time\n", "print(\"🤖 Demo bot đã khởi động!\", flush=True)\n", "while True:\n", " print(f\"💓 demo bot alive · {time.strftime('%H:%M:%S')}\", flush=True)\n", " time.sleep(60)\n", "\"\"\")\n", "\n", "for _ in range(45):\n", " if TUNNELS.get(\"dashboard\") and (TUNNELS.get(\"desktop\") or not DESKTOP_OK):\n", " break\n", " time.sleep(1)\n", "\n", "dash = TUNNELS.get(\"dashboard\")\n", "desk = TUNNELS.get(\"desktop\")\n", "term = TUNNELS.get(\"terminal\")\n", "dash_url = f\"{dash}/?key={TOKEN}\" if dash else \"(thất bại — chạy lại ô này)\"\n", "desk_url = f\"{desk}/vnc.html?autoconnect=1&resize=scale&reconnect=1\" if desk else \"(thất bại — xem log bên trên)\"\n", "term_url = term or \"(thất bại — xem log bên trên)\"\n", "\n", "(GDIR / \"server_info.json\").write_text(json.dumps(\n", " {\"token\": TOKEN, \"tunnels\": dict(TUNNELS),\n", " \"ports\": {\"dashboard\": PORT_DASH, \"desktop\": PORT_NOVNC, \"terminal\": PORT_TTYD}}, indent=2))\n", "\n", "print()\n", "print(\"═\" * 66)\n", "print(\" 🩺 SỬA XONG — GIỮ Ô NÀY CHẠY LIÊN TỤC (thay cho ô Bước 2)!\")\n", "print(\"═\" * 66)\n", "print(f\" 📊 Dashboard {dash_url}\")\n", "print(f\" 🖥️ Cloud Desktop {desk_url}\")\n", "print(f\" ⌨️ Web Terminal {term_url}\")\n", "print(f\" 🔑 Access Key {TOKEN}\")\n", "print(\"═\" * 66)\n", "print(\" ⚠️ URL MỚI khác URL cũ — mở link Dashboard mới này, đừng dùng link cũ!\")\n", "print(\" 💡 Xem trạng thái dịch vụ: Dashboard → Tổng quan → ⚙️ Dịch vụ nền\")\n", "\n", "n = 0\n", "try:\n", " while True:\n", " time.sleep(30)\n", " n += 1\n", " if n % 40 == 0:\n", " print(f\"💓 [{time.strftime('%H:%M:%S')}] server vẫn đang chạy — {dash_url}\")\n", "except KeyboardInterrupt:\n", " print(\"🛑 Đang dừng toàn bộ dịch vụ…\")\n", " for p in PROCS:\n", " try:\n", " p.terminate()\n", " except Exception:\n", " pass\n" ], "execution_count": null, "outputs": [] }, { "id": "md-guide", "cell_type": "markdown", "metadata": {}, "source": [ "## 🎉 Server đang chạy — dùng thế nào?\n", "\n", "### 📊 Tab Tổng quan\n", "Giám sát GPU (tên card, % util, VRAM, nhiệt độ), CPU, RAM, disk, uptime + 3 URL public để copy.\n", "\n", "### 🎮 Tab Cloud Gaming (tính năng hay nhất)\n", "1. Bấm **🖥️ Mở Cloud Desktop** → mở desktop XFCE trong tab mới (noVNC)\n", "2. Bấm **🎮 Cài Steam** trên dashboard (chạy ngầm, xem log bên dưới)\n", "3. Vào desktop → mở Steam → đăng nhập → cài & chơi game\n", "4. Muốn cài gì thêm: ô \"Lệnh tuỳ ý\" hoặc **⌨️ Web Terminal**\n", "\n", "### 🤖 Tab Bots — treo bot 24/7 (trong lúc phiên sống)\n", "- **Upload** file `.py` + ô Env chứa token (`DISCORD_TOKEN=xxx`, mỗi dòng một biến)\n", "- **▶ Start / ■ Stop**, xem **📜 Logs** realtime, auto có thư viện sẵn: cài qua nút ⚡\n", "- Bot mẫu `demo_bot` được tạo sẵn để bạn thử\n", "\n", "Ví dụ bot Discord:\n", "\n", "```python\n", "import os, discord\n", "from discord.ext import commands\n", "intents = discord.Intents.default(); intents.message_content = True\n", "bot = commands.Bot(command_prefix=\"!\", intents=intents)\n", "\n", "@bot.event\n", "async def on_ready(): print(\"✅\", bot.user)\n", "\n", "@bot.command()\n", "async def ping(ctx): await ctx.send(\"🏓 Pong!\")\n", "\n", "bot.run(os.environ[\"DISCORD_TOKEN\"])\n", "```\n", "\n", "### 📁 Tab Files\n", "Upload/download/xoá file trên VM — tiện khi cần đưa model/save game lên.\n", "\n", "### ⌨️ Web Terminal\n", "bash đầy đủ trên VM — cài bất cứ thứ gì (`pip`, `apt`, `git`, …).\n", "\n", "---\n", "\n", "### 🩺 Có sự cố? (Cloud Gaming không có tunnel / Desktop đen / thiếu dịch vụ)\n", "1. **Interrupt (■)** ô Bước 2 đang chạy\n", "2. Chạy ô **🩺 SỬA NHANH** — tự chẩn đoán từng thành phần, cài phần thiếu (kể cả fallback pip/GitHub khi apt hỏng), khởi động lại toàn bộ và in URL mới\n", "3. Theo dõi trạng thái từng dịch vụ ở tab **Tổng quan → ⚙️ Dịch vụ nền** (bấm 📜 để xem log)\n", "\n", "### 💡 Lưu ý quan trọng\n", "- **Giữ ô Bước 2 chạy** — đóng tab/idle lâu Colab sẽ ngắt, server chết → chạy lại từ Bước 2 (URL mới).\n", "- **URL tunnel là tạm thời** — mỗi phiên chạy có URL mới.\n", "- **Đừng share URL desktop/terminal** (không có key bảo vệ như dashboard).\n", "- **Giới hạn phiên:** Colab free ~3–12h, Kaggle ~9–12h/phiên & ~30h/tuần.\n", "- **Disclaimer:** chạy game/bot nền có thể vi phạm ToS Colab/Kaggle — dùng có trách nhiệm, tự chịu rủi ro.\n", "\n", "Repo: https://github.com/tiendatmeow-source/cloud-gaming-gpu · Landing: https://tiendatmeow-source.github.io/cloud-gaming-gpu/\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }