forked from juju/juju
/
mem.go
110 lines (97 loc) · 2.28 KB
/
mem.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package configstore
import (
"fmt"
"sync"
"github.com/juju/errors"
)
type memStore struct {
mu sync.Mutex
envs map[string]*memInfo
}
type memInfo struct {
store *memStore
name string
environInfo
}
// clone returns a copy of the given environment info, isolated
// from the store itself.
func (info *memInfo) clone() *memInfo {
// Note that none of the Set* methods ever set fields inside
// references, which makes this OK to do.
info1 := *info
newAttrs := make(map[string]interface{})
for name, attr := range info.EnvInfo.Config {
newAttrs[name] = attr
}
info1.EnvInfo.Config = newAttrs
info1.created = false
return &info1
}
// NewMem returns a ConfigStorage implementation that
// stores configuration in memory.
func NewMem() Storage {
return &memStore{
envs: make(map[string]*memInfo),
}
}
// CreateInfo implements Storage.CreateInfo.
func (m *memStore) CreateInfo(envName string) (EnvironInfo, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.envs[envName] != nil {
return nil, ErrEnvironInfoAlreadyExists
}
info := &memInfo{
store: m,
name: envName,
}
info.created = true
m.envs[envName] = info.clone()
return info, nil
}
// List implements Storage.List
func (m *memStore) List() ([]string, error) {
var envs []string
m.mu.Lock()
defer m.mu.Unlock()
for name, _ := range m.envs {
envs = append(envs, name)
}
return envs, nil
}
// ReadInfo implements Storage.ReadInfo.
func (m *memStore) ReadInfo(envName string) (EnvironInfo, error) {
m.mu.Lock()
defer m.mu.Unlock()
info := m.envs[envName]
if info != nil {
return info.clone(), nil
}
return nil, errors.NotFoundf("environment %q", envName)
}
// Location implements EnvironInfo.Location.
func (info *memInfo) Location() string {
return "memory"
}
// Write implements EnvironInfo.Write.
func (info *memInfo) Write() error {
m := info.store
m.mu.Lock()
defer m.mu.Unlock()
info.initialized = true
m.envs[info.name] = info.clone()
return nil
}
// Destroy implements EnvironInfo.Destroy.
func (info *memInfo) Destroy() error {
m := info.store
m.mu.Lock()
defer m.mu.Unlock()
if m.envs[info.name] == nil {
return fmt.Errorf("environment info has already been removed")
}
delete(m.envs, info.name)
return nil
}