blob: 741a45ffd81fb548269be7326792c3c0ab87650f [file] [log] [blame]
Kent Hagerman433a31a2020-05-20 19:04:48 -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 flow
18
19import (
20 "context"
21 "fmt"
22 "strconv"
23 "sync"
24
25 "github.com/opencord/voltha-go/db/model"
26 "github.com/opencord/voltha-lib-go/v3/pkg/log"
27 ofp "github.com/opencord/voltha-protos/v3/go/openflow_13"
28 "google.golang.org/grpc/codes"
29 "google.golang.org/grpc/status"
30)
31
32// Loader hides all low-level locking & synchronization related to flow state updates
33type Loader struct {
34 // this lock protects the flows map, it does not protect individual flows
35 lock sync.RWMutex
36 flows map[uint64]*chunk
37
38 dbProxy *model.Proxy
39 logicalDeviceID string // TODO: dbProxy should already have the logicalDeviceID component of the path internally
40}
41
42// chunk keeps a flow and the lock for this flow
43type chunk struct {
44 // this lock is used to synchronize all access to the flow, and also to the "deleted" variable
45 lock sync.Mutex
46 deleted bool
47
48 flow *ofp.OfpFlowStats
49}
50
51func NewLoader(dataProxy *model.Proxy, logicalDeviceID string) *Loader {
52 return &Loader{
53 flows: make(map[uint64]*chunk),
54 dbProxy: dataProxy,
55 logicalDeviceID: logicalDeviceID,
56 }
57}
58
59// Load queries existing flows from the kv,
60// and should only be called once when first created.
61func (loader *Loader) Load(ctx context.Context) {
62 loader.lock.Lock()
63 defer loader.lock.Unlock()
64
65 var flows []*ofp.OfpFlowStats
66 if err := loader.dbProxy.List(ctx, "logical_flows/"+loader.logicalDeviceID, &flows); err != nil {
67 logger.Errorw("failed-to-list-flows-from-cluster-data-proxy", log.Fields{"error": err})
68 return
69 }
70 for _, flow := range flows {
71 loader.flows[flow.Id] = &chunk{flow: flow}
72 }
73}
74
75// LockOrCreate locks this flow if it exists, or creates a new flow if it does not.
76// In the case of flow creation, the provided "flow" must not be modified afterwards.
77func (loader *Loader) LockOrCreate(ctx context.Context, flow *ofp.OfpFlowStats) (*Handle, bool, error) {
78 // try to use read lock instead of full lock if possible
79 if handle, have := loader.Lock(flow.Id); have {
80 return handle, false, nil
81 }
82
83 loader.lock.Lock()
84 entry, have := loader.flows[flow.Id]
85 if !have {
86 entry := &chunk{flow: flow}
87 loader.flows[flow.Id] = entry
88 entry.lock.Lock()
89 loader.lock.Unlock()
90
91 flowID := strconv.FormatUint(uint64(flow.Id), 10)
92 if err := loader.dbProxy.AddWithID(ctx, "logical_flows/"+loader.logicalDeviceID, flowID, flow); err != nil {
93 logger.Errorw("failed-adding-flow-to-db", log.Fields{"deviceID": loader.logicalDeviceID, "flowID": flowID, "err": err})
94
95 // revert the map
96 loader.lock.Lock()
97 delete(loader.flows, flow.Id)
98 loader.lock.Unlock()
99
100 entry.deleted = true
101 entry.lock.Unlock()
102 return nil, false, err
103 }
104 return &Handle{loader: loader, chunk: entry}, true, nil
105 }
106 loader.lock.Unlock()
107
108 entry.lock.Lock()
109 if entry.deleted {
110 entry.lock.Unlock()
111 return loader.LockOrCreate(ctx, flow)
112 }
113 return &Handle{loader: loader, chunk: entry}, false, nil
114}
115
116// Lock acquires the lock for this flow, and returns a handle which can be used to access the meter until it's unlocked.
117// This handle ensures that the flow cannot be accessed if the lock is not held.
118// Returns false if the flow is not present.
119// TODO: consider accepting a ctx and aborting the lock attempt on cancellation
120func (loader *Loader) Lock(id uint64) (*Handle, bool) {
121 loader.lock.RLock()
122 entry, have := loader.flows[id]
123 loader.lock.RUnlock()
124
125 if !have {
126 return nil, false
127 }
128
129 entry.lock.Lock()
130 if entry.deleted {
131 entry.lock.Unlock()
132 return loader.Lock(id)
133 }
134 return &Handle{loader: loader, chunk: entry}, true
135}
136
137type Handle struct {
138 loader *Loader
139 chunk *chunk
140}
141
142// GetReadOnly returns an *ofp.OfpFlowStats which MUST NOT be modified externally, but which is safe to keep indefinitely
143func (h *Handle) GetReadOnly() *ofp.OfpFlowStats {
144 return h.chunk.flow
145}
146
147// Update updates an existing flow in the kv.
148// The provided "flow" must not be modified afterwards.
149func (h *Handle) Update(ctx context.Context, flow *ofp.OfpFlowStats) error {
150 path := fmt.Sprintf("logical_flows/%s/%d", h.loader.logicalDeviceID, flow.Id)
151 if err := h.loader.dbProxy.Update(ctx, path, flow); err != nil {
152 return status.Errorf(codes.Internal, "failed-update-flow:%s:%d %s", h.loader.logicalDeviceID, flow.Id, err)
153 }
154 h.chunk.flow = flow
155 return nil
156}
157
158// Delete removes the device from the kv
159func (h *Handle) Delete(ctx context.Context) error {
160 path := fmt.Sprintf("logical_flows/%s/%d", h.loader.logicalDeviceID, h.chunk.flow.Id)
161 if err := h.loader.dbProxy.Remove(ctx, path); err != nil {
162 return fmt.Errorf("couldnt-delete-flow-from-store-%s", path)
163 }
164 h.chunk.deleted = true
165
166 h.loader.lock.Lock()
167 delete(h.loader.flows, h.chunk.flow.Id)
168 h.loader.lock.Unlock()
169
170 h.Unlock()
171 return nil
172}
173
174// Unlock releases the lock on the flow
175func (h *Handle) Unlock() {
176 if h.chunk != nil {
177 h.chunk.lock.Unlock()
178 h.chunk = nil // attempting to access the flow through this handle in future will panic
179 }
180}
181
182// List returns a snapshot of all the managed flow IDs
183// TODO: iterating through flows safely is expensive now, since all flows are stored & locked separately
184// should avoid this where possible
185func (loader *Loader) List() map[uint64]struct{} {
186 loader.lock.RLock()
187 defer loader.lock.RUnlock()
188 // copy the IDs so caller can safely iterate
189 ret := make(map[uint64]struct{}, len(loader.flows))
190 for id := range loader.flows {
191 ret[id] = struct{}{}
192 }
193 return ret
194}