github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/common/networkingcommon/spaces.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package networkingcommon
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/names.v2"
     9  
    10  	"github.com/juju/juju/apiserver/common"
    11  	"github.com/juju/juju/apiserver/params"
    12  	"github.com/juju/juju/environs"
    13  	"github.com/juju/juju/environs/context"
    14  	"github.com/juju/juju/network"
    15  )
    16  
    17  // SupportsSpaces checks if the environment implements NetworkingEnviron
    18  // and also if it supports spaces.
    19  func SupportsSpaces(backing environs.EnvironConfigGetter, ctx context.ProviderCallContext) error {
    20  	env, err := environs.GetEnviron(backing, environs.New)
    21  	if err != nil {
    22  		return errors.Annotate(err, "getting environ")
    23  	}
    24  	if !environs.SupportsSpaces(ctx, env) {
    25  		return errors.NotSupportedf("spaces")
    26  	}
    27  	return nil
    28  }
    29  
    30  // CreateSpaces creates a new Juju network space, associating the
    31  // specified subnets with it (optional; can be empty).
    32  func CreateSpaces(backing NetworkBacking, ctx context.ProviderCallContext, args params.CreateSpacesParams) (results params.ErrorResults, err error) {
    33  	err = SupportsSpaces(backing, ctx)
    34  	if err != nil {
    35  		return results, common.ServerError(errors.Trace(err))
    36  	}
    37  
    38  	results.Results = make([]params.ErrorResult, len(args.Spaces))
    39  
    40  	for i, space := range args.Spaces {
    41  		err := createOneSpace(backing, space)
    42  		if err == nil {
    43  			continue
    44  		}
    45  		results.Results[i].Error = common.ServerError(errors.Trace(err))
    46  	}
    47  
    48  	return results, nil
    49  }
    50  
    51  func createOneSpace(backing NetworkBacking, args params.CreateSpaceParams) error {
    52  	// Validate the args, assemble information for api.backing.AddSpaces
    53  	var subnets []string
    54  
    55  	spaceTag, err := names.ParseSpaceTag(args.SpaceTag)
    56  	if err != nil {
    57  		return errors.Trace(err)
    58  	}
    59  
    60  	for _, tag := range args.SubnetTags {
    61  		subnetTag, err := names.ParseSubnetTag(tag)
    62  		if err != nil {
    63  			return errors.Trace(err)
    64  		}
    65  		subnets = append(subnets, subnetTag.Id())
    66  	}
    67  
    68  	// Add the validated space.
    69  	err = backing.AddSpace(spaceTag.Id(), network.Id(args.ProviderId), subnets, args.Public)
    70  	if err != nil {
    71  		return errors.Trace(err)
    72  	}
    73  	return nil
    74  }