forked from metal-stack/go-ipam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
89 lines (78 loc) · 1.98 KB
/
memory.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
package ipam
import (
"fmt"
"sync"
)
type memory struct {
prefixes map[string]Prefix
lock sync.RWMutex
}
// NewMemory create a memory storage for ipam
func NewMemory() Storage {
prefixes := make(map[string]Prefix)
return &memory{
prefixes: prefixes,
lock: sync.RWMutex{},
}
}
func (m *memory) CreatePrefix(prefix Prefix) (Prefix, error) {
m.lock.Lock()
defer m.lock.Unlock()
_, ok := m.prefixes[prefix.Cidr]
if ok {
return Prefix{}, fmt.Errorf("prefix already created:%v", prefix)
}
m.prefixes[prefix.Cidr] = *prefix.deepCopy()
return prefix, nil
}
func (m *memory) ReadPrefix(prefix string) (Prefix, error) {
m.lock.RLock()
defer m.lock.RUnlock()
result, ok := m.prefixes[prefix]
if !ok {
return Prefix{}, fmt.Errorf("prefix %s not found", prefix)
}
return *result.deepCopy(), nil
}
func (m *memory) ReadAllPrefixes() ([]Prefix, error) {
m.lock.RLock()
defer m.lock.RUnlock()
ps := make([]Prefix, 0, len(m.prefixes))
for _, v := range m.prefixes {
ps = append(ps, *v.deepCopy())
}
return ps, nil
}
func (m *memory) ReadAllPrefixCidrs() ([]string, error) {
m.lock.RLock()
defer m.lock.RUnlock()
ps := make([]string, 0, len(m.prefixes))
for cidr := range m.prefixes {
ps = append(ps, cidr)
}
return ps, nil
}
func (m *memory) UpdatePrefix(prefix Prefix) (Prefix, error) {
m.lock.Lock()
defer m.lock.Unlock()
oldVersion := prefix.version
prefix.version = oldVersion + 1
if prefix.Cidr == "" {
return Prefix{}, fmt.Errorf("prefix not present:%v", prefix)
}
oldPrefix, ok := m.prefixes[prefix.Cidr]
if !ok {
return Prefix{}, fmt.Errorf("prefix not found:%s", prefix.Cidr)
}
if oldPrefix.version != oldVersion {
return Prefix{}, fmt.Errorf("%w: unable to update prefix:%s", ErrOptimisticLockError, prefix.Cidr)
}
m.prefixes[prefix.Cidr] = *prefix.deepCopy()
return prefix, nil
}
func (m *memory) DeletePrefix(prefix Prefix) (Prefix, error) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.prefixes, prefix.Cidr)
return *prefix.deepCopy(), nil
}