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