2018-08-27 15:09:24 +02:00
|
|
|
package pruning
|
|
|
|
|
|
|
|
import (
|
2018-08-30 11:44:43 +02:00
|
|
|
"fmt"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/zrepl/zrepl/config"
|
2018-08-27 15:09:24 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type KeepRule interface {
|
2018-08-30 11:44:43 +02:00
|
|
|
KeepRule(snaps []Snapshot) (destroyList []Snapshot)
|
2018-08-27 15:09:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type Snapshot interface {
|
|
|
|
Name() string
|
|
|
|
Replicated() bool
|
|
|
|
Date() time.Time
|
|
|
|
}
|
|
|
|
|
2018-08-29 19:00:45 +02:00
|
|
|
// The returned snapshot list is guaranteed to only contains elements of input parameter snaps
|
2018-08-27 15:09:24 +02:00
|
|
|
func PruneSnapshots(snaps []Snapshot, keepRules []KeepRule) []Snapshot {
|
|
|
|
|
2018-08-30 11:44:43 +02:00
|
|
|
if keepRules == nil || len(keepRules) == 0 {
|
|
|
|
return []Snapshot{}
|
2018-08-27 15:09:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
remCount := make(map[Snapshot]int, len(snaps))
|
|
|
|
for _, r := range keepRules {
|
|
|
|
ruleRems := r.KeepRule(snaps)
|
|
|
|
for _, ruleRem := range ruleRems {
|
|
|
|
remCount[ruleRem]++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
remove := make([]Snapshot, 0, len(snaps))
|
|
|
|
for snap, rc := range remCount {
|
|
|
|
if rc == len(keepRules) {
|
|
|
|
remove = append(remove, snap)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return remove
|
|
|
|
}
|
2018-08-30 11:44:43 +02:00
|
|
|
|
|
|
|
func RulesFromConfig(in []config.PruningEnum) (rules []KeepRule, err error) {
|
|
|
|
rules = make([]KeepRule, len(in))
|
|
|
|
for i := range in {
|
|
|
|
rules[i], err = RuleFromConfig(in[i])
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "cannot build rule #%d", i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return rules, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func RuleFromConfig(in config.PruningEnum) (KeepRule, error) {
|
|
|
|
switch v := in.Ret.(type) {
|
|
|
|
case *config.PruneKeepNotReplicated:
|
|
|
|
return NewKeepNotReplicated(), nil
|
|
|
|
case *config.PruneKeepLastN:
|
|
|
|
return NewKeepLastN(v.Count)
|
|
|
|
case *config.PruneKeepRegex:
|
|
|
|
return NewKeepRegex(v.Regex)
|
2018-09-24 17:30:03 +02:00
|
|
|
case *config.PruneGrid:
|
|
|
|
return NewKeepGrid(v)
|
2018-08-30 11:44:43 +02:00
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unknown keep rule type %T", v)
|
|
|
|
}
|
|
|
|
}
|