File size: 9,421 Bytes
13abd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
"""
backup-manager.py โ€” WebDAV + HF Dataset ๅŒๅผ•ๆ“Žๅค‡ไปฝ/ๆขๅค

็ญ–็•ฅ:
  - ๅ…จ้‡ๅค‡ไปฝ (tar.gz): ๆฏ 24h โ†’ WebDAV + HF Dataset
  - ๅขž้‡ๅค‡ไปฝ (SHA256 manifest): ๆฏๅฐๆ—ถ โ†’ WebDAV (ไป…ๅ˜ๆ›ดๆ–‡ไปถ)
  - ๆขๅค: ไผ˜ๅ…ˆ WebDAV (ๅ…จ้‡โ†’ๅขž้‡ๅ ๅŠ ) โ†’ fallback HF Dataset
"""

import hashlib, json, os, tarfile, time, sys, copy
from pathlib import Path

import requests

# โ”€โ”€ ้…็ฝฎ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
STATE_DIR   = os.environ.get("OPENCLAW_STATE_DIR", "/root/.openclaw")
WEBDAV_URL  = os.environ.get("WEBDAV_URL", "").rstrip("/")
WEBDAV_USER = os.environ.get("WEBDAV_USERNAME", "")
WEBDAV_PASS = os.environ.get("WEBDAV_PASSWORD", "")
WEBDAV_PATH = os.environ.get("WEBDAV_BASE_PATH", "openclaw-backup")
HF_REPO     = os.environ.get("HF_DATASET", "")
HF_TOKEN    = os.environ.get("HF_TOKEN", "")

# ๅค‡ไปฝๅ‘จๆœŸ๏ผˆๅˆ†้’Ÿ๏ผ‰
BACKUP_INCREMENT_INTERVAL = int(os.environ.get("BACKUP_INCREMENT_INTERVAL", "60"))
BACKUP_FULL_INTERVAL     = int(os.environ.get("BACKUP_FULL_INTERVAL", "1440"))

FULL_NAME   = "openclaw-full.tar.gz"
MANIFEST_NAME = "_incremental_manifest.json"

# โ”€โ”€ WebDAV ๅŽŸๅง‹ HTTP ๅฑ‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _wd_auth():
    return (WEBDAV_USER, WEBDAV_PASS) if WEBDAV_USER else None

def _wd_url(path=""):
    return f"{WEBDAV_URL}/{WEBDAV_PATH}/{path.lstrip('/')}"

def _wd_req(method, path="", **kwargs):
    url = _wd_url(path)
    resp = requests.request(method, url, auth=_wd_auth(), timeout=60, **kwargs)
    resp.raise_for_status()
    return resp

def wd_exists(path):
    try:
        _wd_req("PROPFIND", path)
        return True
    except Exception:
        return False

def wd_upload(path, data):
    return _wd_req("PUT", path, data=data)

def wd_download(path):
    return _wd_req("GET", path).content

def wd_mkdir(parts):
    """Create parent directories via MKCOL."""
    for i in range(1, len(parts) + 1):
        p = "/".join(parts[:i])
        try:
            _wd_req("MKCOL", p)
        except Exception:
            pass

# โ”€โ”€ HF Dataset ๅฑ‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _hf_upload(tarpath: str):
    if not HF_REPO or not HF_TOKEN:
        return
    from huggingface_hub import HfApi
    api = HfApi()
    with open(tarpath, "rb") as f:
        api.upload_file(
            path_or_fileobj=f,
            path_in_repo=FULL_NAME,
            repo_id=HF_REPO,
            repo_type="dataset",
            token=HF_TOKEN,
        )
    print(f"[backup] Full backup mirrored to HF Dataset ({HF_REPO})")

def _hf_download() -> str | None:
    if not HF_REPO or not HF_TOKEN:
        return None
    try:
        from huggingface_hub import hf_hub_download
        return hf_hub_download(
            repo_id=HF_REPO, filename=FULL_NAME,
            repo_type="dataset", token=HF_TOKEN,
        )
    except Exception as e:
        print(f"[restore] HF fallback unavailable: {e}")
        return None

# โ”€โ”€ ๆ–‡ไปถๅ“ˆๅธŒ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _file_hash(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            chunk = f.read(65536)
            if not chunk:
                break
            h.update(chunk)
    return h.hexdigest()

# โ”€โ”€ Manifest (ๅขž้‡็ดขๅผ•) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _load_manifest() -> dict:
    try:
        data = wd_download(MANIFEST_NAME)
        return json.loads(data)
    except Exception:
        return {}

def _save_manifest(manifest: dict):
    wd_upload(MANIFEST_NAME, json.dumps(manifest, indent=2).encode())

# โ”€โ”€ ๅ…จ้‡ๅค‡ไปฝ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def full_backup():
    tarpath = f"/tmp/{FULL_NAME}"
    with tarfile.open(tarpath, "w:gz") as tar:
        root = Path(STATE_DIR)
        if root.exists():
            for item in root.iterdir():
                if item.exists():
                    tar.add(str(item), arcname=item.name)
    size = os.path.getsize(tarpath)
    print(f"[backup] Full archive created ({size} bytes)")

    # Upload to WebDAV
    if WEBDAV_URL:
        wd_mkdir([])
        with open(tarpath, "rb") as f:
            wd_upload(FULL_NAME, f.read())
        print(f"[backup] Full backup uploaded to WebDAV")

    # Mirror to HF Dataset
    _hf_upload(tarpath)

    os.remove(tarpath)

# โ”€โ”€ ๅขž้‡ๅค‡ไปฝ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def incremental_backup() -> int:
    root = Path(STATE_DIR)
    if not root.exists():
        return 0

    manifest = _load_manifest()
    changed = 0

    for fpath in root.rglob("*"):
        if not fpath.is_file():
            continue
        rel = str(fpath.relative_to(root))
        if rel.startswith(".") or rel == MANIFEST_NAME or rel.startswith("_incremental"):
            continue

        cur_h = _file_hash(str(fpath))
        prev = manifest.get(rel, {})

        if cur_h != prev.get("sha256"):
            parts = ["files", *rel.split("/")]
            wd_mkdir(parts[:-1])
            wd_upload("/".join(parts), fpath.read_bytes())
            manifest[rel] = {
                "sha256": cur_h,
                "mtime": fpath.stat().st_mtime,
                "size": fpath.stat().st_size,
            }
            changed += 1

    if changed:
        _save_manifest(manifest)
    return changed

# โ”€โ”€ ๆขๅค โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def restore():
    """Restore: WebDAV primary (full โ†’ incremental) โ†’ HF Dataset fallback."""
    root = Path(STATE_DIR)
    root.mkdir(parents=True, exist_ok=True)

    restored = False

    # Strategy 1: WebDAV full backup + incremental overrides
    if WEBDAV_URL and wd_exists(FULL_NAME):
        print("[restore] Downloading full backup from WebDAV...")
        data = wd_download(FULL_NAME)
        tarpath = f"/tmp/{FULL_NAME}"
        with open(tarpath, "wb") as f:
            f.write(data)
        with tarfile.open(tarpath, "r:gz") as tar:
            tar.extractall(path=STATE_DIR)
        os.remove(tarpath)

        # Apply incremental overrides
        try:
            manifest = _load_manifest()
            count = 0
            for rel, meta in manifest.items():
                p = root / rel
                p.parent.mkdir(parents=True, exist_ok=True)
                try:
                    data = wd_download(f"files/{rel}")
                    p.write_bytes(data)
                    count += 1
                except Exception:
                    pass
            print(f"[restore] Applied {count} incremental file overrides")
        except Exception:
            print("[restore] No incremental manifest found (clean start)")

        print("[restore] Restore from WebDAV complete")
        restored = True

    # Strategy 2: HF Dataset fallback
    if not restored:
        print("[restore] WebDAV unavailable, trying HF Dataset fallback...")
        path = _hf_download()
        if path:
            with tarfile.open(path, "r:gz") as tar:
                tar.extractall(path=STATE_DIR)
            print("[restore] Restore from HF Dataset complete")
            restored = True

    if not restored:
        print("[restore] No backup found โ€” fresh start")

# โ”€โ”€ ่ฐƒๅบฆๅ™จ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def scheduler_loop():
    from datetime import datetime, timedelta
    last_full: datetime | None = None

    inc_interval = BACKUP_INCREMENT_INTERVAL
    full_interval = BACKUP_FULL_INTERVAL

    while True:
        time.sleep(inc_interval * 60)
        c = incremental_backup()
        print(f"[scheduler] Incremental: {c} files changed")

        now = datetime.now()
        if last_full is None or (now - last_full).total_seconds() / 60 >= full_interval:
            full_backup()
            last_full = now

# โ”€โ”€ CLI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "restore"

    if cmd == "restore":
        restore()
    elif cmd == "incremental":
        c = incremental_backup()
        print(f"[backup] Incremental: {c} files changed")
    elif cmd == "full":
        full_backup()
    elif cmd == "scheduler":
        scheduler_loop()
    else:
        print(f"Usage: {sys.argv[0]} {{restore|incremental|full|scheduler}}")
        sys.exit(1)