Files
pg-bkup/pkg/backup.go

289 lines
7.7 KiB
Go
Raw Normal View History

// Package pkg /*
/*
2024-02-25 14:40:48 +01:00
Copyright © 2024 Jonas Kaninda
*/
package pkg
import (
"fmt"
2024-07-28 16:59:26 +02:00
"github.com/hpcloud/tail"
"github.com/jkaninda/pg-bkup/utils"
"github.com/spf13/cobra"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
func StartBackup(cmd *cobra.Command) {
_, _ = cmd.Flags().GetString("operation")
//Set env
utils.SetEnv("STORAGE_PATH", storagePath)
utils.GetEnv(cmd, "dbname", "DB_NAME")
utils.GetEnv(cmd, "port", "DB_PORT")
utils.GetEnv(cmd, "period", "SCHEDULE_PERIOD")
//Get flag value and set env
s3Path = utils.GetEnv(cmd, "path", "S3_PATH")
storage = utils.GetEnv(cmd, "storage", "STORAGE")
file = utils.GetEnv(cmd, "file", "FILE_NAME")
keepLast, _ := cmd.Flags().GetInt("keep-last")
prune, _ := cmd.Flags().GetBool("prune")
disableCompression, _ = cmd.Flags().GetBool("disable-compression")
executionMode, _ = cmd.Flags().GetString("mode")
2024-07-29 07:33:26 +02:00
dbName = os.Getenv("DB_NAME")
storagePath = os.Getenv("STORAGE_PATH")
//Generate file name
backupFileName := fmt.Sprintf("%s_%s.sql.gz", dbName, time.Now().Format("20060102_150405"))
if disableCompression {
backupFileName = fmt.Sprintf("%s_%s.sql", dbName, time.Now().Format("20060102_150405"))
}
if executionMode == "default" {
2024-07-29 07:33:26 +02:00
switch storage {
case "s3":
utils.Info("Backup database to s3 storage")
2024-07-29 07:33:26 +02:00
BackupDatabase(backupFileName, disableCompression, prune, keepLast)
s3Upload(backupFileName, s3Path)
case "local":
utils.Info("Backup database to local storage")
2024-07-29 07:33:26 +02:00
BackupDatabase(backupFileName, disableCompression, prune, keepLast)
moveToBackup(backupFileName, storagePath)
case "ssh":
fmt.Println("x is 2")
case "ftp":
fmt.Println("x is 3")
default:
utils.Info("Backup database to local storage")
BackupDatabase(backupFileName, disableCompression, prune, keepLast)
moveToBackup(backupFileName, storagePath)
}
2024-07-29 07:33:26 +02:00
} else if executionMode == "scheduled" {
scheduledMode()
} else {
utils.Fatal("Error, unknown execution mode!")
}
}
// Run in scheduled mode
func scheduledMode() {
fmt.Println()
fmt.Println("**********************************")
fmt.Println(" Starting PostgreSQL Bkup... ")
fmt.Println("***********************************")
utils.Info("Running in Scheduled mode")
utils.Info("Execution period ", os.Getenv("SCHEDULE_PERIOD"))
//Test database connexion
utils.TestDatabaseConnection()
utils.Info("Creating backup job...")
CreateCrontabScript(disableCompression, storage)
2024-07-28 16:59:26 +02:00
supervisorConfig := "/etc/supervisor/supervisord.conf"
// Start Supervisor
cmd := exec.Command("supervisord", "-c", supervisorConfig)
err := cmd.Start()
if err != nil {
utils.Fatal("Failed to start supervisord: %v", err)
}
utils.Info("Starting backup job...")
defer func() {
if err := cmd.Process.Kill(); err != nil {
utils.Info("Failed to kill supervisord process: %v", err)
} else {
utils.Info("Supervisor stopped.")
}
}()
if _, err := os.Stat(cronLogFile); os.IsNotExist(err) {
utils.Fatal("Log file %s does not exist.", cronLogFile)
}
t, err := tail.TailFile(cronLogFile, tail.Config{Follow: true})
if err != nil {
utils.Fatalf("Failed to tail file: %v", err)
}
// Read and print new lines from the log file
for line := range t.Lines {
fmt.Println(line.Text)
}
}
2024-01-19 06:49:29 +01:00
// BackupDatabase backup database
2024-07-29 07:33:26 +02:00
func BackupDatabase(backupFileName string, disableCompression bool, prune bool, keepLast int) {
dbHost = os.Getenv("DB_HOST")
dbPassword = os.Getenv("DB_PASSWORD")
dbUserName = os.Getenv("DB_USERNAME")
dbName = os.Getenv("DB_NAME")
dbPort = os.Getenv("DB_PORT")
storagePath = os.Getenv("STORAGE_PATH")
2024-07-28 16:59:26 +02:00
utils.Info("Starting database backup...")
if os.Getenv("DB_HOST") == "" || os.Getenv("DB_NAME") == "" || os.Getenv("DB_USERNAME") == "" || os.Getenv("DB_PASSWORD") == "" {
utils.Fatal("Please make sure all required environment variables for database are set")
} else {
err := os.Setenv("PGPASSWORD", dbPassword)
if err != nil {
return
}
utils.TestDatabaseConnection()
// Backup Database database
utils.Info("Backing up database...")
// Verify is compression is disabled
if disableCompression {
2024-01-19 14:41:25 +01:00
// Execute pg_dump
cmd := exec.Command("pg_dump",
"-h", dbHost,
"-p", dbPort,
"-U", dbUserName,
"-d", dbName,
)
output, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
2024-01-19 14:41:25 +01:00
// save output
2024-07-29 07:33:26 +02:00
file, err := os.Create(fmt.Sprintf("%s/%s", tmpPath, backupFileName))
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.Write(output)
if err != nil {
log.Fatal(err)
}
} else {
2024-01-19 14:41:25 +01:00
// Execute pg_dump
cmd := exec.Command("pg_dump",
"-h", dbHost,
"-p", dbPort,
"-U", dbUserName,
"-d", dbName,
)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
gzipCmd := exec.Command("gzip")
gzipCmd.Stdin = stdout
2024-01-19 14:41:25 +01:00
// save output
2024-07-29 07:33:26 +02:00
gzipCmd.Stdout, err = os.Create(fmt.Sprintf("%s/%s", tmpPath, backupFileName))
gzipCmd.Start()
if err != nil {
log.Fatal(err)
}
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
if err := gzipCmd.Wait(); err != nil {
log.Fatal(err)
}
2024-02-20 07:55:55 +01:00
}
2024-07-29 07:33:26 +02:00
utils.Done("Database has been backed up")
2024-02-20 07:55:55 +01:00
//Delete old backup
2024-07-29 07:33:26 +02:00
//if prune {
// deleteOldBackup(keepLast)
//}
2024-07-29 07:33:26 +02:00
historyFile, err := os.OpenFile(fmt.Sprintf("%s/history.txt", tmpPath), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer historyFile.Close()
2024-07-29 07:33:26 +02:00
if _, err := historyFile.WriteString(backupFileName + "\n"); err != nil {
log.Fatal(err)
}
}
}
2024-07-29 07:33:26 +02:00
func moveToBackup(backupFileName string, destinationPath string) {
//Copy backup from tmp folder to storage destination
err := utils.CopyFile(filepath.Join(tmpPath, backupFileName), filepath.Join(destinationPath, backupFileName))
if err != nil {
utils.Fatal("Error copying file ", backupFileName, err)
}
//Delete backup file from tmp folder
err = utils.DeleteFile(filepath.Join(tmpPath, backupFileName))
if err != nil {
fmt.Println("Error deleting file:", err)
}
utils.Done("Database has been backed up and copied to destination ")
}
func s3Upload(backupFileName string, s3Path string) {
bucket := os.Getenv("BUCKET_NAME")
utils.Info("Uploading file to S3 storage")
err := utils.UploadFileToS3(tmpPath, backupFileName, bucket, s3Path)
if err != nil {
utils.Fatalf("Error uploading file to S3: %s ", err)
2024-07-29 07:33:26 +02:00
}
//Delete backup file from tmp folder
err = utils.DeleteFile(filepath.Join(tmpPath, backupFileName))
if err != nil {
fmt.Println("Error deleting file:", err)
}
utils.Done("Database has been backed up and uploaded to s3 ")
}
func s3Backup(backupFileName string, disableCompression bool, s3Path string, prune bool, keepLast int) {
// Backup Database to S3 storage
2024-07-29 07:33:26 +02:00
//MountS3Storage(s3Path)
//BackupDatabase(backupFileName, disableCompression, prune, keepLast)
}
func deleteOldBackup(keepLast int) {
utils.Info("Deleting old backups...")
storagePath = os.Getenv("STORAGE_PATH")
// Define the directory path
backupDir := storagePath + "/"
// Get current time
currentTime := time.Now()
// Delete file
deleteFile := func(filePath string) error {
err := os.Remove(filePath)
if err != nil {
utils.Fatal("Error:", err)
} else {
2024-02-20 07:55:55 +01:00
utils.Done("File ", filePath, " deleted successfully")
}
return err
}
// Walk through the directory and delete files modified more than specified days ago
err := filepath.Walk(backupDir, func(filePath string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
// Check if it's a regular file and if it was modified more than specified days ago
if fileInfo.Mode().IsRegular() {
timeDiff := currentTime.Sub(fileInfo.ModTime())
if timeDiff.Hours() > 24*float64(keepLast) {
err := deleteFile(filePath)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
utils.Fatal("Error:", err)
return
}
}