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