帮我做一个按需启动服务器的方案吧
- User
帮我做一个按需启动服务器的方案吧
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
帮我做一个按需启动服务器的方案吧
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
下面给出一套「按需启动服务器 C」的完整方案,满足:
整套流程分 4 部分:
etherwake 或 wakeonlan00:11:32:aa:bb:cc# A 上执行
sudo apt install wakeonlan
wakeonlan 00:11:32:aa:bb:cc
# 安装 CLI
pip install tccli
# 开机
tccli cvm StartInstances --InstanceIds '["ins-xxxxxxxx"]'
把云 API 调用包装成脚本 /usr/local/bin/start-c.sh,下文统一用 start-c.sh。
在 C 的镜像里放一次即可:
# /var/lib/cloud/scripts/per-boot/join-k3s.sh
#!/bin/bash
set -e
TOKEN=$(curl -s https://<A公网IP>:6443/token.txt) # 见下文
curl -sfL https://get.k3s.io | K3S_URL=https://<A公网IP>:6443 \
K3S_TOKEN=$TOKEN sh -
把 token 暴露成只读文件:
A 上echo $NODE_TOKEN > /var/lib/rancher/k3s/server/node-token.txt
然后python3 -m http.server 8080 --directory /var/lib/rancher/k3s/server
防火墙仅允许 C 的公网出口 IP 段访问 8080。
在 A 上 apply:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: idle-shutdown
namespace: kube-system
spec:
selector:
matchLabels:
app: idle-shutdown
template:
metadata:
labels:
app: idle-shutdown
spec:
nodeName: <C的节点名> # 只调度到 C
hostPID: true
containers:
- name: idle
image: alpine:latest
command:
- /bin/sh
- -c
- |
apk add --no-cache procps
while true; do
# 如果 10 分钟 CPU 均值 < 5% 且没有非 DaemonSet Pod → 关机
CPU=$(awk -v FS=" " '{u=$2+$3+$4; t=$2+$3+$4+$5+$6+$7+$8; print (u)/(t)*100}' <(grep '^cpu ' /proc/stat))
PODS=$(kubectl get pods --all-namespaces --field-selector spec.nodeName=$NODE_NAME -o json | \
jq '[ .items[] | select(.metadata.labels["app"]!="idle-shutdown") ] | length')
if (( $(echo "$CPU < 5" | bc -l) )) && [ "$PODS" -eq 0 ]; then
echo "Idle, shutting down..."
poweroff
fi
sleep 60
done
env:
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumeMounts:
- name: kubectl
mountPath: /usr/local/bin/kubectl
readOnly: true
volumes:
- name: kubectl
hostPath:
path: /usr/local/bin/kubectl
如果 C 是云主机,把
poweroff换成云 APIStopInstances即可。
#!/bin/bash
# /usr/local/bin/k3s-up-c.sh
set -e
echo "Starting C..."
start-c.sh
echo "Waiting for node Ready..."
until kubectl get node <C节点名> | grep -q Ready; do
sleep 5
done
echo "C is Ready!"
在 A 上跑一个轻量 Flask:
# /opt/webhook/start_c.py
from flask import Flask, request
import subprocess
app = Flask(__name__)
@app.route('/start-c', methods=['POST'])
def start_c():
subprocess.run(['/usr/local/bin/start-c.sh'])
return 'OK', 200
app.run(host='0.0.0.0', port=8080)
然后用 curl -X POST http://<A公网IP>:8080/start-c 即可。
k3s-up-c.sh 或 POST Webhook| 文件 | 所在节点 | 作用 |
|---|---|---|
/usr/local/bin/start-c.sh | A | 远程开机脚本(WoL / 云 API) |
/var/lib/cloud/scripts/per-boot/join-k3s.sh | C 镜像 | 开机自动加入 K3s |
idle-shutdown.yaml | A | 空闲关机 DaemonSet |
/usr/local/bin/k3s-up-c.sh | 任意 | 一键启动 C |
start_c.py | A | Webhook 触发器(可选) |
如需我帮你打包成 Ansible Playbook 或 Terraform 模块,再喊我即可。