github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/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  // HistoryPrunerParams specifies how history logs should be prunned.
    15  type HistoryPrunerParams struct {
    16  	// TODO(perrito666) We might want to have some sort of limitation of the collection size too.
    17  	MaxLogsPerEntity int
    18  	PruneInterval    time.Duration
    19  }
    20  
    21  // Facade represents an API that implements status history pruning.
    22  type Facade interface {
    23  	Prune(int) error
    24  }
    25  
    26  // Config holds all necessary attributes to start a pruner worker.
    27  type Config struct {
    28  	Facade           Facade
    29  	MaxLogsPerEntity uint
    30  	PruneInterval    time.Duration
    31  	// TODO(fwereade): 2016-03-17 lp:1558657
    32  	NewTimer worker.NewTimerFunc
    33  }
    34  
    35  // Validate will err unless basic requirements for a valid
    36  // config are met.
    37  func (c *Config) Validate() error {
    38  	if c.Facade == nil {
    39  		return errors.New("missing Facade")
    40  	}
    41  	if c.NewTimer == nil {
    42  		return errors.New("missing Timer")
    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(int(conf.MaxLogsPerEntity))
    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  }