github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/state/stateenvirons/config.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package stateenvirons
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/names.v2"
     9  
    10  	"github.com/juju/juju/cloud"
    11  	"github.com/juju/juju/environs"
    12  	"github.com/juju/juju/state"
    13  )
    14  
    15  // EnvironConfigGetter implements environs.EnvironConfigGetter
    16  // in terms of a *state.State.
    17  type EnvironConfigGetter struct {
    18  	*state.State
    19  }
    20  
    21  // CloudSpec implements environs.EnvironConfigGetter.
    22  func (g EnvironConfigGetter) CloudSpec(tag names.ModelTag) (environs.CloudSpec, error) {
    23  	model, err := g.GetModel(tag)
    24  	if err != nil {
    25  		return environs.CloudSpec{}, errors.Trace(err)
    26  	}
    27  	cloudName := model.Cloud()
    28  	regionName := model.CloudRegion()
    29  	credentialTag, _ := model.CloudCredential()
    30  	return CloudSpec(g.State, cloudName, regionName, credentialTag)
    31  }
    32  
    33  // CloudSpec returns an environs.CloudSpec from a *state.State,
    34  // given the cloud, region and credential names.
    35  func CloudSpec(
    36  	accessor state.CloudAccessor,
    37  	cloudName, regionName string,
    38  	credentialTag names.CloudCredentialTag,
    39  ) (environs.CloudSpec, error) {
    40  	modelCloud, err := accessor.Cloud(cloudName)
    41  	if err != nil {
    42  		return environs.CloudSpec{}, errors.Trace(err)
    43  	}
    44  
    45  	var credential *cloud.Credential
    46  	if credentialTag != (names.CloudCredentialTag{}) {
    47  		credentialValue, err := accessor.CloudCredential(credentialTag)
    48  		if err != nil {
    49  			return environs.CloudSpec{}, errors.Trace(err)
    50  		}
    51  		credential = &credentialValue
    52  	}
    53  
    54  	return environs.MakeCloudSpec(modelCloud, cloudName, regionName, credential)
    55  }
    56  
    57  // NewEnvironFunc defines the type of a function that, given a state.State,
    58  // returns a new Environ.
    59  type NewEnvironFunc func(*state.State) (environs.Environ, error)
    60  
    61  // GetNewEnvironFunc returns a NewEnvironFunc, that constructs Environs
    62  // using the given environs.NewEnvironFunc.
    63  func GetNewEnvironFunc(newEnviron environs.NewEnvironFunc) NewEnvironFunc {
    64  	return func(st *state.State) (environs.Environ, error) {
    65  		g := EnvironConfigGetter{st}
    66  		return environs.GetEnviron(g, newEnviron)
    67  	}
    68  }