124 lines
2.5 KiB
Go
124 lines
2.5 KiB
Go
package api
|
|
|
|
import (
|
|
"ddbb/pkg/backup"
|
|
"ddbb/pkg/docker"
|
|
"ddbb/pkg/restore"
|
|
"log"
|
|
"net/http"
|
|
"sync"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Init backup status
|
|
var (
|
|
backupStatus = "Idle"
|
|
statusMutex sync.Mutex
|
|
)
|
|
|
|
func BackupAllDatabases() {
|
|
allBackups, _ := docker.GetBackupConfigsFromContainers()
|
|
for _, job := range allBackups {
|
|
backup.BackupJob(job)
|
|
}
|
|
}
|
|
|
|
// Dump any database giving an Id
|
|
func triggerDump(c *gin.Context) {
|
|
// Extract backup job name from the form POST data
|
|
backupId := c.PostForm("id")
|
|
if backupId == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing backup job id"})
|
|
return
|
|
}
|
|
|
|
// Find the backup job config with the matching name
|
|
var chosenJob *backup.Config
|
|
jobs, err := docker.GetBackupConfigsFromContainers()
|
|
if err != nil {
|
|
log.Fatalf("Error while parsing docker labels: %v", err)
|
|
}
|
|
for i, job := range jobs {
|
|
if job.Id == backupId {
|
|
chosenJob = &jobs[i]
|
|
break
|
|
}
|
|
}
|
|
|
|
if chosenJob == nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Backup job not found"})
|
|
return
|
|
}
|
|
|
|
// Run the backup asynchronously
|
|
go func(cfg backup.Config) {
|
|
statusMutex.Lock()
|
|
backupStatus = "Running"
|
|
statusMutex.Unlock()
|
|
|
|
backup.BackupJob(cfg)
|
|
|
|
statusMutex.Lock()
|
|
backupStatus = "Completed"
|
|
statusMutex.Unlock()
|
|
}(*chosenJob)
|
|
|
|
c.Redirect(http.StatusSeeOther, "/")
|
|
}
|
|
|
|
// Restore any database giving an Id
|
|
func triggerRestore(c *gin.Context) {
|
|
// Extract backup job name from the form POST data
|
|
restoreId := c.PostForm("id")
|
|
if restoreId == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing restore job id"})
|
|
return
|
|
}
|
|
|
|
// Find the backup job config with the matching name
|
|
var chosenJob *backup.Config
|
|
jobs, err := docker.GetBackupConfigsFromContainers()
|
|
if err != nil {
|
|
log.Fatalf("Error while parsing docker labels: %v", err)
|
|
}
|
|
for i, job := range jobs {
|
|
if job.Id == restoreId {
|
|
chosenJob = &jobs[i]
|
|
break
|
|
}
|
|
}
|
|
|
|
if chosenJob == nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Restore job not found"})
|
|
return
|
|
}
|
|
|
|
// Run the backup asynchronously
|
|
go func(cfg backup.Config) {
|
|
statusMutex.Lock()
|
|
backupStatus = "Running"
|
|
statusMutex.Unlock()
|
|
|
|
restore.RestoreJob(cfg)
|
|
|
|
statusMutex.Lock()
|
|
backupStatus = "Completed"
|
|
statusMutex.Unlock()
|
|
}(*chosenJob)
|
|
|
|
c.Redirect(http.StatusSeeOther, "/")
|
|
}
|
|
|
|
func SetupRouter() *gin.Engine {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
r := gin.Default()
|
|
r.SetTrustedProxies([]string{"127.0.0.1"})
|
|
r.LoadHTMLGlob("templates/*")
|
|
r.POST("/backup", triggerDump)
|
|
r.POST("/restore", triggerRestore)
|
|
r.GET("/", ServeBackupPage)
|
|
|
|
return r
|
|
}
|