77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package core
|
|
|
|
import (
|
|
"backea/internal/backup/models"
|
|
"backea/internal/backup/strategy"
|
|
"backea/internal/mail"
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// Service represents a service to be backed up
|
|
type Service struct {
|
|
Name string
|
|
Directory string
|
|
Strategy strategy.Strategy
|
|
Mailer *mail.Mailer
|
|
}
|
|
|
|
// NewService creates a new backup service
|
|
func NewService(name string, directory string, strategy strategy.Strategy, mailer *mail.Mailer) *Service {
|
|
return &Service{
|
|
Name: name,
|
|
Directory: directory,
|
|
Strategy: strategy,
|
|
Mailer: mailer,
|
|
}
|
|
}
|
|
|
|
// Backup performs the backup for this service
|
|
func (s *Service) Backup(ctx context.Context) error {
|
|
log.Printf("Backing up service: %s", s.Name)
|
|
startTime := time.Now()
|
|
|
|
// Ensure directory exists
|
|
if _, err := os.Stat(s.Directory); os.IsNotExist(err) {
|
|
return fmt.Errorf("directory does not exist: %s", s.Directory)
|
|
}
|
|
|
|
// Execute the backup strategy
|
|
if err := s.Strategy.Execute(ctx, s.Name, s.Directory); err != nil {
|
|
if s.Mailer != nil {
|
|
s.Mailer.SendErrorNotification(s.Name, err)
|
|
}
|
|
return fmt.Errorf("backup failed: %w", err)
|
|
}
|
|
|
|
// Record backup completion
|
|
duration := time.Since(startTime)
|
|
log.Printf("Backup completed for %s in %v", s.Name, duration)
|
|
|
|
// Send success notification
|
|
if s.Mailer != nil {
|
|
s.Mailer.SendSuccessNotification(s.Name, duration)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetBackupInfos retrieves information about existing backups
|
|
func (s *Service) GetBackupInfos(ctx context.Context) ([]models.BackupInfo, error) {
|
|
return s.Strategy.ListBackups(ctx, s.Name)
|
|
}
|
|
|
|
// GetStorageUsage retrieves information about storage usage
|
|
func (s *Service) GetStorageUsage(ctx context.Context) (*models.StorageUsageInfo, error) {
|
|
return s.Strategy.GetStorageUsage(ctx, s.Name)
|
|
}
|
|
|
|
// RestoreBackup restores a backup by ID
|
|
func (s *Service) RestoreBackup(ctx context.Context, backupID string) error {
|
|
log.Printf("Restoring backup %s for service %s", backupID, s.Name)
|
|
return s.Strategy.RestoreBackup(ctx, backupID, s.Name)
|
|
}
|