-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
84 lines (70 loc) · 1.99 KB
/
database.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
76
77
78
79
80
81
82
83
84
package instances
import (
"encoding/json"
"fmt"
"io"
"log"
)
type Database struct {
Instances map[string]Instance `json:"instances"`
support io.ReadWriter
}
// NewDatabase creates a new Database populated with the content read from the given
// io.ReadWriter.
func NewDatabase(support io.ReadWriter) (*Database, error) {
database := Database{
support: support,
}
err := json.NewDecoder(support).Decode(&database)
if err != nil {
return &database, fmt.Errorf("open database: %s", err)
}
return &database, nil
}
// Save saves the database to the provided io.Writer.
func (d *Database) Save() error {
b, err := json.MarshalIndent(d, "", " ")
if err != nil {
return fmt.Errorf("serialize database: %s", err)
}
_, err = d.support.Write(b)
if err != nil {
return fmt.Errorf("save database: %s", err)
}
return nil
}
// AddInstance adds an instance to the database.
func (d *Database) AddInstance(id string, name string, cloudProvider CloudProvider) error {
log.Printf("adding instance %s", id)
if _, instanceExists := d.Instances[name]; instanceExists {
return fmt.Errorf("instance %q exists already", name)
}
for instanceName, instance := range d.Instances {
if instance.Id == id {
return fmt.Errorf("instance id %q already referenced by instance %q", id, instanceName)
}
}
_, err := cloudProvider.GetInstanceStatus(id)
if err != nil {
return err
}
d.Instances[name] = Instance{Id: id, CloudProviderName: cloudProvider.GetName()}
return nil
}
// GetInstance gets an instance from the database
func (d *Database) GetInstance(name string) (Instance, error) {
instance, instanceExists := d.Instances[name]
if !instanceExists {
return Instance{}, fmt.Errorf("no instance named %s", name)
}
return instance, nil
}
// RemoveInstance removes an instance from the database
func (d *Database) RemoveInstance(name string) error {
_, instanceExists := d.Instances[name]
if !instanceExists {
return fmt.Errorf("no instance named %s", name)
}
delete(d.Instances, name)
return nil
}