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