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