blob: a61ca2524feaf37dc5361a0590518cb3650f82e2 [file] [log] [blame]
khenaidoob9203542018-09-17 22:56:37 -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 */
16package core
17
18import (
19 "context"
khenaidoo3ab34882019-05-02 21:33:30 -040020 "fmt"
khenaidoob9203542018-09-17 22:56:37 -040021 "github.com/gogo/protobuf/proto"
22 "github.com/opencord/voltha-go/common/log"
23 "github.com/opencord/voltha-go/db/model"
serkant.uluderya334479d2019-04-10 08:26:15 -070024 fu "github.com/opencord/voltha-go/rw_core/utils"
William Kurkiandaa6bb22019-03-07 12:26:28 -050025 ic "github.com/opencord/voltha-protos/go/inter_container"
26 ofp "github.com/opencord/voltha-protos/go/openflow_13"
27 "github.com/opencord/voltha-protos/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040028 "google.golang.org/grpc/codes"
29 "google.golang.org/grpc/status"
khenaidoo19d7b632018-10-30 10:49:50 -040030 "reflect"
31 "sync"
Stephane Barbarieef6650d2019-07-18 12:15:09 -040032 "time"
khenaidoob9203542018-09-17 22:56:37 -040033)
34
35type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040036 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040037 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050038 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040039 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040040 lastData *voltha.Device
41 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070042 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040043 deviceMgr *DeviceManager
44 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040045 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040046 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040047 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040048 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040049}
50
khenaidoo4d4802d2018-10-04 21:59:49 -040051//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
52//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040053func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040054 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040055 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040056 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050057 if cloned.Id == "" {
58 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050059 cloned.AdminState = voltha.AdminState_PREPROVISIONED
60 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
61 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050062 }
khenaidoo19d7b632018-10-30 10:49:50 -040063 if !device.GetRoot() && device.ProxyAddress != nil {
64 // Set the default vlan ID to the one specified by the parent adapter. It can be
65 // overwritten by the child adapter during a device update request
66 cloned.Vlan = device.ProxyAddress.ChannelId
67 }
khenaidoo2c6a0992019-04-29 13:46:56 -040068 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040069 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040070 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050071 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040072 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040073 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050074 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040075 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040076 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040077 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040078 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040079 return &agent
80}
81
khenaidoo297cd252019-02-07 22:10:23 -050082// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
83// it will load the data from the dB and setup teh necessary callbacks and proxies.
84func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040085 agent.lockDevice.Lock()
86 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050087 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
88 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040089 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050090 if d, ok := device.(*voltha.Device); ok {
91 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050092 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050093 }
94 } else {
95 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
96 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
97 }
98 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
99 } else {
100 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400101 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500102 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
103 }
khenaidoob9203542018-09-17 22:56:37 -0400104 }
khenaidoo297cd252019-02-07 22:10:23 -0500105
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400106 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500107 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400108
khenaidoob9203542018-09-17 22:56:37 -0400109 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500110 return nil
khenaidoob9203542018-09-17 22:56:37 -0400111}
112
khenaidoo4d4802d2018-10-04 21:59:49 -0400113// stop stops the device agent. Not much to do for now
114func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400115 agent.lockDevice.Lock()
116 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400117 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400118 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400119 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400120 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400121 }
khenaidoob9203542018-09-17 22:56:37 -0400122 agent.exitChannel <- 1
123 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400124
khenaidoob9203542018-09-17 22:56:37 -0400125}
126
khenaidoo19d7b632018-10-30 10:49:50 -0400127// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400128func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400129 agent.lockDevice.RLock()
130 defer agent.lockDevice.RUnlock()
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400131 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, true, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400132 if d, ok := device.(*voltha.Device); ok {
133 cloned := proto.Clone(d).(*voltha.Device)
134 return cloned, nil
135 }
136 }
137 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
138}
139
khenaidoo4d4802d2018-10-04 21:59:49 -0400140// getDeviceWithoutLock is a helper function to be used ONLY by any device agent function AFTER it has acquired the device lock.
khenaidoo92e62c52018-10-03 14:02:54 -0400141// This function is meant so that we do not have duplicate code all over the device agent functions
142func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400143 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400144 if d, ok := device.(*voltha.Device); ok {
145 cloned := proto.Clone(d).(*voltha.Device)
146 return cloned, nil
147 }
148 }
149 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
150}
151
khenaidoo3ab34882019-05-02 21:33:30 -0400152// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400153func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400154 agent.lockDevice.Lock()
155 defer agent.lockDevice.Unlock()
156 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500157
khenaidoo92e62c52018-10-03 14:02:54 -0400158 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400159 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
160 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500161 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
162 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
163 // with the adapter then we need to know the adapter that will handle this request
164 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
165 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
166 return err
167 } else {
168 device.Adapter = adapterName
169 }
170
khenaidoo92e62c52018-10-03 14:02:54 -0400171 if device.AdminState == voltha.AdminState_ENABLED {
172 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400173 return nil
174 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400175
176 if device.AdminState == voltha.AdminState_DELETED {
177 // This is a temporary state when a device is deleted before it gets removed from the model.
178 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
179 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
180 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400181 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400182
183 previousAdminState := device.AdminState
184
185 // Update the Admin State and set the operational state to activating before sending the request to the
186 // Adapters
187 cloned := proto.Clone(device).(*voltha.Device)
188 cloned.AdminState = voltha.AdminState_ENABLED
189 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400190
Mahir Gunyelb5851672019-07-24 10:46:26 +0300191 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
192 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400193 }
194
195 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
196 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400197 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
198 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400199 return err
200 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400201 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400202 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
203 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
204 return err
205 }
khenaidoob9203542018-09-17 22:56:37 -0400206 }
207 }
208 return nil
209}
210
khenaidoo2c6a0992019-04-29 13:46:56 -0400211func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
212 if err := agent.updateDeviceWithoutLock(device); err != nil {
213 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400214 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400215 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400216}
217
Manikkaraj kb1a10922019-07-29 12:10:34 -0400218func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
219 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400220 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
221 ch <- err
222 }
223 ch <- nil
224}
225
Manikkaraj kb1a10922019-07-29 12:10:34 -0400226func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
227 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400228 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
229 ch <- err
230 }
231 ch <- nil
232}
233
khenaidoo0458db62019-06-20 08:50:36 -0400234//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
235//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400236func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
237 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400238
khenaidoo2c6a0992019-04-29 13:46:56 -0400239 if (len(newFlows) | len(newGroups)) == 0 {
240 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
241 return nil
242 }
243
khenaidoo19d7b632018-10-30 10:49:50 -0400244 agent.lockDevice.Lock()
245 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400246
khenaidoo0458db62019-06-20 08:50:36 -0400247 var device *voltha.Device
248 var err error
249 if device, err = agent.getDeviceWithoutLock(); err != nil {
250 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
251 }
252
253 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
254 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
255
256 var updatedFlows []*ofp.OfpFlowStats
257 var flowsToDelete []*ofp.OfpFlowStats
258 var groupsToDelete []*ofp.OfpGroupEntry
259 var updatedGroups []*ofp.OfpGroupEntry
260
261 // Process flows
262 for _, flow := range newFlows {
263 updatedFlows = append(updatedFlows, flow)
264 }
265 for _, flow := range existingFlows.Items {
266 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
267 updatedFlows = append(updatedFlows, flow)
268 } else {
269 flowsToDelete = append(flowsToDelete, flow)
270 }
271 }
272
273 // Process groups
274 for _, g := range newGroups {
275 updatedGroups = append(updatedGroups, g)
276 }
277 for _, group := range existingGroups.Items {
278 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
279 updatedGroups = append(updatedGroups, group)
280 } else {
281 groupsToDelete = append(groupsToDelete, group)
282 }
283 }
284
285 // Sanity check
286 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
287 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
288 return nil
289 }
290
291 // Send update to adapters
292 // Create two channels to receive responses from the dB and from the adapters.
293 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
294 // to send their responses. These channels will be garbage collected once all the responses are
295 // received
296 chAdapters := make(chan interface{})
297 chdB := make(chan interface{})
298 dType := agent.adapterMgr.getDeviceType(device.Type)
299 if !dType.AcceptsAddRemoveFlowUpdates {
300
301 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
302 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
303 return nil
304 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400305 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400306
307 } else {
308 flowChanges := &ofp.FlowChanges{
309 ToAdd: &voltha.Flows{Items: newFlows},
310 ToRemove: &voltha.Flows{Items: flowsToDelete},
311 }
312 groupChanges := &ofp.FlowGroupChanges{
313 ToAdd: &voltha.FlowGroups{Items: newGroups},
314 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
315 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
316 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400317 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400318 }
319
320 // store the changed data
321 device.Flows = &voltha.Flows{Items: updatedFlows}
322 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
323 go agent.updateDeviceWithoutLockAsync(device, chdB)
324
325 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400326 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400327 return status.Errorf(codes.Aborted, "errors-%s", res)
328 }
329
330 return nil
331}
332
333//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
334//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400335func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400336 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
337
338 if (len(flowsToDel) | len(groupsToDel)) == 0 {
339 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
340 return nil
341 }
342
343 agent.lockDevice.Lock()
344 defer agent.lockDevice.Unlock()
345
346 var device *voltha.Device
347 var err error
348
349 if device, err = agent.getDeviceWithoutLock(); err != nil {
350 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
351 }
352
353 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
354 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
355
356 var flowsToKeep []*ofp.OfpFlowStats
357 var groupsToKeep []*ofp.OfpGroupEntry
358
359 // Process flows
360 for _, flow := range existingFlows.Items {
361 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
362 flowsToKeep = append(flowsToKeep, flow)
363 }
364 }
365
366 // Process groups
367 for _, group := range existingGroups.Items {
368 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
369 groupsToKeep = append(groupsToKeep, group)
370 }
371 }
372
373 log.Debugw("deleteFlowsAndGroups",
374 log.Fields{
375 "deviceId": agent.deviceId,
376 "flowsToDel": len(flowsToDel),
377 "flowsToKeep": len(flowsToKeep),
378 "groupsToDel": len(groupsToDel),
379 "groupsToKeep": len(groupsToKeep),
380 })
381
382 // Sanity check
383 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
384 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
385 return nil
386 }
387
388 // Send update to adapters
389 chAdapters := make(chan interface{})
390 chdB := make(chan interface{})
391 dType := agent.adapterMgr.getDeviceType(device.Type)
392 if !dType.AcceptsAddRemoveFlowUpdates {
393 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
394 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
395 return nil
396 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400397 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400398 } else {
399 flowChanges := &ofp.FlowChanges{
400 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
401 ToRemove: &voltha.Flows{Items: flowsToDel},
402 }
403 groupChanges := &ofp.FlowGroupChanges{
404 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
405 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
406 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
407 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400408 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400409 }
410
411 // store the changed data
412 device.Flows = &voltha.Flows{Items: flowsToKeep}
413 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
414 go agent.updateDeviceWithoutLockAsync(device, chdB)
415
416 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
417 return status.Errorf(codes.Aborted, "errors-%s", res)
418 }
419 return nil
420
421}
422
423//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
424//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400425func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400426 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
427
428 if (len(updatedFlows) | len(updatedGroups)) == 0 {
429 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
430 return nil
431 }
432
433 agent.lockDevice.Lock()
434 defer agent.lockDevice.Unlock()
435 var device *voltha.Device
436 var err error
437 if device, err = agent.getDeviceWithoutLock(); err != nil {
438 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
439 }
440 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
441 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
442
443 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
444 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
445 return nil
446 }
447
448 log.Debugw("updating-flows-and-groups",
449 log.Fields{
450 "deviceId": agent.deviceId,
451 "updatedFlows": updatedFlows,
452 "updatedGroups": updatedGroups,
453 })
454
455 chAdapters := make(chan interface{})
456 chdB := make(chan interface{})
457 dType := agent.adapterMgr.getDeviceType(device.Type)
458
459 // Process bulk flow update differently than incremental update
460 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400461 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400462 } else {
463 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400464 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400465 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400466 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400467
468 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400469 for _, flow := range updatedFlows {
470 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
471 flowsToAdd = append(flowsToAdd, flow)
472 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400473 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400474 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400475 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400476 flowsToDelete = append(flowsToDelete, flow)
477 }
478 }
479
480 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400481 for _, g := range updatedGroups {
482 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
483 groupsToAdd = append(groupsToAdd, g)
484 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400485 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400486 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400487 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400488 groupsToDelete = append(groupsToDelete, group)
489 }
490 }
491
khenaidoo0458db62019-06-20 08:50:36 -0400492 log.Debugw("updating-flows-and-groups",
493 log.Fields{
494 "deviceId": agent.deviceId,
495 "flowsToAdd": flowsToAdd,
496 "flowsToDelete": flowsToDelete,
497 "groupsToAdd": groupsToAdd,
498 "groupsToDelete": groupsToDelete,
499 })
500
khenaidoo2c6a0992019-04-29 13:46:56 -0400501 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400502 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
503 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400505 }
506
khenaidoo0458db62019-06-20 08:50:36 -0400507 flowChanges := &ofp.FlowChanges{
508 ToAdd: &voltha.Flows{Items: flowsToAdd},
509 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400510 }
khenaidoo0458db62019-06-20 08:50:36 -0400511 groupChanges := &ofp.FlowGroupChanges{
512 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
513 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
514 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
515 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400516 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400517 }
khenaidoo0458db62019-06-20 08:50:36 -0400518
519 // store the updated data
520 device.Flows = &voltha.Flows{Items: updatedFlows}
521 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
522 go agent.updateDeviceWithoutLockAsync(device, chdB)
523
524 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
525 return status.Errorf(codes.Aborted, "errors-%s", res)
526 }
527 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400528}
529
khenaidoo4d4802d2018-10-04 21:59:49 -0400530//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400531func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400532 agent.lockDevice.Lock()
533 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400534 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
535 // Get the most up to date the device info
536 if device, err := agent.getDeviceWithoutLock(); err != nil {
537 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
538 } else {
539 if device.AdminState == voltha.AdminState_DISABLED {
540 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400541 return nil
542 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400543 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
544 device.AdminState == voltha.AdminState_DELETED {
545 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
546 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
547 }
548
khenaidoo59ef7be2019-06-21 12:40:28 -0400549 // Update the Admin State and operational state before sending the request out
550 cloned := proto.Clone(device).(*voltha.Device)
551 cloned.AdminState = voltha.AdminState_DISABLED
552 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300553 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
554 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400555 }
556
khenaidoo92e62c52018-10-03 14:02:54 -0400557 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
558 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400559 return err
560 }
khenaidoo0a822f92019-05-08 15:15:57 -0400561 }
562 return nil
563}
564
565func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
566 agent.lockDevice.Lock()
567 defer agent.lockDevice.Unlock()
568 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
569 // Get the most up to date the device info
570 if device, err := agent.getDeviceWithoutLock(); err != nil {
571 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
572 } else {
573 if device.AdminState == adminState {
574 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
575 return nil
576 }
khenaidoo92e62c52018-10-03 14:02:54 -0400577 // Received an Ack (no error found above). Now update the device in the model to the expected state
578 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400579 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300580 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
581 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400582 }
khenaidoo92e62c52018-10-03 14:02:54 -0400583 }
584 return nil
585}
586
khenaidoo4d4802d2018-10-04 21:59:49 -0400587func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
588 agent.lockDevice.Lock()
589 defer agent.lockDevice.Unlock()
590 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
591 // Get the most up to date the device info
592 if device, err := agent.getDeviceWithoutLock(); err != nil {
593 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
594 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400595 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
596 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
597 return err
598 }
599 }
600 return nil
601}
602
603func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
604 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400605 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400606 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
607 // Get the most up to date the device info
608 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400609 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
610 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400611 if device.AdminState == voltha.AdminState_DELETED {
612 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
613 return nil
614 }
khenaidoo43c82122018-11-22 18:38:28 -0500615 if (device.AdminState != voltha.AdminState_DISABLED) &&
616 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400617 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
618 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400619 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
620 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400621 if device.AdminState != voltha.AdminState_PREPROVISIONED {
622 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
623 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
624 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
625 return err
626 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400627 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400628 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
629 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400630 cloned := proto.Clone(device).(*voltha.Device)
631 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300632 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
633 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400634 }
khenaidoo0a822f92019-05-08 15:15:57 -0400635 // If this is a child device then remove the associated peer ports on the parent device
636 if !device.Root {
637 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
638 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400639 }
640 return nil
641}
642
khenaidoob3127472019-07-24 21:04:55 -0400643func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
644 agent.lockDevice.Lock()
645 defer agent.lockDevice.Unlock()
646 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
647 // Work only on latest data
648 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
649 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
650 } else {
651 // clone the device
652 cloned := proto.Clone(storeDevice).(*voltha.Device)
653 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
654 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300655 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
656 return err
khenaidoob3127472019-07-24 21:04:55 -0400657 }
658 // Send the request to the adapter
659 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
660 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
661 return err
662 }
663 return nil
664 }
665}
666
667func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
668 agent.lockDevice.Lock()
669 defer agent.lockDevice.Unlock()
670 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
671 // Work only on latest data
672 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
673 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
674 } else {
675 // clone the device
676 cloned := proto.Clone(storeDevice).(*voltha.Device)
677 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
678 // Store the device
679 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
680 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
681 if afterUpdate == nil {
682 return status.Errorf(codes.Internal, "%s", agent.deviceId)
683 }
684 return nil
685 }
686}
687
688func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
689 agent.lockDevice.RLock()
690 defer agent.lockDevice.RUnlock()
691 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
692 // Get the most up to date the device info
693 if device, err := agent.getDeviceWithoutLock(); err != nil {
694 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
695 } else {
696 cloned := proto.Clone(device).(*voltha.Device)
697 return cloned.PmConfigs, nil
698 }
699}
700
khenaidoof5a5bfa2019-01-23 22:20:29 -0500701func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
702 agent.lockDevice.Lock()
703 defer agent.lockDevice.Unlock()
704 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
705 // Get the most up to date the device info
706 if device, err := agent.getDeviceWithoutLock(); err != nil {
707 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
708 } else {
709 if device.AdminState != voltha.AdminState_ENABLED {
710 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
711 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
712 }
713 // Save the image
714 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500715 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500716 cloned := proto.Clone(device).(*voltha.Device)
717 if cloned.ImageDownloads == nil {
718 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
719 } else {
720 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
721 }
722 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300723 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
724 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500725 }
726 // Send the request to the adapter
727 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
728 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
729 return nil, err
730 }
731 }
732 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
733}
734
735// isImageRegistered is a helper method to figure out if an image is already registered
736func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
737 for _, image := range device.ImageDownloads {
738 if image.Id == img.Id && image.Name == img.Name {
739 return true
740 }
741 }
742 return false
743}
744
745func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
746 agent.lockDevice.Lock()
747 defer agent.lockDevice.Unlock()
748 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
749 // Get the most up to date the device info
750 if device, err := agent.getDeviceWithoutLock(); err != nil {
751 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
752 } else {
753 // Verify whether the Image is in the list of image being downloaded
754 if !isImageRegistered(img, device) {
755 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
756 }
757
758 // Update image download state
759 cloned := proto.Clone(device).(*voltha.Device)
760 for _, image := range cloned.ImageDownloads {
761 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500762 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500763 }
764 }
765
khenaidoof5a5bfa2019-01-23 22:20:29 -0500766 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500767 // Set the device to Enabled
768 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300769 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
770 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500771 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400772 // Send the request to teh adapter
773 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
774 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
775 return nil, err
776 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500777 }
778 }
779 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700780}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500781
782func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
783 agent.lockDevice.Lock()
784 defer agent.lockDevice.Unlock()
785 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
786 // Get the most up to date the device info
787 if device, err := agent.getDeviceWithoutLock(); err != nil {
788 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
789 } else {
790 // Verify whether the Image is in the list of image being downloaded
791 if !isImageRegistered(img, device) {
792 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
793 }
794
795 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
796 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
797 }
798 // Update image download state
799 cloned := proto.Clone(device).(*voltha.Device)
800 for _, image := range cloned.ImageDownloads {
801 if image.Id == img.Id && image.Name == img.Name {
802 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
803 }
804 }
805 // Set the device to downloading_image
806 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300807 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
808 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500809 }
810
811 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
812 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
813 return nil, err
814 }
815 // The status of the AdminState will be changed following the update_download_status response from the adapter
816 // The image name will also be removed from the device list
817 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700818 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
819}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500820
821func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
822 agent.lockDevice.Lock()
823 defer agent.lockDevice.Unlock()
824 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
825 // Get the most up to date the device info
826 if device, err := agent.getDeviceWithoutLock(); err != nil {
827 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
828 } else {
829 // Verify whether the Image is in the list of image being downloaded
830 if !isImageRegistered(img, device) {
831 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
832 }
833
834 if device.AdminState != voltha.AdminState_ENABLED {
835 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
836 }
837 // Update image download state
838 cloned := proto.Clone(device).(*voltha.Device)
839 for _, image := range cloned.ImageDownloads {
840 if image.Id == img.Id && image.Name == img.Name {
841 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
842 }
843 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300844
845 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
846 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500847 }
848
849 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
850 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
851 return nil, err
852 }
853 }
854 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700855}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500856
857func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
858 agent.lockDevice.Lock()
859 defer agent.lockDevice.Unlock()
860 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
861 // Get the most up to date the device info
862 if device, err := agent.getDeviceWithoutLock(); err != nil {
863 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
864 } else {
865 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
866 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
867 return nil, err
868 } else {
869 return resp, nil
870 }
871 }
872}
873
serkant.uluderya334479d2019-04-10 08:26:15 -0700874func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500875 agent.lockDevice.Lock()
876 defer agent.lockDevice.Unlock()
877 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
878 // Get the most up to date the device info
879 if device, err := agent.getDeviceWithoutLock(); err != nil {
880 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
881 } else {
882 // Update the image as well as remove it if the download was cancelled
883 cloned := proto.Clone(device).(*voltha.Device)
884 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
885 for _, image := range cloned.ImageDownloads {
886 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500887 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500888 clonedImages = append(clonedImages, img)
889 }
890 }
891 }
892 cloned.ImageDownloads = clonedImages
893 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500894 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
895 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700896 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500897 cloned.AdminState = voltha.AdminState_ENABLED
898 }
899
Mahir Gunyelb5851672019-07-24 10:46:26 +0300900 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
901 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500902 }
903 }
904 return nil
905}
906
907func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400908 agent.lockDevice.RLock()
909 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500910 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
911 // Get the most up to date the device info
912 if device, err := agent.getDeviceWithoutLock(); err != nil {
913 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
914 } else {
915 for _, image := range device.ImageDownloads {
916 if image.Id == img.Id && image.Name == img.Name {
917 return image, nil
918 }
919 }
920 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
921 }
922}
923
924func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400925 agent.lockDevice.RLock()
926 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500927 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
928 // Get the most up to date the device info
929 if device, err := agent.getDeviceWithoutLock(); err != nil {
930 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
931 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700932 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500933 }
934}
935
khenaidoo4d4802d2018-10-04 21:59:49 -0400936// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400937func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
938 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400939 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400940 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400941 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400942 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400943 ports.Items = append(ports.Items, port)
944 }
945 }
946 }
947 return ports
948}
949
khenaidoo4d4802d2018-10-04 21:59:49 -0400950// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
951// parent device
khenaidoo79232702018-12-04 11:00:41 -0500952func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400953 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400954 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400955 return nil, err
956 } else {
khenaidoo79232702018-12-04 11:00:41 -0500957 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400958 var err error
959 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
960 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
961 return nil, err
962 }
963 return switchCap, nil
964 }
965}
966
khenaidoo4d4802d2018-10-04 21:59:49 -0400967// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
968// device
khenaidoo79232702018-12-04 11:00:41 -0500969func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400970 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400971 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400972 return nil, err
973 } else {
khenaidoo79232702018-12-04 11:00:41 -0500974 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400975 var err error
976 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
977 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
978 return nil, err
979 }
980 return portCap, nil
981 }
982}
983
khenaidoofdbad6e2018-11-06 22:26:38 -0500984func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
985 // Send packet to adapter
986 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
987 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
988 return err
989 }
990 return nil
991}
992
khenaidoo4d4802d2018-10-04 21:59:49 -0400993// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400994func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500995 //// Run this callback in its own go routine
996 go func(args ...interface{}) interface{} {
997 var previous *voltha.Device
998 var current *voltha.Device
999 var ok bool
1000 if len(args) == 2 {
1001 if previous, ok = args[0].(*voltha.Device); !ok {
1002 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1003 return nil
1004 }
1005 if current, ok = args[1].(*voltha.Device); !ok {
1006 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1007 return nil
1008 }
1009 } else {
1010 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1011 return nil
1012 }
1013 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001014 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1015 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1016 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1017 }
khenaidoo43c82122018-11-22 18:38:28 -05001018 return nil
1019 }(args...)
1020
khenaidoo92e62c52018-10-03 14:02:54 -04001021 return nil
1022}
1023
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001024// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1025// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1026func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1027 // First retrieve the most up to date device info
1028 var currentDevice *voltha.Device
1029 var err error
1030 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1031 return nil, err
1032 }
1033 cloned := proto.Clone(currentDevice).(*voltha.Device)
1034 cloned.Root = device.Root
1035 cloned.Vendor = device.Vendor
1036 cloned.Model = device.Model
1037 cloned.SerialNumber = device.SerialNumber
1038 cloned.MacAddress = device.MacAddress
1039 cloned.Vlan = device.Vlan
1040 cloned.Reason = device.Reason
1041 return cloned, nil
1042}
1043func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001044 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001045 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001046 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1047 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1048 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1049 return status.Errorf(codes.Internal, "%s", err.Error())
1050 } else {
1051 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1052 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1053 }
khenaidoo43c82122018-11-22 18:38:28 -05001054}
1055
1056func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1057 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1058 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001059 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001060}
1061
khenaidoo92e62c52018-10-03 14:02:54 -04001062func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1063 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001064 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001065 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001066 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001067 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1068 } else {
1069 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001070 cloned := proto.Clone(storeDevice).(*voltha.Device)
1071 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1072 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1073 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1074 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001075 }
khenaidoo92e62c52018-10-03 14:02:54 -04001076 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1077 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1078 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001079 }
khenaidoo92e62c52018-10-03 14:02:54 -04001080 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001081 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001082 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001083 }
1084}
1085
khenaidoo3ab34882019-05-02 21:33:30 -04001086func (agent *DeviceAgent) enablePorts() error {
1087 agent.lockDevice.Lock()
1088 defer agent.lockDevice.Unlock()
1089 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1090 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1091 } else {
1092 // clone the device
1093 cloned := proto.Clone(storeDevice).(*voltha.Device)
1094 for _, port := range cloned.Ports {
1095 port.AdminState = voltha.AdminState_ENABLED
1096 port.OperStatus = voltha.OperStatus_ACTIVE
1097 }
1098 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001099 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001100 }
1101}
1102
1103func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001104 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001105 agent.lockDevice.Lock()
1106 defer agent.lockDevice.Unlock()
1107 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1108 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1109 } else {
1110 // clone the device
1111 cloned := proto.Clone(storeDevice).(*voltha.Device)
1112 for _, port := range cloned.Ports {
1113 port.AdminState = voltha.AdminState_DISABLED
1114 port.OperStatus = voltha.OperStatus_UNKNOWN
1115 }
1116 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001117 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001118 }
1119}
1120
khenaidoo92e62c52018-10-03 14:02:54 -04001121func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1122 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001123 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001124 // Work only on latest data
1125 // TODO: Get list of ports from device directly instead of the entire device
1126 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001127 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1128 } else {
1129 // clone the device
1130 cloned := proto.Clone(storeDevice).(*voltha.Device)
1131 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1132 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001133 return status.Errorf(codes.InvalidArgument, "%s", portType)
1134 }
1135 for _, port := range cloned.Ports {
1136 if port.Type == portType && port.PortNo == portNo {
1137 port.OperStatus = operStatus
1138 // Set the admin status to ENABLED if the operational status is ACTIVE
1139 // TODO: Set by northbound system?
1140 if operStatus == voltha.OperStatus_ACTIVE {
1141 port.AdminState = voltha.AdminState_ENABLED
1142 }
1143 break
1144 }
1145 }
1146 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1147 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001148 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001149 }
1150}
1151
khenaidoo0a822f92019-05-08 15:15:57 -04001152func (agent *DeviceAgent) deleteAllPorts() error {
1153 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1154 agent.lockDevice.Lock()
1155 defer agent.lockDevice.Unlock()
1156 // Work only on latest data
1157 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1158 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1159 } else {
1160 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1161 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1162 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1163 return err
1164 }
1165 if len(storeDevice.Ports) == 0 {
1166 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1167 return nil
1168 }
1169 // clone the device & set the fields to empty
1170 cloned := proto.Clone(storeDevice).(*voltha.Device)
1171 cloned.Ports = []*voltha.Port{}
1172 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1173 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001174 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001175 }
1176}
1177
khenaidoob9203542018-09-17 22:56:37 -04001178func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001179 agent.lockDevice.Lock()
1180 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001181 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001182 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001183 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001184 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1185 } else {
1186 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001187 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001188 if cloned.Ports == nil {
1189 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001190 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001191 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001192 } else {
1193 for _, p := range cloned.Ports {
1194 if p.Type == port.Type && p.PortNo == port.PortNo {
1195 log.Debugw("port already exists", log.Fields{"port": *port})
1196 return nil
1197 }
1198 }
khenaidoob9203542018-09-17 22:56:37 -04001199 }
khenaidoo92e62c52018-10-03 14:02:54 -04001200 cp := proto.Clone(port).(*voltha.Port)
1201 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1202 // TODO: Set by northbound system?
1203 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1204 cp.AdminState = voltha.AdminState_ENABLED
1205 }
1206 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001207 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001208 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001209 }
1210}
1211
1212func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1213 agent.lockDevice.Lock()
1214 defer agent.lockDevice.Unlock()
1215 log.Debug("addPeerPort")
1216 // Work only on latest data
1217 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1218 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1219 } else {
1220 // clone the device
1221 cloned := proto.Clone(storeDevice).(*voltha.Device)
1222 // Get the peer port on the device based on the port no
1223 for _, peerPort := range cloned.Ports {
1224 if peerPort.PortNo == port.PortNo { // found port
1225 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1226 peerPort.Peers = append(peerPort.Peers, cp)
1227 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1228 break
1229 }
1230 }
1231 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001232 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001233 }
1234}
1235
khenaidoo0a822f92019-05-08 15:15:57 -04001236func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1237 agent.lockDevice.Lock()
1238 defer agent.lockDevice.Unlock()
1239 log.Debug("deletePeerPorts")
1240 // Work only on latest data
1241 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1242 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1243 } else {
1244 // clone the device
1245 cloned := proto.Clone(storeDevice).(*voltha.Device)
1246 var updatedPeers []*voltha.Port_PeerPort
1247 for _, port := range cloned.Ports {
1248 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1249 for _, peerPort := range port.Peers {
1250 if peerPort.DeviceId != deviceId {
1251 updatedPeers = append(updatedPeers, peerPort)
1252 }
1253 }
1254 port.Peers = updatedPeers
1255 }
1256
1257 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001258 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001259 }
1260}
1261
khenaidoob9203542018-09-17 22:56:37 -04001262// TODO: A generic device update by attribute
1263func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001264 agent.lockDevice.Lock()
1265 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001266 if value == nil {
1267 return
1268 }
1269 var storeDevice *voltha.Device
1270 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001271 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001272 return
1273 }
1274 updated := false
1275 s := reflect.ValueOf(storeDevice).Elem()
1276 if s.Kind() == reflect.Struct {
1277 // exported field
1278 f := s.FieldByName(name)
1279 if f.IsValid() && f.CanSet() {
1280 switch f.Kind() {
1281 case reflect.String:
1282 f.SetString(value.(string))
1283 updated = true
1284 case reflect.Uint32:
1285 f.SetUint(uint64(value.(uint32)))
1286 updated = true
1287 case reflect.Bool:
1288 f.SetBool(value.(bool))
1289 updated = true
1290 }
1291 }
1292 }
khenaidoo92e62c52018-10-03 14:02:54 -04001293 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001294 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001295 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001296 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001297 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1298 }
1299 return
1300}
serkant.uluderya334479d2019-04-10 08:26:15 -07001301
1302func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1303 agent.lockDevice.Lock()
1304 defer agent.lockDevice.Unlock()
1305 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1306 // Get the most up to date the device info
1307 if device, err := agent.getDeviceWithoutLock(); err != nil {
1308 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1309 } else {
1310 // First send the request to an Adapter and wait for a response
1311 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1312 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1313 return err
1314 }
1315 }
1316 return nil
1317}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001318
1319//This is an update operation to model without Lock.This function must never be invoked by another function unless the latter holds a lock on the device.
1320// It is an internal helper function.
1321func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1322 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1323 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1324 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1325 }
1326 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1327
1328 return nil
1329}