Files
nmon/internal/backup/backup_inventory.go

68 lines
1.8 KiB
Go

package backup
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/v10networks/nmon/internal/store"
)
// addInventory archives the inventory: a VACUUM INTO copy on SQLite (counted by opening that copy, so the
// numbers describe the archived data), the JSON-lines export elsewhere.
func addInventory(ctx context.Context, o *Options, aw *archiveWriter, m *Manifest, scratch string) error {
m.Dialect = o.Store.Dialect()
var err error
if m.Dialect == store.DriverSQLite {
err = snapshotSQLite(ctx, o, aw, m, scratch)
} else {
err = exportJSONL(ctx, o, aw, m, scratch)
}
if err != nil {
return fmt.Errorf("backup: inventory: %w", err)
}
return nil
}
func snapshotSQLite(ctx context.Context, o *Options, aw *archiveWriter, m *Manifest, scratch string) error {
snap := filepath.Join(scratch, inventoryDB)
if err := o.Store.SnapshotInto(ctx, snap); err != nil {
return err
}
cp, err := store.Open(ctx, store.DriverSQLite, snap, nil, o.Clock)
if err != nil {
return err
}
defer func() { _ = cp.Close() }() // read-only use of the copy
if m.Rows, err = cp.RowCounts(ctx); err != nil {
return err
}
if m.Rollup, err = cp.RollupCheckpoints(ctx); err != nil {
return err
}
m.Inventory = inventoryDB
return aw.addFile(inventoryDB, snap)
}
func exportJSONL(ctx context.Context, o *Options, aw *archiveWriter, m *Manifest, scratch string) error {
path := filepath.Join(scratch, inventoryJSONL)
f, err := os.Create(path)
if err != nil {
return err
}
counts, err := o.Store.ExportJSONL(ctx, f)
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
return err
}
m.Rows = counts
if m.Rollup, err = o.Store.RollupCheckpoints(ctx); err != nil {
return err
}
m.Inventory = inventoryJSONL
return aw.addFile(inventoryJSONL, path)
}