blob: b45fb1d28a0a3dcd826b3cb0f33450ff583db238 [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 "crypto/md5"
21 "errors"
22 "fmt"
23 "github.com/opencord/voltha-go/common/log"
24 "reflect"
25 "runtime"
26 "strings"
27 "sync"
28)
29
30// OperationContext holds details on the information used during an operation
31type OperationContext struct {
32 Path string
33 Data interface{}
34 FieldName string
35 ChildKey string
36}
37
38// NewOperationContext instantiates a new OperationContext structure
39func NewOperationContext(path string, data interface{}, fieldName string, childKey string) *OperationContext {
40 oc := &OperationContext{
41 Path: path,
42 Data: data,
43 FieldName: fieldName,
44 ChildKey: childKey,
45 }
46 return oc
47}
48
49// Update applies new data to the context structure
50func (oc *OperationContext) Update(data interface{}) *OperationContext {
51 oc.Data = data
52 return oc
53}
54
55// Proxy holds the information for a specific location with the data model
56type Proxy struct {
57 sync.RWMutex
58 Root *root
59 Node *node
60 ParentNode *node
61 Path string
62 FullPath string
63 Exclusive bool
64 Callbacks map[CallbackType]map[string]*CallbackTuple
65 Operation ProxyOperation
66}
67
68// NewProxy instantiates a new proxy to a specific location
69func NewProxy(root *root, node *node, parentNode *node, path string, fullPath string, exclusive bool) *Proxy {
70 callbacks := make(map[CallbackType]map[string]*CallbackTuple)
71 if fullPath == "/" {
72 fullPath = ""
73 }
74 p := &Proxy{
75 Root: root,
76 Node: node,
77 ParentNode: parentNode,
78 Exclusive: exclusive,
79 Path: path,
80 FullPath: fullPath,
81 Callbacks: callbacks,
82 }
83 return p
84}
85
86// GetRoot returns the root attribute of the proxy
87func (p *Proxy) GetRoot() *root {
88 return p.Root
89}
90
91// getPath returns the path attribute of the proxy
92func (p *Proxy) getPath() string {
93 return p.Path
94}
95
96// getFullPath returns the full path attribute of the proxy
97func (p *Proxy) getFullPath() string {
98 return p.FullPath
99}
100
101// getCallbacks returns the full list of callbacks associated to the proxy
102func (p *Proxy) getCallbacks(callbackType CallbackType) map[string]*CallbackTuple {
103 if cb, exists := p.Callbacks[callbackType]; exists {
104 return cb
105 }
106 return nil
107}
108
109// getCallback returns a specific callback matching the type and function hash
110func (p *Proxy) getCallback(callbackType CallbackType, funcHash string) *CallbackTuple {
111 p.Lock()
112 defer p.Unlock()
113 if tuple, exists := p.Callbacks[callbackType][funcHash]; exists {
114 return tuple
115 }
116 return nil
117}
118
119// setCallbacks applies a callbacks list to a type
120func (p *Proxy) setCallbacks(callbackType CallbackType, callbacks map[string]*CallbackTuple) {
121 p.Lock()
122 defer p.Unlock()
123 p.Callbacks[callbackType] = callbacks
124}
125
126// setCallback applies a callback to a type and hash value
127func (p *Proxy) setCallback(callbackType CallbackType, funcHash string, tuple *CallbackTuple) {
128 p.Lock()
129 defer p.Unlock()
130 p.Callbacks[callbackType][funcHash] = tuple
131}
132
133// DeleteCallback removes a callback matching the type and hash
134func (p *Proxy) DeleteCallback(callbackType CallbackType, funcHash string) {
135 p.Lock()
136 defer p.Unlock()
137 delete(p.Callbacks[callbackType], funcHash)
138}
139
140// CallbackType is an enumerated value to express when a callback should be executed
141type ProxyOperation uint8
142
143// Enumerated list of callback types
144const (
145 PROXY_GET ProxyOperation = iota
146 PROXY_LIST
147 PROXY_ADD
148 PROXY_UPDATE
149 PROXY_REMOVE
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400150 PROXY_CREATE
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400151)
152
153// parseForControlledPath verifies if a proxy path matches a pattern
154// for locations that need to be access controlled.
155func (p *Proxy) parseForControlledPath(path string) (pathLock string, controlled bool) {
156 // TODO: Add other path prefixes that may need control
157 if strings.HasPrefix(path, "/devices") ||
158 strings.HasPrefix(path, "/logical_devices") ||
159 strings.HasPrefix(path, "/adapters") {
160
161 split := strings.SplitN(path, "/", -1)
162 switch len(split) {
163 case 2:
164 controlled = false
165 pathLock = ""
166 break
167 case 3:
168 fallthrough
169 default:
170 pathLock = fmt.Sprintf("%s/%s", split[1], split[2])
171 controlled = true
172 }
173 }
174 return pathLock, controlled
175}
176
177// List will retrieve information from the data model at the specified path location
178// A list operation will force access to persistence storage
179func (p *Proxy) List(path string, depth int, deep bool, txid string) interface{} {
180 var effectivePath string
181 if path == "/" {
182 effectivePath = p.getFullPath()
183 } else {
184 effectivePath = p.getFullPath() + path
185 }
186
187 pathLock, controlled := p.parseForControlledPath(effectivePath)
188
189 log.Debugf("Path: %s, Effective: %s, PathLock: %s", path, effectivePath, pathLock)
190
191 pac := PAC().ReservePath(effectivePath, p, pathLock)
192 defer PAC().ReleasePath(pathLock)
193 pac.SetProxy(p)
194
195 rv := pac.List(path, depth, deep, txid, controlled)
196
197 return rv
198}
199
200// Get will retrieve information from the data model at the specified path location
201func (p *Proxy) Get(path string, depth int, deep bool, txid string) interface{} {
202 var effectivePath string
203 if path == "/" {
204 effectivePath = p.getFullPath()
205 } else {
206 effectivePath = p.getFullPath() + path
207 }
208
209 pathLock, controlled := p.parseForControlledPath(effectivePath)
210
211 log.Debugf("Path: %s, Effective: %s, PathLock: %s", path, effectivePath, pathLock)
212
213 pac := PAC().ReservePath(effectivePath, p, pathLock)
214 defer PAC().ReleasePath(pathLock)
215 pac.SetProxy(p)
216
217 rv := pac.Get(path, depth, deep, txid, controlled)
218
219 return rv
220}
221
222// Update will modify information in the data model at the specified location with the provided data
223func (p *Proxy) Update(path string, data interface{}, strict bool, txid string) interface{} {
224 if !strings.HasPrefix(path, "/") {
225 log.Errorf("invalid path: %s", path)
226 return nil
227 }
228 var fullPath string
229 var effectivePath string
230 if path == "/" {
231 fullPath = p.getPath()
232 effectivePath = p.getFullPath()
233 } else {
234 fullPath = p.getPath() + path
235 effectivePath = p.getFullPath() + path
236 }
237
238 pathLock, controlled := p.parseForControlledPath(effectivePath)
239
240 log.Debugf("Path: %s, Effective: %s, Full: %s, PathLock: %s, Controlled: %b", path, effectivePath, fullPath, pathLock, controlled)
241
242 pac := PAC().ReservePath(effectivePath, p, pathLock)
243 defer PAC().ReleasePath(pathLock)
244
245 p.Operation = PROXY_UPDATE
246 pac.SetProxy(p)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400247 defer func(op ProxyOperation) {
248 pac.getProxy().Operation = op
249 }(PROXY_GET)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400250
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400251 log.Debugw("proxy-operation--update", log.Fields{"operation": p.Operation})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400252
253 return pac.Update(fullPath, data, strict, txid, controlled)
254}
255
256// AddWithID will insert new data at specified location.
257// This method also allows the user to specify the ID of the data entry to ensure
258// that access control is active while inserting the information.
259func (p *Proxy) AddWithID(path string, id string, data interface{}, txid string) interface{} {
260 if !strings.HasPrefix(path, "/") {
261 log.Errorf("invalid path: %s", path)
262 return nil
263 }
264 var fullPath string
265 var effectivePath string
266 if path == "/" {
267 fullPath = p.getPath()
268 effectivePath = p.getFullPath()
269 } else {
270 fullPath = p.getPath() + path
271 effectivePath = p.getFullPath() + path + "/" + id
272 }
273
274 pathLock, controlled := p.parseForControlledPath(effectivePath)
275
276 log.Debugf("Path: %s, Effective: %s, Full: %s, PathLock: %s", path, effectivePath, fullPath, pathLock)
277
278 pac := PAC().ReservePath(path, p, pathLock)
279 defer PAC().ReleasePath(pathLock)
280
281 p.Operation = PROXY_ADD
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400282 defer func() {
283 p.Operation = PROXY_GET
284 }()
285
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400286 pac.SetProxy(p)
287
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400288 log.Debugw("proxy-operation--add", log.Fields{"operation": p.Operation})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400289
290 return pac.Add(fullPath, data, txid, controlled)
291}
292
293// Add will insert new data at specified location.
294func (p *Proxy) Add(path string, data interface{}, txid string) interface{} {
295 if !strings.HasPrefix(path, "/") {
296 log.Errorf("invalid path: %s", path)
297 return nil
298 }
299 var fullPath string
300 var effectivePath string
301 if path == "/" {
302 fullPath = p.getPath()
303 effectivePath = p.getFullPath()
304 } else {
305 fullPath = p.getPath() + path
306 effectivePath = p.getFullPath() + path
307 }
308
309 pathLock, controlled := p.parseForControlledPath(effectivePath)
310
311 log.Debugf("Path: %s, Effective: %s, Full: %s, PathLock: %s", path, effectivePath, fullPath, pathLock)
312
313 pac := PAC().ReservePath(path, p, pathLock)
314 defer PAC().ReleasePath(pathLock)
315
316 p.Operation = PROXY_ADD
317 pac.SetProxy(p)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400318 defer func() {
319 p.Operation = PROXY_GET
320 }()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400321
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400322 log.Debugw("proxy-operation--add", log.Fields{"operation": p.Operation})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400323
324 return pac.Add(fullPath, data, txid, controlled)
325}
326
327// Remove will delete an entry at the specified location
328func (p *Proxy) Remove(path string, txid string) interface{} {
329 if !strings.HasPrefix(path, "/") {
330 log.Errorf("invalid path: %s", path)
331 return nil
332 }
333 var fullPath string
334 var effectivePath string
335 if path == "/" {
336 fullPath = p.getPath()
337 effectivePath = p.getFullPath()
338 } else {
339 fullPath = p.getPath() + path
340 effectivePath = p.getFullPath() + path
341 }
342
343 pathLock, controlled := p.parseForControlledPath(effectivePath)
344
345 log.Debugf("Path: %s, Effective: %s, Full: %s, PathLock: %s", path, effectivePath, fullPath, pathLock)
346
347 pac := PAC().ReservePath(effectivePath, p, pathLock)
348 defer PAC().ReleasePath(pathLock)
349
350 p.Operation = PROXY_REMOVE
351 pac.SetProxy(p)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400352 defer func() {
353 p.Operation = PROXY_GET
354 }()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400355
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400356 log.Debugw("proxy-operation--remove", log.Fields{"operation": p.Operation})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400357
358 return pac.Remove(fullPath, txid, controlled)
359}
360
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400361// CreateProxy to interact with specific path directly
362func (p *Proxy) CreateProxy(path string, exclusive bool) *Proxy {
363 if !strings.HasPrefix(path, "/") {
364 log.Errorf("invalid path: %s", path)
365 return nil
366 }
367
368 var fullPath string
369 var effectivePath string
370 if path == "/" {
371 fullPath = p.getPath()
372 effectivePath = p.getFullPath()
373 } else {
374 fullPath = p.getPath() + path
375 effectivePath = p.getFullPath() + path
376 }
377
378 pathLock, controlled := p.parseForControlledPath(effectivePath)
379
380 log.Debugf("Path: %s, Effective: %s, Full: %s, PathLock: %s", path, effectivePath, fullPath, pathLock)
381
382 pac := PAC().ReservePath(path, p, pathLock)
383 defer PAC().ReleasePath(pathLock)
384
385 p.Operation = PROXY_CREATE
386 pac.SetProxy(p)
387 defer func() {
388 p.Operation = PROXY_GET
389 }()
390
391 log.Debugw("proxy-operation--create-proxy", log.Fields{"operation": p.Operation})
392
393 return pac.CreateProxy(fullPath, exclusive, controlled)
394}
395
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400396// OpenTransaction creates a new transaction branch to isolate operations made to the data model
397func (p *Proxy) OpenTransaction() *Transaction {
398 txid := p.GetRoot().MakeTxBranch()
399 return NewTransaction(p, txid)
400}
401
402// commitTransaction will apply and merge modifications made in the transaction branch to the data model
403func (p *Proxy) commitTransaction(txid string) {
404 p.GetRoot().FoldTxBranch(txid)
405}
406
407// cancelTransaction will terminate a transaction branch along will all changes within it
408func (p *Proxy) cancelTransaction(txid string) {
409 p.GetRoot().DeleteTxBranch(txid)
410}
411
412// CallbackFunction is a type used to define callback functions
413type CallbackFunction func(args ...interface{}) interface{}
414
415// CallbackTuple holds the function and arguments details of a callback
416type CallbackTuple struct {
417 callback CallbackFunction
418 args []interface{}
419}
420
421// Execute will process the a callback with its provided arguments
422func (tuple *CallbackTuple) Execute(contextArgs []interface{}) interface{} {
423 args := []interface{}{}
424
425 for _, ta := range tuple.args {
426 args = append(args, ta)
427 }
428
429 if contextArgs != nil {
430 for _, ca := range contextArgs {
431 args = append(args, ca)
432 }
433 }
434
435 return tuple.callback(args...)
436}
437
438// RegisterCallback associates a callback to the proxy
439func (p *Proxy) RegisterCallback(callbackType CallbackType, callback CallbackFunction, args ...interface{}) {
440 if p.getCallbacks(callbackType) == nil {
441 p.setCallbacks(callbackType, make(map[string]*CallbackTuple))
442 }
443 funcName := runtime.FuncForPC(reflect.ValueOf(callback).Pointer()).Name()
444 log.Debugf("value of function: %s", funcName)
445 funcHash := fmt.Sprintf("%x", md5.Sum([]byte(funcName)))[:12]
446
447 p.setCallback(callbackType, funcHash, &CallbackTuple{callback, args})
448}
449
450// UnregisterCallback removes references to a callback within a proxy
451func (p *Proxy) UnregisterCallback(callbackType CallbackType, callback CallbackFunction, args ...interface{}) {
452 if p.getCallbacks(callbackType) == nil {
453 log.Errorf("no such callback type - %s", callbackType.String())
454 return
455 }
456
457 funcName := runtime.FuncForPC(reflect.ValueOf(callback).Pointer()).Name()
458 funcHash := fmt.Sprintf("%x", md5.Sum([]byte(funcName)))[:12]
459
460 log.Debugf("value of function: %s", funcName)
461
462 if p.getCallback(callbackType, funcHash) == nil {
463 log.Errorf("function with hash value: '%s' not registered with callback type: '%s'", funcHash, callbackType)
464 return
465 }
466
467 p.DeleteCallback(callbackType, funcHash)
468}
469
470func (p *Proxy) invoke(callback *CallbackTuple, context []interface{}) (result interface{}, err error) {
471 defer func() {
472 if r := recover(); r != nil {
473 errStr := fmt.Sprintf("callback error occurred: %+v", r)
474 err = errors.New(errStr)
475 log.Error(errStr)
476 }
477 }()
478
479 result = callback.Execute(context)
480
481 return result, err
482}
483
484// InvokeCallbacks executes all callbacks associated to a specific type
485func (p *Proxy) InvokeCallbacks(args ...interface{}) (result interface{}) {
486 callbackType := args[0].(CallbackType)
487 proceedOnError := args[1].(bool)
488 context := args[2:]
489
490 var err error
491
492 if callbacks := p.getCallbacks(callbackType); callbacks != nil {
493 p.Lock()
494 for _, callback := range callbacks {
495 if result, err = p.invoke(callback, context); err != nil {
496 if !proceedOnError {
497 log.Info("An error occurred. Stopping callback invocation")
498 break
499 }
500 log.Info("An error occurred. Invoking next callback")
501 }
502 }
503 p.Unlock()
504 }
505
506 return result
507}