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