github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/worker/statushistorypruner/worker.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package statushistorypruner
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/errors"
    10  
    11  	"github.com/juju/juju/worker"
    12  )
    13  
    14  // Facade represents an API that implements status history pruning.
    15  type Facade interface {
    16  	Prune(time.Duration, int) error
    17  }
    18  
    19  // Config holds all necessary attributes to start a pruner worker.
    20  type Config struct {
    21  	Facade         Facade
    22  	MaxHistoryTime time.Duration
    23  	MaxHistoryMB   uint
    24  	PruneInterval  time.Duration
    25  	// TODO(fwereade): 2016-03-17 lp:1558657
    26  	NewTimer worker.NewTimerFunc
    27  }
    28  
    29  // Validate will err unless basic requirements for a valid
    30  // config are met.
    31  func (c *Config) Validate() error {
    32  	if c.Facade == nil {
    33  		return errors.New("missing Facade")
    34  	}
    35  	if c.NewTimer == nil {
    36  		return errors.New("missing Timer")
    37  	}
    38  	// TODO(perrito666) this assumes out of band knowledge of how filter
    39  	// values are treated, expand config to support the "dont use this filter"
    40  	// case as an explicit statement.
    41  	if c.MaxHistoryMB <= 0 && c.MaxHistoryTime <= 0 {
    42  		return errors.New("missing prune criteria, no size or date limit provided")
    43  	}
    44  	return nil
    45  }
    46  
    47  // New returns a worker.Worker for history Pruner.
    48  func New(conf Config) (worker.Worker, error) {
    49  	if err := conf.Validate(); err != nil {
    50  		return nil, errors.Trace(err)
    51  	}
    52  	doPruning := func(stop <-chan struct{}) error {
    53  		err := conf.Facade.Prune(conf.MaxHistoryTime, int(conf.MaxHistoryMB))
    54  		if err != nil {
    55  			return errors.Trace(err)
    56  		}
    57  		return nil
    58  	}
    59  
    60  	return worker.NewPeriodicWorker(doPruning, conf.PruneInterval, conf.NewTimer), nil
    61  }