blob: 3d9f0655d544bf143fede70df65d2a0a43f9f015 [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 {
Kent Hagermanfa9d6d42020-05-25 11:49:40 -040033 dbProxy *model.Proxy
Kent Hagerman433a31a2020-05-20 19:04:48 -040034 // this lock protects the flows map, it does not protect individual flows
35 lock sync.RWMutex
36 flows map[uint64]*chunk
Kent Hagerman433a31a2020-05-20 19:04:48 -040037}
38
39// chunk keeps a flow and the lock for this flow
40type chunk struct {
41 // this lock is used to synchronize all access to the flow, and also to the "deleted" variable
42 lock sync.Mutex
43 deleted bool
44
45 flow *ofp.OfpFlowStats
46}
47
Kent Hagermanf5a67352020-04-30 15:15:26 -040048func NewLoader(dbProxy *model.Proxy) *Loader {
Kent Hagerman433a31a2020-05-20 19:04:48 -040049 return &Loader{
Kent Hagermanf5a67352020-04-30 15:15:26 -040050 dbProxy: dbProxy,
Kent Hagermanfa9d6d42020-05-25 11:49:40 -040051 flows: make(map[uint64]*chunk),
Kent Hagerman433a31a2020-05-20 19:04:48 -040052 }
53}
54
55// Load queries existing flows from the kv,
56// and should only be called once when first created.
57func (loader *Loader) Load(ctx context.Context) {
58 loader.lock.Lock()
59 defer loader.lock.Unlock()
60
61 var flows []*ofp.OfpFlowStats
Kent Hagermanf5a67352020-04-30 15:15:26 -040062 if err := loader.dbProxy.List(ctx, &flows); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000063 logger.Errorw(ctx, "failed-to-list-flows-from-cluster-data-proxy", log.Fields{"error": err})
Kent Hagerman433a31a2020-05-20 19:04:48 -040064 return
65 }
66 for _, flow := range flows {
67 loader.flows[flow.Id] = &chunk{flow: flow}
68 }
69}
70
71// LockOrCreate locks this flow if it exists, or creates a new flow if it does not.
72// In the case of flow creation, the provided "flow" must not be modified afterwards.
73func (loader *Loader) LockOrCreate(ctx context.Context, flow *ofp.OfpFlowStats) (*Handle, bool, error) {
74 // try to use read lock instead of full lock if possible
75 if handle, have := loader.Lock(flow.Id); have {
76 return handle, false, nil
77 }
78
79 loader.lock.Lock()
80 entry, have := loader.flows[flow.Id]
81 if !have {
82 entry := &chunk{flow: flow}
83 loader.flows[flow.Id] = entry
84 entry.lock.Lock()
85 loader.lock.Unlock()
86
Kent Hagermanf5a67352020-04-30 15:15:26 -040087 if err := loader.dbProxy.Set(ctx, fmt.Sprint(flow.Id), flow); err != nil {
Kent Hagerman433a31a2020-05-20 19:04:48 -040088 // revert the map
89 loader.lock.Lock()
90 delete(loader.flows, flow.Id)
91 loader.lock.Unlock()
92
93 entry.deleted = true
94 entry.lock.Unlock()
95 return nil, false, err
96 }
97 return &Handle{loader: loader, chunk: entry}, true, nil
98 }
99 loader.lock.Unlock()
100
101 entry.lock.Lock()
102 if entry.deleted {
103 entry.lock.Unlock()
104 return loader.LockOrCreate(ctx, flow)
105 }
106 return &Handle{loader: loader, chunk: entry}, false, nil
107}
108
Kent Hagermanfa9d6d42020-05-25 11:49:40 -0400109// Lock acquires the lock for this flow, and returns a handle which can be used to access the flow until it's unlocked.
Kent Hagerman433a31a2020-05-20 19:04:48 -0400110// This handle ensures that the flow cannot be accessed if the lock is not held.
111// Returns false if the flow is not present.
112// TODO: consider accepting a ctx and aborting the lock attempt on cancellation
113func (loader *Loader) Lock(id uint64) (*Handle, bool) {
114 loader.lock.RLock()
115 entry, have := loader.flows[id]
116 loader.lock.RUnlock()
117
118 if !have {
119 return nil, false
120 }
121
122 entry.lock.Lock()
123 if entry.deleted {
124 entry.lock.Unlock()
125 return loader.Lock(id)
126 }
127 return &Handle{loader: loader, chunk: entry}, true
128}
129
Kent Hagermanfa9d6d42020-05-25 11:49:40 -0400130// Handle is allocated for each Lock() call, all modifications are made using it, and it is invalidated by Unlock()
131// This enforces correct Lock()-Usage()-Unlock() ordering.
Kent Hagerman433a31a2020-05-20 19:04:48 -0400132type Handle struct {
133 loader *Loader
134 chunk *chunk
135}
136
137// GetReadOnly returns an *ofp.OfpFlowStats which MUST NOT be modified externally, but which is safe to keep indefinitely
138func (h *Handle) GetReadOnly() *ofp.OfpFlowStats {
139 return h.chunk.flow
140}
141
142// Update updates an existing flow in the kv.
143// The provided "flow" must not be modified afterwards.
144func (h *Handle) Update(ctx context.Context, flow *ofp.OfpFlowStats) error {
Kent Hagermanf5a67352020-04-30 15:15:26 -0400145 if err := h.loader.dbProxy.Set(ctx, fmt.Sprint(flow.Id), flow); err != nil {
146 return status.Errorf(codes.Internal, "failed-update-flow-%v: %s", flow.Id, err)
Kent Hagerman433a31a2020-05-20 19:04:48 -0400147 }
148 h.chunk.flow = flow
149 return nil
150}
151
152// Delete removes the device from the kv
153func (h *Handle) Delete(ctx context.Context) error {
Kent Hagermanf5a67352020-04-30 15:15:26 -0400154 if err := h.loader.dbProxy.Remove(ctx, fmt.Sprint(h.chunk.flow.Id)); err != nil {
155 return fmt.Errorf("couldnt-delete-flow-from-store-%v", h.chunk.flow.Id)
Kent Hagerman433a31a2020-05-20 19:04:48 -0400156 }
157 h.chunk.deleted = true
158
159 h.loader.lock.Lock()
160 delete(h.loader.flows, h.chunk.flow.Id)
161 h.loader.lock.Unlock()
162
163 h.Unlock()
164 return nil
165}
166
167// Unlock releases the lock on the flow
168func (h *Handle) Unlock() {
169 if h.chunk != nil {
170 h.chunk.lock.Unlock()
171 h.chunk = nil // attempting to access the flow through this handle in future will panic
172 }
173}
174
Kent Hagermanfa9d6d42020-05-25 11:49:40 -0400175// ListIDs returns a snapshot of all the managed flow IDs
Kent Hagerman433a31a2020-05-20 19:04:48 -0400176// TODO: iterating through flows safely is expensive now, since all flows are stored & locked separately
177// should avoid this where possible
Kent Hagermanfa9d6d42020-05-25 11:49:40 -0400178func (loader *Loader) ListIDs() map[uint64]struct{} {
Kent Hagerman433a31a2020-05-20 19:04:48 -0400179 loader.lock.RLock()
180 defer loader.lock.RUnlock()
181 // copy the IDs so caller can safely iterate
182 ret := make(map[uint64]struct{}, len(loader.flows))
183 for id := range loader.flows {
184 ret[id] = struct{}{}
185 }
186 return ret
187}