-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource.go
330 lines (309 loc) · 8.27 KB
/
resource.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright 2016 F. Alan Jones. All rights reserved.
// Use of this source code is governed by a Mozilla
// license that can be found in the LICENSE file.
package ketch
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"github.com/Sirupsen/logrus"
"github.com/boltdb/bolt"
"github.com/satori/go.uuid"
"github.com/watercraft/ketch/api"
)
type ResourceMgrInterface interface {
Init(ketch Ketch, myType api.Type, instance ResourceMgrInstance)
RefreshResources()
GetResources() api.ResourceList
ClearResources()
CreateResources(list api.ResourceList) (api.ResourceList, error, int)
LoadResources()
}
type ResourceMgrInstance interface {
InitResource(api.Resource) (error, int)
GetList() api.ResourceList
UpdateAfterLoad(api.Resource) bool
}
type ResourceMgr struct {
instance ResourceMgrInstance
k *Ketch
myType api.Type
assignIDs bool
named bool
persist bool
resource map[uuid.UUID]api.Resource
resourceByName map[string]uuid.UUID
}
// Links up an instance of the resource manager
func (m *ResourceMgr) Init(k *Ketch, instance ResourceMgrInstance) {
m.k = k
m.instance = instance
m.resource = make(map[uuid.UUID]api.Resource)
m.resourceByName = make(map[string]uuid.UUID)
m.k.resourceMgr[m.myType] = m
m.LoadResources()
}
// RefreshResources
// calls resource specific getList() to refresh resources.
func (m *ResourceMgr) RefreshResources() {
list := m.instance.GetList()
if list != nil {
m.ClearResources()
// TODO: Error handling
_, _, _ = m.CreateResources(list)
}
}
// GetResources
// returns list of resources.
func (m *ResourceMgr) GetResources() api.ResourceList {
m.RefreshResources()
var list api.ResourceList
for _, obj := range m.resource {
// Copy object so the original is not modified
list = append(list, obj.Clone())
}
sort.Sort(list)
return list
}
// ClearResources
// clears all resources of the specified type.
func (m *ResourceMgr) ClearResources() {
m.resource = make(map[uuid.UUID]api.Resource)
m.resourceByName = make(map[string]uuid.UUID)
}
// CreateResources
// creates resources from a list.
// Returns the list created, error and http status
func (m *ResourceMgr) CreateResources(list api.ResourceList) (api.ResourceList, error, int) {
// Validate list against ketch state
for _, resource := range list {
common := resource.GetCommon()
if m.named && common.Name == "" {
err := fmt.Errorf("Resource missing name")
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Error("Failed to create resource")
return nil, err, http.StatusBadRequest
}
if m.named {
if _, ok := m.resourceByName[common.Name]; ok {
err := fmt.Errorf("Resource already exists")
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
"name": common.Name,
})).Error(err.Error())
return nil, err, http.StatusConflict
}
}
if m.assignIDs {
// New ID if not coming from from outside
common.ID = uuid.NewV4()
}
if _, ok := m.resource[common.ID]; ok {
err := fmt.Errorf("Resource ID already exists")
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
"name": common.Name,
"id": common.ID,
})).Error(err.Error())
return nil, err, http.StatusInternalServerError
}
err, status := m.instance.InitResource(resource)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
"name": common.Name,
"id": common.ID,
})).Error("Failed to initialize resource")
return nil, err, status
}
}
// Put resources into Ketch state
for _, resource := range list {
common := resource.GetCommon()
m.resource[common.ID] = resource.Clone()
m.resourceByName[common.Name] = common.ID
}
// Persist resources
if !m.persist {
return list, nil, http.StatusCreated
}
err := m.k.db.Update(func(tx *bolt.Tx) error {
// Create Ketch bucket
b, err := tx.CreateBucketIfNotExists([]byte(m.myType))
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Error("Failed to create bucket")
return err
}
// Put resources in bucket
for _, resource := range list {
common := resource.GetCommon()
out, err := json.Marshal(resource)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"id": common.ID,
"err": err,
})).Error("Failed to marshal resource")
return err
}
err = b.Put(common.ID.Bytes(), out)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"key": common.ID,
"out": out,
"err": err,
})).Error("Failed to put resource")
return err
}
}
return nil
})
if err != nil {
return nil, err, http.StatusInternalServerError
}
return list, nil, http.StatusCreated
}
// LoadResources
// loads existing resources from database into Ketch.
// Called locked.
func (m *ResourceMgr) LoadResources() {
// Iterate over resources
err := m.k.db.Update(func(tx *bolt.Tx) error {
// Create Ketch bucket if it doesn't exist
bk, err := tx.CreateBucketIfNotExists([]byte(m.myType))
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Error("Failed to create bucket")
return err
}
// Look for keys in the bucket
cur := bk.Cursor()
for key, value := cur.First(); key != nil; key, value = cur.Next() {
resource := api.NewByType(m.myType)
err := json.Unmarshal(value, &resource)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
"key": key,
"value": string(value),
})).Fatal("Failed to unmarshal resource")
}
common := resource.GetCommon()
if id, err := uuid.FromBytes(key); err != nil || id != common.ID {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
"name": common.Name,
"id": common.ID,
})).Fatal("Failed to match resource key")
}
m.resource[common.ID] = resource
m.resourceByName[common.Name] = common.ID
if m.instance.UpdateAfterLoad(resource) {
out, err := json.Marshal(resource)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"id": common.ID,
"err": err,
})).Error("Failed to marshal resource")
return err
}
err = bk.Put(common.ID.Bytes(), out)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"key": common.ID,
"out": out,
"err": err,
})).Error("Failed to put resource")
return err
}
}
}
return nil
})
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Fatal("Failed to load resources")
}
}
// saveResource
// update an existing resource in database from memory.
// Called locked.
// TODO: Return error for API PATCH; fatal for now.
func (m *ResourceMgr) saveResource(id uuid.UUID) {
err := m.k.db.Update(func(tx *bolt.Tx) error {
// Create Ketch bucket if it doesn't exist
bk, err := tx.CreateBucketIfNotExists([]byte(m.myType))
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Error("Failed to create bucket")
return err
}
// Marshal resource
resource, ok := m.resource[id]
if !ok {
err = bk.Delete(id.Bytes())
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"key": id,
"err": err,
})).Error("Failed to delete resource")
return err
}
return nil
}
common := resource.GetCommon()
out, err := json.Marshal(resource)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"id": common.ID,
"err": err,
})).Error("Failed to marshal resource")
return err
}
err = bk.Put(common.ID.Bytes(), out)
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"name": common.Name,
"key": common.ID,
"out": out,
"err": err,
})).Error("Failed to put resource")
return err
}
return nil
})
if err != nil {
m.k.log.WithFields(Locate(logrus.Fields{
"type": m.myType,
"err": err,
})).Fatal("Failed to update resources")
}
}