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