github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/apiserver/common/instanceidgetter.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package common
     5  
     6  import (
     7  	"github.com/juju/juju/apiserver/params"
     8  	"github.com/juju/juju/instance"
     9  	"github.com/juju/juju/state"
    10  	"github.com/juju/names"
    11  )
    12  
    13  // InstanceIdGetter implements a common InstanceId method for use by
    14  // various facades.
    15  type InstanceIdGetter struct {
    16  	st         state.EntityFinder
    17  	getCanRead GetAuthFunc
    18  }
    19  
    20  // NewInstanceIdGetter returns a new InstanceIdGetter. The GetAuthFunc
    21  // will be used on each invocation of InstanceId to determine current
    22  // permissions.
    23  func NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter {
    24  	return &InstanceIdGetter{
    25  		st:         st,
    26  		getCanRead: getCanRead,
    27  	}
    28  }
    29  
    30  func (ig *InstanceIdGetter) getInstanceId(tag names.Tag) (instance.Id, error) {
    31  	entity0, err := ig.st.FindEntity(tag)
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  	entity, ok := entity0.(state.InstanceIdGetter)
    36  	if !ok {
    37  		return "", NotSupportedError(tag, "instance id")
    38  	}
    39  	return entity.InstanceId()
    40  }
    41  
    42  // InstanceId returns the provider specific instance id for each given
    43  // machine or an CodeNotProvisioned error, if not set.
    44  func (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) {
    45  	result := params.StringResults{
    46  		Results: make([]params.StringResult, len(args.Entities)),
    47  	}
    48  	canRead, err := ig.getCanRead()
    49  	if err != nil {
    50  		return result, err
    51  	}
    52  	for i, entity := range args.Entities {
    53  		tag, err := names.ParseTag(entity.Tag)
    54  		if err != nil {
    55  			result.Results[i].Error = ServerError(ErrPerm)
    56  			continue
    57  		}
    58  		err = ErrPerm
    59  		if canRead(tag) {
    60  			var instanceId instance.Id
    61  			instanceId, err = ig.getInstanceId(tag)
    62  			if err == nil {
    63  				result.Results[i].Result = string(instanceId)
    64  			}
    65  		}
    66  		result.Results[i].Error = ServerError(err)
    67  	}
    68  	return result, nil
    69  }