-
Notifications
You must be signed in to change notification settings - Fork 49
/
graphmanager_nodes.go
616 lines (439 loc) · 13.1 KB
/
graphmanager_nodes.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/*
* EliasDB
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package graph
import (
"encoding/binary"
"encoding/gob"
"github.com/krotik/eliasdb/graph/data"
"github.com/krotik/eliasdb/graph/util"
"github.com/krotik/eliasdb/hash"
)
func init() {
// It is possible to store nested structures on nodes
gob.Register(make(map[string]interface{}))
}
/*
NodeCount returns the node count for a given node kind.
*/
func (gm *Manager) NodeCount(kind string) uint64 {
if val, ok := gm.gs.MainDB()[MainDBNodeCount+kind]; ok {
return binary.LittleEndian.Uint64([]byte(val))
}
return 0
}
/*
NodeKeyIterator iterates node keys of a certain kind.
*/
func (gm *Manager) NodeKeyIterator(part string, kind string) (*NodeKeyIterator, error) {
// Get the HTrees which stores the node
tree, _, err := gm.getNodeStorageHTree(part, kind, false)
if err != nil || tree == nil {
return nil, err
}
it := hash.NewHTreeIterator(tree)
if it.LastError != nil {
return nil, &util.GraphError{
Type: util.ErrReading,
Detail: it.LastError.Error(),
}
}
return &NodeKeyIterator{gm, it, nil}, nil
}
/*
FetchNode fetches a single node from a partition of the graph.
*/
func (gm *Manager) FetchNode(part string, key string, kind string) (data.Node, error) {
return gm.FetchNodePart(part, key, kind, nil)
}
/*
FetchNodePart fetches part of a single node from a partition of the graph.
*/
func (gm *Manager) FetchNodePart(part string, key string, kind string,
attrs []string) (data.Node, error) {
// Get the HTrees which stores the node
attht, valht, err := gm.getNodeStorageHTree(part, kind, false)
if err != nil || attht == nil || valht == nil {
return nil, err
}
// Take reader lock
gm.mutex.RLock()
defer gm.mutex.RUnlock()
// Read the node from the datastore
return gm.readNode(key, kind, attrs, attht, valht)
}
/*
readNode reads a given node from the datastore.
*/
func (gm *Manager) readNode(key string, kind string, attrs []string,
attrTree *hash.HTree, valTree *hash.HTree) (data.Node, error) {
keyAttrs := PrefixNSAttrs + key
keyAttrPrefix := PrefixNSAttr + key
// Check if the node exists
attrList, err := attrTree.Get([]byte(keyAttrs))
if err != nil {
return nil, &util.GraphError{Type: util.ErrReading, Detail: err.Error()}
} else if attrList == nil {
return nil, nil
}
var node data.Node
tryPopulateNode := func(encattr string, attr string) error {
// Try to lookup the attribute
val, err := valTree.Get([]byte(keyAttrPrefix + encattr))
if err != nil {
return &util.GraphError{Type: util.ErrReading, Detail: err.Error()}
}
if val != nil {
if node == nil {
node = data.NewGraphNode()
}
node.SetAttr(attr, val)
}
return nil
}
if len(attrs) == 0 {
// Allways create a node if we fetch all attributes
node = data.NewGraphNode()
// Lookup all attributes
for _, encattr := range attrList.([]string) {
attr := gm.nm.Decode32(encattr)
if err := tryPopulateNode(encattr, attr); err != nil {
return nil, err
}
}
} else {
// Lookup the given attributes - it is assumed that most of the time the
// queried attributes do exist
for _, attr := range attrs {
if (attr == data.NodeKey || attr == data.NodeKind) && node == nil {
// Create node - we might only query for node key or node kind
node = data.NewGraphNode()
continue
}
// Only try to populate the attribute if it can be decoded
if encattr := gm.nm.Encode32(attr, false); encattr != "" {
if err := tryPopulateNode(encattr, attr); err != nil {
return nil, err
}
}
}
}
// Set key and kind attributes
if node != nil {
node.SetAttr(data.NodeKey, key)
node.SetAttr(data.NodeKind, kind)
}
return node, nil
}
/*
StoreNode stores a single node in a partition of the graph. This function will
overwrites any existing node.
*/
func (gm *Manager) StoreNode(part string, node data.Node) error {
trans := newInternalGraphTrans(gm)
trans.subtrans = true
err := gm.gr.graphEvent(trans, EventNodeStore, part, node)
if err != nil {
if err == ErrEventHandled {
err = nil
}
return err
}
if err = trans.Commit(); err == nil {
err = gm.storeOrUpdateNode(part, node, false)
}
return err
}
/*
UpdateNode updates a single node in a partition of the graph. This function will
only update the given values of the node.
*/
func (gm *Manager) UpdateNode(part string, node data.Node) error {
trans := newInternalGraphTrans(gm)
trans.subtrans = true
err := gm.gr.graphEvent(trans, EventNodeUpdate, part, node)
if err != nil {
if err == ErrEventHandled {
err = nil
}
return err
}
if err = trans.Commit(); err == nil {
err = gm.storeOrUpdateNode(part, node, true)
}
return err
}
/*
storeOrUpdateNode stores or updates a single node in a partition of the graph.
*/
func (gm *Manager) storeOrUpdateNode(part string, node data.Node, onlyUpdate bool) error {
// Check if the node can be stored
if err := gm.checkNode(node); err != nil {
return err
}
// Get the HTrees which stores the node index and node
iht, err := gm.getNodeIndexHTree(part, node.Kind(), true)
if err != nil {
return err
}
attht, valht, err := gm.getNodeStorageHTree(part, node.Kind(), true)
if err != nil || attht == nil || valht == nil {
return err
}
// Take writer lock
gm.mutex.Lock()
defer gm.mutex.Unlock()
// Write the node to the datastore
oldnode, err := gm.writeNode(node, onlyUpdate, attht, valht, nodeAttributeFilter)
if err != nil {
return err
}
// Increase node count if the node was inserted and write the changes
// to the index.
if oldnode == nil {
currentCount := gm.NodeCount(node.Kind())
if err := gm.writeNodeCount(node.Kind(), currentCount+1, true); err != nil {
return err
}
if iht != nil {
err := util.NewIndexManager(iht).Index(node.Key(), node.IndexMap())
if err != nil {
// The node was written at this point and the model is
// consistent only the index is missing entries
return err
}
}
} else if iht != nil {
err := util.NewIndexManager(iht).Reindex(node.Key(), node.IndexMap(),
oldnode.IndexMap())
if err != nil {
// The node was written at this point and the model is
// consistent only the index is missing entries
return err
}
}
defer func() {
// Flush changes
gm.gs.FlushMain()
gm.flushNodeIndex(part, node.Kind())
gm.flushNodeStorage(part, node.Kind())
}()
// Execute rules
trans := newInternalGraphTrans(gm)
trans.subtrans = true
var event int
if oldnode == nil {
event = EventNodeCreated
} else {
event = EventNodeUpdated
}
if err := gm.gr.graphEvent(trans, event, part, node, oldnode); err != nil && err != ErrEventHandled {
return err
} else if err := trans.Commit(); err != nil {
return err
}
return nil
}
/*
writeNode writes a given node in full or part to the datastore. It is assumed
that the caller holds the writer lock before calling the functions and that,
after the function returns, the changes are flushed to the storage. Returns
the old node if an update occurred. An attribute filter can be speified to skip
specific attributes.
*/
func (gm *Manager) writeNode(node data.Node, onlyUpdate bool, attrTree *hash.HTree,
valTree *hash.HTree, attFilter func(attr string) bool) (data.Node, error) {
keyAttrs := PrefixNSAttrs + node.Key()
keyAttrPrefix := PrefixNSAttr + node.Key()
var oldnode data.Node
var attrListOld interface{}
var err error
// Store the node attributes
attrList := make([]string, 0, len(node.IndexMap()))
attrMap := make(map[string]string)
for attr, val := range node.Data() {
// Ignore filtered attributes
if attFilter(attr) {
continue
}
encattr := gm.nm.Encode32(attr, true)
// Build up a lookup map to identify which attribute exist
attrMap[encattr] = ""
// Build up new attributes list
attrList = append(attrList, encattr)
// Store the value in the datastore
oldval, err := valTree.Put([]byte(keyAttrPrefix+encattr), val)
if err != nil {
return nil, &util.GraphError{Type: util.ErrWriting, Detail: err.Error()}
}
// Build up old node
if oldval != nil {
if oldnode == nil {
oldnode = data.NewGraphNode()
}
oldnode.SetAttr(attr, oldval)
}
}
if onlyUpdate {
// If we do only an update write the attribute list only if we added
// new attributes
attrListOld, err = attrTree.Get([]byte(keyAttrs))
if err != nil {
return nil, &util.GraphError{Type: util.ErrReading, Detail: err.Error()}
}
if attrListOld != nil {
// Fill up the attrMap with the existing attributes
for _, encattr := range attrListOld.([]string) {
attrMap[encattr] = ""
}
// Now check if we need to write the attribute list
if len(attrListOld.([]string)) != len(attrMap) {
// Store the new node attributes
attrList = make([]string, 0, len(attrMap))
for encattr := range attrMap {
attrList = append(attrList, encattr)
}
attrListOld, err = attrTree.Put([]byte(keyAttrs), attrList)
}
} else {
// We are actually doing an insert - just write the attribute list
_, err = attrTree.Put([]byte(keyAttrs), attrList)
}
} else {
// Store the new node attributes
attrListOld, err = attrTree.Put([]byte(keyAttrs), attrList)
}
if err != nil {
// Do not try cleanup in case we updated a node - we would do more
// harm than good.
return nil, &util.GraphError{Type: util.ErrWriting, Detail: err.Error()}
}
// Remove deleted keys
if attrListOld != nil {
// Create old node if non of the new attributes were on the old node
if oldnode == nil {
oldnode = data.NewGraphNode()
}
oldnode.SetAttr(data.NodeKey, node.Key())
oldnode.SetAttr(data.NodeKind, node.Kind())
for _, encattrold := range attrListOld.([]string) {
if _, ok := attrMap[encattrold]; !ok {
oldval, err := valTree.Remove([]byte(keyAttrPrefix + encattrold))
if err != nil {
return nil, &util.GraphError{Type: util.ErrWriting, Detail: err.Error()}
}
oldnode.SetAttr(gm.nm.Decode32(encattrold), oldval)
}
}
return oldnode, nil
}
return nil, nil
}
/*
RemoveNode removes a single node from a partition of the graph.
*/
func (gm *Manager) RemoveNode(part string, key string, kind string) (data.Node, error) {
var err error
trans := newInternalGraphTrans(gm)
trans.subtrans = true
if err = gm.gr.graphEvent(trans, EventNodeDelete, part, key, kind); err != nil {
if err == ErrEventHandled {
err = nil
}
return nil, err
}
err = trans.Commit()
if err == nil {
// Get the HTree which stores the node index and node kind
iht, err := gm.getNodeIndexHTree(part, kind, false)
if err != nil {
return nil, err
}
attTree, valTree, err := gm.getNodeStorageHTree(part, kind, false)
if err != nil || attTree == nil || valTree == nil {
return nil, err
}
// Take writer lock
gm.mutex.Lock()
defer gm.mutex.Unlock()
// Delete the node from the datastore
node, err := gm.deleteNode(key, kind, attTree, valTree)
if err != nil {
return node, err
}
// Update the index
if node != nil {
if iht != nil {
err := util.NewIndexManager(iht).Deindex(key, node.IndexMap())
if err != nil {
return node, err
}
}
// Decrease the node count
currentCount := gm.NodeCount(kind)
if err := gm.writeNodeCount(kind, currentCount-1, true); err != nil {
return node, err
}
defer func() {
// Flush changes
gm.gs.FlushMain()
gm.flushNodeIndex(part, kind)
gm.flushNodeStorage(part, kind)
}()
// Execute rules
trans := newInternalGraphTrans(gm)
trans.subtrans = true
if err := gm.gr.graphEvent(trans, EventNodeDeleted, part, node); err != nil && err != ErrEventHandled {
return node, err
} else if err := trans.Commit(); err != nil {
return node, err
}
return node, nil
}
}
return nil, err
}
/*
deleteNode deletes a given node from the datastore. It is assumed that the caller
holds the writer lock before calling the functions and that, after the function
returns, the changes are flushed to the storage. Returns the deleted node.
*/
func (gm *Manager) deleteNode(key string, kind string, attrTree *hash.HTree,
valTree *hash.HTree) (data.Node, error) {
keyAttrs := PrefixNSAttrs + key
keyAttrPrefix := PrefixNSAttr + key
// Remove the attribute list entry
attrList, err := attrTree.Remove([]byte(keyAttrs))
if err != nil {
return nil, &util.GraphError{Type: util.ErrWriting, Detail: err.Error()}
} else if attrList == nil {
return nil, nil
}
// Create the node object which is returned
node := data.NewGraphNode()
node.SetAttr(data.NodeKey, key)
node.SetAttr(data.NodeKind, kind)
// Remove node attributes
for _, encattr := range attrList.([]string) {
attr := gm.nm.Decode32(encattr)
// Try to remove the attribute
val, err := valTree.Remove([]byte(keyAttrPrefix + encattr))
if err != nil {
return node, &util.GraphError{Type: util.ErrWriting, Detail: err.Error()}
}
node.SetAttr(attr, val)
}
return node, nil
}
/*
Default filter function to filter out system node attributes.
*/
func nodeAttributeFilter(attr string) bool {
return attr == data.NodeKey || attr == data.NodeKind
}