blob: 5036ce14ac46098086a4b3cff324be057b92ee72 [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
19import (
20 "encoding/hex"
21 "encoding/json"
22 "github.com/golang/protobuf/proto"
23 "github.com/google/uuid"
24 "github.com/opencord/voltha-go/common/log"
25 "reflect"
26 "sync"
27)
28
29// Root is used to provide an abstraction to the base root structure
30type Root interface {
31 Node
32
33 ExecuteCallbacks()
34 AddCallback(callback CallbackFunction, args ...interface{})
35 AddNotificationCallback(callback CallbackFunction, args ...interface{})
36}
37
38// root points to the top of the data model tree or sub-tree identified by a proxy
39type root struct {
40 *node
41
42 Callbacks []CallbackTuple
43 NotificationCallbacks []CallbackTuple
44
45 DirtyNodes map[string][]*node
46 KvStore *Backend
47 Loading bool
48 RevisionClass interface{}
49
50 mutex sync.RWMutex
51}
52
53// NewRoot creates an new instance of a root object
54func NewRoot(initialData interface{}, kvStore *Backend) *root {
55 root := &root{}
56
57 root.KvStore = kvStore
58 root.DirtyNodes = make(map[string][]*node)
59 root.Loading = false
60
61 // If there is no storage in place just revert to
62 // a non persistent mechanism
63 if kvStore != nil {
64 root.RevisionClass = reflect.TypeOf(PersistedRevision{})
65 } else {
66 root.RevisionClass = reflect.TypeOf(NonPersistedRevision{})
67 }
68
69 root.Callbacks = []CallbackTuple{}
70 root.NotificationCallbacks = []CallbackTuple{}
71
72 root.node = NewNode(root, initialData, false, "")
73
74 return root
75}
76
77// MakeTxBranch creates a new transaction branch
78func (r *root) MakeTxBranch() string {
79 txidBin, _ := uuid.New().MarshalBinary()
80 txid := hex.EncodeToString(txidBin)[:12]
81
82 r.DirtyNodes[txid] = []*node{r.node}
83 r.node.MakeBranch(txid)
84
85 return txid
86}
87
88// DeleteTxBranch removes a transaction branch
89func (r *root) DeleteTxBranch(txid string) {
90 for _, dirtyNode := range r.DirtyNodes[txid] {
91 dirtyNode.DeleteBranch(txid)
92 }
93 delete(r.DirtyNodes, txid)
Mahir Gunyele77977b2019-06-27 05:36:22 -070094 r.node.DeleteBranch(txid)
Matt Jeanneretcab955f2019-04-10 15:45:57 -040095}
96
97// FoldTxBranch will merge the contents of a transaction branch with the root object
98func (r *root) FoldTxBranch(txid string) {
99 // Start by doing a dry run of the merge
100 // If that fails, it bails out and the branch is deleted
101 if _, err := r.node.MergeBranch(txid, true); err != nil {
102 // Merge operation fails
103 r.DeleteTxBranch(txid)
104 } else {
105 r.node.MergeBranch(txid, false)
106 r.ExecuteCallbacks()
107 r.DeleteTxBranch(txid)
108 }
109}
110
111// ExecuteCallbacks will invoke all the callbacks linked to root object
112func (r *root) ExecuteCallbacks() {
113 r.mutex.Lock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400114 defer r.mutex.Unlock()
Mahir Gunyele77977b2019-06-27 05:36:22 -0700115
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400116 for len(r.Callbacks) > 0 {
117 callback := r.Callbacks[0]
118 r.Callbacks = r.Callbacks[1:]
119 go callback.Execute(nil)
120 }
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400121 //for len(r.NotificationCallbacks) > 0 {
122 // callback := r.NotificationCallbacks[0]
123 // r.NotificationCallbacks = r.NotificationCallbacks[1:]
124 // go callback.Execute(nil)
125 //}
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400126}
127
128func (r *root) hasCallbacks() bool {
129 return len(r.Callbacks) == 0
130}
131
132// getCallbacks returns the available callbacks
133func (r *root) GetCallbacks() []CallbackTuple {
134 r.mutex.Lock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400135 defer r.mutex.Unlock()
Mahir Gunyele77977b2019-06-27 05:36:22 -0700136
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400137 return r.Callbacks
138}
139
140// getCallbacks returns the available notification callbacks
141func (r *root) GetNotificationCallbacks() []CallbackTuple {
142 r.mutex.Lock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400143 defer r.mutex.Unlock()
Mahir Gunyele77977b2019-06-27 05:36:22 -0700144
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400145 return r.NotificationCallbacks
146}
147
148// AddCallback inserts a new callback with its arguments
149func (r *root) AddCallback(callback CallbackFunction, args ...interface{}) {
150 r.mutex.Lock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400151 defer r.mutex.Unlock()
Mahir Gunyele77977b2019-06-27 05:36:22 -0700152
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400153 r.Callbacks = append(r.Callbacks, CallbackTuple{callback, args})
154}
155
156// AddNotificationCallback inserts a new notification callback with its arguments
157func (r *root) AddNotificationCallback(callback CallbackFunction, args ...interface{}) {
158 r.mutex.Lock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400159 defer r.mutex.Unlock()
Mahir Gunyele77977b2019-06-27 05:36:22 -0700160
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400161 r.NotificationCallbacks = append(r.NotificationCallbacks, CallbackTuple{callback, args})
162}
163
164func (r *root) syncParent(childRev Revision, txid string) {
165 data := proto.Clone(r.Proxy.ParentNode.Latest().GetData().(proto.Message))
166
167 for fieldName, _ := range ChildrenFields(data) {
168 childDataName, childDataHolder := GetAttributeValue(data, fieldName, 0)
169 if reflect.TypeOf(childRev.GetData()) == reflect.TypeOf(childDataHolder.Interface()) {
170 childDataHolder = reflect.ValueOf(childRev.GetData())
171 reflect.ValueOf(data).Elem().FieldByName(childDataName).Set(childDataHolder)
172 }
173 }
174
175 r.Proxy.ParentNode.Latest().SetConfig(NewDataRevision(r.Proxy.ParentNode.Root, data))
176 r.Proxy.ParentNode.Latest(txid).Finalize(false)
177}
178
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400179// Update modifies the content of an object at a given path with the provided data
180func (r *root) Update(path string, data interface{}, strict bool, txid string, makeBranch MakeBranchFunction) Revision {
181 var result Revision
182
183 if makeBranch != nil {
184 // TODO: raise error
185 }
186
187 if r.hasCallbacks() {
188 // TODO: raise error
189 }
190
191 if txid != "" {
192 trackDirty := func(node *node) *Branch {
193 r.DirtyNodes[txid] = append(r.DirtyNodes[txid], node)
194 return node.MakeBranch(txid)
195 }
196 result = r.node.Update(path, data, strict, txid, trackDirty)
197 } else {
198 result = r.node.Update(path, data, strict, "", nil)
199 }
200
201 if result != nil {
202 if r.Proxy.FullPath != r.Proxy.Path {
203 r.syncParent(result, txid)
204 } else {
205 result.Finalize(false)
206 }
207 }
208
209 r.node.GetRoot().ExecuteCallbacks()
210
211 return result
212}
213
214// Add creates a new object at the given path with the provided data
215func (r *root) Add(path string, data interface{}, txid string, makeBranch MakeBranchFunction) Revision {
216 var result Revision
217
218 if makeBranch != nil {
219 // TODO: raise error
220 }
221
222 if r.hasCallbacks() {
223 // TODO: raise error
224 }
225
226 if txid != "" {
227 trackDirty := func(node *node) *Branch {
228 r.DirtyNodes[txid] = append(r.DirtyNodes[txid], node)
229 return node.MakeBranch(txid)
230 }
231 result = r.node.Add(path, data, txid, trackDirty)
232 } else {
233 result = r.node.Add(path, data, "", nil)
234 }
235
236 if result != nil {
237 result.Finalize(true)
238 r.node.GetRoot().ExecuteCallbacks()
239 }
240 return result
241}
242
243// Remove discards an object at a given path
244func (r *root) Remove(path string, txid string, makeBranch MakeBranchFunction) Revision {
245 var result Revision
246
247 if makeBranch != nil {
248 // TODO: raise error
249 }
250
251 if r.hasCallbacks() {
252 // TODO: raise error
253 }
254
255 if txid != "" {
256 trackDirty := func(node *node) *Branch {
257 r.DirtyNodes[txid] = append(r.DirtyNodes[txid], node)
258 return node.MakeBranch(txid)
259 }
260 result = r.node.Remove(path, txid, trackDirty)
261 } else {
262 result = r.node.Remove(path, "", nil)
263 }
264
265 r.node.GetRoot().ExecuteCallbacks()
266
267 return result
268}
269
270// MakeLatest updates a branch with the latest node revision
271func (r *root) MakeLatest(branch *Branch, revision Revision, changeAnnouncement []ChangeTuple) {
272 r.makeLatest(branch, revision, changeAnnouncement)
273}
274
275func (r *root) MakeRevision(branch *Branch, data interface{}, children map[string][]Revision) Revision {
276 if r.RevisionClass.(reflect.Type) == reflect.TypeOf(PersistedRevision{}) {
277 return NewPersistedRevision(branch, data, children)
278 }
279
280 return NewNonPersistedRevision(r, branch, data, children)
281}
282
283func (r *root) makeLatest(branch *Branch, revision Revision, changeAnnouncement []ChangeTuple) {
284 r.node.makeLatest(branch, revision, changeAnnouncement)
285
286 if r.KvStore != nil && branch.Txid == "" {
287 tags := make(map[string]string)
288 for k, v := range r.node.Tags {
289 tags[k] = v.GetHash()
290 }
291 data := &rootData{
292 Latest: branch.GetLatest().GetHash(),
293 Tags: tags,
294 }
295 if blob, err := json.Marshal(data); err != nil {
296 // TODO report error
297 } else {
298 log.Debugf("Changing root to : %s", string(blob))
299 if err := r.KvStore.Put("root", blob); err != nil {
300 log.Errorf("failed to properly put value in kvstore - err: %s", err.Error())
301 }
302 }
303 }
304}
305
306type rootData struct {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400307 Latest string `json:"latest"`
308 Tags map[string]string `json:"tags"`
309}