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
76
77
|
package mstate
import (
"fmt"
"labix.org/v2/mgo/bson"
"strconv"
)
// Machine represents the state of a machine.
type Machine struct {
st *State
id int
}
// machineDoc represents the internal state of a machine in MongoDB.
type machineDoc struct {
Id int `bson:"_id"`
InstanceId string
Life Life
}
// Id returns the machine id.
func (m *Machine) Id() int {
return m.id
}
// InstanceId returns the provider specific machine id for this machine.
func (m *Machine) InstanceId() (string, error) {
mdoc := &machineDoc{}
sel := bson.D{
{"_id", m.id},
{"life", Alive},
}
err := m.st.machines.Find(sel).One(mdoc)
if err != nil {
return "", fmt.Errorf("can't get instance id of machine %s: %v", m, err)
}
return mdoc.InstanceId, nil
}
// Units returns all the units that have been assigned to the machine.
func (m *Machine) Units() (units []*Unit, err error) {
defer errorContextf(&err, "can't get units assigned to machine %s", m)
pudocs := []unitDoc{}
err = m.st.units.Find(bson.D{{"machineid", m.id}}).All(&pudocs)
if err != nil {
return nil, err
}
for _, pudoc := range pudocs {
units = append(units, newUnit(m.st, &pudoc))
docs := []unitDoc{}
sel := bson.D{{"principal", pudoc.Name}, {"life", Alive}}
err = m.st.units.Find(sel).All(&docs)
if err != nil {
return nil, err
}
for _, doc := range docs {
units = append(units, newUnit(m.st, &doc))
}
}
return units, nil
}
// SetInstanceId sets the provider specific machine id for this machine.
func (m *Machine) SetInstanceId(id string) error {
change := bson.D{{"$set", bson.D{{"instanceid", id}}}}
err := m.st.machines.Update(bson.D{{"_id", m.id}}, change)
if err != nil {
return fmt.Errorf("can't set instance id of machine %s: %v", m, err)
}
return nil
}
// String returns a unique description of this machine.
func (m *Machine) String() string {
return strconv.Itoa(m.id)
}
|