github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/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 ( 7 "github.com/juju/errors" 8 "gopkg.in/mgo.v2/bson" 9 10 "github.com/juju/juju/mongo" 11 ) 12 13 // Life represents the lifecycle state of the entities 14 // Relation, Unit, Service and Machine. 15 type Life int8 16 17 const ( 18 Alive Life = iota 19 Dying 20 Dead 21 ) 22 23 func (l Life) String() string { 24 switch l { 25 case Alive: 26 return "alive" 27 case Dying: 28 return "dying" 29 case Dead: 30 return "dead" 31 default: 32 return "unknown" 33 } 34 } 35 36 var ( 37 isAliveDoc = bson.D{{"life", Alive}} 38 isDyingDoc = bson.D{{"life", Dying}} 39 isDeadDoc = bson.D{{"life", Dead}} 40 notDeadDoc = bson.D{{"life", bson.D{{"$ne", Dead}}}} 41 42 errDeadOrGone = errors.New("neither alive nor dying") 43 errAlreadyDying = errors.New("already dying") 44 errAlreadyDead = errors.New("already dead") 45 errAlreadyRemoved = errors.New("already removed") 46 errNotDying = errors.New("not dying") 47 ) 48 49 // Living describes state entities with a lifecycle. 50 type Living interface { 51 Life() Life 52 Destroy() error 53 Refresh() error 54 } 55 56 // AgentLiving describes state entities with a lifecycle and an agent that 57 // manages it. 58 type AgentLiving interface { 59 Living 60 EnsureDead() error 61 Remove() error 62 } 63 64 func isAlive(st *State, collName string, id interface{}) (bool, error) { 65 coll, closer := st.getCollection(collName) 66 defer closer() 67 return isAliveWithSession(coll, id) 68 } 69 70 func isAliveWithSession(coll mongo.Collection, id interface{}) (bool, error) { 71 n, err := coll.Find(bson.D{{"_id", id}, {"life", Alive}}).Count() 72 return n == 1, err 73 } 74 75 func isNotDead(st *State, collName string, id interface{}) (bool, error) { 76 coll, closer := st.getCollection(collName) 77 defer closer() 78 return isNotDeadWithSession(coll, id) 79 } 80 81 func isNotDeadWithSession(coll mongo.Collection, id interface{}) (bool, error) { 82 n, err := coll.Find(bson.D{{"_id", id}, {"life", bson.D{{"$ne", Dead}}}}).Count() 83 return n == 1, err 84 }