github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/worker/discoverspaces/manifold.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package discoverspaces
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  
     9  	"github.com/juju/juju/api/base"
    10  	"github.com/juju/juju/api/discoverspaces"
    11  	"github.com/juju/juju/environs"
    12  	"github.com/juju/juju/network"
    13  	"github.com/juju/juju/worker"
    14  	"github.com/juju/juju/worker/dependency"
    15  	"github.com/juju/juju/worker/gate"
    16  )
    17  
    18  type ManifoldConfig struct {
    19  	APICallerName string
    20  	EnvironName   string
    21  	UnlockerName  string
    22  
    23  	NewFacade func(base.APICaller) (Facade, error)
    24  	NewWorker func(Config) (worker.Worker, error)
    25  }
    26  
    27  func NewFacade(apiCaller base.APICaller) (Facade, error) {
    28  	return discoverspaces.NewAPI(apiCaller), nil
    29  }
    30  
    31  func Manifold(config ManifoldConfig) dependency.Manifold {
    32  	inputs := []string{config.APICallerName, config.EnvironName}
    33  	if config.UnlockerName != "" {
    34  		inputs = append(inputs, config.UnlockerName)
    35  	}
    36  	return dependency.Manifold{
    37  		Inputs: inputs,
    38  		Start:  startFunc(config),
    39  	}
    40  }
    41  
    42  func startFunc(config ManifoldConfig) dependency.StartFunc {
    43  	return func(context dependency.Context) (worker.Worker, error) {
    44  
    45  		// optional unlocker, might stay nil
    46  		var unlocker gate.Unlocker
    47  		if config.UnlockerName != "" {
    48  			if err := context.Get(config.UnlockerName, &unlocker); err != nil {
    49  				return nil, errors.Trace(err)
    50  			}
    51  		}
    52  
    53  		var environ environs.Environ
    54  		if err := context.Get(config.EnvironName, &environ); err != nil {
    55  			return nil, errors.Trace(err)
    56  		}
    57  
    58  		var apiCaller base.APICaller
    59  		if err := context.Get(config.APICallerName, &apiCaller); err != nil {
    60  			return nil, errors.Trace(err)
    61  		}
    62  		facade, err := config.NewFacade(apiCaller)
    63  		if err != nil {
    64  			return nil, errors.Trace(err)
    65  		}
    66  
    67  		w, err := config.NewWorker(Config{
    68  			Facade:   facade,
    69  			Environ:  environ,
    70  			NewName:  network.ConvertSpaceName,
    71  			Unlocker: unlocker,
    72  		})
    73  		if err != nil {
    74  			return nil, errors.Trace(err)
    75  		}
    76  		return w, nil
    77  	}
    78  }