blob: 15ea04e49d5bbc91fb0c1288f33f8d8e4bcdf5e0 [file] [log] [blame]
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package model
18
19// TODO: proper error handling
20// TODO: proper logging
21
22import (
23 "fmt"
24 "github.com/golang/protobuf/proto"
25 "github.com/opencord/voltha-go/common/log"
26 "reflect"
Matt Jeanneretcab955f2019-04-10 15:45:57 -040027 "strings"
28 "sync"
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040029 "time"
Matt Jeanneretcab955f2019-04-10 15:45:57 -040030)
31
32// When a branch has no transaction id, everything gets stored in NONE
33const (
34 NONE string = "none"
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040035
36 // period to determine when data requires a refresh (in seconds)
37 // TODO: make this configurable?
38 DATA_REFRESH_PERIOD int64 = 5000
Matt Jeanneretcab955f2019-04-10 15:45:57 -040039)
40
41// Node interface is an abstraction of the node data structure
42type Node interface {
43 MakeLatest(branch *Branch, revision Revision, changeAnnouncement []ChangeTuple)
44
45 // CRUD functions
46 Add(path string, data interface{}, txid string, makeBranch MakeBranchFunction) Revision
47 Get(path string, hash string, depth int, deep bool, txid string) interface{}
48 Update(path string, data interface{}, strict bool, txid string, makeBranch MakeBranchFunction) Revision
49 Remove(path string, txid string, makeBranch MakeBranchFunction) Revision
50
51 MakeBranch(txid string) *Branch
52 DeleteBranch(txid string)
53 MergeBranch(txid string, dryRun bool) (Revision, error)
54
55 MakeTxBranch() string
56 DeleteTxBranch(txid string)
57 FoldTxBranch(txid string)
58
59 CreateProxy(path string, exclusive bool) *Proxy
60 GetProxy() *Proxy
61}
62
63type node struct {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040064 mutex sync.RWMutex
Matt Jeanneretcab955f2019-04-10 15:45:57 -040065 Root *root
66 Type interface{}
67 Branches map[string]*Branch
68 Tags map[string]Revision
69 Proxy *Proxy
70 EventBus *EventBus
71 AutoPrune bool
72}
73
74// ChangeTuple holds details of modifications made to a revision
75type ChangeTuple struct {
76 Type CallbackType
77 PreviousData interface{}
78 LatestData interface{}
79}
80
81// NewNode creates a new instance of the node data structure
82func NewNode(root *root, initialData interface{}, autoPrune bool, txid string) *node {
83 n := &node{}
84
85 n.Root = root
86 n.Branches = make(map[string]*Branch)
87 n.Tags = make(map[string]Revision)
88 n.Proxy = nil
89 n.EventBus = nil
90 n.AutoPrune = autoPrune
91
92 if IsProtoMessage(initialData) {
93 n.Type = reflect.ValueOf(initialData).Interface()
94 dataCopy := proto.Clone(initialData.(proto.Message))
95 n.initialize(dataCopy, txid)
96 } else if reflect.ValueOf(initialData).IsValid() {
97 // FIXME: this block does not reflect the original implementation
98 // it should be checking if the provided initial_data is already a type!??!
99 // it should be checked before IsProtoMessage
100 n.Type = reflect.ValueOf(initialData).Interface()
101 } else {
102 // not implemented error
103 log.Errorf("cannot process initial data - %+v", initialData)
104 }
105
106 return n
107}
108
109// MakeNode creates a new node in the tree
110func (n *node) MakeNode(data interface{}, txid string) *node {
111 return NewNode(n.Root, data, true, txid)
112}
113
114// MakeRevision create a new revision of the node in the tree
115func (n *node) MakeRevision(branch *Branch, data interface{}, children map[string][]Revision) Revision {
116 return n.GetRoot().MakeRevision(branch, data, children)
117}
118
119// makeLatest will mark the revision of a node as being the latest
120func (n *node) makeLatest(branch *Branch, revision Revision, changeAnnouncement []ChangeTuple) {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400121 // Keep a reference to the current revision
122 var previous string
123 if branch.GetLatest() != nil {
124 previous = branch.GetLatest().GetHash()
125 }
126
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400127 branch.AddRevision(revision)
128
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400129 // If anything is new, then set the revision as the latest
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400130 if branch.GetLatest() == nil || revision.GetHash() != branch.GetLatest().GetHash() {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400131 if revision.GetName() != "" {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400132 log.Debugw("saving-latest-data", log.Fields{"hash": revision.GetHash(), "data": revision.GetData()})
133 // Tag a timestamp to that revision
134 revision.SetLastUpdate()
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400135 GetRevCache().Cache.Store(revision.GetName(), revision)
136 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400137 branch.SetLatest(revision)
138 }
139
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400140 // Delete the previous revision if anything has changed
141 if previous != "" && previous != branch.GetLatest().GetHash() {
142 branch.DeleteRevision(previous)
143 }
144
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400145 if changeAnnouncement != nil && branch.Txid == "" {
146 if n.Proxy != nil {
147 for _, change := range changeAnnouncement {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400148 log.Debugw("adding-callback",
149 log.Fields{
150 "callbacks": n.Proxy.getCallbacks(change.Type),
151 "type": change.Type,
152 "previousData": change.PreviousData,
153 "latestData": change.LatestData,
154 })
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400155 n.Root.AddCallback(
156 n.Proxy.InvokeCallbacks,
157 change.Type,
158 true,
159 change.PreviousData,
160 change.LatestData)
161 }
162 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400163 }
164}
165
166// Latest returns the latest revision of node with or without the transaction id
167func (n *node) Latest(txid ...string) Revision {
168 var branch *Branch
169
170 if len(txid) > 0 && txid[0] != "" {
171 if branch = n.GetBranch(txid[0]); branch != nil {
172 return branch.GetLatest()
173 }
174 } else if branch = n.GetBranch(NONE); branch != nil {
175 return branch.GetLatest()
176 }
177 return nil
178}
179
180// initialize prepares the content of a node along with its possible ramifications
181func (n *node) initialize(data interface{}, txid string) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400182 children := make(map[string][]Revision)
183 for fieldName, field := range ChildrenFields(n.Type) {
184 _, fieldValue := GetAttributeValue(data, fieldName, 0)
185
186 if fieldValue.IsValid() {
187 if field.IsContainer {
188 if field.Key != "" {
189 for i := 0; i < fieldValue.Len(); i++ {
190 v := fieldValue.Index(i)
191
192 if rev := n.MakeNode(v.Interface(), txid).Latest(txid); rev != nil {
193 children[fieldName] = append(children[fieldName], rev)
194 }
195
196 // TODO: The following logic was ported from v1.0. Need to verify if it is required
197 //var keysSeen []string
198 //_, key := GetAttributeValue(v.Interface(), field.Key, 0)
199 //for _, k := range keysSeen {
200 // if k == key.String() {
201 // //log.Errorf("duplicate key - %s", k)
202 // }
203 //}
204 //keysSeen = append(keysSeen, key.String())
205 }
206
207 } else {
208 for i := 0; i < fieldValue.Len(); i++ {
209 v := fieldValue.Index(i)
210 if newNodeRev := n.MakeNode(v.Interface(), txid).Latest(); newNodeRev != nil {
211 children[fieldName] = append(children[fieldName], newNodeRev)
212 }
213 }
214 }
215 } else {
216 if newNodeRev := n.MakeNode(fieldValue.Interface(), txid).Latest(); newNodeRev != nil {
217 children[fieldName] = append(children[fieldName], newNodeRev)
218 }
219 }
220 } else {
221 log.Errorf("field is invalid - %+v", fieldValue)
222 }
223 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400224
225 branch := NewBranch(n, "", nil, n.AutoPrune)
226 rev := n.MakeRevision(branch, data, children)
227 n.makeLatest(branch, rev, nil)
228
229 if txid == "" {
230 n.SetBranch(NONE, branch)
231 } else {
232 n.SetBranch(txid, branch)
233 }
234}
235
236// findRevByKey retrieves a specific revision from a node tree
237func (n *node) findRevByKey(revs []Revision, keyName string, value interface{}) (int, Revision) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400238 for i, rev := range revs {
239 dataValue := reflect.ValueOf(rev.GetData())
240 dataStruct := GetAttributeStructure(rev.GetData(), keyName, 0)
241
242 fieldValue := dataValue.Elem().FieldByName(dataStruct.Name)
243
244 a := fmt.Sprintf("%s", fieldValue.Interface())
245 b := fmt.Sprintf("%s", value)
246 if a == b {
247 return i, revs[i]
248 }
249 }
250
251 return -1, nil
252}
253
254// Get retrieves the data from a node tree that resides at the specified path
255func (n *node) List(path string, hash string, depth int, deep bool, txid string) interface{} {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400256 n.mutex.Lock()
257 defer n.mutex.Unlock()
258
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400259 log.Debugw("node-list-request", log.Fields{"path": path, "hash": hash, "depth": depth, "deep": deep, "txid": txid})
260 if deep {
261 depth = -1
262 }
263
264 for strings.HasPrefix(path, "/") {
265 path = path[1:]
266 }
267
268 var branch *Branch
269 var rev Revision
270
271 if branch = n.GetBranch(txid); txid == "" || branch == nil {
272 branch = n.GetBranch(NONE)
273 }
274
275 if hash != "" {
276 rev = branch.GetRevision(hash)
277 } else {
278 rev = branch.GetLatest()
279 }
280
281 var result interface{}
282 var prList []interface{}
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400283 if pr := rev.LoadFromPersistence(path, txid, nil); pr != nil {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400284 for _, revEntry := range pr {
285 prList = append(prList, revEntry.GetData())
286 }
287 result = prList
288 }
289
290 return result
291}
292
293// Get retrieves the data from a node tree that resides at the specified path
294func (n *node) Get(path string, hash string, depth int, reconcile bool, txid string) interface{} {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400295 n.mutex.Lock()
296 defer n.mutex.Unlock()
297
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400298 log.Debugw("node-get-request", log.Fields{"path": path, "hash": hash, "depth": depth, "reconcile": reconcile, "txid": txid})
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400299
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400300 for strings.HasPrefix(path, "/") {
301 path = path[1:]
302 }
303
304 var branch *Branch
305 var rev Revision
306
307 if branch = n.GetBranch(txid); txid == "" || branch == nil {
308 branch = n.GetBranch(NONE)
309 }
310
311 if hash != "" {
312 rev = branch.GetRevision(hash)
313 } else {
314 rev = branch.GetLatest()
315 }
316
317 var result interface{}
318
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400319 // If there is no request to reconcile, try to get it from memory
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400320 if !reconcile {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400321 // Try to find an entry matching the path value from one of these sources
322 // 1. Start with the cache which stores revisions by watch names
323 // 2. Then look in the revision tree, especially if it's a sub-path such as /devices/1234/flows
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400324 // 3. Move on to the KV store if that path cannot be found or if the entry has expired
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400325 if entry, exists := GetRevCache().Cache.Load(path); exists && entry.(Revision) != nil {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400326 entryAge := time.Now().Sub(entry.(Revision).GetLastUpdate()).Nanoseconds() / int64(time.Millisecond)
327 if entryAge < DATA_REFRESH_PERIOD {
328 log.Debugw("using-cache-entry", log.Fields{"path": path, "hash": hash, "age": entryAge})
329 return proto.Clone(entry.(Revision).GetData().(proto.Message))
330 } else {
331 log.Debugw("cache-entry-expired", log.Fields{"path": path, "hash": hash, "age": entryAge})
332 }
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400333 } else if result = n.getPath(rev.GetBranch().GetLatest(), path, depth); result != nil && reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400334 log.Debugw("using-rev-tree-entry", log.Fields{"path": path, "hash": hash, "depth": depth, "reconcile": reconcile, "txid": txid})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400335 return result
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400336 } else {
337 log.Debugw("not-using-cache-entry", log.Fields{
338 "path": path,
339 "hash": hash, "depth": depth,
340 "reconcile": reconcile,
341 "txid": txid,
342 })
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400343 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400344 } else {
345 log.Debugw("reconcile-requested", log.Fields{
346 "path": path,
347 "hash": hash,
348 "reconcile": reconcile,
349 })
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400350 }
351
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400352 // If we got to this point, we are either trying to reconcile with the db
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400353 // or we simply failed at getting information from memory
354 if n.Root.KvStore != nil {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400355 if pr := rev.LoadFromPersistence(path, txid, nil); pr != nil && len(pr) > 0 {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400356 // Did we receive a single or multiple revisions?
357 if len(pr) > 1 {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400358 var revs []interface{}
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400359 for _, revEntry := range pr {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400360 revs = append(revs, revEntry.GetData())
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400361 }
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400362 result = revs
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400363 } else {
364 result = pr[0].GetData()
365 }
366 }
367 }
368
369 return result
370}
371
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400372//getPath traverses the specified path and retrieves the data associated to it
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400373func (n *node) getPath(rev Revision, path string, depth int) interface{} {
374 if path == "" {
375 return n.getData(rev, depth)
376 }
377
378 partition := strings.SplitN(path, "/", 2)
379 name := partition[0]
380
381 if len(partition) < 2 {
382 path = ""
383 } else {
384 path = partition[1]
385 }
386
387 names := ChildrenFields(n.Type)
388 field := names[name]
389
390 if field != nil && field.IsContainer {
391 children := make([]Revision, len(rev.GetChildren(name)))
392 copy(children, rev.GetChildren(name))
393
394 if field.Key != "" {
395 if path != "" {
396 partition = strings.SplitN(path, "/", 2)
397 key := partition[0]
398 path = ""
399 keyValue := field.KeyFromStr(key)
400 if _, childRev := n.findRevByKey(children, field.Key, keyValue); childRev == nil {
401 return nil
402 } else {
403 childNode := childRev.GetNode()
404 return childNode.getPath(childRev, path, depth)
405 }
406 } else {
407 var response []interface{}
408 for _, childRev := range children {
409 childNode := childRev.GetNode()
410 value := childNode.getData(childRev, depth)
411 response = append(response, value)
412 }
413 return response
414 }
415 } else {
416 var response []interface{}
417 if path != "" {
418 // TODO: raise error
419 return response
420 }
421 for _, childRev := range children {
422 childNode := childRev.GetNode()
423 value := childNode.getData(childRev, depth)
424 response = append(response, value)
425 }
426 return response
427 }
428 }
429
430 childRev := rev.GetChildren(name)[0]
431 childNode := childRev.GetNode()
432 return childNode.getPath(childRev, path, depth)
433}
434
435// getData retrieves the data from a node revision
436func (n *node) getData(rev Revision, depth int) interface{} {
437 msg := rev.GetBranch().GetLatest().Get(depth)
438 var modifiedMsg interface{}
439
440 if n.GetProxy() != nil {
441 log.Debugw("invoking-get-callbacks", log.Fields{"data": msg})
442 if modifiedMsg = n.GetProxy().InvokeCallbacks(GET, false, msg); modifiedMsg != nil {
443 msg = modifiedMsg
444 }
445
446 }
447
448 return msg
449}
450
451// Update changes the content of a node at the specified path with the provided data
452func (n *node) Update(path string, data interface{}, strict bool, txid string, makeBranch MakeBranchFunction) Revision {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400453 n.mutex.Lock()
454 defer n.mutex.Unlock()
455
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400456 log.Debugw("node-update-request", log.Fields{"path": path, "strict": strict, "txid": txid, "makeBranch": makeBranch})
457
458 for strings.HasPrefix(path, "/") {
459 path = path[1:]
460 }
461
462 var branch *Branch
463 if txid == "" {
464 branch = n.GetBranch(NONE)
465 } else if branch = n.GetBranch(txid); branch == nil {
466 branch = makeBranch(n)
467 }
468
469 if branch.GetLatest() != nil {
470 log.Debugf("Branch data : %+v, Passed data: %+v", branch.GetLatest().GetData(), data)
471 }
472 if path == "" {
473 return n.doUpdate(branch, data, strict)
474 }
475
476 rev := branch.GetLatest()
477
478 partition := strings.SplitN(path, "/", 2)
479 name := partition[0]
480
481 if len(partition) < 2 {
482 path = ""
483 } else {
484 path = partition[1]
485 }
486
487 field := ChildrenFields(n.Type)[name]
488 var children []Revision
489
490 if field == nil {
491 return n.doUpdate(branch, data, strict)
492 }
493
494 if field.IsContainer {
495 if path == "" {
496 log.Errorf("cannot update a list")
497 } else if field.Key != "" {
498 partition := strings.SplitN(path, "/", 2)
499 key := partition[0]
500 if len(partition) < 2 {
501 path = ""
502 } else {
503 path = partition[1]
504 }
505 keyValue := field.KeyFromStr(key)
506
507 children = make([]Revision, len(rev.GetChildren(name)))
508 copy(children, rev.GetChildren(name))
509
510 idx, childRev := n.findRevByKey(children, field.Key, keyValue)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400511
512 if childRev == nil {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400513 log.Debugw("child-revision-is-nil", log.Fields{"key": keyValue})
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400514 return branch.GetLatest()
515 }
516
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400517 childNode := childRev.GetNode()
518
519 // Save proxy in child node to ensure callbacks are called later on
520 // only assign in cases of non sub-folder proxies, i.e. "/"
521 if childNode.Proxy == nil && n.Proxy != nil && n.Proxy.getFullPath() == "" {
522 childNode.Proxy = n.Proxy
523 }
524
525 newChildRev := childNode.Update(path, data, strict, txid, makeBranch)
526
527 if newChildRev.GetHash() == childRev.GetHash() {
528 if newChildRev != childRev {
529 log.Debug("clear-hash - %s %+v", newChildRev.GetHash(), newChildRev)
530 newChildRev.ClearHash()
531 }
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400532 log.Debugw("child-revisions-have-matching-hash", log.Fields{"hash": childRev.GetHash(), "key": keyValue})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400533 return branch.GetLatest()
534 }
535
536 _, newKey := GetAttributeValue(newChildRev.GetData(), field.Key, 0)
537
538 _newKeyType := fmt.Sprintf("%s", newKey)
539 _keyValueType := fmt.Sprintf("%s", keyValue)
540
541 if _newKeyType != _keyValueType {
542 log.Errorf("cannot change key field")
543 }
544
545 // Prefix the hash value with the data type (e.g. devices, logical_devices, adapters)
546 newChildRev.SetName(name + "/" + _keyValueType)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400547
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400548 branch.LatestLock.Lock()
549 defer branch.LatestLock.Unlock()
550
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400551 if idx >= 0 {
552 children[idx] = newChildRev
553 } else {
554 children = append(children, newChildRev)
555 }
556
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400557 updatedRev := rev.UpdateChildren(name, children, branch)
558
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400559 n.makeLatest(branch, updatedRev, nil)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400560 updatedRev.ChildDrop(name, childRev.GetHash())
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400561
562 return newChildRev
563
564 } else {
565 log.Errorf("cannot index into container with no keys")
566 }
567 } else {
568 childRev := rev.GetChildren(name)[0]
569 childNode := childRev.GetNode()
570 newChildRev := childNode.Update(path, data, strict, txid, makeBranch)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400571
572 branch.LatestLock.Lock()
573 defer branch.LatestLock.Unlock()
574
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400575 updatedRev := rev.UpdateChildren(name, []Revision{newChildRev}, branch)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400576 n.makeLatest(branch, updatedRev, nil)
577
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400578 updatedRev.ChildDrop(name, childRev.GetHash())
579
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400580 return newChildRev
581 }
582
583 return nil
584}
585
586func (n *node) doUpdate(branch *Branch, data interface{}, strict bool) Revision {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400587 log.Debugw("comparing-types", log.Fields{"expected": reflect.ValueOf(n.Type).Type(), "actual": reflect.TypeOf(data)})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400588
589 if reflect.TypeOf(data) != reflect.ValueOf(n.Type).Type() {
590 // TODO raise error
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400591 log.Errorw("types-do-not-match: %+v", log.Fields{"actual": reflect.TypeOf(data), "expected": n.Type})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400592 return nil
593 }
594
595 // TODO: validate that this actually works
596 //if n.hasChildren(data) {
597 // return nil
598 //}
599
600 if n.GetProxy() != nil {
601 log.Debug("invoking proxy PRE_UPDATE Callbacks")
602 n.GetProxy().InvokeCallbacks(PRE_UPDATE, false, branch.GetLatest(), data)
603 }
604
605 if branch.GetLatest().GetData().(proto.Message).String() != data.(proto.Message).String() {
606 if strict {
607 // TODO: checkAccessViolations(data, Branch.GetLatest.data)
608 log.Debugf("checking access violations")
609 }
610
611 rev := branch.GetLatest().UpdateData(data, branch)
612 changes := []ChangeTuple{{POST_UPDATE, branch.GetLatest().GetData(), rev.GetData()}}
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400613 n.makeLatest(branch, rev, changes)
614
615 return rev
616 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400617 return branch.GetLatest()
618}
619
620// Add inserts a new node at the specified path with the provided data
621func (n *node) Add(path string, data interface{}, txid string, makeBranch MakeBranchFunction) Revision {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400622 n.mutex.Lock()
623 defer n.mutex.Unlock()
624
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400625 log.Debugw("node-add-request", log.Fields{"path": path, "txid": txid, "makeBranch": makeBranch})
626
627 for strings.HasPrefix(path, "/") {
628 path = path[1:]
629 }
630 if path == "" {
631 // TODO raise error
632 log.Errorf("cannot add for non-container mode")
633 return nil
634 }
635
636 var branch *Branch
637 if txid == "" {
638 branch = n.GetBranch(NONE)
639 } else if branch = n.GetBranch(txid); branch == nil {
640 branch = makeBranch(n)
641 }
642
643 rev := branch.GetLatest()
644
645 partition := strings.SplitN(path, "/", 2)
646 name := partition[0]
647
648 if len(partition) < 2 {
649 path = ""
650 } else {
651 path = partition[1]
652 }
653
654 field := ChildrenFields(n.Type)[name]
655
656 var children []Revision
657
658 if field.IsContainer {
659 if path == "" {
660 if field.Key != "" {
661 if n.GetProxy() != nil {
662 log.Debug("invoking proxy PRE_ADD Callbacks")
663 n.GetProxy().InvokeCallbacks(PRE_ADD, false, data)
664 }
665
666 children = make([]Revision, len(rev.GetChildren(name)))
667 copy(children, rev.GetChildren(name))
668
669 _, key := GetAttributeValue(data, field.Key, 0)
670
671 if _, exists := n.findRevByKey(children, field.Key, key.String()); exists != nil {
672 // TODO raise error
673 log.Warnw("duplicate-key-found", log.Fields{"key": key.String()})
674 return exists
675 }
676 childRev := n.MakeNode(data, "").Latest()
677
678 // Prefix the hash with the data type (e.g. devices, logical_devices, adapters)
679 childRev.SetName(name + "/" + key.String())
680
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400681 branch.LatestLock.Lock()
682 defer branch.LatestLock.Unlock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400683
684 children = append(children, childRev)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400685
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400686 updatedRev := rev.UpdateChildren(name, children, branch)
687 changes := []ChangeTuple{{POST_ADD, nil, childRev.GetData()}}
688 childRev.SetupWatch(childRev.GetName())
689
690 n.makeLatest(branch, updatedRev, changes)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400691
692 return childRev
693 }
694 log.Errorf("cannot add to non-keyed container")
695
696 } else if field.Key != "" {
697 partition := strings.SplitN(path, "/", 2)
698 key := partition[0]
699 if len(partition) < 2 {
700 path = ""
701 } else {
702 path = partition[1]
703 }
704 keyValue := field.KeyFromStr(key)
705
706 children = make([]Revision, len(rev.GetChildren(name)))
707 copy(children, rev.GetChildren(name))
708
709 idx, childRev := n.findRevByKey(children, field.Key, keyValue)
710
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400711 if childRev == nil {
712 return branch.GetLatest()
713 }
714
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400715 childNode := childRev.GetNode()
716 newChildRev := childNode.Add(path, data, txid, makeBranch)
717
718 // Prefix the hash with the data type (e.g. devices, logical_devices, adapters)
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400719 newChildRev.SetName(name + "/" + keyValue.(string))
720
721 branch.LatestLock.Lock()
722 defer branch.LatestLock.Unlock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400723
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400724 if idx >= 0 {
725 children[idx] = newChildRev
726 } else {
727 children = append(children, newChildRev)
728 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400729
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400730 updatedRev := rev.UpdateChildren(name, children, branch)
731 n.makeLatest(branch, updatedRev, nil)
732
733 updatedRev.ChildDrop(name, childRev.GetHash())
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400734
735 return newChildRev
736 } else {
737 log.Errorf("cannot add to non-keyed container")
738 }
739 } else {
740 log.Errorf("cannot add to non-container field")
741 }
742
743 return nil
744}
745
746// Remove eliminates a node at the specified path
747func (n *node) Remove(path string, txid string, makeBranch MakeBranchFunction) Revision {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400748 n.mutex.Lock()
749 defer n.mutex.Unlock()
750
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400751 log.Debugw("node-remove-request", log.Fields{"path": path, "txid": txid, "makeBranch": makeBranch})
752
753 for strings.HasPrefix(path, "/") {
754 path = path[1:]
755 }
756 if path == "" {
757 // TODO raise error
758 log.Errorf("cannot remove for non-container mode")
759 }
760 var branch *Branch
761 if txid == "" {
762 branch = n.GetBranch(NONE)
763 } else if branch = n.GetBranch(txid); branch == nil {
764 branch = makeBranch(n)
765 }
766
767 rev := branch.GetLatest()
768
769 partition := strings.SplitN(path, "/", 2)
770 name := partition[0]
771 if len(partition) < 2 {
772 path = ""
773 } else {
774 path = partition[1]
775 }
776
777 field := ChildrenFields(n.Type)[name]
778 var children []Revision
779 postAnnouncement := []ChangeTuple{}
780
781 if field.IsContainer {
782 if path == "" {
783 log.Errorw("cannot-remove-without-key", log.Fields{"name": name, "key": path})
784 } else if field.Key != "" {
785 partition := strings.SplitN(path, "/", 2)
786 key := partition[0]
787 if len(partition) < 2 {
788 path = ""
789 } else {
790 path = partition[1]
791 }
792
793 keyValue := field.KeyFromStr(key)
794 children = make([]Revision, len(rev.GetChildren(name)))
795 copy(children, rev.GetChildren(name))
796
797 if path != "" {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400798 if idx, childRev := n.findRevByKey(children, field.Key, keyValue); childRev != nil {
799 childNode := childRev.GetNode()
800 if childNode.Proxy == nil {
801 childNode.Proxy = n.Proxy
802 }
803 newChildRev := childNode.Remove(path, txid, makeBranch)
804
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400805 branch.LatestLock.Lock()
806 defer branch.LatestLock.Unlock()
807
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400808 if idx >= 0 {
809 children[idx] = newChildRev
810 } else {
811 children = append(children, newChildRev)
812 }
813
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400814 rev.SetChildren(name, children)
815 branch.GetLatest().Drop(txid, false)
816 n.makeLatest(branch, rev, nil)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400817 }
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400818 return branch.GetLatest()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400819 }
820
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400821 if idx, childRev := n.findRevByKey(children, field.Key, keyValue); childRev != nil && idx >= 0 {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400822 if n.GetProxy() != nil {
823 data := childRev.GetData()
824 n.GetProxy().InvokeCallbacks(PRE_REMOVE, false, data)
825 postAnnouncement = append(postAnnouncement, ChangeTuple{POST_REMOVE, data, nil})
826 } else {
827 postAnnouncement = append(postAnnouncement, ChangeTuple{POST_REMOVE, childRev.GetData(), nil})
828 }
829
830 childRev.StorageDrop(txid, true)
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400831 GetRevCache().Cache.Delete(childRev.GetName())
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400832
833 branch.LatestLock.Lock()
834 defer branch.LatestLock.Unlock()
835
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400836 children = append(children[:idx], children[idx+1:]...)
837 rev.SetChildren(name, children)
838
839 branch.GetLatest().Drop(txid, false)
840 n.makeLatest(branch, rev, postAnnouncement)
841
842 return rev
843 } else {
844 log.Errorw("failed-to-find-revision", log.Fields{"name": name, "key": keyValue.(string)})
845 }
846 }
847 log.Errorw("cannot-add-to-non-keyed-container", log.Fields{"name": name, "path": path, "fieldKey": field.Key})
848
849 } else {
850 log.Errorw("cannot-add-to-non-container-field", log.Fields{"name": name, "path": path})
851 }
852
853 return nil
854}
855
856// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Branching ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
857
858// MakeBranchFunction is a type for function references intented to create a branch
859type MakeBranchFunction func(*node) *Branch
860
861// MakeBranch creates a new branch for the provided transaction id
862func (n *node) MakeBranch(txid string) *Branch {
863 branchPoint := n.GetBranch(NONE).GetLatest()
864 branch := NewBranch(n, txid, branchPoint, true)
865 n.SetBranch(txid, branch)
866 return branch
867}
868
869// DeleteBranch removes a branch with the specified id
870func (n *node) DeleteBranch(txid string) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400871 delete(n.Branches, txid)
872}
873
874func (n *node) mergeChild(txid string, dryRun bool) func(Revision) Revision {
875 f := func(rev Revision) Revision {
876 childBranch := rev.GetBranch()
877
878 if childBranch.Txid == txid {
879 rev, _ = childBranch.Node.MergeBranch(txid, dryRun)
880 }
881
882 return rev
883 }
884 return f
885}
886
887// MergeBranch will integrate the contents of a transaction branch within the latest branch of a given node
888func (n *node) MergeBranch(txid string, dryRun bool) (Revision, error) {
889 srcBranch := n.GetBranch(txid)
890 dstBranch := n.GetBranch(NONE)
891
892 forkRev := srcBranch.Origin
893 srcRev := srcBranch.GetLatest()
894 dstRev := dstBranch.GetLatest()
895
896 rev, changes := Merge3Way(forkRev, srcRev, dstRev, n.mergeChild(txid, dryRun), dryRun)
897
898 if !dryRun {
899 if rev != nil {
900 rev.SetName(dstRev.GetName())
901 n.makeLatest(dstBranch, rev, changes)
902 }
903 n.DeleteBranch(txid)
904 }
905
906 // TODO: return proper error when one occurs
907 return rev, nil
908}
909
910// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Diff utility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
911
912//func (n *node) diff(hash1, hash2, txid string) {
913// branch := n.Branches[txid]
914// rev1 := branch.GetHash(hash1)
915// rev2 := branch.GetHash(hash2)
916//
917// if rev1.GetHash() == rev2.GetHash() {
918// // empty patch
919// } else {
920// // translate data to json and generate patch
921// patch, err := jsonpatch.MakePatch(rev1.GetData(), rev2.GetData())
922// patch.
923// }
924//}
925
926// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tag utility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
927
928// TODO: is tag mgmt used in the python implementation? Need to validate
929
930// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Internals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931
932func (n *node) hasChildren(data interface{}) bool {
933 for fieldName, field := range ChildrenFields(n.Type) {
934 _, fieldValue := GetAttributeValue(data, fieldName, 0)
935
936 if (field.IsContainer && fieldValue.Len() > 0) || !fieldValue.IsNil() {
937 log.Error("cannot update external children")
938 return true
939 }
940 }
941
942 return false
943}
944
945// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ node Proxy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
946
947// CreateProxy returns a reference to a sub-tree of the data model
948func (n *node) CreateProxy(path string, exclusive bool) *Proxy {
949 return n.createProxy(path, path, n, exclusive)
950}
951
952func (n *node) createProxy(path string, fullPath string, parentNode *node, exclusive bool) *Proxy {
953 for strings.HasPrefix(path, "/") {
954 path = path[1:]
955 }
956 if path == "" {
957 return n.makeProxy(path, fullPath, parentNode, exclusive)
958 }
959
960 rev := n.GetBranch(NONE).GetLatest()
961 partition := strings.SplitN(path, "/", 2)
962 name := partition[0]
963 if len(partition) < 2 {
964 path = ""
965 } else {
966 path = partition[1]
967 }
968
969 field := ChildrenFields(n.Type)[name]
970 if field.IsContainer {
971 if path == "" {
972 //log.Error("cannot proxy a container field")
973 newNode := n.MakeNode(reflect.New(field.ClassType.Elem()).Interface(), "")
974 return newNode.makeProxy(path, fullPath, parentNode, exclusive)
975 } else if field.Key != "" {
976 partition := strings.SplitN(path, "/", 2)
977 key := partition[0]
978 if len(partition) < 2 {
979 path = ""
980 } else {
981 path = partition[1]
982 }
983 keyValue := field.KeyFromStr(key)
984 var children []Revision
985 children = make([]Revision, len(rev.GetChildren(name)))
986 copy(children, rev.GetChildren(name))
987 if _, childRev := n.findRevByKey(children, field.Key, keyValue); childRev != nil {
988 childNode := childRev.GetNode()
989 return childNode.createProxy(path, fullPath, n, exclusive)
990 }
991 } else {
992 log.Error("cannot index into container with no keys")
993 }
994 } else {
995 childRev := rev.GetChildren(name)[0]
996 childNode := childRev.GetNode()
997 return childNode.createProxy(path, fullPath, n, exclusive)
998 }
999
1000 log.Warnf("Cannot create proxy - latest rev:%s, all revs:%+v", rev.GetHash(), n.GetBranch(NONE).Revisions)
1001 return nil
1002}
1003
1004func (n *node) makeProxy(path string, fullPath string, parentNode *node, exclusive bool) *Proxy {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001005 r := &root{
1006 node: n,
1007 Callbacks: n.Root.GetCallbacks(),
1008 NotificationCallbacks: n.Root.GetNotificationCallbacks(),
1009 DirtyNodes: n.Root.DirtyNodes,
1010 KvStore: n.Root.KvStore,
1011 Loading: n.Root.Loading,
1012 RevisionClass: n.Root.RevisionClass,
1013 }
1014
1015 if n.Proxy == nil {
1016 n.Proxy = NewProxy(r, n, parentNode, path, fullPath, exclusive)
1017 } else {
1018 if n.Proxy.Exclusive {
1019 log.Error("node is already owned exclusively")
1020 }
1021 }
1022
1023 return n.Proxy
1024}
1025
1026func (n *node) makeEventBus() *EventBus {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001027 if n.EventBus == nil {
1028 n.EventBus = NewEventBus()
1029 }
1030 return n.EventBus
1031}
1032
1033func (n *node) SetProxy(proxy *Proxy) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001034 n.Proxy = proxy
1035}
1036
1037func (n *node) GetProxy() *Proxy {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001038 return n.Proxy
1039}
1040
1041func (n *node) GetBranch(key string) *Branch {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001042 if n.Branches != nil {
1043 if branch, exists := n.Branches[key]; exists {
1044 return branch
1045 }
1046 }
1047 return nil
1048}
1049
1050func (n *node) SetBranch(key string, branch *Branch) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001051 n.Branches[key] = branch
1052}
1053
1054func (n *node) GetRoot() *root {
Matt Jeanneretcab955f2019-04-10 15:45:57 -04001055 return n.Root
1056}