ceshi001awdhg commited on
Commit
7fed03b
·
verified ·
1 Parent(s): 246a6c6

Upload 5 files

Browse files
Files changed (5) hide show
  1. .dockerignore +4 -0
  2. Dockerfile +74 -0
  3. entrypoint.sh +151 -0
  4. space.yaml +8 -0
  5. sync.py +125 -0
.dockerignore CHANGED
@@ -39,3 +39,7 @@ build/
39
  # Test
40
  tests/
41
  test/
 
 
 
 
 
39
  # Test
40
  tests/
41
  test/
42
+
43
+ # 环境变量文件(敏感)
44
+ .env
45
+ .env.local
Dockerfile ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenClaw Hugging Face Spaces 部署镜像
2
+ FROM node:22-bookworm
3
+
4
+ # 安装系统依赖(合并为一个 RUN,减少层数)
5
+ RUN apt-get update && apt-get install -y --no-install-recommends \
6
+ git openssh-client build-essential python3 python3-pip \
7
+ g++ make ca-certificates curl \
8
+ chromium \
9
+ libxcb-shm0 libx11-xcb1 libx11-6 libxcb1 libxext6 libxrandr2 \
10
+ libxcomposite1 libxcursor1 libxdamage1 libxfixes3 libxi6 libgtk-3-0 \
11
+ libpangocairo-1.0-0 libpango-1.0-0 libatk1.0-0 libcairo-gobject2 \
12
+ libcairo2 libgdk-pixbuf-2.0-0 libxrender1 libasound2 libfreetype6 \
13
+ libfontconfig1 libdbus-1-3 libnss3 libnspr4 libatk-bridge2.0-0 \
14
+ libdrm2 libxkbcommon0 libatspi2.0-0 libcups2 libxshmfence1 libgbm1 \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ # 设置工作目录
18
+ WORKDIR /app
19
+
20
+ # 设置时区为北京时间
21
+ ENV TZ=Asia/Shanghai
22
+ RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
23
+ echo "Asia/Shanghai" > /etc/timezone
24
+
25
+ # 使用 npm 全局安装 OpenClaw
26
+ RUN npm install -g openclaw@latest --unsafe-perm
27
+
28
+ # Git 配置(解决 SSL 问题)
29
+ RUN update-ca-certificates && \
30
+ git config --global http.sslVerify false && \
31
+ git config --global url."https://github.com/".insteadOf ssh://git@github.com/
32
+
33
+ # 安装 agent-browser 和 Playwright
34
+ RUN npm install -g agent-browser@latest playwright
35
+ ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
36
+ ENV PLAYWRIGHT_BROWSERS_PATH=/root/.cache/ms-playwright
37
+
38
+ # 安装 Hugging Face 工具(备份功能需要)
39
+ RUN pip3 install --no-cache-dir huggingface_hub --break-system-packages
40
+
41
+ # 安装 @openclaw-china/channels 插件(支持飞书、企业微信等)
42
+ RUN npm install -g @openclaw-china/channels || \
43
+ echo "Warning: Failed to install @openclaw-china/channels"
44
+
45
+ # 创建必要的目录
46
+ RUN mkdir -p /root/.openclaw/sessions \
47
+ /root/.openclaw/workspace \
48
+ /root/.openclaw/agents \
49
+ /root/.openclaw/memory
50
+
51
+ # 复制备份脚本
52
+ COPY sync.py /usr/local/bin/sync.py
53
+ RUN chmod +x /usr/local/bin/sync.py
54
+
55
+ # 复制 entrypoint 脚本
56
+ COPY entrypoint.sh /app/entrypoint.sh
57
+ RUN chmod +x /app/entrypoint.sh
58
+
59
+ # 设置环境变量默认值
60
+ ENV PORT=7860 \
61
+ OPENCLAW_GATEWAY_MODE=local \
62
+ HOME=/root \
63
+ BACKUP_INTERVAL_HOURS=2 \
64
+ KEEP_BACKUPS_COUNT=31 \
65
+ BACKUP_LOOKBACK_DAYS=10 \
66
+ BACKUP_TARGETS="sessions,workspace,agents,memory,openclaw.json"
67
+
68
+ # 健康检查(Hugging Face Spaces 必需)
69
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
70
+ CMD curl -f http://localhost:7860/ || exit 1
71
+
72
+ EXPOSE 7860
73
+
74
+ CMD ["/app/entrypoint.sh"]
entrypoint.sh ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+ # 强制使用北京时间
5
+ export TZ="Asia/Shanghai"
6
+
7
+ CONFIG="/root/.openclaw/openclaw.json"
8
+
9
+ echo "=== Starting OpenClaw Gateway ==="
10
+ echo "Timezone: $(date +%Z)"
11
+
12
+ # ============================================================
13
+ # 检查必需的环境变量
14
+ # ============================================================
15
+
16
+ check_env() {
17
+ local var_name=$1
18
+ local var_value=${!var_name}
19
+ if [ -z "$var_value" ]; then
20
+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Error: Required env variable $var_name not set"
21
+ exit 1
22
+ fi
23
+ }
24
+
25
+ echo "Checking required environment variables..."
26
+ check_env "OPENAI_API_KEY"
27
+ check_env "OPENAI_API_BASE"
28
+ check_env "MODEL"
29
+ check_env "GATEWAY_TOKEN"
30
+
31
+ # 备份相关变量(可选,但建议设置)
32
+ if [ -z "$HF_TOKEN" ] || [ -z "$HF_DATASET" ]; then
33
+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Warning: HF_TOKEN or HF_DATASET not set, backup disabled"
34
+ fi
35
+
36
+ # ============================================================
37
+ # 生成 openclaw.json 配置文件
38
+ # ============================================================
39
+
40
+ # 清理 API Base 地址
41
+ CLEAN_BASE=$(echo "$OPENAI_API_BASE" | sed "s|/chat/completions||g" | sed "s|/v1/|/v1|g" | sed "s|/v1$|/v1|g")
42
+
43
+ echo "Generating openclaw.json configuration..."
44
+
45
+ # 生成配置文件(支持飞书、企业微信等)
46
+ cat > "$CONFIG" <<EOF
47
+ {
48
+ "models": {
49
+ "mode": "merge",
50
+ "providers": {
51
+ "siliconflow": {
52
+ "baseUrl": "$CLEAN_BASE",
53
+ "apiKey": "$OPENAI_API_KEY",
54
+ "api": "openai-completions",
55
+ "models": [
56
+ {
57
+ "id": "$MODEL",
58
+ "name": "DeepSeek",
59
+ "contextWindow": 128000
60
+ }
61
+ ]
62
+ }
63
+ }
64
+ },
65
+ "agents": {
66
+ "defaults": {
67
+ "model": {
68
+ "primary": "siliconflow/$MODEL"
69
+ }
70
+ }
71
+ },
72
+ "channels": {
73
+ "feishu": {
74
+ "enabled": ${FEISHU_ENABLED:-false},
75
+ "appId": "${FEISHU_APP_ID:-}",
76
+ "appSecret": "${FEISHU_APP_SECRET:-}",
77
+ "connectionMode": "websocket"
78
+ }
79
+ },
80
+ "gateway": {
81
+ "mode": "local",
82
+ "bind": "lan",
83
+ "port": ${PORT:-7860},
84
+ "trustedProxies": ["0.0.0.0/0", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"],
85
+ "auth": {
86
+ "mode": "token",
87
+ "token": "${GATEWAY_TOKEN:-openclaw}"
88
+ },
89
+ "controlUi": {
90
+ "allowInsecureAuth": true
91
+ }
92
+ }
93
+ }
94
+ EOF
95
+
96
+ echo "Configuration generated: $CONFIG"
97
+
98
+ # ============================================================
99
+ # 启动定时备份进程
100
+ # ============================================================
101
+
102
+ BACKUP_INTERVAL_HOURS=${BACKUP_INTERVAL_HOURS:-2}
103
+ BACKUP_INTERVAL_SECONDS=$((BACKUP_INTERVAL_HOURS * 3600))
104
+
105
+ echo "=== Starting scheduled backup service (interval: ${BACKUP_INTERVAL_HOURS} hours) ==="
106
+ (while true; do
107
+ sleep $BACKUP_INTERVAL_SECONDS
108
+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Triggering scheduled backup..."
109
+ python3 /usr/local/bin/sync.py backup || echo "Backup failed, will retry next time"
110
+ done) &
111
+
112
+ BACKUP_PID=$!
113
+
114
+ # ============================================================
115
+ # 启动 Keep-Alive(防止 Hugging Face Spaces 休眠)
116
+ # ============================================================
117
+
118
+ if [ -n "$SPACE_ID" ]; then
119
+ echo "=== Starting Keep-Alive service (interval: 10 minutes) ==="
120
+ (while true; do
121
+ sleep 600
122
+ SPACE_URL="https://${SPACE_ID}.hf.space"
123
+ curl -s --max-time 30 "$SPACE_URL" > /dev/null 2>&1 || echo "[$(date '+%Y-%m-%d %H:%M:%S')] Keep-Alive: Space is sleeping, waiting for wake up..."
124
+ done) &
125
+ KEEPALIVE_PID=$!
126
+ fi
127
+
128
+ # ============================================================
129
+ # 捕获信号并优雅关闭
130
+ # ============================================================
131
+
132
+ cleanup() {
133
+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Received shutdown signal, cleaning up..."
134
+ kill $BACKUP_PID 2>/dev/null || true
135
+ [ -n "$KEEPALIVE_PID" ] && kill $KEEPALIVE_PID 2>/dev/null || true
136
+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Performing final backup..."
137
+ python3 /usr/local/bin/sync.py backup || echo "Final backup failed"
138
+ exit 0
139
+ }
140
+
141
+ trap cleanup SIGTERM SIGINT
142
+
143
+ # ============================================================
144
+ # 修复配置并启动 OpenClaw 网关
145
+ # ============================================================
146
+
147
+ echo "=== Running openclaw doctor to fix config ==="
148
+ openclaw doctor --fix || echo "Warning: Doctor fix completed with warnings"
149
+
150
+ echo "=== Starting OpenClaw Gateway ==="
151
+ exec openclaw gateway run --port ${PORT:-7860}
space.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ title: OpenClaw Gateway
2
+ emoji: 🤖
3
+ colorFrom: blue
4
+ colorTo: purple
5
+ sdk: docker
6
+ app_port: 7860
7
+ timeout: 300
8
+ persistent_storage: true
sync.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import sys
4
+ import tarfile
5
+ from datetime import datetime, timedelta
6
+ from huggingface_hub import HfApi, hf_hub_download
7
+
8
+ api = HfApi()
9
+ repo_id = os.getenv("HF_DATASET")
10
+ token = os.getenv("HF_TOKEN")
11
+
12
+ # 配置(从环境变量读取,带默认值)
13
+ LOOKBACK_DAYS = int(os.getenv("BACKUP_LOOKBACK_DAYS", "10"))
14
+ KEEP_BACKUPS = int(os.getenv("KEEP_BACKUPS_COUNT", "31"))
15
+ BACKUP_TARGETS = os.getenv(
16
+ "BACKUP_TARGETS", "sessions,workspace,agents,memory,openclaw.json"
17
+ ).split(",")
18
+
19
+
20
+ def log(msg):
21
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}")
22
+
23
+
24
+ def restore():
25
+ """从 Hugging Face Hub 恢复最近10天的备份"""
26
+ try:
27
+ log(f"[SYNC] 启动恢复流程, 目标仓库: {repo_id}")
28
+ if not repo_id or not token:
29
+ log("[SYNC] 跳过恢复: 未配置 HF_DATASET 或 HF_TOKEN")
30
+ return False
31
+
32
+ files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)
33
+ now = datetime.now()
34
+
35
+ for i in range(LOOKBACK_DAYS):
36
+ day = (now - timedelta(days=i)).strftime("%Y-%m-%d")
37
+ name = f"backup_{day}.tar.gz"
38
+ if name in files:
39
+ log(f"[SYNC] 发现备份文件: {name}, 正在下载...")
40
+ path = hf_hub_download(
41
+ repo_id=repo_id,
42
+ filename=name,
43
+ repo_type="dataset",
44
+ token=token,
45
+ )
46
+ with tarfile.open(path, "r:gz") as tar:
47
+ tar.extractall(path="/root/.openclaw/")
48
+ log("[SYNC] 恢复成功! 数据已覆盖至 /root/.openclaw/")
49
+ return True
50
+
51
+ log("[SYNC] 未找到最近10天的备份包")
52
+ return False
53
+ except Exception as e:
54
+ log(f"[SYNC] 恢复异常: {e}")
55
+ return False
56
+
57
+
58
+ def backup():
59
+ """执行备份并清理旧备份"""
60
+ try:
61
+ day = datetime.now().strftime("%Y-%m-%d")
62
+ name = f"backup_{day}.tar.gz"
63
+ log(f"[SYNC] 正在执行全量备份: {name}")
64
+
65
+ # 在工作目录创建备份
66
+ work_dir = "/tmp/openclaw-backup"
67
+ os.makedirs(work_dir, exist_ok=True)
68
+ backup_path = os.path.join(work_dir, name)
69
+
70
+ with tarfile.open(backup_path, "w:gz") as tar:
71
+ targets = [t.strip() for t in BACKUP_TARGETS if t.strip()]
72
+ for target in targets:
73
+ full_path = f"/root/.openclaw/{target}"
74
+ if os.path.exists(full_path):
75
+ tar.add(full_path, arcname=target)
76
+
77
+ # 上传备份
78
+ api.upload_file(
79
+ path_or_fileobj=backup_path,
80
+ path_in_repo=name,
81
+ repo_id=repo_id,
82
+ repo_type="dataset",
83
+ token=token,
84
+ )
85
+ log("[SYNC] 备份上传成功!")
86
+
87
+ # 清理旧备份
88
+ cleanup_old_backups()
89
+
90
+ # 清理临时文件
91
+ os.remove(backup_path)
92
+ return True
93
+
94
+ except Exception as e:
95
+ log(f"[SYNC] 备份失败: {e}")
96
+ return False
97
+
98
+
99
+ def cleanup_old_backups():
100
+ """保留最近10个备份,删除旧的"""
101
+ try:
102
+ files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)
103
+ backups = [
104
+ f for f in files if f.startswith("backup_") and f.endswith(".tar.gz")
105
+ ]
106
+ backups.sort(reverse=True)
107
+
108
+ if len(backups) > KEEP_BACKUPS:
109
+ for old_backup in backups[KEEP_BACKUPS:]:
110
+ log(f"[SYNC] 清理旧备份: {old_backup}")
111
+ api.delete_file(
112
+ path_in_repo=old_backup,
113
+ repo_id=repo_id,
114
+ repo_type="dataset",
115
+ token=token,
116
+ )
117
+ except Exception as e:
118
+ log(f"[SYNC] 清理旧备份失败: {e}")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ if len(sys.argv) > 1 and sys.argv[1] == "backup":
123
+ backup()
124
+ else:
125
+ restore()