github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/apiserver/utils.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package apiserver
     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/state"
    12  )
    13  
    14  // isMachineWithJob returns whether the given entity is a machine that
    15  // is configured to run the given job.
    16  func isMachineWithJob(e state.Entity, j state.MachineJob) bool {
    17  	m, ok := e.(*state.Machine)
    18  	if !ok {
    19  		return false
    20  	}
    21  	for _, mj := range m.Jobs() {
    22  		if mj == j {
    23  			return true
    24  		}
    25  	}
    26  	return false
    27  }
    28  
    29  type validateArgs struct {
    30  	statePool *state.StatePool
    31  	modelUUID string
    32  	// strict validation does not allow empty UUID values
    33  	strict bool
    34  	// controllerModelOnly only validates the controller model
    35  	controllerModelOnly bool
    36  }
    37  
    38  // validateModelUUID is the common validator for the various
    39  // apiserver components that need to check for a valid model
    40  // UUID.  An empty modelUUID means that the connection has come in at
    41  // the root of the URL space and refers to the controller
    42  // model.
    43  //
    44  // It returns the validated model UUID.
    45  func validateModelUUID(args validateArgs) (string, error) {
    46  	ssState := args.statePool.SystemState()
    47  	if args.modelUUID == "" {
    48  		// We allow the modelUUID to be empty so that:
    49  		//    TODO: server a limited API at the root (empty modelUUID)
    50  		//    just the user manager and model manager are able to accept
    51  		//    requests that don't require a modelUUID, like add-model.
    52  		if args.strict {
    53  			return "", errors.Trace(common.UnknownModelError(args.modelUUID))
    54  		}
    55  		return ssState.ModelUUID(), nil
    56  	}
    57  	if args.modelUUID == ssState.ModelUUID() {
    58  		return args.modelUUID, nil
    59  	}
    60  	if args.controllerModelOnly {
    61  		return "", errors.Unauthorizedf("requested model %q is not the controller model", args.modelUUID)
    62  	}
    63  	if !names.IsValidModel(args.modelUUID) {
    64  		return "", errors.Trace(common.UnknownModelError(args.modelUUID))
    65  	}
    66  	modelTag := names.NewModelTag(args.modelUUID)
    67  	if _, err := ssState.GetModel(modelTag); err != nil {
    68  		return "", errors.Wrap(err, common.UnknownModelError(args.modelUUID))
    69  	}
    70  	return args.modelUUID, nil
    71  }