Create sync.py
Browse files
sync.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import tarfile
|
| 4 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 5 |
+
|
| 6 |
+
api = HfApi()
|
| 7 |
+
repo_id = os.getenv("HF_DATASET")
|
| 8 |
+
token = os.getenv("HF_TOKEN")
|
| 9 |
+
FILENAME = "latest_backup.tar.gz"
|
| 10 |
+
|
| 11 |
+
def restore():
|
| 12 |
+
try:
|
| 13 |
+
if not repo_id or not token:
|
| 14 |
+
print("Skip Restore: HF_DATASET or HF_TOKEN not set")
|
| 15 |
+
return
|
| 16 |
+
|
| 17 |
+
# 直接下载最新文件
|
| 18 |
+
print(f"Downloading {FILENAME} from {repo_id}...")
|
| 19 |
+
path = hf_hub_download(repo_id=repo_id, filename=FILENAME, repo_type="dataset", token=token)
|
| 20 |
+
|
| 21 |
+
with tarfile.open(path, "r:gz") as tar:
|
| 22 |
+
tar.extractall(path="/root/.openclaw/")
|
| 23 |
+
print(f"Success: Restored from {FILENAME}")
|
| 24 |
+
return True
|
| 25 |
+
except Exception as e:
|
| 26 |
+
# 如果是第一次运行,仓库里没文件,报错是正常的
|
| 27 |
+
print(f"Restore Note: No existing backup found or error: {e}")
|
| 28 |
+
|
| 29 |
+
def backup():
|
| 30 |
+
try:
|
| 31 |
+
if not repo_id or not token:
|
| 32 |
+
print("Skip Backup: HF_DATASET or HF_TOKEN not set")
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
with tarfile.open(FILENAME, "w:gz") as tar:
|
| 36 |
+
# 备份关键数据
|
| 37 |
+
paths_to_backup = [
|
| 38 |
+
"/root/.openclaw/sessions",
|
| 39 |
+
"/root/.openclaw/agents/main/sessions",
|
| 40 |
+
"/root/.openclaw/openclaw.json"
|
| 41 |
+
]
|
| 42 |
+
for p in paths_to_backup:
|
| 43 |
+
if os.path.exists(p):
|
| 44 |
+
arcname = p.replace("/root/.openclaw/", "")
|
| 45 |
+
tar.add(p, arcname=arcname)
|
| 46 |
+
|
| 47 |
+
# 上传并覆盖
|
| 48 |
+
api.upload_file(
|
| 49 |
+
path_or_fileobj=FILENAME,
|
| 50 |
+
path_in_repo=FILENAME,
|
| 51 |
+
repo_id=repo_id,
|
| 52 |
+
repo_type="dataset",
|
| 53 |
+
token=token
|
| 54 |
+
)
|
| 55 |
+
print(f"Backup {FILENAME} Success (Overwritten).")
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"Backup Error: {e}")
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
if len(sys.argv) > 1 and sys.argv[1] == "backup":
|
| 61 |
+
backup()
|
| 62 |
+
else:
|
| 63 |
+
restore()
|