blob: 42f4264441966fd0531be0d9a210fa420927457d [file] [log] [blame]
khenaidoo1a0d6222021-06-30 16:48:44 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 * http://www.apache.org/licenses/LICENSE-2.0
7 * Unless required by applicable law or agreed to in writing, software
8 * distributed under the License is distributed on an "AS IS" BASIS,
9 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 * See the License for the specific language governing permissions and
11 * limitations under the License.
12 */
13package meter
14
15import (
16 "context"
17 "fmt"
18 "github.com/opencord/voltha-go/db/model"
19 "github.com/opencord/voltha-lib-go/v5/pkg/log"
20 ofp "github.com/opencord/voltha-protos/v4/go/openflow_13"
21 "google.golang.org/grpc/codes"
22 "google.golang.org/grpc/status"
23 "sync"
24)
25
26// Loader hides all low-level locking & synchronization related to meter state updates
27type Loader struct {
28 dbProxy *model.Proxy
29 // this lock protects the meters map, it does not protect individual meters
30 lock sync.RWMutex
31 meters map[uint32]*chunk
32}
33
34// chunk keeps a meter and the lock for this meter
35type chunk struct {
36 // this lock is used to synchronize all access to the meter, and also to the "deleted" variable
37 lock sync.Mutex
38 deleted bool
39 meter *ofp.OfpMeterEntry
40}
41
42func NewLoader(dbProxy *model.Proxy) *Loader {
43 return &Loader{
44 dbProxy: dbProxy,
45 meters: make(map[uint32]*chunk),
46 }
47}
48
49// Load queries existing meters from the kv,
50// and should only be called once when first created.
51func (loader *Loader) Load(ctx context.Context) {
52 loader.lock.Lock()
53 defer loader.lock.Unlock()
54 var meters []*ofp.OfpMeterEntry
55 if err := loader.dbProxy.List(ctx, &meters); err != nil {
56 logger.Errorw(ctx, "failed-to-list-meters-from-cluster-data-proxy", log.Fields{"error": err})
57 return
58 }
59 for _, meter := range meters {
60 loader.meters[meter.Config.MeterId] = &chunk{meter: meter}
61 }
62}
63
64// LockOrCreate locks this meter if it exists, or creates a new meter if it does not.
65// In the case of meter creation, the provided "meter" must not be modified afterwards.
66func (loader *Loader) LockOrCreate(ctx context.Context, meter *ofp.OfpMeterEntry) (*Handle, bool, error) {
67 // try to use read lock instead of full lock if possible
68 if handle, have := loader.Lock(meter.Config.MeterId); have {
69 return handle, false, nil
70 }
71 loader.lock.Lock()
72 entry, have := loader.meters[meter.Config.MeterId]
73 if !have {
74 entry := &chunk{meter: meter}
75 loader.meters[meter.Config.MeterId] = entry
76 entry.lock.Lock()
77 loader.lock.Unlock()
78 if err := loader.dbProxy.Set(ctx, fmt.Sprint(meter.Config.MeterId), meter); err != nil {
79 // revert the map
80 loader.lock.Lock()
81 delete(loader.meters, meter.Config.MeterId)
82 loader.lock.Unlock()
83 entry.deleted = true
84 entry.lock.Unlock()
85 return nil, false, err
86 }
87 return &Handle{loader: loader, chunk: entry}, true, nil
88 }
89 loader.lock.Unlock()
90 entry.lock.Lock()
91 if entry.deleted {
92 entry.lock.Unlock()
93 return loader.LockOrCreate(ctx, meter)
94 }
95 return &Handle{loader: loader, chunk: entry}, false, nil
96}
97
98// Lock acquires the lock for this meter, and returns a handle which can be used to access the meter until it's unlocked.
99// This handle ensures that the meter cannot be accessed if the lock is not held.
100// Returns false if the meter is not present.
101// TODO: consider accepting a ctx and aborting the lock attempt on cancellation
102func (loader *Loader) Lock(id uint32) (*Handle, bool) {
103 loader.lock.RLock()
104 entry, have := loader.meters[id]
105 loader.lock.RUnlock()
106 if !have {
107 return nil, false
108 }
109 entry.lock.Lock()
110 if entry.deleted {
111 entry.lock.Unlock()
112 return loader.Lock(id)
113 }
114 return &Handle{loader: loader, chunk: entry}, true
115}
116
117// Handle is allocated for each Lock() call, all modifications are made using it, and it is invalidated by Unlock()
118// This enforces correct Lock()-Usage()-Unlock() ordering.
119type Handle struct {
120 loader *Loader
121 chunk *chunk
122}
123
124// GetReadOnly returns an *ofp.OfpMeterEntry which MUST NOT be modified externally, but which is safe to keep indefinitely
125func (h *Handle) GetReadOnly() *ofp.OfpMeterEntry {
126 return h.chunk.meter
127}
128
129// Update updates an existing meter in the kv.
130// The provided "meter" must not be modified afterwards.
131func (h *Handle) Update(ctx context.Context, meter *ofp.OfpMeterEntry) error {
132 if err := h.loader.dbProxy.Set(ctx, fmt.Sprint(meter.Config.MeterId), meter); err != nil {
133 return status.Errorf(codes.Internal, "failed-update-meter-%v: %s", meter.Config.MeterId, err)
134 }
135 h.chunk.meter = meter
136 return nil
137}
138
139// Delete removes the device from the kv
140func (h *Handle) Delete(ctx context.Context) error {
141 if err := h.loader.dbProxy.Remove(ctx, fmt.Sprint(h.chunk.meter.Config.MeterId)); err != nil {
142 return fmt.Errorf("couldnt-delete-meter-from-store-%v", h.chunk.meter.Config.MeterId)
143 }
144 h.chunk.deleted = true
145 h.loader.lock.Lock()
146 delete(h.loader.meters, h.chunk.meter.Config.MeterId)
147 h.loader.lock.Unlock()
148 h.Unlock()
149 return nil
150}
151
152// Unlock releases the lock on the meter
153func (h *Handle) Unlock() {
154 if h.chunk != nil {
155 h.chunk.lock.Unlock()
156 h.chunk = nil // attempting to access the meter through this handle in future will panic
157 }
158}
159
160// ListIDs returns a snapshot of all the managed meter IDs
161// TODO: iterating through meters safely is expensive now, since all meters are stored & locked separately
162// should avoid this where possible
163func (loader *Loader) ListIDs() map[uint32]struct{} {
164 loader.lock.RLock()
165 defer loader.lock.RUnlock()
166 // copy the IDs so caller can safely iterate
167 ret := make(map[uint32]struct{}, len(loader.meters))
168 for id := range loader.meters {
169 ret[id] = struct{}{}
170 }
171 return ret
172}