github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/state/life.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package state
     5  
     6  import "gopkg.in/mgo.v2/bson"
     7  
     8  // Life represents the lifecycle state of the entities
     9  // Relation, Unit, Service and Machine.
    10  type Life int8
    11  
    12  const (
    13  	Alive Life = iota
    14  	Dying
    15  	Dead
    16  	nLife
    17  )
    18  
    19  func (l Life) String() string {
    20  	switch l {
    21  	case Alive:
    22  		return "alive"
    23  	case Dying:
    24  		return "dying"
    25  	case Dead:
    26  		return "dead"
    27  	default:
    28  		return "unknown"
    29  	}
    30  }
    31  
    32  var isAliveDoc = bson.D{{"life", Alive}}
    33  var isDeadDoc = bson.D{{"life", Dead}}
    34  var notDeadDoc = bson.D{{"life", bson.D{{"$ne", Dead}}}}
    35  
    36  // Living describes state entities with a lifecycle.
    37  type Living interface {
    38  	Life() Life
    39  	Destroy() error
    40  	Refresh() error
    41  }
    42  
    43  // AgentLiving describes state entities with a lifecycle and an agent that
    44  // manages it.
    45  type AgentLiving interface {
    46  	Living
    47  	EnsureDead() error
    48  	Remove() error
    49  }
    50  
    51  func isAlive(st *State, collName string, id interface{}) (bool, error) {
    52  	coll, closer := st.getCollection(collName)
    53  	defer closer()
    54  	return isAliveWithSession(coll, id)
    55  }
    56  
    57  func isAliveWithSession(coll stateCollection, id interface{}) (bool, error) {
    58  	n, err := coll.Find(bson.D{{"_id", id}, {"life", Alive}}).Count()
    59  	return n == 1, err
    60  }
    61  
    62  func isNotDead(st *State, collName string, id interface{}) (bool, error) {
    63  	coll, closer := st.getCollection(collName)
    64  	defer closer()
    65  	return isNotDeadWithSession(coll, id)
    66  }
    67  
    68  func isNotDeadWithSession(coll stateCollection, id interface{}) (bool, error) {
    69  	n, err := coll.Find(bson.D{{"_id", id}, {"life", bson.D{{"$ne", Dead}}}}).Count()
    70  	return n == 1, err
    71  }