'wdcli backup': Move to separate package

This commit is contained in:
Tom Wiesing 2022-09-17 18:17:37 +02:00
parent 5cd5ae9be2
commit 822c70cd69
No known key found for this signature in database
11 changed files with 493 additions and 380 deletions

141
internal/backup/backup.go Normal file
View file

@ -0,0 +1,141 @@
// Package backup implements Distillery backups.
package backup
import (
"io/fs"
"os"
"path/filepath"
"sync"
"time"
"github.com/FAU-CDI/wisski-distillery/internal/component"
"github.com/FAU-CDI/wisski-distillery/internal/wisski"
"github.com/FAU-CDI/wisski-distillery/pkg/logging"
"github.com/tkw1536/goprogram/stream"
"golang.org/x/exp/slices"
)
// New create a new Backup
func New(io stream.IOStream, dis *wisski.Distillery, description Description) (backup Backup) {
backup.Description = description
// catch anything critical that happened during the snapshot
defer func() {
backup.ErrPanic = recover()
}()
// do the create keeping track of time!
logging.LogOperation(func() error {
backup.StartTime = time.Now()
backup.run(io, dis)
backup.EndTime = time.Now()
return nil
}, io, "Writing backup files")
return
}
type backupResult struct {
name string
err error
}
func (backup *Backup) run(io stream.IOStream, dis *wisski.Distillery) {
backups := dis.Backupable()
files := make(chan string, len(backups)) // channel for files being added into the backups
results := make(chan backupResult, len(backups)) // channel for results to be stored into
backup.ComponentErrors = make(map[string]error, len(backups))
wg := &sync.WaitGroup{} // to wait for the results
wg.Add(len(backups)) // tell the group about all the operations
for _, bc := range backups {
go func(bc component.Backupable, context component.BackupContext) {
defer wg.Done()
// make the backup and store the result
results <- backupResult{
name: bc.Name(),
err: bc.Backup(context),
}
}(bc, &context{
io: io,
dst: filepath.Join(backup.Description.Dest, bc.BackupName()),
files: files,
})
}
// backup instances
wg.Add(1)
go func() {
defer wg.Done()
instancesBackupDir := filepath.Join(backup.Description.Dest, "instances")
if err := os.Mkdir(instancesBackupDir, fs.ModeDir); err != nil {
backup.InstanceListErr = err
return
}
// list all instances
instances, err := dis.Instances().All()
if err != nil {
backup.InstanceListErr = err
return
}
backup.InstanceSnapshots = make([]wisski.Snapshot, len(instances))
for i, instance := range instances {
backup.InstanceSnapshots[i] = func() wisski.Snapshot {
dir := filepath.Join(instancesBackupDir, instance.Slug)
if err := os.Mkdir(dir, fs.ModeDir); err != nil {
return wisski.Snapshot{
ErrPanic: err,
}
}
files <- dir
return dis.Snapshot(instance, io.NonInteractive(), wisski.SnapshotDescription{
Dest: dir,
})
}()
}
}()
// finish processing all the results as soon as the group is done.
go func() {
defer close(results)
wg.Wait()
}()
// finish the message processing once results are finished.
go func() {
defer close(files) // no more file processing!
for result := range results {
backup.ComponentErrors[result.name] = result.err
}
}()
for file := range files {
// get the relative path to the root of the manifest.
// nothing *should* go wrong, but in case it does, use the original path.
path, err := filepath.Rel(backup.Description.Dest, file)
if err != nil {
path = file
}
// write it to the command line
// and also add it to the manifest
io.Printf("\033[2K\r%s", path)
backup.Manifest = append(backup.Manifest, path)
}
slices.Sort(backup.Manifest) // backup the manifest
io.Println("")
// sort the instances manifest
slices.SortFunc(backup.InstanceSnapshots, func(a, b wisski.Snapshot) bool {
return a.Instance.Slug < b.Instance.Slug
})
}

View file

@ -0,0 +1,98 @@
package backup
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/FAU-CDI/wisski-distillery/pkg/fsx"
"github.com/tkw1536/goprogram/stream"
)
// context implements [components.BackupContext]
type context struct {
io stream.IOStream
dst string // destination directory
files chan string // files channel
}
func (bc *context) sendPath(path string) {
// resolve the path, or bail out!
// TODO: Use the relative path here!
dst, err := bc.resolve(path)
if err != nil {
return
}
bc.files <- dst
}
func (bc *context) IO() stream.IOStream {
return bc.io
}
var errResolveAbsolute = errors.New("resolve: path must be relative")
func (bc *context) resolve(path string) (dest string, err error) {
if path == "" {
return bc.dst, nil
}
if filepath.IsAbs(path) {
return "", errResolveAbsolute
}
return filepath.Join(bc.dst, path), nil
}
func (bc *context) AddDirectory(path string, op func() error) error {
// resolve the path!
dst, err := bc.resolve(path)
if err != nil {
return err
}
// run the make directory
if err := os.Mkdir(dst, fs.ModeDir); err != nil {
return err
}
// tell the files that we are creating it!
bc.sendPath(path)
// and run the files!
// TODO: Add to manifest of some sort
return op()
}
func (bc *context) CopyFile(dst, src string) error {
dstPath, err := bc.resolve(dst)
if err != nil {
return err
}
bc.sendPath(dst)
return fsx.CopyFile(dstPath, src)
}
func (bc *context) AddFile(path string, op func(file io.Writer) error) error {
// resolve the path!
dst, err := bc.resolve(path)
if err != nil {
return err
}
// create the file
file, err := os.Create(dst)
if err != nil {
return err
}
defer file.Close()
// tell them that we are creating it!
bc.sendPath(path)
// and do whatever they wanted to do
// TODO: Add to the manifest of some sort
return op(file)
}

115
internal/backup/report.go Normal file
View file

@ -0,0 +1,115 @@
package backup
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/FAU-CDI/wisski-distillery/internal/wisski"
"github.com/FAU-CDI/wisski-distillery/pkg/countwriter"
"github.com/FAU-CDI/wisski-distillery/pkg/logging"
"github.com/tkw1536/goprogram/stream"
)
// Description provides a description for a backup
type Description struct {
Dest string // Destination path
Auto bool // Was the path created automatically?
}
// Backup describes a backup
type Backup struct {
Description Description
// Start and End Time of the backup
StartTime time.Time
EndTime time.Time
// various error states, which are ignored when creating the snapshot
ErrPanic interface{}
// errors for the various components
ComponentErrors map[string]error
// TODO: Make this proper
ConfigFileErr error
// Snapshots containing instances
InstanceListErr error
InstanceSnapshots []wisski.Snapshot
// List of files included
Manifest []string
}
// Strings turns this backup into a string for the BackupReport.
func (backup Backup) String() string {
var builder strings.Builder
backup.Report(&builder)
return builder.String()
}
// Report formats a report for this backup, and writes it into Writer.
func (backup Backup) Report(w io.Writer) (int, error) {
cw := countwriter.NewCountWriter(w)
encoder := json.NewEncoder(cw)
encoder.SetIndent("", " ")
io.WriteString(cw, "======= Backup =======\n")
fmt.Fprintf(cw, "Start: %s\n", backup.StartTime)
fmt.Fprintf(cw, "End: %s\n", backup.EndTime)
io.WriteString(cw, "\n")
io.WriteString(cw, "======= Description =======\n")
encoder.Encode(backup.Description)
io.WriteString(cw, "\n")
io.WriteString(cw, "======= Errors =======\n")
fmt.Fprintf(cw, "Panic: %v\n", backup.ErrPanic)
fmt.Fprintf(cw, "Component Errors: %v\n", backup.ComponentErrors)
fmt.Fprintf(cw, "ConfigFileErr: %s\n", backup.ConfigFileErr)
fmt.Fprintf(cw, "InstanceListErr: %s\n", backup.InstanceListErr)
io.WriteString(cw, "\n")
io.WriteString(cw, "======= Snapshots =======\n")
for _, s := range backup.InstanceSnapshots {
io.WriteString(cw, s.String())
io.WriteString(cw, "\n")
}
io.WriteString(cw, "======= Manifest =======\n")
for _, file := range backup.Manifest {
io.WriteString(cw, file+"\n")
}
io.WriteString(cw, "\n")
return cw.Sum()
}
// WriteReport writes out the report belonging to this backup.
// It is a separate function, to allow writing it indepenently of the rest.
func (backup Backup) WriteReport(io stream.IOStream) error {
return logging.LogOperation(func() error {
reportPath := filepath.Join(backup.Description.Dest, "report.txt")
io.Println(reportPath)
// create the report file!
report, err := os.Create(reportPath)
if err != nil {
return err
}
defer report.Close()
// print the report into it!
_, err = report.WriteString(backup.String())
return err
}, io, "Writing backup report")
}