Repository navigation
Expand file tree
/
Copy pathAPI_
More file actions
187 lines (152 loc) · 6.73 KB
/
Copy pathAPI_
File metadata and controls
187 lines (152 loc) · 6.73 KB
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
#!/usr/bin/env python3
"""
Hourly backup script for stats.db
Creates timestamped backups and deletes backups older than 24 hours.
Usage:
python backup_hourly.py
Setup with cron (Linux):
crontab -e
# Add this line to run every hour:
0 * * * * cd /home/timothy/backup && /usr/bin/python3 backup_hourly.py >> backup_hourly.log 2>&1
Setup with Task Scheduler (Windows):
- Create a new task that runs hourly
- Action: Start program python.exe
- Arguments: backup_hourly.py
- Start in: /home/timothy/backup
"""
import os
import shutil
from pathlib import Path
from datetime import datetime, timedelta
# Configuration
SCRIPT_DIR = Path(__file__).parent.absolute()
DB_FILE = SCRIPT_DIR / "stats.db"
BACKUP_DIR = SCRIPT_DIR / "backups"
BACKUP_RETENTION_HOURS = 24
def create_backup() -> bool:
"""Create an hourly backup of stats.db with timestamp.
Returns:
bool: True if backup succeeded, False otherwise
"""
try:
print(f"[BACKUP] Script directory: {SCRIPT_DIR}")
print(f"[BACKUP] Database file path: {DB_FILE}")
print(f"[BACKUP] Backup directory: {BACKUP_DIR}")
print(f"[BACKUP] Database file exists: {DB_FILE.exists()}")
print(f"[BACKUP] Database file readable: {os.access(DB_FILE, os.R_OK) if DB_FILE.exists() else 'N/A'}")
print(f"[BACKUP] Backup dir exists: {BACKUP_DIR.exists()}")
print(f"[BACKUP] Backup dir writable: {os.access(BACKUP_DIR, os.W_OK) if BACKUP_DIR.exists() else 'N/A'}")
# Create backup directory if it doesn't exist
try:
BACKUP_DIR.mkdir(exist_ok=True, mode=0o755)
print(f"[BACKUP] Backup directory ensured: {BACKUP_DIR}")
except PermissionError:
# Fallback: try creating in home directory
fallback_dir = Path.home() / "backup_api_backups"
print(f"[FALLBACK] Cannot create {BACKUP_DIR}, trying {fallback_dir}")
fallback_dir.mkdir(exist_ok=True, mode=0o755)
global BACKUP_DIR
BACKUP_DIR = fallback_dir
print(f"[FALLBACK] Using alternate backup directory: {BACKUP_DIR}")
except Exception as e:
print(f"[ERROR] Failed to create backup directory: {e}")
# Last resort: use temp directory
import tempfile
BACKUP_DIR = Path(tempfile.gettempdir()) / "api_backups"
BACKUP_DIR.mkdir(exist_ok=True)
print(f"[FALLBACK] Using temporary directory: {BACKUP_DIR}")
# Check if source file exists
if not DB_FILE.exists():
print(f"[ERROR] Source file not found: {DB_FILE}")
return False
# Generate timestamp for backup filename (YYYY-MM-DD_HH-00-00)
timestamp = datetime.now().strftime("%Y-%m-%d_%H-00-00")
backup_filename = f"stats_{timestamp}.db"
backup_path = BACKUP_DIR / backup_filename
# Check if backup for this hour already exists
if backup_path.exists():
print(f"[SKIP] Backup already exists: {backup_filename}")
return True
# Copy the file with fallback methods
print(f"[BACKUP] Creating backup: {backup_filename}")
copy_success = False
# Method 1: Try shutil.copy2 (preserves metadata)
try:
shutil.copy2(DB_FILE, backup_path)
copy_success = True
print(f"[BACKUP] Copy method: shutil.copy2")
except Exception as e:
print(f"[FALLBACK] shutil.copy2 failed: {e}, trying alternative...")
# Method 2: Try shutil.copy (without metadata)
try:
shutil.copy(DB_FILE, backup_path)
copy_success = True
print(f"[FALLBACK] Copy method: shutil.copy")
except Exception as e2:
print(f"[FALLBACK] shutil.copy failed: {e2}, trying manual read/write...")
# Method 3: Manual byte copy
try:
with open(DB_FILE, 'rb') as src:
with open(backup_path, 'wb') as dst:
dst.write(src.read())
copy_success = True
print(f"[FALLBACK] Copy method: manual byte copy")
except Exception as e3:
print(f"[ERROR] All copy methods failed: {e3}")
return False
if copy_success:
# Verify the backup was created and has content
if backup_path.exists() and backup_path.stat().st_size > 0:
print(f"[SUCCESS] Backup created: {backup_filename} ({backup_path.stat().st_size} bytes)")
return True
else:
print(f"[ERROR] Backup file is empty or missing: {backup_filename}")
return False
return False
except Exception as e:
print(f"[ERROR] Unexpected error during backup: {e}")
import traceback
traceback.print_exc()
return False
def cleanup_old_backups():
"""Delete backups older than BACKUP_RETENTION_HOURS."""
try:
if not BACKUP_DIR.exists():
print("[CLEANUP] Backup directory doesn't exist, nothing to clean up")
return
now = datetime.now()
cutoff = now - timedelta(hours=BACKUP_RETENTION_HOURS)
deleted_count = 0
kept_count = 0
print(f"[CLEANUP] Scanning for backups older than {cutoff.strftime('%Y-%m-%d %H:%M:%S')}")
for backup_file in BACKUP_DIR.glob("stats_*.db"):
try:
# Get file modification time
mtime = datetime.fromtimestamp(backup_file.stat().st_mtime)
if mtime < cutoff:
backup_file.unlink()
print(f"[CLEANUP] Deleted old backup: {backup_file.name} (from {mtime.strftime('%Y-%m-%d %H:%M:%S')})")
deleted_count += 1
else:
kept_count += 1
except Exception as e:
print(f"[CLEANUP] Error processing {backup_file.name}: {e}")
print(f"[CLEANUP] Deleted {deleted_count} old backup(s), kept {kept_count} recent backup(s)")
except Exception as e:
print(f"[ERROR] Cleanup failed: {e}")
def main():
print("=" * 60)
print(f"Database Backup - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
# Create backup
success = create_backup()
if success:
print("\n[SUCCESS] Backup completed successfully")
# Clean up old backups
print("\n" + "-" * 60)
cleanup_old_backups()
else:
print("\n[FAILURE] Backup failed")
print("=" * 60)
if __name__ == "__main__":
main()