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

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package cleaner
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"github.com/juju/loggo"
     9  
    10  	"github.com/juju/juju/watcher"
    11  	"github.com/juju/juju/worker"
    12  )
    13  
    14  var logger = loggo.GetLogger("juju.worker.cleaner")
    15  
    16  type StateCleaner interface {
    17  	Cleanup() error
    18  	WatchCleanups() (watcher.NotifyWatcher, error)
    19  }
    20  
    21  // Cleaner is responsible for cleaning up the state.
    22  type Cleaner struct {
    23  	st StateCleaner
    24  }
    25  
    26  // NewCleaner returns a worker.Worker that runs state.Cleanup()
    27  // if the CleanupWatcher signals documents marked for deletion.
    28  func NewCleaner(st StateCleaner) (worker.Worker, error) {
    29  	w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{
    30  		Handler: &Cleaner{st: st},
    31  	})
    32  	if err != nil {
    33  		return nil, errors.Trace(err)
    34  	}
    35  	return w, nil
    36  }
    37  
    38  func (c *Cleaner) SetUp() (watcher.NotifyWatcher, error) {
    39  	return c.st.WatchCleanups()
    40  }
    41  
    42  func (c *Cleaner) Handle(_ <-chan struct{}) error {
    43  	if err := c.st.Cleanup(); err != nil {
    44  		logger.Errorf("cannot cleanup state: %v", err)
    45  	}
    46  	// We do not return the err from Cleanup, because we don't want to stop
    47  	// the loop as a failure
    48  	return nil
    49  }
    50  
    51  func (c *Cleaner) TearDown() error {
    52  	// Nothing to cleanup, only state is the watcher
    53  	return nil
    54  }