github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/apiserver/spaces/spaces.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package spaces 5 6 import ( 7 "github.com/juju/errors" 8 9 "github.com/juju/juju/apiserver/common" 10 "github.com/juju/juju/apiserver/common/networkingcommon" 11 "github.com/juju/juju/apiserver/params" 12 "github.com/juju/juju/state" 13 ) 14 15 func init() { 16 common.RegisterStandardFacade("Spaces", 2, NewAPI) 17 } 18 19 // API defines the methods the Spaces API facade implements. 20 type API interface { 21 CreateSpaces(params.CreateSpacesParams) (params.ErrorResults, error) 22 ListSpaces() (params.ListSpacesResults, error) 23 } 24 25 // spacesAPI implements the API interface. 26 type spacesAPI struct { 27 backing networkingcommon.NetworkBacking 28 resources *common.Resources 29 authorizer common.Authorizer 30 } 31 32 // NewAPI creates a new Space API server-side facade with a 33 // state.State backing. 34 func NewAPI(st *state.State, res *common.Resources, auth common.Authorizer) (API, error) { 35 return newAPIWithBacking(networkingcommon.NewStateShim(st), res, auth) 36 } 37 38 // newAPIWithBacking creates a new server-side Spaces API facade with 39 // the given Backing. 40 func newAPIWithBacking(backing networkingcommon.NetworkBacking, resources *common.Resources, authorizer common.Authorizer) (API, error) { 41 // Only clients can access the Spaces facade. 42 if !authorizer.AuthClient() { 43 return nil, common.ErrPerm 44 } 45 return &spacesAPI{ 46 backing: backing, 47 resources: resources, 48 authorizer: authorizer, 49 }, nil 50 } 51 52 // CreateSpaces creates a new Juju network space, associating the 53 // specified subnets with it (optional; can be empty). 54 func (api *spacesAPI) CreateSpaces(args params.CreateSpacesParams) (results params.ErrorResults, err error) { 55 return networkingcommon.CreateSpaces(api.backing, args) 56 } 57 58 // ListSpaces lists all the available spaces and their associated subnets. 59 func (api *spacesAPI) ListSpaces() (results params.ListSpacesResults, err error) { 60 err = networkingcommon.SupportsSpaces(api.backing) 61 if err != nil { 62 return results, common.ServerError(errors.Trace(err)) 63 } 64 65 spaces, err := api.backing.AllSpaces() 66 if err != nil { 67 return results, errors.Trace(err) 68 } 69 70 results.Results = make([]params.Space, len(spaces)) 71 for i, space := range spaces { 72 result := params.Space{} 73 result.Name = space.Name() 74 75 subnets, err := space.Subnets() 76 if err != nil { 77 err = errors.Annotatef(err, "fetching subnets") 78 result.Error = common.ServerError(err) 79 results.Results[i] = result 80 continue 81 } 82 83 result.Subnets = make([]params.Subnet, len(subnets)) 84 for i, subnet := range subnets { 85 result.Subnets[i] = networkingcommon.BackingSubnetToParamsSubnet(subnet) 86 } 87 results.Results[i] = result 88 } 89 return results, nil 90 }