blob: d7b0b584be90aff754f3b6a7f69c60a2c3355f3c [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 */
16package model
17
18import (
19 "bytes"
20 "crypto/md5"
21 "fmt"
22 "github.com/golang/protobuf/proto"
23 "github.com/opencord/voltha-go/common/log"
manikkaraj k9eb6cac2019-05-09 12:32:03 -040024 "github.com/opencord/voltha-go/db/kvstore"
Matt Jeanneretcab955f2019-04-10 15:45:57 -040025 "reflect"
26 "sort"
27 "sync"
28)
29
Matt Jeanneret384d8c92019-05-06 14:27:31 -040030// TODO: Cache logic will have to be revisited to cleanup unused entries in memory (disabled for now)
31//
manikkaraj k9eb6cac2019-05-09 12:32:03 -040032type revCacheSingleton struct {
33 sync.RWMutex
34 Cache sync.Map
35}
36
37var revCacheInstance *revCacheSingleton
38var revCacheOnce sync.Once
39
40func GetRevCache() *revCacheSingleton {
41 revCacheOnce.Do(func() {
42 revCacheInstance = &revCacheSingleton{Cache: sync.Map{}}
43 })
44 return revCacheInstance
45}
Matt Jeanneretcab955f2019-04-10 15:45:57 -040046
47type NonPersistedRevision struct {
Matt Jeanneret384d8c92019-05-06 14:27:31 -040048 mutex sync.RWMutex
49 Root *root
50 Config *DataRevision
51 childrenLock sync.RWMutex
52 Children map[string][]Revision
53 Hash string
54 Branch *Branch
55 WeakRef string
56 Name string
57 discarded bool
Matt Jeanneretcab955f2019-04-10 15:45:57 -040058}
59
60func NewNonPersistedRevision(root *root, branch *Branch, data interface{}, children map[string][]Revision) Revision {
61 r := &NonPersistedRevision{}
62 r.Root = root
63 r.Branch = branch
64 r.Config = NewDataRevision(root, data)
65 r.Children = children
66 r.Hash = r.hashContent()
Matt Jeanneret384d8c92019-05-06 14:27:31 -040067 r.discarded = false
Matt Jeanneretcab955f2019-04-10 15:45:57 -040068 return r
69}
70
Matt Jeanneret384d8c92019-05-06 14:27:31 -040071func (npr *NonPersistedRevision) IsDiscarded() bool {
72 return npr.discarded
73}
74
Matt Jeanneretcab955f2019-04-10 15:45:57 -040075func (npr *NonPersistedRevision) SetConfig(config *DataRevision) {
76 npr.mutex.Lock()
77 defer npr.mutex.Unlock()
78 npr.Config = config
79}
80
81func (npr *NonPersistedRevision) GetConfig() *DataRevision {
82 npr.mutex.Lock()
83 defer npr.mutex.Unlock()
84 return npr.Config
85}
86
87func (npr *NonPersistedRevision) SetAllChildren(children map[string][]Revision) {
Matt Jeanneret384d8c92019-05-06 14:27:31 -040088 npr.childrenLock.Lock()
89 defer npr.childrenLock.Unlock()
90 npr.Children = make(map[string][]Revision)
Matt Jeanneretcab955f2019-04-10 15:45:57 -040091
Matt Jeanneret384d8c92019-05-06 14:27:31 -040092 for key, value := range children {
93 npr.Children[key] = make([]Revision, len(value))
94 copy(npr.Children[key], value)
Matt Jeanneretcab955f2019-04-10 15:45:57 -040095 }
96}
97
Matt Jeanneret384d8c92019-05-06 14:27:31 -040098func (npr *NonPersistedRevision) SetChildren(name string, children []Revision) {
99 npr.childrenLock.Lock()
100 defer npr.childrenLock.Unlock()
101
102 npr.Children[name] = make([]Revision, len(children))
103 copy(npr.Children[name], children)
104}
105
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400106func (npr *NonPersistedRevision) GetAllChildren() map[string][]Revision {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400107 npr.childrenLock.Lock()
108 defer npr.childrenLock.Unlock()
109
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400110 return npr.Children
111}
112
113func (npr *NonPersistedRevision) GetChildren(name string) []Revision {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400114 npr.childrenLock.Lock()
115 defer npr.childrenLock.Unlock()
116
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400117 if _, exists := npr.Children[name]; exists {
118 return npr.Children[name]
119 }
120 return nil
121}
122
123func (npr *NonPersistedRevision) SetHash(hash string) {
124 npr.mutex.Lock()
125 defer npr.mutex.Unlock()
126 npr.Hash = hash
127}
128
129func (npr *NonPersistedRevision) GetHash() string {
130 //npr.mutex.Lock()
131 //defer npr.mutex.Unlock()
132 return npr.Hash
133}
134
135func (npr *NonPersistedRevision) ClearHash() {
136 npr.mutex.Lock()
137 defer npr.mutex.Unlock()
138 npr.Hash = ""
139}
140
141func (npr *NonPersistedRevision) GetName() string {
142 //npr.mutex.Lock()
143 //defer npr.mutex.Unlock()
144 return npr.Name
145}
146
147func (npr *NonPersistedRevision) SetName(name string) {
148 //npr.mutex.Lock()
149 //defer npr.mutex.Unlock()
150 npr.Name = name
151}
152func (npr *NonPersistedRevision) SetBranch(branch *Branch) {
153 npr.mutex.Lock()
154 defer npr.mutex.Unlock()
155 npr.Branch = branch
156}
157
158func (npr *NonPersistedRevision) GetBranch() *Branch {
159 npr.mutex.Lock()
160 defer npr.mutex.Unlock()
161 return npr.Branch
162}
163
164func (npr *NonPersistedRevision) GetData() interface{} {
165 npr.mutex.Lock()
166 defer npr.mutex.Unlock()
167 if npr.Config == nil {
168 return nil
169 }
170 return npr.Config.Data
171}
172
173func (npr *NonPersistedRevision) GetNode() *node {
174 npr.mutex.Lock()
175 defer npr.mutex.Unlock()
176 return npr.Branch.Node
177}
178
179func (npr *NonPersistedRevision) Finalize(skipOnExist bool) {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400180 npr.Hash = npr.hashContent()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400181}
182
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400183// hashContent generates a hash string based on the contents of the revision.
184// The string should be unique to avoid conflicts with other revisions
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400185func (npr *NonPersistedRevision) hashContent() string {
186 var buffer bytes.Buffer
187 var childrenKeys []string
188
189 if npr.Config != nil {
190 buffer.WriteString(npr.Config.Hash)
191 }
192
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400193 if npr.Name != "" {
194 buffer.WriteString(npr.Name)
195 }
196
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400197 for key := range npr.Children {
198 childrenKeys = append(childrenKeys, key)
199 }
200
201 sort.Strings(childrenKeys)
202
203 if len(npr.Children) > 0 {
204 // Loop through sorted Children keys
205 for _, key := range childrenKeys {
206 for _, child := range npr.Children[key] {
207 if child != nil && child.GetHash() != "" {
208 buffer.WriteString(child.GetHash())
209 }
210 }
211 }
212 }
213
214 return fmt.Sprintf("%x", md5.Sum(buffer.Bytes()))[:12]
215}
216
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400217// Get will retrieve the data for the current revision
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400218func (npr *NonPersistedRevision) Get(depth int) interface{} {
219 // 1. Clone the data to avoid any concurrent access issues
220 // 2. The current rev might still be pointing to an old config
221 // thus, force the revision to get its latest value
222 latestRev := npr.GetBranch().GetLatest()
223 originalData := proto.Clone(latestRev.GetData().(proto.Message))
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400224 data := originalData
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400225
226 if depth != 0 {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400227 // FIXME: Traversing the struct through reflection sometimes corrupts the data.
228 // Unlike the original python implementation, golang structs are not lazy loaded.
229 // Keeping this non-critical logic for now, but Get operations should be forced to
230 // depth=0 to avoid going through the following loop.
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400231 for fieldName, field := range ChildrenFields(latestRev.GetData()) {
232 childDataName, childDataHolder := GetAttributeValue(data, fieldName, 0)
233 if field.IsContainer {
234 for _, rev := range latestRev.GetChildren(fieldName) {
235 childData := rev.Get(depth - 1)
236 foundEntry := false
237 for i := 0; i < childDataHolder.Len(); i++ {
238 cdh_if := childDataHolder.Index(i).Interface()
239 if cdh_if.(proto.Message).String() == childData.(proto.Message).String() {
240 foundEntry = true
241 break
242 }
243 }
244 if !foundEntry {
245 // avoid duplicates by adding it only if the child was not found in the holder
246 childDataHolder = reflect.Append(childDataHolder, reflect.ValueOf(childData))
247 }
248 }
249 } else {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400250 if revs := npr.GetBranch().GetLatest().GetChildren(fieldName); revs != nil && len(revs) > 0 {
251 rev := revs[0]
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400252 if rev != nil {
253 childData := rev.Get(depth - 1)
254 if reflect.TypeOf(childData) == reflect.TypeOf(childDataHolder.Interface()) {
255 childDataHolder = reflect.ValueOf(childData)
256 }
257 }
258 }
259 }
260 // Merge child data with cloned object
261 reflect.ValueOf(data).Elem().FieldByName(childDataName).Set(childDataHolder)
262 }
263 }
264
265 result := data
266
267 if result != nil {
268 // We need to send back a copy of the retrieved object
269 result = proto.Clone(data.(proto.Message))
270 }
271
272 return result
273}
274
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400275// UpdateData will refresh the data content of the revision
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400276func (npr *NonPersistedRevision) UpdateData(data interface{}, branch *Branch) Revision {
277 npr.mutex.Lock()
278 defer npr.mutex.Unlock()
279
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400280 // Do not update the revision if data is the same
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400281 if npr.Config.Data != nil && npr.Config.hashData(npr.Root, data) == npr.Config.Hash {
282 log.Debugw("stored-data-matches-latest", log.Fields{"stored": npr.Config.Data, "provided": data})
283 return npr
284 }
285
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400286 // Construct a new revision based on the current one
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400287 newRev := NonPersistedRevision{}
288 newRev.Config = NewDataRevision(npr.Root, data)
289 newRev.Hash = npr.Hash
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400290 newRev.Root = npr.Root
291 newRev.Name = npr.Name
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400292 newRev.Branch = branch
293
294 newRev.Children = make(map[string][]Revision)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400295 for entryName, childrenEntry := range branch.GetLatest().GetAllChildren() {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400296 newRev.Children[entryName] = append(newRev.Children[entryName], childrenEntry...)
297 }
298
299 newRev.Finalize(false)
300
301 return &newRev
302}
303
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400304// UpdateChildren will refresh the list of children with the provided ones
305// It will carefully go through the list and ensure that no child is lost
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400306func (npr *NonPersistedRevision) UpdateChildren(name string, children []Revision, branch *Branch) Revision {
307 npr.mutex.Lock()
308 defer npr.mutex.Unlock()
309
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400310 // Construct a new revision based on the current one
311 updatedRev := &NonPersistedRevision{}
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400312 updatedRev.Config = NewDataRevision(npr.Root, npr.Config.Data)
313 updatedRev.Hash = npr.Hash
314 updatedRev.Branch = branch
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400315 updatedRev.Name = npr.Name
316
317 updatedRev.Children = make(map[string][]Revision)
318 for entryName, childrenEntry := range branch.GetLatest().GetAllChildren() {
319 updatedRev.Children[entryName] = append(updatedRev.Children[entryName], childrenEntry...)
320 }
321
322 var updatedChildren []Revision
323
324 // Verify if the map contains already contains an entry matching the name value
325 // If so, we need to retain the contents of that entry and merge them with the provided children revision list
326 if existingChildren := branch.GetLatest().GetChildren(name); existingChildren != nil {
327 // Construct a map of unique child names with the respective index value
328 // for the children in the existing revision as well as the new ones
329 existingNames := make(map[string]int)
330 newNames := make(map[string]int)
331
332 for i, newChild := range children {
333 newNames[newChild.GetName()] = i
334 }
335
336 for i, existingChild := range existingChildren {
337 existingNames[existingChild.GetName()] = i
338
339 // If an existing entry is not in the new list, add it to the updated list, so it is not forgotten
340 if _, exists := newNames[existingChild.GetName()]; !exists {
341 updatedChildren = append(updatedChildren, existingChild)
342 }
343 }
344
345 log.Debugw("existing-children-names", log.Fields{"hash": npr.GetHash(), "names": existingNames})
346
347 // Merge existing and new children
348 for _, newChild := range children {
349 nameIndex, nameExists := existingNames[newChild.GetName()]
350
351 // Does the existing list contain a child with that name?
352 if nameExists {
353 // Check if the data has changed or not
354 if existingChildren[nameIndex].GetData().(proto.Message).String() != newChild.GetData().(proto.Message).String() {
355 // replace entry
356 newChild.GetNode().Root = existingChildren[nameIndex].GetNode().Root
357 updatedChildren = append(updatedChildren, newChild)
358 } else {
359 // keep existing entry
360 updatedChildren = append(updatedChildren, existingChildren[nameIndex])
361 }
362 } else {
363 // new entry ... just add it
364 updatedChildren = append(updatedChildren, newChild)
365 }
366 }
367
368 // Save children in new revision
369 updatedRev.SetChildren(name, updatedChildren)
370
371 updatedNames := make(map[string]int)
372 for i, updatedChild := range updatedChildren {
373 updatedNames[updatedChild.GetName()] = i
374 }
375
376 log.Debugw("updated-children-names", log.Fields{"hash": npr.GetHash(), "names": updatedNames})
377
378 } else {
379 // There are no children available, just save the provided ones
380 updatedRev.SetChildren(name, children)
381 }
382
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400383 updatedRev.Finalize(false)
384
385 return updatedRev
386}
387
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400388// UpdateAllChildren will replace the current list of children with the provided ones
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400389func (npr *NonPersistedRevision) UpdateAllChildren(children map[string][]Revision, branch *Branch) Revision {
390 npr.mutex.Lock()
391 defer npr.mutex.Unlock()
392
393 newRev := npr
394 newRev.Config = npr.Config
395 newRev.Hash = npr.Hash
396 newRev.Branch = branch
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400397 newRev.Name = npr.Name
398
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400399 newRev.Children = make(map[string][]Revision)
400 for entryName, childrenEntry := range children {
401 newRev.Children[entryName] = append(newRev.Children[entryName], childrenEntry...)
402 }
403 newRev.Finalize(false)
404
405 return newRev
406}
407
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400408// Drop is used to indicate when a revision is no longer required
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400409func (npr *NonPersistedRevision) Drop(txid string, includeConfig bool) {
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400410 log.Debugw("dropping-revision", log.Fields{"hash": npr.GetHash(), "name": npr.GetName()})
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400411 npr.discarded = true
412}
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400413
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400414// ChildDrop will remove a child entry matching the provided parameters from the current revision
415func (npr *NonPersistedRevision) ChildDrop(childType string, childHash string) {
416 if childType != "" {
417 children := make([]Revision, len(npr.GetChildren(childType)))
418 copy(children, npr.GetChildren(childType))
419 for i, child := range children {
420 if child.GetHash() == childHash {
421 children = append(children[:i], children[i+1:]...)
422 npr.SetChildren(childType, children)
423 break
424 }
425 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400426 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400427}
428
manikkaraj k9eb6cac2019-05-09 12:32:03 -0400429func (npr *NonPersistedRevision) LoadFromPersistence(path string, txid string, blobs map[string]*kvstore.KVPair) []Revision {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400430 // stub... required by interface
431 return nil
432}
433
434func (npr *NonPersistedRevision) SetupWatch(key string) {
435 // stub ... required by interface
436}
437
438func (pr *NonPersistedRevision) StorageDrop(txid string, includeConfig bool) {
439 // stub ... required by interface
440}