blob: 2f322ef9e3992ad21359fa8e3deabb89d200140c [file] [log] [blame]
Kent Hagerman2a07b862020-06-19 15:23:07 -04001/*
Joey Armstrong5f51f2e2023-01-17 17:06:26 -05002 * Copyright 2018-2023 Open Networking Foundation (ONF) and the ONF Contributors
Kent Hagerman2a07b862020-06-19 15:23:07 -04003
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 port
18
19import (
20 "context"
21 "fmt"
22 "sync"
23
24 "github.com/opencord/voltha-go/db/model"
khenaidood948f772021-08-11 17:49:24 -040025 "github.com/opencord/voltha-lib-go/v7/pkg/log"
26 "github.com/opencord/voltha-protos/v5/go/voltha"
Kent Hagerman2a07b862020-06-19 15:23:07 -040027 "google.golang.org/grpc/codes"
28 "google.golang.org/grpc/status"
29)
30
31// Loader hides all low-level locking & synchronization related to port state updates
32type Loader struct {
33 dbProxy *model.Proxy
34 // this lock protects the ports map, it does not protect individual ports
35 lock sync.RWMutex
36 ports map[uint32]*chunk
37}
38
39// chunk keeps a port and the lock for this port
40type chunk struct {
41 // this lock is used to synchronize all access to the port, and also to the "deleted" variable
42 lock sync.Mutex
43 deleted bool
44
45 port *voltha.Port
46}
47
48func NewLoader(dbProxy *model.Proxy) *Loader {
49 return &Loader{
50 dbProxy: dbProxy,
51 ports: make(map[uint32]*chunk),
52 }
53}
54
55// Load queries existing ports 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 ports []*voltha.Port
62 if err := loader.dbProxy.List(ctx, &ports); err != nil {
63 logger.Errorw(ctx, "failed-to-list-ports-from-cluster-data-proxy", log.Fields{"error": err})
64 return
65 }
66 for _, port := range ports {
67 loader.ports[port.PortNo] = &chunk{port: port}
68 }
69}
70
71// LockOrCreate locks this port if it exists, or creates a new port if it does not.
72// In the case of port creation, the provided "port" must not be modified afterwards.
73func (loader *Loader) LockOrCreate(ctx context.Context, port *voltha.Port) (*Handle, bool, error) {
74 // try to use read lock instead of full lock if possible
75 if handle, have := loader.Lock(port.PortNo); have {
76 return handle, false, nil
77 }
78
79 loader.lock.Lock()
80 entry, have := loader.ports[port.PortNo]
81 if !have {
82 entry := &chunk{port: port}
83 loader.ports[port.PortNo] = entry
84 entry.lock.Lock()
85 loader.lock.Unlock()
86
87 if err := loader.dbProxy.Set(ctx, fmt.Sprint(port.PortNo), port); err != nil {
88 // revert the map
89 loader.lock.Lock()
90 delete(loader.ports, port.PortNo)
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, port)
105 }
106 return &Handle{loader: loader, chunk: entry}, false, nil
107}
108
109// Lock acquires the lock for this port, and returns a handle which can be used to access the port until it's unlocked.
110// This handle ensures that the port cannot be accessed if the lock is not held.
111// Returns false if the port is not present.
112// TODO: consider accepting a ctx and aborting the lock attempt on cancellation
113func (loader *Loader) Lock(id uint32) (*Handle, bool) {
114 loader.lock.RLock()
115 entry, have := loader.ports[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
130// 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.
132type Handle struct {
133 loader *Loader
134 chunk *chunk
135}
136
137// GetReadOnly returns an *voltha.Port which MUST NOT be modified externally, but which is safe to keep indefinitely
138func (h *Handle) GetReadOnly() *voltha.Port {
139 return h.chunk.port
140}
141
142// Update updates an existing port in the kv.
143// The provided "port" must not be modified afterwards.
144func (h *Handle) Update(ctx context.Context, port *voltha.Port) error {
145 if err := h.loader.dbProxy.Set(ctx, fmt.Sprint(port.PortNo), port); err != nil {
146 return status.Errorf(codes.Internal, "failed-update-port-%v: %s", port.PortNo, err)
147 }
148 h.chunk.port = port
149 return nil
150}
151
152// Delete removes the device from the kv
153func (h *Handle) Delete(ctx context.Context) error {
154 if err := h.loader.dbProxy.Remove(ctx, fmt.Sprint(h.chunk.port.PortNo)); err != nil {
155 return fmt.Errorf("couldnt-delete-port-from-store-%v", h.chunk.port.PortNo)
156 }
157 h.chunk.deleted = true
158
159 h.loader.lock.Lock()
160 delete(h.loader.ports, h.chunk.port.PortNo)
161 h.loader.lock.Unlock()
162
163 h.Unlock()
164 return nil
165}
166
167// Unlock releases the lock on the port
168func (h *Handle) Unlock() {
169 if h.chunk != nil {
170 h.chunk.lock.Unlock()
171 h.chunk = nil // attempting to access the port through this handle in future will panic
172 }
173}
174
175// ListIDs returns a snapshot of all the managed port IDs
176// TODO: iterating through ports safely is expensive now, since all ports are stored & locked separately
177// should avoid this where possible
178func (loader *Loader) ListIDs() map[uint32]struct{} {
179 loader.lock.RLock()
180 defer loader.lock.RUnlock()
181 // copy the IDs so caller can safely iterate
182 ret := make(map[uint32]struct{}, len(loader.ports))
183 for id := range loader.ports {
184 ret[id] = struct{}{}
185 }
186 return ret
187}