launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/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/errors" 8 "launchpad.net/juju-core/instance" 9 "launchpad.net/juju-core/state" 10 "launchpad.net/juju-core/state/api/params" 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 string) (instance.Id, error) { 31 entity0, err := ig.st.FindEntity(tag) 32 if err != nil { 33 return "", mask(err, errors.IsNotFoundError) 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, mask(err) 51 } 52 for i, entity := range args.Entities { 53 err := ErrPerm 54 if canRead(entity.Tag) { 55 var instanceId instance.Id 56 instanceId, err = ig.getInstanceId(entity.Tag) 57 if err == nil { 58 result.Results[i].Result = string(instanceId) 59 } 60 } 61 result.Results[i].Error = ServerError(err) 62 } 63 return result, nil 64 }