github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/apiserver/common/ensuredead.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/errors" 8 "github.com/juju/juju/apiserver/params" 9 "github.com/juju/juju/state" 10 "github.com/juju/names" 11 ) 12 13 // DeadEnsurer implements a common EnsureDead method for use by 14 // various facades. 15 type DeadEnsurer struct { 16 st state.EntityFinder 17 getCanModify GetAuthFunc 18 } 19 20 // NewDeadEnsurer returns a new DeadEnsurer. The GetAuthFunc will be 21 // used on each invocation of EnsureDead to determine current 22 // permissions. 23 func NewDeadEnsurer(st state.EntityFinder, getCanModify GetAuthFunc) *DeadEnsurer { 24 return &DeadEnsurer{ 25 st: st, 26 getCanModify: getCanModify, 27 } 28 } 29 30 func (d *DeadEnsurer) ensureEntityDead(tag names.Tag) error { 31 entity0, err := d.st.FindEntity(tag) 32 if err != nil { 33 return err 34 } 35 entity, ok := entity0.(state.EnsureDeader) 36 if !ok { 37 return NotSupportedError(tag, "ensuring death") 38 } 39 return entity.EnsureDead() 40 } 41 42 // EnsureDead calls EnsureDead on each given entity from state. It 43 // will fail if the entity is not present. If it's Alive, nothing will 44 // happen (see state/EnsureDead() for units or machines). 45 func (d *DeadEnsurer) EnsureDead(args params.Entities) (params.ErrorResults, error) { 46 result := params.ErrorResults{ 47 Results: make([]params.ErrorResult, len(args.Entities)), 48 } 49 if len(args.Entities) == 0 { 50 return result, nil 51 } 52 canModify, err := d.getCanModify() 53 if err != nil { 54 return params.ErrorResults{}, errors.Trace(err) 55 } 56 for i, entity := range args.Entities { 57 tag, err := names.ParseTag(entity.Tag) 58 if err != nil { 59 return params.ErrorResults{}, errors.Trace(err) 60 } 61 62 err = ErrPerm 63 if canModify(tag) { 64 err = d.ensureEntityDead(tag) 65 } 66 result.Results[i].Error = ServerError(err) 67 } 68 return result, nil 69 }