github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/dblogpruner/manifold.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package dblogpruner
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/clock"
    10  	"github.com/juju/errors"
    11  	"gopkg.in/juju/worker.v1"
    12  	"gopkg.in/juju/worker.v1/dependency"
    13  
    14  	workerstate "github.com/juju/juju/worker/state"
    15  )
    16  
    17  // ManifoldConfig holds the information necessary to run a log pruner
    18  // worker in a dependency.Engine.
    19  type ManifoldConfig struct {
    20  	ClockName string
    21  	StateName string
    22  
    23  	PruneInterval time.Duration
    24  	NewWorker     func(Config) (worker.Worker, error)
    25  }
    26  
    27  func (config ManifoldConfig) Validate() error {
    28  	if config.ClockName == "" {
    29  		return errors.NotValidf("empty ClockName")
    30  	}
    31  	if config.StateName == "" {
    32  		return errors.NotValidf("empty StateName")
    33  	}
    34  	if config.PruneInterval <= 0 {
    35  		return errors.NotValidf("non-positive PruneInterval")
    36  	}
    37  	if config.NewWorker == nil {
    38  		return errors.NotValidf("nil NewWorker")
    39  	}
    40  	return nil
    41  }
    42  
    43  // Manifold returns a dependency.Manifold that will run a log pruner
    44  // worker.
    45  func Manifold(config ManifoldConfig) dependency.Manifold {
    46  	return dependency.Manifold{
    47  		Inputs: []string{
    48  			config.ClockName,
    49  			config.StateName,
    50  		},
    51  		Start: config.start,
    52  	}
    53  }
    54  
    55  // start is a method on ManifoldConfig because it's more readable than a closure.
    56  func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
    57  	if err := config.Validate(); err != nil {
    58  		return nil, errors.Trace(err)
    59  	}
    60  
    61  	var clock clock.Clock
    62  	if err := context.Get(config.ClockName, &clock); err != nil {
    63  		return nil, errors.Trace(err)
    64  	}
    65  
    66  	var stTracker workerstate.StateTracker
    67  	if err := context.Get(config.StateName, &stTracker); err != nil {
    68  		return nil, errors.Trace(err)
    69  	}
    70  	statePool, err := stTracker.Use()
    71  	if err != nil {
    72  		return nil, errors.Trace(err)
    73  	}
    74  
    75  	worker, err := config.NewWorker(Config{
    76  		State:         statePool.SystemState(),
    77  		Clock:         clock,
    78  		PruneInterval: config.PruneInterval,
    79  	})
    80  	if err != nil {
    81  		stTracker.Done()
    82  		return nil, errors.Trace(err)
    83  	}
    84  
    85  	go func() {
    86  		worker.Wait()
    87  		stTracker.Done()
    88  	}()
    89  	return worker, nil
    90  }