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