Enhance Gitea database backup script with relative paths, logging, and Docker checks; update scheduling script to include Docker check

This commit is contained in:
2025-04-19 19:36:36 -06:00
parent 5f329bc7e3
commit cba5e8167b
8 changed files with 157 additions and 9 deletions

View File

@@ -1,32 +1,58 @@
# Gitea Database Backup Script
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$backupDir = ".\backups"
$backupFile = "$backupDir\gitea-db-backup-$timestamp.sql"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$backupDir = Join-Path $scriptDir "backups"
$backupFile = Join-Path $backupDir "gitea-db-backup-$timestamp.sql"
# Ensure backup directory exists
if (-not (Test-Path $backupDir)) {
New-Item -ItemType Directory -Path $backupDir
}
# Log execution of the script
$logFile = Join-Path $backupDir "backup-log.txt"
"[$timestamp] Starting database backup..." | Out-File -Append -FilePath $logFile
# Check if Docker is running
$dockerRunning = $false
try {
$dockerStatus = docker info 2>&1
$dockerRunning = $LASTEXITCODE -eq 0
} catch {
$dockerRunning = $false
}
if (-not $dockerRunning) {
"[$timestamp] Error: Docker is not running. Backup failed." | Out-File -Append -FilePath $logFile
exit 1
}
# Check if Gitea container is running
$containerRunning = docker ps --format "{{.Names}}" | Select-String -Pattern "gitea-db" -Quiet
if (-not $containerRunning) {
"[$timestamp] Error: Gitea database container is not running. Backup failed." | Out-File -Append -FilePath $logFile
exit 1
}
# Create database dump
Write-Host "Creating database backup to $backupFile..."
"[$timestamp] Creating database backup to $backupFile..." | Out-File -Append -FilePath $logFile
docker exec gitea-db pg_dump -U gitea -d gitea > $backupFile
# Check if backup was successful
if ($LASTEXITCODE -eq 0 -and (Test-Path $backupFile) -and (Get-Item $backupFile).Length -gt 0) {
Write-Host "Backup completed successfully!"
"[$timestamp] Backup completed successfully!" | Out-File -Append -FilePath $logFile
# Optional: Compress the backup file
Compress-Archive -Path $backupFile -DestinationPath "$backupFile.zip" -Force
Remove-Item $backupFile
Write-Host "Backup compressed to $backupFile.zip"
"[$timestamp] Backup compressed to $backupFile.zip" | Out-File -Append -FilePath $logFile
} else {
Write-Host "Backup failed!" -ForegroundColor Red
"[$timestamp] Backup failed!" | Out-File -Append -FilePath $logFile
}
# Optional: Clean up old backups (keep last 10)
$oldBackups = Get-ChildItem -Path $backupDir -Filter "gitea-db-backup-*.zip" | Sort-Object LastWriteTime -Descending | Select-Object -Skip 10
foreach ($backup in $oldBackups) {
Remove-Item $backup.FullName
Write-Host "Removed old backup: $($backup.Name)"
"[$timestamp] Removed old backup: $($backup.Name)" | Out-File -Append -FilePath $logFile
}