/
store.go
137 lines (105 loc) · 2.5 KB
/
store.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package test
import (
"crypto/sha256"
"encoding/json"
"fmt"
"sync"
"github.com/openshift-online/maestro/pkg/api"
"open-cluster-management.io/sdk-go/pkg/cloudevents/generic/types"
)
type MemoryStore struct {
sync.RWMutex
resources map[string]*api.Resource
}
func NewStore() *MemoryStore {
return &MemoryStore{
resources: make(map[string]*api.Resource),
}
}
func (s *MemoryStore) Add(resource *api.Resource) {
s.Lock()
defer s.Unlock()
if resource.ID == "" {
return
}
_, ok := s.resources[resource.ID]
if !ok {
s.resources[resource.ID] = resource
}
}
func (s *MemoryStore) Update(resource *api.Resource) error {
s.Lock()
defer s.Unlock()
if resource.ID == "" {
return fmt.Errorf("the resource ID is empty")
}
_, ok := s.resources[resource.ID]
if !ok {
return fmt.Errorf("the resource %s does not exist", resource.ID)
}
s.resources[resource.ID] = resource
return nil
}
func (s *MemoryStore) UpSert(resource *api.Resource) {
s.Lock()
defer s.Unlock()
if resource.ID == "" {
return
}
s.resources[resource.ID] = resource
}
func (s *MemoryStore) UpdateStatus(resource *api.Resource) error {
s.Lock()
defer s.Unlock()
if resource.ID == "" {
return fmt.Errorf("the resource ID is empty")
}
last, ok := s.resources[resource.ID]
if !ok {
return fmt.Errorf("the resource %s does not exist", resource.ID)
}
last.Status = resource.Status
s.resources[resource.ID] = last
return nil
}
func (s *MemoryStore) Delete(resourceID string) {
s.Lock()
defer s.Unlock()
if resourceID == "" {
return
}
delete(s.resources, resourceID)
}
func (s *MemoryStore) Get(resourceID string) (*api.Resource, error) {
s.RLock()
defer s.RUnlock()
resource, ok := s.resources[resourceID]
if !ok {
return nil, fmt.Errorf("failed to find resource %s", resourceID)
}
return resource, nil
}
func (s *MemoryStore) ListByNamespace(namespace string) []*api.Resource {
s.RLock()
defer s.RUnlock()
resources := make([]*api.Resource, len(s.resources))
i := 0
for _, res := range s.resources {
if res.ConsumerName != namespace {
continue
}
resources[i] = res
i++
}
return resources
}
func (s *MemoryStore) List(listOpts types.ListOptions) ([]*api.Resource, error) {
return s.ListByNamespace(listOpts.ClusterName), nil
}
func resourceStatusHashGetter(obj *api.Resource) (string, error) {
statusBytes, err := json.Marshal(obj.Status)
if err != nil {
return "", fmt.Errorf("failed to marshal resource status, %v", err)
}
return fmt.Sprintf("%x", sha256.Sum256(statusBytes)), nil
}