github.com/Pankov404/juju@v0.0.0-20150703034450-be266991dceb/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  	"launchpad.net/tomb"
    11  
    12  	"github.com/juju/juju/state"
    13  	"github.com/juju/juju/worker"
    14  )
    15  
    16  // HistoryPrunerParams specifies how history logs should be prunned.
    17  type HistoryPrunerParams struct {
    18  	// TODO(perrito666) We might want to have some sort of limitation of the collection size too.
    19  	MaxLogsPerState int
    20  	PruneInterval   time.Duration
    21  }
    22  
    23  const DefaultMaxLogsPerState = 100
    24  const DefaultPruneInterval = 5 * time.Minute
    25  
    26  // NewHistoryPrunerParams returns a HistoryPrunerParams initialized with default parameter.
    27  func NewHistoryPrunerParams() *HistoryPrunerParams {
    28  	return &HistoryPrunerParams{
    29  		MaxLogsPerState: DefaultMaxLogsPerState,
    30  		PruneInterval:   DefaultPruneInterval,
    31  	}
    32  }
    33  
    34  type pruneWorker struct {
    35  	st     *state.State
    36  	params *HistoryPrunerParams
    37  }
    38  
    39  // New returns a worker.Worker for history Pruner.
    40  func New(st *state.State, params *HistoryPrunerParams) worker.Worker {
    41  	w := &pruneWorker{
    42  		st:     st,
    43  		params: params,
    44  	}
    45  	return worker.NewSimpleWorker(w.loop)
    46  }
    47  
    48  // TODO(perrito666) Adda comprehensive test for the worker features
    49  func (w *pruneWorker) loop(stopCh <-chan struct{}) error {
    50  	p := w.params
    51  	for {
    52  		select {
    53  		case <-stopCh:
    54  			return tomb.ErrDying
    55  		case <-time.After(p.PruneInterval):
    56  			err := state.PruneStatusHistory(w.st, p.MaxLogsPerState)
    57  			if err != nil {
    58  				return errors.Trace(err)
    59  			}
    60  		}
    61  	}
    62  }