github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/apiserver/common/cloudspec/cloudspec.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package cloudspec 5 6 import ( 7 "gopkg.in/juju/names.v2" 8 9 "github.com/juju/juju/apiserver/common" 10 "github.com/juju/juju/apiserver/params" 11 "github.com/juju/juju/environs" 12 ) 13 14 // CloudSpecAPI implements common methods for use by various 15 // facades for querying the cloud spec of models. 16 type CloudSpecAPI struct { 17 getCloudSpec func(names.ModelTag) (environs.CloudSpec, error) 18 getAuthFunc common.GetAuthFunc 19 } 20 21 // NewCloudSpec returns a new CloudSpecAPI. 22 func NewCloudSpec( 23 getCloudSpec func(names.ModelTag) (environs.CloudSpec, error), 24 getAuthFunc common.GetAuthFunc, 25 ) CloudSpecAPI { 26 return CloudSpecAPI{getCloudSpec, getAuthFunc} 27 } 28 29 // NewCloudSpecForModel returns a new CloudSpecAPI that permits access to only 30 // one model. 31 func NewCloudSpecForModel( 32 modelTag names.ModelTag, 33 getCloudSpec func() (environs.CloudSpec, error), 34 ) CloudSpecAPI { 35 return CloudSpecAPI{ 36 func(names.ModelTag) (environs.CloudSpec, error) { 37 // The tag passed in is guaranteed to be the 38 // same as "modelTag", as the authorizer below 39 // would have failed otherwise. 40 return getCloudSpec() 41 }, 42 func() (common.AuthFunc, error) { 43 return func(tag names.Tag) bool { 44 return tag == modelTag 45 }, nil 46 }, 47 } 48 } 49 50 // CloudSpec returns the model's cloud spec. 51 func (s CloudSpecAPI) CloudSpec(args params.Entities) (params.CloudSpecResults, error) { 52 authFunc, err := s.getAuthFunc() 53 if err != nil { 54 return params.CloudSpecResults{}, err 55 } 56 results := params.CloudSpecResults{ 57 Results: make([]params.CloudSpecResult, len(args.Entities)), 58 } 59 for i, arg := range args.Entities { 60 tag, err := names.ParseModelTag(arg.Tag) 61 if err != nil { 62 results.Results[i].Error = common.ServerError(err) 63 continue 64 } 65 if !authFunc(tag) { 66 results.Results[i].Error = common.ServerError(common.ErrPerm) 67 continue 68 } 69 results.Results[i] = s.GetCloudSpec(tag) 70 } 71 return results, nil 72 } 73 74 // GetCloudSpec constucts the CloudSpec for a validated and authorized model. 75 func (s CloudSpecAPI) GetCloudSpec(tag names.ModelTag) params.CloudSpecResult { 76 var result params.CloudSpecResult 77 spec, err := s.getCloudSpec(tag) 78 if err != nil { 79 result.Error = common.ServerError(err) 80 return result 81 } 82 var paramsCloudCredential *params.CloudCredential 83 if spec.Credential != nil && spec.Credential.AuthType() != "" { 84 paramsCloudCredential = ¶ms.CloudCredential{ 85 AuthType: string(spec.Credential.AuthType()), 86 Attributes: spec.Credential.Attributes(), 87 } 88 } 89 result.Result = ¶ms.CloudSpec{ 90 spec.Type, 91 spec.Name, 92 spec.Region, 93 spec.Endpoint, 94 spec.IdentityEndpoint, 95 spec.StorageEndpoint, 96 paramsCloudCredential, 97 } 98 return result 99 }