blob: 0ce1cce84ba26a11b71e844041fb8e69c0925a98 [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"
khenaidoob9203542018-09-17 22:56:37 -040032)
33
34type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040035 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040036 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050037 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040038 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040039 lastData *voltha.Device
40 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070041 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040042 deviceMgr *DeviceManager
43 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040044 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040045 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040046 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040047 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040048}
49
khenaidoo4d4802d2018-10-04 21:59:49 -040050//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
51//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040052func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040053 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040054 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040055 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050056 if cloned.Id == "" {
57 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050058 cloned.AdminState = voltha.AdminState_PREPROVISIONED
59 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
60 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050061 }
khenaidoo19d7b632018-10-30 10:49:50 -040062 if !device.GetRoot() && device.ProxyAddress != nil {
63 // Set the default vlan ID to the one specified by the parent adapter. It can be
64 // overwritten by the child adapter during a device update request
65 cloned.Vlan = device.ProxyAddress.ChannelId
66 }
khenaidoo2c6a0992019-04-29 13:46:56 -040067 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040068 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040069 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050070 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040071 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040072 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050073 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040074 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040075 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040076 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040077 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040078 return &agent
79}
80
khenaidoo297cd252019-02-07 22:10:23 -050081// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
82// it will load the data from the dB and setup teh necessary callbacks and proxies.
83func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040084 agent.lockDevice.Lock()
85 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050086 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
87 if loadFromdB {
88 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
89 if d, ok := device.(*voltha.Device); ok {
90 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050091 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050092 }
93 } else {
94 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
95 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
96 }
97 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
98 } else {
99 // Add the initial device to the local model
100 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
101 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
102 }
khenaidoob9203542018-09-17 22:56:37 -0400103 }
khenaidoo297cd252019-02-07 22:10:23 -0500104
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400105 agent.deviceProxy = agent.clusterDataProxy.CreateProxy("/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500106 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400107
khenaidoob9203542018-09-17 22:56:37 -0400108 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500109 return nil
khenaidoob9203542018-09-17 22:56:37 -0400110}
111
khenaidoo4d4802d2018-10-04 21:59:49 -0400112// stop stops the device agent. Not much to do for now
113func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400114 agent.lockDevice.Lock()
115 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400116 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400117 // Remove the device from the KV store
118 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400119 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400120 }
khenaidoob9203542018-09-17 22:56:37 -0400121 agent.exitChannel <- 1
122 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400123
khenaidoob9203542018-09-17 22:56:37 -0400124}
125
khenaidoo19d7b632018-10-30 10:49:50 -0400126// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400127func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400128 agent.lockDevice.RLock()
129 defer agent.lockDevice.RUnlock()
khenaidoo297cd252019-02-07 22:10:23 -0500130 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400131 if d, ok := device.(*voltha.Device); ok {
132 cloned := proto.Clone(d).(*voltha.Device)
133 return cloned, nil
134 }
135 }
136 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
137}
138
khenaidoo4d4802d2018-10-04 21:59:49 -0400139// 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 -0400140// This function is meant so that we do not have duplicate code all over the device agent functions
141func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400142 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400143 if d, ok := device.(*voltha.Device); ok {
144 cloned := proto.Clone(d).(*voltha.Device)
145 return cloned, nil
146 }
147 }
148 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
149}
150
khenaidoo3ab34882019-05-02 21:33:30 -0400151// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400152func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400153 agent.lockDevice.Lock()
154 defer agent.lockDevice.Unlock()
155 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500156
khenaidoo92e62c52018-10-03 14:02:54 -0400157 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400158 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
159 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500160 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
161 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
162 // with the adapter then we need to know the adapter that will handle this request
163 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
164 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
165 return err
166 } else {
167 device.Adapter = adapterName
168 }
169
khenaidoo92e62c52018-10-03 14:02:54 -0400170 if device.AdminState == voltha.AdminState_ENABLED {
171 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400172 return nil
173 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400174
175 if device.AdminState == voltha.AdminState_DELETED {
176 // This is a temporary state when a device is deleted before it gets removed from the model.
177 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
178 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
179 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400180 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400181
182 previousAdminState := device.AdminState
183
184 // Update the Admin State and set the operational state to activating before sending the request to the
185 // Adapters
186 cloned := proto.Clone(device).(*voltha.Device)
187 cloned.AdminState = voltha.AdminState_ENABLED
188 cloned.OperStatus = voltha.OperStatus_ACTIVATING
189 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
190 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
191 }
192
193 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
194 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400195 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
196 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400197 return err
198 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400199 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400200 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
201 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
202 return err
203 }
khenaidoob9203542018-09-17 22:56:37 -0400204 }
205 }
206 return nil
207}
208
khenaidoo2c6a0992019-04-29 13:46:56 -0400209func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
210 if err := agent.updateDeviceWithoutLock(device); err != nil {
211 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400212 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400213 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400214}
215
khenaidoo2c6a0992019-04-29 13:46:56 -0400216func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
217 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
218 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
219 ch <- err
220 }
221 ch <- nil
222}
223
224func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
225 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
226 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
227 ch <- err
228 }
229 ch <- nil
230}
231
khenaidoo0458db62019-06-20 08:50:36 -0400232//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
233//adapters
khenaidoo2c6a0992019-04-29 13:46:56 -0400234func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
khenaidoo0458db62019-06-20 08:50:36 -0400235 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
236
khenaidoo2c6a0992019-04-29 13:46:56 -0400237 if (len(newFlows) | len(newGroups)) == 0 {
238 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
239 return nil
240 }
241
khenaidoo19d7b632018-10-30 10:49:50 -0400242 agent.lockDevice.Lock()
243 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400244
khenaidoo0458db62019-06-20 08:50:36 -0400245 var device *voltha.Device
246 var err error
247 if device, err = agent.getDeviceWithoutLock(); err != nil {
248 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
249 }
250
251 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
252 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
253
254 var updatedFlows []*ofp.OfpFlowStats
255 var flowsToDelete []*ofp.OfpFlowStats
256 var groupsToDelete []*ofp.OfpGroupEntry
257 var updatedGroups []*ofp.OfpGroupEntry
258
259 // Process flows
260 for _, flow := range newFlows {
261 updatedFlows = append(updatedFlows, flow)
262 }
263 for _, flow := range existingFlows.Items {
264 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
265 updatedFlows = append(updatedFlows, flow)
266 } else {
267 flowsToDelete = append(flowsToDelete, flow)
268 }
269 }
270
271 // Process groups
272 for _, g := range newGroups {
273 updatedGroups = append(updatedGroups, g)
274 }
275 for _, group := range existingGroups.Items {
276 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
277 updatedGroups = append(updatedGroups, group)
278 } else {
279 groupsToDelete = append(groupsToDelete, group)
280 }
281 }
282
283 // Sanity check
284 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
285 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
286 return nil
287 }
288
289 // Send update to adapters
290 // Create two channels to receive responses from the dB and from the adapters.
291 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
292 // to send their responses. These channels will be garbage collected once all the responses are
293 // received
294 chAdapters := make(chan interface{})
295 chdB := make(chan interface{})
296 dType := agent.adapterMgr.getDeviceType(device.Type)
297 if !dType.AcceptsAddRemoveFlowUpdates {
298
299 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
300 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
301 return nil
302 }
303 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
304
305 } else {
306 flowChanges := &ofp.FlowChanges{
307 ToAdd: &voltha.Flows{Items: newFlows},
308 ToRemove: &voltha.Flows{Items: flowsToDelete},
309 }
310 groupChanges := &ofp.FlowGroupChanges{
311 ToAdd: &voltha.FlowGroups{Items: newGroups},
312 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
313 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
314 }
315 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
316 }
317
318 // store the changed data
319 device.Flows = &voltha.Flows{Items: updatedFlows}
320 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
321 go agent.updateDeviceWithoutLockAsync(device, chdB)
322
323 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
324 return status.Errorf(codes.Aborted, "errors-%s", res)
325 }
326
327 return nil
328}
329
330//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
331//adapters
332func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry) error {
333 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
334
335 if (len(flowsToDel) | len(groupsToDel)) == 0 {
336 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
337 return nil
338 }
339
340 agent.lockDevice.Lock()
341 defer agent.lockDevice.Unlock()
342
343 var device *voltha.Device
344 var err error
345
346 if device, err = agent.getDeviceWithoutLock(); err != nil {
347 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
348 }
349
350 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
351 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
352
353 var flowsToKeep []*ofp.OfpFlowStats
354 var groupsToKeep []*ofp.OfpGroupEntry
355
356 // Process flows
357 for _, flow := range existingFlows.Items {
358 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
359 flowsToKeep = append(flowsToKeep, flow)
360 }
361 }
362
363 // Process groups
364 for _, group := range existingGroups.Items {
365 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
366 groupsToKeep = append(groupsToKeep, group)
367 }
368 }
369
370 log.Debugw("deleteFlowsAndGroups",
371 log.Fields{
372 "deviceId": agent.deviceId,
373 "flowsToDel": len(flowsToDel),
374 "flowsToKeep": len(flowsToKeep),
375 "groupsToDel": len(groupsToDel),
376 "groupsToKeep": len(groupsToKeep),
377 })
378
379 // Sanity check
380 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
381 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
382 return nil
383 }
384
385 // Send update to adapters
386 chAdapters := make(chan interface{})
387 chdB := make(chan interface{})
388 dType := agent.adapterMgr.getDeviceType(device.Type)
389 if !dType.AcceptsAddRemoveFlowUpdates {
390 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
391 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
392 return nil
393 }
394 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, chAdapters)
395 } else {
396 flowChanges := &ofp.FlowChanges{
397 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
398 ToRemove: &voltha.Flows{Items: flowsToDel},
399 }
400 groupChanges := &ofp.FlowGroupChanges{
401 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
402 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
403 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
404 }
405 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
406 }
407
408 // store the changed data
409 device.Flows = &voltha.Flows{Items: flowsToKeep}
410 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
411 go agent.updateDeviceWithoutLockAsync(device, chdB)
412
413 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
414 return status.Errorf(codes.Aborted, "errors-%s", res)
415 }
416 return nil
417
418}
419
420//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
421//also sends the updates to the adapters
422func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry) error {
423 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
424
425 if (len(updatedFlows) | len(updatedGroups)) == 0 {
426 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
427 return nil
428 }
429
430 agent.lockDevice.Lock()
431 defer agent.lockDevice.Unlock()
432 var device *voltha.Device
433 var err error
434 if device, err = agent.getDeviceWithoutLock(); err != nil {
435 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
436 }
437 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
438 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
439
440 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
441 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
442 return nil
443 }
444
445 log.Debugw("updating-flows-and-groups",
446 log.Fields{
447 "deviceId": agent.deviceId,
448 "updatedFlows": updatedFlows,
449 "updatedGroups": updatedGroups,
450 })
451
452 chAdapters := make(chan interface{})
453 chdB := make(chan interface{})
454 dType := agent.adapterMgr.getDeviceType(device.Type)
455
456 // Process bulk flow update differently than incremental update
457 if !dType.AcceptsAddRemoveFlowUpdates {
458 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
459 } else {
460 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400461 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400462 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400463 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400464
465 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400466 for _, flow := range updatedFlows {
467 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
468 flowsToAdd = append(flowsToAdd, flow)
469 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400470 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400471 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400472 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400473 flowsToDelete = append(flowsToDelete, flow)
474 }
475 }
476
477 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400478 for _, g := range updatedGroups {
479 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
480 groupsToAdd = append(groupsToAdd, g)
481 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400482 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400483 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400484 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400485 groupsToDelete = append(groupsToDelete, group)
486 }
487 }
488
khenaidoo0458db62019-06-20 08:50:36 -0400489 log.Debugw("updating-flows-and-groups",
490 log.Fields{
491 "deviceId": agent.deviceId,
492 "flowsToAdd": flowsToAdd,
493 "flowsToDelete": flowsToDelete,
494 "groupsToAdd": groupsToAdd,
495 "groupsToDelete": groupsToDelete,
496 })
497
khenaidoo2c6a0992019-04-29 13:46:56 -0400498 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400499 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
500 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400501 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400502 }
503
khenaidoo0458db62019-06-20 08:50:36 -0400504 flowChanges := &ofp.FlowChanges{
505 ToAdd: &voltha.Flows{Items: flowsToAdd},
506 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400507 }
khenaidoo0458db62019-06-20 08:50:36 -0400508 groupChanges := &ofp.FlowGroupChanges{
509 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
510 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
511 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
512 }
513 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400514 }
khenaidoo0458db62019-06-20 08:50:36 -0400515
516 // store the updated data
517 device.Flows = &voltha.Flows{Items: updatedFlows}
518 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
519 go agent.updateDeviceWithoutLockAsync(device, chdB)
520
521 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
522 return status.Errorf(codes.Aborted, "errors-%s", res)
523 }
524 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400525}
526
khenaidoo4d4802d2018-10-04 21:59:49 -0400527//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400528func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400529 agent.lockDevice.Lock()
530 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400531 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
532 // Get the most up to date the device info
533 if device, err := agent.getDeviceWithoutLock(); err != nil {
534 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
535 } else {
536 if device.AdminState == voltha.AdminState_DISABLED {
537 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400538 return nil
539 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400540 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
541 device.AdminState == voltha.AdminState_DELETED {
542 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
543 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
544 }
545
khenaidoo59ef7be2019-06-21 12:40:28 -0400546 // Update the Admin State and operational state before sending the request out
547 cloned := proto.Clone(device).(*voltha.Device)
548 cloned.AdminState = voltha.AdminState_DISABLED
549 cloned.OperStatus = voltha.OperStatus_UNKNOWN
550 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
551 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
552 }
553
khenaidoo92e62c52018-10-03 14:02:54 -0400554 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
555 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400556 return err
557 }
khenaidoo0a822f92019-05-08 15:15:57 -0400558 }
559 return nil
560}
561
562func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
563 agent.lockDevice.Lock()
564 defer agent.lockDevice.Unlock()
565 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
566 // Get the most up to date the device info
567 if device, err := agent.getDeviceWithoutLock(); err != nil {
568 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
569 } else {
570 if device.AdminState == adminState {
571 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
572 return nil
573 }
khenaidoo92e62c52018-10-03 14:02:54 -0400574 // Received an Ack (no error found above). Now update the device in the model to the expected state
575 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400576 cloned.AdminState = adminState
khenaidoo92e62c52018-10-03 14:02:54 -0400577 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400578 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
579 }
khenaidoo92e62c52018-10-03 14:02:54 -0400580 }
581 return nil
582}
583
khenaidoo4d4802d2018-10-04 21:59:49 -0400584func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
585 agent.lockDevice.Lock()
586 defer agent.lockDevice.Unlock()
587 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
588 // Get the most up to date the device info
589 if device, err := agent.getDeviceWithoutLock(); err != nil {
590 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
591 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400592 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
593 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
594 return err
595 }
596 }
597 return nil
598}
599
600func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
601 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400602 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400603 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
604 // Get the most up to date the device info
605 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400606 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
607 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400608 if device.AdminState == voltha.AdminState_DELETED {
609 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
610 return nil
611 }
khenaidoo43c82122018-11-22 18:38:28 -0500612 if (device.AdminState != voltha.AdminState_DISABLED) &&
613 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400614 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
615 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400616 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
617 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400618 if device.AdminState != voltha.AdminState_PREPROVISIONED {
619 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
620 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
621 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
622 return err
623 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400624 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400625 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
626 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400627 cloned := proto.Clone(device).(*voltha.Device)
628 cloned.AdminState = voltha.AdminState_DELETED
629 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400630 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
631 }
khenaidoo0a822f92019-05-08 15:15:57 -0400632
633 // If this is a child device then remove the associated peer ports on the parent device
634 if !device.Root {
635 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
636 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400637 }
638 return nil
639}
640
khenaidoof5a5bfa2019-01-23 22:20:29 -0500641func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
642 agent.lockDevice.Lock()
643 defer agent.lockDevice.Unlock()
644 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
645 // Get the most up to date the device info
646 if device, err := agent.getDeviceWithoutLock(); err != nil {
647 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
648 } else {
649 if device.AdminState != voltha.AdminState_ENABLED {
650 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
651 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
652 }
653 // Save the image
654 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500655 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500656 cloned := proto.Clone(device).(*voltha.Device)
657 if cloned.ImageDownloads == nil {
658 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
659 } else {
660 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
661 }
662 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
663 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
664 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
665 }
666 // Send the request to the adapter
667 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
668 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
669 return nil, err
670 }
671 }
672 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
673}
674
675// isImageRegistered is a helper method to figure out if an image is already registered
676func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
677 for _, image := range device.ImageDownloads {
678 if image.Id == img.Id && image.Name == img.Name {
679 return true
680 }
681 }
682 return false
683}
684
685func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
686 agent.lockDevice.Lock()
687 defer agent.lockDevice.Unlock()
688 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
689 // Get the most up to date the device info
690 if device, err := agent.getDeviceWithoutLock(); err != nil {
691 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
692 } else {
693 // Verify whether the Image is in the list of image being downloaded
694 if !isImageRegistered(img, device) {
695 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
696 }
697
698 // Update image download state
699 cloned := proto.Clone(device).(*voltha.Device)
700 for _, image := range cloned.ImageDownloads {
701 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500702 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500703 }
704 }
705
khenaidoof5a5bfa2019-01-23 22:20:29 -0500706 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500707 // Set the device to Enabled
708 cloned.AdminState = voltha.AdminState_ENABLED
709 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
710 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
711 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400712 // Send the request to teh adapter
713 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
714 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
715 return nil, err
716 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500717 }
718 }
719 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700720}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500721
722func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
723 agent.lockDevice.Lock()
724 defer agent.lockDevice.Unlock()
725 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
726 // Get the most up to date the device info
727 if device, err := agent.getDeviceWithoutLock(); err != nil {
728 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
729 } else {
730 // Verify whether the Image is in the list of image being downloaded
731 if !isImageRegistered(img, device) {
732 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
733 }
734
735 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
736 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
737 }
738 // Update image download state
739 cloned := proto.Clone(device).(*voltha.Device)
740 for _, image := range cloned.ImageDownloads {
741 if image.Id == img.Id && image.Name == img.Name {
742 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
743 }
744 }
745 // Set the device to downloading_image
746 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
747 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
748 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
749 }
750
751 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
752 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
753 return nil, err
754 }
755 // The status of the AdminState will be changed following the update_download_status response from the adapter
756 // The image name will also be removed from the device list
757 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700758 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
759}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500760
761func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
762 agent.lockDevice.Lock()
763 defer agent.lockDevice.Unlock()
764 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
765 // Get the most up to date the device info
766 if device, err := agent.getDeviceWithoutLock(); err != nil {
767 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
768 } else {
769 // Verify whether the Image is in the list of image being downloaded
770 if !isImageRegistered(img, device) {
771 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
772 }
773
774 if device.AdminState != voltha.AdminState_ENABLED {
775 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
776 }
777 // Update image download state
778 cloned := proto.Clone(device).(*voltha.Device)
779 for _, image := range cloned.ImageDownloads {
780 if image.Id == img.Id && image.Name == img.Name {
781 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
782 }
783 }
784 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
785 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
786 }
787
788 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
789 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
790 return nil, err
791 }
792 }
793 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700794}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500795
796func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
797 agent.lockDevice.Lock()
798 defer agent.lockDevice.Unlock()
799 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
800 // Get the most up to date the device info
801 if device, err := agent.getDeviceWithoutLock(); err != nil {
802 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
803 } else {
804 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
805 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
806 return nil, err
807 } else {
808 return resp, nil
809 }
810 }
811}
812
serkant.uluderya334479d2019-04-10 08:26:15 -0700813func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500814 agent.lockDevice.Lock()
815 defer agent.lockDevice.Unlock()
816 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
817 // Get the most up to date the device info
818 if device, err := agent.getDeviceWithoutLock(); err != nil {
819 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
820 } else {
821 // Update the image as well as remove it if the download was cancelled
822 cloned := proto.Clone(device).(*voltha.Device)
823 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
824 for _, image := range cloned.ImageDownloads {
825 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500826 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500827 clonedImages = append(clonedImages, img)
828 }
829 }
830 }
831 cloned.ImageDownloads = clonedImages
832 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500833 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
834 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700835 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500836 cloned.AdminState = voltha.AdminState_ENABLED
837 }
838
839 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
840 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
841 }
842 }
843 return nil
844}
845
846func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400847 agent.lockDevice.RLock()
848 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500849 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
850 // Get the most up to date the device info
851 if device, err := agent.getDeviceWithoutLock(); err != nil {
852 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
853 } else {
854 for _, image := range device.ImageDownloads {
855 if image.Id == img.Id && image.Name == img.Name {
856 return image, nil
857 }
858 }
859 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
860 }
861}
862
863func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400864 agent.lockDevice.RLock()
865 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500866 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
867 // Get the most up to date the device info
868 if device, err := agent.getDeviceWithoutLock(); err != nil {
869 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
870 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700871 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500872 }
873}
874
khenaidoo4d4802d2018-10-04 21:59:49 -0400875// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400876func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
877 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400878 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400879 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400880 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400881 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400882 ports.Items = append(ports.Items, port)
883 }
884 }
885 }
886 return ports
887}
888
khenaidoo4d4802d2018-10-04 21:59:49 -0400889// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
890// parent device
khenaidoo79232702018-12-04 11:00:41 -0500891func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400892 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400893 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400894 return nil, err
895 } else {
khenaidoo79232702018-12-04 11:00:41 -0500896 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400897 var err error
898 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
899 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
900 return nil, err
901 }
902 return switchCap, nil
903 }
904}
905
khenaidoo4d4802d2018-10-04 21:59:49 -0400906// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
907// device
khenaidoo79232702018-12-04 11:00:41 -0500908func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400909 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400910 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400911 return nil, err
912 } else {
khenaidoo79232702018-12-04 11:00:41 -0500913 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400914 var err error
915 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
916 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
917 return nil, err
918 }
919 return portCap, nil
920 }
921}
922
khenaidoofdbad6e2018-11-06 22:26:38 -0500923func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
924 // Send packet to adapter
925 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
926 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
927 return err
928 }
929 return nil
930}
931
khenaidoo4d4802d2018-10-04 21:59:49 -0400932// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400933func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500934 //// Run this callback in its own go routine
935 go func(args ...interface{}) interface{} {
936 var previous *voltha.Device
937 var current *voltha.Device
938 var ok bool
939 if len(args) == 2 {
940 if previous, ok = args[0].(*voltha.Device); !ok {
941 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
942 return nil
943 }
944 if current, ok = args[1].(*voltha.Device); !ok {
945 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
946 return nil
947 }
948 } else {
949 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
950 return nil
951 }
952 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500953 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
954 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
955 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
956 }
khenaidoo43c82122018-11-22 18:38:28 -0500957 return nil
958 }(args...)
959
khenaidoo92e62c52018-10-03 14:02:54 -0400960 return nil
961}
962
khenaidoob9203542018-09-17 22:56:37 -0400963func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400964 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500965 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400966 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500967 cloned := proto.Clone(device).(*voltha.Device)
968 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
969 if afterUpdate == nil {
970 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400971 }
khenaidoo43c82122018-11-22 18:38:28 -0500972 return nil
973}
974
975func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
976 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
977 cloned := proto.Clone(device).(*voltha.Device)
978 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
979 if afterUpdate == nil {
980 return status.Errorf(codes.Internal, "%s", device.Id)
981 }
982 return nil
khenaidoob9203542018-09-17 22:56:37 -0400983}
984
khenaidoo92e62c52018-10-03 14:02:54 -0400985func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
986 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400987 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400988 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400989 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400990 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
991 } else {
992 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400993 cloned := proto.Clone(storeDevice).(*voltha.Device)
994 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
995 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
996 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
997 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400998 }
khenaidoo92e62c52018-10-03 14:02:54 -0400999 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1000 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1001 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001002 }
khenaidoo92e62c52018-10-03 14:02:54 -04001003 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001004 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -04001005 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001006 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1007 }
khenaidoo92e62c52018-10-03 14:02:54 -04001008 return nil
1009 }
1010}
1011
khenaidoo3ab34882019-05-02 21:33:30 -04001012func (agent *DeviceAgent) enablePorts() error {
1013 agent.lockDevice.Lock()
1014 defer agent.lockDevice.Unlock()
1015 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1016 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1017 } else {
1018 // clone the device
1019 cloned := proto.Clone(storeDevice).(*voltha.Device)
1020 for _, port := range cloned.Ports {
1021 port.AdminState = voltha.AdminState_ENABLED
1022 port.OperStatus = voltha.OperStatus_ACTIVE
1023 }
1024 // Store the device
1025 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
1026 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1027 }
1028 return nil
1029 }
1030}
1031
1032func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001033 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001034 agent.lockDevice.Lock()
1035 defer agent.lockDevice.Unlock()
1036 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1037 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1038 } else {
1039 // clone the device
1040 cloned := proto.Clone(storeDevice).(*voltha.Device)
1041 for _, port := range cloned.Ports {
1042 port.AdminState = voltha.AdminState_DISABLED
1043 port.OperStatus = voltha.OperStatus_UNKNOWN
1044 }
1045 // Store the device
1046 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
1047 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1048 }
1049 return nil
1050 }
1051}
1052
khenaidoo92e62c52018-10-03 14:02:54 -04001053func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1054 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001055 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001056 // Work only on latest data
1057 // TODO: Get list of ports from device directly instead of the entire device
1058 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001059 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1060 } else {
1061 // clone the device
1062 cloned := proto.Clone(storeDevice).(*voltha.Device)
1063 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1064 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001065 return status.Errorf(codes.InvalidArgument, "%s", portType)
1066 }
1067 for _, port := range cloned.Ports {
1068 if port.Type == portType && port.PortNo == portNo {
1069 port.OperStatus = operStatus
1070 // Set the admin status to ENABLED if the operational status is ACTIVE
1071 // TODO: Set by northbound system?
1072 if operStatus == voltha.OperStatus_ACTIVE {
1073 port.AdminState = voltha.AdminState_ENABLED
1074 }
1075 break
1076 }
1077 }
1078 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1079 // Store the device
1080 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001081 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1082 }
khenaidoob9203542018-09-17 22:56:37 -04001083 return nil
1084 }
1085}
1086
khenaidoo0a822f92019-05-08 15:15:57 -04001087func (agent *DeviceAgent) deleteAllPorts() error {
1088 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1089 agent.lockDevice.Lock()
1090 defer agent.lockDevice.Unlock()
1091 // Work only on latest data
1092 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1093 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1094 } else {
1095 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1096 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1097 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1098 return err
1099 }
1100 if len(storeDevice.Ports) == 0 {
1101 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1102 return nil
1103 }
1104 // clone the device & set the fields to empty
1105 cloned := proto.Clone(storeDevice).(*voltha.Device)
1106 cloned.Ports = []*voltha.Port{}
1107 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1108 // Store the device
1109 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
1110 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1111 }
1112 return nil
1113 }
1114}
1115
khenaidoob9203542018-09-17 22:56:37 -04001116func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001117 agent.lockDevice.Lock()
1118 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001119 log.Debug("updatePmConfigs")
1120 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001121 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001122 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1123 } else {
1124 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001125 cloned := proto.Clone(storeDevice).(*voltha.Device)
1126 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -04001127 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -04001128 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001129 if afterUpdate == nil {
1130 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1131 }
1132 return nil
1133 }
1134}
1135
1136func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001137 agent.lockDevice.Lock()
1138 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001139 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001140 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001141 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001142 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1143 } else {
1144 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001145 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001146 if cloned.Ports == nil {
1147 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001148 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001149 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001150 } else {
1151 for _, p := range cloned.Ports {
1152 if p.Type == port.Type && p.PortNo == port.PortNo {
1153 log.Debugw("port already exists", log.Fields{"port": *port})
1154 return nil
1155 }
1156 }
khenaidoob9203542018-09-17 22:56:37 -04001157 }
khenaidoo92e62c52018-10-03 14:02:54 -04001158 cp := proto.Clone(port).(*voltha.Port)
1159 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1160 // TODO: Set by northbound system?
1161 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1162 cp.AdminState = voltha.AdminState_ENABLED
1163 }
1164 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001165 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -04001166 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1167 if afterUpdate == nil {
1168 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1169 }
1170 return nil
1171 }
1172}
1173
1174func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1175 agent.lockDevice.Lock()
1176 defer agent.lockDevice.Unlock()
1177 log.Debug("addPeerPort")
1178 // Work only on latest data
1179 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1180 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1181 } else {
1182 // clone the device
1183 cloned := proto.Clone(storeDevice).(*voltha.Device)
1184 // Get the peer port on the device based on the port no
1185 for _, peerPort := range cloned.Ports {
1186 if peerPort.PortNo == port.PortNo { // found port
1187 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1188 peerPort.Peers = append(peerPort.Peers, cp)
1189 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1190 break
1191 }
1192 }
1193 // Store the device
1194 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001195 if afterUpdate == nil {
1196 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1197 }
1198 return nil
1199 }
1200}
1201
khenaidoo0a822f92019-05-08 15:15:57 -04001202func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1203 agent.lockDevice.Lock()
1204 defer agent.lockDevice.Unlock()
1205 log.Debug("deletePeerPorts")
1206 // Work only on latest data
1207 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1208 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1209 } else {
1210 // clone the device
1211 cloned := proto.Clone(storeDevice).(*voltha.Device)
1212 var updatedPeers []*voltha.Port_PeerPort
1213 for _, port := range cloned.Ports {
1214 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1215 for _, peerPort := range port.Peers {
1216 if peerPort.DeviceId != deviceId {
1217 updatedPeers = append(updatedPeers, peerPort)
1218 }
1219 }
1220 port.Peers = updatedPeers
1221 }
1222
1223 // Store the device with updated peer ports
1224 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1225 if afterUpdate == nil {
1226 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1227 }
1228 return nil
1229 }
1230}
1231
khenaidoob9203542018-09-17 22:56:37 -04001232// TODO: A generic device update by attribute
1233func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001234 agent.lockDevice.Lock()
1235 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001236 if value == nil {
1237 return
1238 }
1239 var storeDevice *voltha.Device
1240 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001241 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001242 return
1243 }
1244 updated := false
1245 s := reflect.ValueOf(storeDevice).Elem()
1246 if s.Kind() == reflect.Struct {
1247 // exported field
1248 f := s.FieldByName(name)
1249 if f.IsValid() && f.CanSet() {
1250 switch f.Kind() {
1251 case reflect.String:
1252 f.SetString(value.(string))
1253 updated = true
1254 case reflect.Uint32:
1255 f.SetUint(uint64(value.(uint32)))
1256 updated = true
1257 case reflect.Bool:
1258 f.SetBool(value.(bool))
1259 updated = true
1260 }
1261 }
1262 }
khenaidoo92e62c52018-10-03 14:02:54 -04001263 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001264 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001265 cloned := proto.Clone(storeDevice).(*voltha.Device)
1266 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001267 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1268 }
1269 return
1270}
serkant.uluderya334479d2019-04-10 08:26:15 -07001271
1272func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1273 agent.lockDevice.Lock()
1274 defer agent.lockDevice.Unlock()
1275 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1276 // Get the most up to date the device info
1277 if device, err := agent.getDeviceWithoutLock(); err != nil {
1278 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1279 } else {
1280 // First send the request to an Adapter and wait for a response
1281 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1282 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1283 return err
1284 }
1285 }
1286 return nil
1287}