blob: 31720c139d9395f554436e06e5f55e0d2ff676b4 [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"
khenaidoo19d7b632018-10-30 10:49:50 -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"
khenaidoo79232702018-12-04 11:00:41 -050024 ic "github.com/opencord/voltha-go/protos/inter_container"
khenaidoo19d7b632018-10-30 10:49:50 -040025 ofp "github.com/opencord/voltha-go/protos/openflow_13"
khenaidoob9203542018-09-17 22:56:37 -040026 "github.com/opencord/voltha-go/protos/voltha"
khenaidoo19d7b632018-10-30 10:49:50 -040027 fu "github.com/opencord/voltha-go/rw_core/utils"
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
khenaidoo43c82122018-11-22 18:38:28 -050036 deviceType string
khenaidoo9a468962018-09-19 15:33:13 -040037 lastData *voltha.Device
38 adapterProxy *AdapterProxy
39 deviceMgr *DeviceManager
40 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040041 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040042 exitChannel chan int
khenaidoo19d7b632018-10-30 10:49:50 -040043 flowProxy *model.Proxy
44 groupProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040045 lockDevice sync.RWMutex
khenaidoob9203542018-09-17 22:56:37 -040046}
47
khenaidoo4d4802d2018-10-04 21:59:49 -040048//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
49//preprovisioning
khenaidoo9a468962018-09-19 15:33:13 -040050func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040051 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040052 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040053 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050054 if cloned.Id == "" {
55 cloned.Id = CreateDeviceId()
56 }
khenaidoo92e62c52018-10-03 14:02:54 -040057 cloned.AdminState = voltha.AdminState_PREPROVISIONED
khenaidoo19d7b632018-10-30 10:49:50 -040058 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
59 cloned.Flows = &ofp.Flows{Items: nil}
60 if !device.GetRoot() && device.ProxyAddress != nil {
61 // Set the default vlan ID to the one specified by the parent adapter. It can be
62 // overwritten by the child adapter during a device update request
63 cloned.Vlan = device.ProxyAddress.ChannelId
64 }
khenaidoo92e62c52018-10-03 14:02:54 -040065 agent.deviceId = cloned.Id
khenaidoofdbad6e2018-11-06 22:26:38 -050066 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040067 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040068 agent.deviceMgr = deviceMgr
69 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040070 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040071 agent.lockDevice = sync.RWMutex{}
khenaidoob9203542018-09-17 22:56:37 -040072 return &agent
73}
74
khenaidoo4d4802d2018-10-04 21:59:49 -040075// start save the device to the data model and registers for callbacks on that device
khenaidoob9203542018-09-17 22:56:37 -040076func (agent *DeviceAgent) start(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -040077 agent.lockDevice.Lock()
78 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -040079 log.Debugw("starting-device-agent", log.Fields{"device": agent.lastData})
80 // Add the initial device to the local model
Stephane Barbarie933b09b2019-01-09 11:12:09 -050081 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoob9203542018-09-17 22:56:37 -040082 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
83 }
khenaidoo43c82122018-11-22 18:38:28 -050084 agent.deviceProxy = agent.clusterDataProxy.Root.CreateProxy("/devices/"+agent.deviceId, false)
85 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -040086
khenaidoo43c82122018-11-22 18:38:28 -050087 agent.flowProxy = agent.clusterDataProxy.Root.CreateProxy(
khenaidoo19d7b632018-10-30 10:49:50 -040088 fmt.Sprintf("/devices/%s/flows", agent.deviceId),
89 false)
khenaidoo43c82122018-11-22 18:38:28 -050090 agent.groupProxy = agent.clusterDataProxy.Root.CreateProxy(
khenaidoo19d7b632018-10-30 10:49:50 -040091 fmt.Sprintf("/devices/%s/flow_groups", agent.deviceId),
92 false)
93
94 agent.flowProxy.RegisterCallback(model.POST_UPDATE, agent.flowTableUpdated)
khenaidoo43c82122018-11-22 18:38:28 -050095 agent.groupProxy.RegisterCallback(model.POST_UPDATE, agent.groupTableUpdated)
khenaidoo19d7b632018-10-30 10:49:50 -040096
khenaidoob9203542018-09-17 22:56:37 -040097 log.Debug("device-agent-started")
98}
99
khenaidoo4d4802d2018-10-04 21:59:49 -0400100// stop stops the device agent. Not much to do for now
101func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400102 agent.lockDevice.Lock()
103 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400104 log.Debug("stopping-device-agent")
105 agent.exitChannel <- 1
106 log.Debug("device-agent-stopped")
107}
108
khenaidoo19d7b632018-10-30 10:49:50 -0400109// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400110func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
111 agent.lockDevice.Lock()
112 defer agent.lockDevice.Unlock()
113 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
114 if d, ok := device.(*voltha.Device); ok {
115 cloned := proto.Clone(d).(*voltha.Device)
116 return cloned, nil
117 }
118 }
119 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
120}
121
khenaidoo4d4802d2018-10-04 21:59:49 -0400122// 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 -0400123// This function is meant so that we do not have duplicate code all over the device agent functions
124func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
125 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
126 if d, ok := device.(*voltha.Device); ok {
127 cloned := proto.Clone(d).(*voltha.Device)
128 return cloned, nil
129 }
130 }
131 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
132}
133
khenaidoo4d4802d2018-10-04 21:59:49 -0400134// enableDevice activates a preprovisioned or disable device
khenaidoob9203542018-09-17 22:56:37 -0400135func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400136 agent.lockDevice.Lock()
137 defer agent.lockDevice.Unlock()
138 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
139 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400140 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
141 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400142 if device.AdminState == voltha.AdminState_ENABLED {
143 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
144 //TODO: Needs customized error message
145 return nil
146 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400147 //TODO: if parent device is disabled then do not enable device
khenaidoo92e62c52018-10-03 14:02:54 -0400148 // Verify whether we need to adopt the device the first time
149 // TODO: A state machine for these state transitions would be better (we just have to handle
150 // a limited set of states now or it may be an overkill)
151 if device.AdminState == voltha.AdminState_PREPROVISIONED {
152 // First send the request to an Adapter and wait for a response
153 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
154 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400155 return err
156 }
khenaidoo92e62c52018-10-03 14:02:54 -0400157 } else {
158 // First send the request to an Adapter and wait for a response
159 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
160 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
161 return err
162 }
163 }
164 // Received an Ack (no error found above). Now update the device in the model to the expected state
165 cloned := proto.Clone(device).(*voltha.Device)
166 cloned.AdminState = voltha.AdminState_ENABLED
167 cloned.OperStatus = voltha.OperStatus_ACTIVATING
168 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
169 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
khenaidoob9203542018-09-17 22:56:37 -0400170 }
171 }
172 return nil
173}
174
khenaidoo19d7b632018-10-30 10:49:50 -0400175func (agent *DeviceAgent) updateFlows(flows []*ofp.OfpFlowStats) error {
176 agent.lockDevice.Lock()
177 defer agent.lockDevice.Unlock()
178 log.Debugw("updateFlows", log.Fields{"deviceId": agent.deviceId, "flows": flows})
179 var oldData *voltha.Flows
180 if storedData, err := agent.getDeviceWithoutLock(); err != nil {
181 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
182 } else {
183 oldData = proto.Clone(storedData.Flows).(*voltha.Flows)
184 log.Debugw("updateFlows", log.Fields{"deviceId": agent.deviceId, "flows": flows, "old": oldData})
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500185
khenaidoo19d7b632018-10-30 10:49:50 -0400186 // store the changed data
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500187 afterUpdate := agent.flowProxy.Update("/", &ofp.Flows{Items: flows}, false, "")
khenaidoo19d7b632018-10-30 10:49:50 -0400188 if afterUpdate == nil {
189 return status.Errorf(codes.Internal, "%s", agent.deviceId)
190 }
191
khenaidoo19d7b632018-10-30 10:49:50 -0400192 return nil
193 }
194}
195
196func (agent *DeviceAgent) updateGroups(groups []*ofp.OfpGroupEntry) error {
197 agent.lockDevice.Lock()
198 defer agent.lockDevice.Unlock()
khenaidoo19d7b632018-10-30 10:49:50 -0400199 log.Debugw("updateGroups", log.Fields{"deviceId": agent.deviceId, "groups": groups})
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500200 if _, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo19d7b632018-10-30 10:49:50 -0400201 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
202 } else {
khenaidoo19d7b632018-10-30 10:49:50 -0400203 // store the changed data
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500204 afterUpdate := agent.groupProxy.Update("/", &ofp.FlowGroups{Items: groups}, false, "")
khenaidoo19d7b632018-10-30 10:49:50 -0400205 if afterUpdate == nil {
206 return status.Errorf(codes.Internal, "%s", agent.deviceId)
207 }
208
khenaidoo19d7b632018-10-30 10:49:50 -0400209 return nil
210 }
211}
212
khenaidoo4d4802d2018-10-04 21:59:49 -0400213//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400214func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
215 agent.lockDevice.Lock()
216 //defer agent.lockDevice.Unlock()
217 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
218 // Get the most up to date the device info
219 if device, err := agent.getDeviceWithoutLock(); err != nil {
220 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
221 } else {
222 if device.AdminState == voltha.AdminState_DISABLED {
223 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
224 //TODO: Needs customized error message
225 agent.lockDevice.Unlock()
226 return nil
227 }
228 // First send the request to an Adapter and wait for a response
229 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
230 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
231 agent.lockDevice.Unlock()
232 return err
233 }
234 // Received an Ack (no error found above). Now update the device in the model to the expected state
235 cloned := proto.Clone(device).(*voltha.Device)
236 cloned.AdminState = voltha.AdminState_DISABLED
237 // Set the state of all ports on that device to disable
238 for _, port := range cloned.Ports {
239 port.AdminState = voltha.AdminState_DISABLED
240 port.OperStatus = voltha.OperStatus_UNKNOWN
241 }
242 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
243 agent.lockDevice.Unlock()
244 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
245 }
246 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400247 }
248 return nil
249}
250
khenaidoo4d4802d2018-10-04 21:59:49 -0400251func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
252 agent.lockDevice.Lock()
253 defer agent.lockDevice.Unlock()
254 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
255 // Get the most up to date the device info
256 if device, err := agent.getDeviceWithoutLock(); err != nil {
257 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
258 } else {
259 if device.AdminState != voltha.AdminState_DISABLED {
260 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
261 //TODO: Needs customized error message
262 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
263 }
264 // First send the request to an Adapter and wait for a response
265 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
266 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
267 return err
268 }
269 }
270 return nil
271}
272
273func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
274 agent.lockDevice.Lock()
275 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
276 // Get the most up to date the device info
277 if device, err := agent.getDeviceWithoutLock(); err != nil {
278 agent.lockDevice.Unlock()
279 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
280 } else {
khenaidoo43c82122018-11-22 18:38:28 -0500281 if (device.AdminState != voltha.AdminState_DISABLED) &&
282 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400283 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
284 //TODO: Needs customized error message
285 agent.lockDevice.Unlock()
286 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
287 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500288 if device.AdminState != voltha.AdminState_PREPROVISIONED {
289 // Send the request to an Adapter and wait for a response
290 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
291 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
292 agent.lockDevice.Unlock()
293 return err
294 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400295 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500296 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400297 agent.lockDevice.Unlock()
298 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
299 }
300 agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400301 }
302 return nil
303}
304
khenaidoof5a5bfa2019-01-23 22:20:29 -0500305func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
306 agent.lockDevice.Lock()
307 defer agent.lockDevice.Unlock()
308 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
309 // Get the most up to date the device info
310 if device, err := agent.getDeviceWithoutLock(); err != nil {
311 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
312 } else {
313 if device.AdminState != voltha.AdminState_ENABLED {
314 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
315 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
316 }
317 // Save the image
318 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500319 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500320 cloned := proto.Clone(device).(*voltha.Device)
321 if cloned.ImageDownloads == nil {
322 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
323 } else {
324 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
325 }
326 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
327 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
328 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
329 }
330 // Send the request to the adapter
331 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
332 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
333 return nil, err
334 }
335 }
336 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
337}
338
339// isImageRegistered is a helper method to figure out if an image is already registered
340func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
341 for _, image := range device.ImageDownloads {
342 if image.Id == img.Id && image.Name == img.Name {
343 return true
344 }
345 }
346 return false
347}
348
349func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
350 agent.lockDevice.Lock()
351 defer agent.lockDevice.Unlock()
352 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
353 // Get the most up to date the device info
354 if device, err := agent.getDeviceWithoutLock(); err != nil {
355 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
356 } else {
357 // Verify whether the Image is in the list of image being downloaded
358 if !isImageRegistered(img, device) {
359 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
360 }
361
362 // Update image download state
363 cloned := proto.Clone(device).(*voltha.Device)
364 for _, image := range cloned.ImageDownloads {
365 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500366 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500367 }
368 }
369
370 //If device is in downloading state, send the request to cancel the download
371 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
372 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
373 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
374 return nil, err
375 }
376 // Set the device to Enabled
377 cloned.AdminState = voltha.AdminState_ENABLED
378 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
379 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
380 }
381 }
382 }
383 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
384 }
385
386func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
387 agent.lockDevice.Lock()
388 defer agent.lockDevice.Unlock()
389 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
390 // Get the most up to date the device info
391 if device, err := agent.getDeviceWithoutLock(); err != nil {
392 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
393 } else {
394 // Verify whether the Image is in the list of image being downloaded
395 if !isImageRegistered(img, device) {
396 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
397 }
398
399 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
400 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
401 }
402 // Update image download state
403 cloned := proto.Clone(device).(*voltha.Device)
404 for _, image := range cloned.ImageDownloads {
405 if image.Id == img.Id && image.Name == img.Name {
406 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
407 }
408 }
409 // Set the device to downloading_image
410 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
411 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
412 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
413 }
414
415 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
416 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
417 return nil, err
418 }
419 // The status of the AdminState will be changed following the update_download_status response from the adapter
420 // The image name will also be removed from the device list
421 }
422 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil}
423
424
425func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
426 agent.lockDevice.Lock()
427 defer agent.lockDevice.Unlock()
428 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
429 // Get the most up to date the device info
430 if device, err := agent.getDeviceWithoutLock(); err != nil {
431 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
432 } else {
433 // Verify whether the Image is in the list of image being downloaded
434 if !isImageRegistered(img, device) {
435 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
436 }
437
438 if device.AdminState != voltha.AdminState_ENABLED {
439 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
440 }
441 // Update image download state
442 cloned := proto.Clone(device).(*voltha.Device)
443 for _, image := range cloned.ImageDownloads {
444 if image.Id == img.Id && image.Name == img.Name {
445 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
446 }
447 }
448 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
449 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
450 }
451
452 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
453 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
454 return nil, err
455 }
456 }
457 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
458 }
459
460
461func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
462 agent.lockDevice.Lock()
463 defer agent.lockDevice.Unlock()
464 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
465 // Get the most up to date the device info
466 if device, err := agent.getDeviceWithoutLock(); err != nil {
467 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
468 } else {
469 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
470 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
471 return nil, err
472 } else {
473 return resp, nil
474 }
475 }
476}
477
478func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error{
479 agent.lockDevice.Lock()
480 defer agent.lockDevice.Unlock()
481 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
482 // Get the most up to date the device info
483 if device, err := agent.getDeviceWithoutLock(); err != nil {
484 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
485 } else {
486 // Update the image as well as remove it if the download was cancelled
487 cloned := proto.Clone(device).(*voltha.Device)
488 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
489 for _, image := range cloned.ImageDownloads {
490 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500491 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500492 clonedImages = append(clonedImages, img)
493 }
494 }
495 }
496 cloned.ImageDownloads = clonedImages
497 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500498 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
499 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
khenaidoof5a5bfa2019-01-23 22:20:29 -0500500 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING){
501 cloned.AdminState = voltha.AdminState_ENABLED
502 }
503
504 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
505 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
506 }
507 }
508 return nil
509}
510
511func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
512 agent.lockDevice.Lock()
513 defer agent.lockDevice.Unlock()
514 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
515 // Get the most up to date the device info
516 if device, err := agent.getDeviceWithoutLock(); err != nil {
517 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
518 } else {
519 for _, image := range device.ImageDownloads {
520 if image.Id == img.Id && image.Name == img.Name {
521 return image, nil
522 }
523 }
524 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
525 }
526}
527
528func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
529 agent.lockDevice.Lock()
530 defer agent.lockDevice.Unlock()
531 log.Debugw("listImageDownloads", 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 nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
535 } else {
536 return &voltha.ImageDownloads{Items:device.ImageDownloads}, nil
537 }
538}
539
khenaidoo4d4802d2018-10-04 21:59:49 -0400540// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400541func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
542 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400543 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400544 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400545 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400546 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400547 ports.Items = append(ports.Items, port)
548 }
549 }
550 }
551 return ports
552}
553
khenaidoo4d4802d2018-10-04 21:59:49 -0400554// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
555// parent device
khenaidoo79232702018-12-04 11:00:41 -0500556func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400557 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400558 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400559 return nil, err
560 } else {
khenaidoo79232702018-12-04 11:00:41 -0500561 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400562 var err error
563 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
564 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
565 return nil, err
566 }
567 return switchCap, nil
568 }
569}
570
khenaidoo4d4802d2018-10-04 21:59:49 -0400571// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
572// device
khenaidoo79232702018-12-04 11:00:41 -0500573func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400574 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400575 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400576 return nil, err
577 } else {
khenaidoo79232702018-12-04 11:00:41 -0500578 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400579 var err error
580 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
581 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
582 return nil, err
583 }
584 return portCap, nil
585 }
586}
587
khenaidoofdbad6e2018-11-06 22:26:38 -0500588func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
589 // Send packet to adapter
590 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
591 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
592 return err
593 }
594 return nil
595}
596
khenaidoo4d4802d2018-10-04 21:59:49 -0400597// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400598func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500599 //// Run this callback in its own go routine
600 go func(args ...interface{}) interface{} {
601 var previous *voltha.Device
602 var current *voltha.Device
603 var ok bool
604 if len(args) == 2 {
605 if previous, ok = args[0].(*voltha.Device); !ok {
606 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
607 return nil
608 }
609 if current, ok = args[1].(*voltha.Device); !ok {
610 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
611 return nil
612 }
613 } else {
614 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
615 return nil
616 }
617 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500618 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
619 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
620 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
621 }
khenaidoo43c82122018-11-22 18:38:28 -0500622 return nil
623 }(args...)
624
khenaidoo92e62c52018-10-03 14:02:54 -0400625 return nil
626}
627
khenaidoob9203542018-09-17 22:56:37 -0400628func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400629 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500630 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400631 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500632 cloned := proto.Clone(device).(*voltha.Device)
633 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
634 if afterUpdate == nil {
635 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400636 }
khenaidoo43c82122018-11-22 18:38:28 -0500637 return nil
638}
639
640func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
641 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
642 cloned := proto.Clone(device).(*voltha.Device)
643 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
644 if afterUpdate == nil {
645 return status.Errorf(codes.Internal, "%s", device.Id)
646 }
647 return nil
khenaidoob9203542018-09-17 22:56:37 -0400648}
649
khenaidoo92e62c52018-10-03 14:02:54 -0400650func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
651 agent.lockDevice.Lock()
652 //defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400653 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400654 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
655 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400656 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
657 } else {
658 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400659 cloned := proto.Clone(storeDevice).(*voltha.Device)
660 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
661 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
662 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
663 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400664 }
khenaidoo92e62c52018-10-03 14:02:54 -0400665 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
666 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
667 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400668 }
khenaidoo92e62c52018-10-03 14:02:54 -0400669 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400670 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400671 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
672 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400673 return status.Errorf(codes.Internal, "%s", agent.deviceId)
674 }
khenaidoo92e62c52018-10-03 14:02:54 -0400675 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400676 return nil
677 }
678}
679
680func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
681 agent.lockDevice.Lock()
682 //defer agent.lockDevice.Unlock()
683 // Work only on latest data
684 // TODO: Get list of ports from device directly instead of the entire device
685 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
686 agent.lockDevice.Unlock()
687 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
688 } else {
689 // clone the device
690 cloned := proto.Clone(storeDevice).(*voltha.Device)
691 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
692 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
693 agent.lockDevice.Unlock()
694 return status.Errorf(codes.InvalidArgument, "%s", portType)
695 }
696 for _, port := range cloned.Ports {
697 if port.Type == portType && port.PortNo == portNo {
698 port.OperStatus = operStatus
699 // Set the admin status to ENABLED if the operational status is ACTIVE
700 // TODO: Set by northbound system?
701 if operStatus == voltha.OperStatus_ACTIVE {
702 port.AdminState = voltha.AdminState_ENABLED
703 }
704 break
705 }
706 }
707 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
708 // Store the device
709 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
710 agent.lockDevice.Unlock()
711 return status.Errorf(codes.Internal, "%s", agent.deviceId)
712 }
713 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400714 return nil
715 }
716}
717
718func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400719 agent.lockDevice.Lock()
720 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400721 log.Debug("updatePmConfigs")
722 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400723 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400724 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
725 } else {
726 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400727 cloned := proto.Clone(storeDevice).(*voltha.Device)
728 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400729 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400730 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400731 if afterUpdate == nil {
732 return status.Errorf(codes.Internal, "%s", agent.deviceId)
733 }
734 return nil
735 }
736}
737
738func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400739 agent.lockDevice.Lock()
740 defer agent.lockDevice.Unlock()
741 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400742 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400743 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400744 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
745 } else {
746 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400747 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400748 if cloned.Ports == nil {
749 // First port
khenaidoo92e62c52018-10-03 14:02:54 -0400750 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400751 cloned.Ports = make([]*voltha.Port, 0)
752 }
khenaidoo92e62c52018-10-03 14:02:54 -0400753 cp := proto.Clone(port).(*voltha.Port)
754 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
755 // TODO: Set by northbound system?
756 if cp.OperStatus == voltha.OperStatus_ACTIVE {
757 cp.AdminState = voltha.AdminState_ENABLED
758 }
759 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400760 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400761 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
762 if afterUpdate == nil {
763 return status.Errorf(codes.Internal, "%s", agent.deviceId)
764 }
765 return nil
766 }
767}
768
769func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
770 agent.lockDevice.Lock()
771 defer agent.lockDevice.Unlock()
772 log.Debug("addPeerPort")
773 // Work only on latest data
774 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
775 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
776 } else {
777 // clone the device
778 cloned := proto.Clone(storeDevice).(*voltha.Device)
779 // Get the peer port on the device based on the port no
780 for _, peerPort := range cloned.Ports {
781 if peerPort.PortNo == port.PortNo { // found port
782 cp := proto.Clone(port).(*voltha.Port_PeerPort)
783 peerPort.Peers = append(peerPort.Peers, cp)
784 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
785 break
786 }
787 }
788 // Store the device
789 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400790 if afterUpdate == nil {
791 return status.Errorf(codes.Internal, "%s", agent.deviceId)
792 }
793 return nil
794 }
795}
796
khenaidoo19d7b632018-10-30 10:49:50 -0400797//flowTableUpdated is the callback after flows have been updated in the model to push them
798//to the adapters
799func (agent *DeviceAgent) flowTableUpdated(args ...interface{}) interface{} {
800 log.Debugw("flowTableUpdated-callback", log.Fields{"argsLen": len(args)})
801
802 agent.lockDevice.Lock()
803 defer agent.lockDevice.Unlock()
804
805 var previousData *voltha.Flows
806 var latestData *voltha.Flows
807
808 var ok bool
809 if previousData, ok = args[0].(*ofp.Flows); !ok {
810 log.Errorw("invalid-args", log.Fields{"args0": args[0]})
811 return nil
812 }
813 if latestData, ok = args[1].(*ofp.Flows); !ok {
814 log.Errorw("invalid-args", log.Fields{"args1": args[1]})
815 return nil
816 }
817
818 // Sanity check - should not happen as this is already handled in logical device agent
819 if reflect.DeepEqual(previousData.Items, latestData.Items) {
820 log.Debugw("flow-update-not-required", log.Fields{"previous": previousData.Items, "new": latestData.Items})
821 return nil
822 }
823
824 var device *voltha.Device
825 var err error
826 if device, err = agent.getDeviceWithoutLock(); err != nil {
827 log.Errorw("no-device", log.Fields{"id": agent.deviceId, "error": err})
828 return nil
829 }
830 groups := device.FlowGroups
831
832 // Send update to adapters
khenaidoo43c82122018-11-22 18:38:28 -0500833 // TODO: Check whether the device supports incremental flow changes
khenaidoo19d7b632018-10-30 10:49:50 -0400834 // Assume false for test
835 acceptsAddRemoveFlowUpdates := false
836 if !acceptsAddRemoveFlowUpdates {
837 if err := agent.adapterProxy.UpdateFlowsBulk(device, latestData, groups); err != nil {
838 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
839 return err
840 }
841 return nil
842 }
843 // Incremental flow changes accepted
844 var toAdd []*ofp.OfpFlowStats
845 var toDelete []*ofp.OfpFlowStats
846
847 for _, flow := range latestData.Items {
848 if fu.FindFlowById(previousData.Items, flow) == -1 { // did not exist before
849 toAdd = append(toAdd, flow)
850 }
851 }
852 for _, flow := range previousData.Items {
853 if fu.FindFlowById(latestData.Items, flow) == -1 { // does not exist now
854 toDelete = append(toDelete, flow)
855 }
856 }
857 flowChanges := &ofp.FlowChanges{
858 ToAdd: &voltha.Flows{Items: toAdd},
859 ToRemove: &voltha.Flows{Items: toDelete},
860 }
861 // Send an empty group changes as it would be dealt with a call to groupTableUpdated
862 groupChanges := &ofp.FlowGroupChanges{}
863
864 // Send changes only
865 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flowChanges, groupChanges); err != nil {
866 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
867 return err
868 }
869
870 return nil
871}
872
873//groupTableUpdated is the callback after group table has been updated in the model to push them
874//to the adapters
875func (agent *DeviceAgent) groupTableUpdated(args ...interface{}) interface{} {
876 log.Debugw("groupTableUpdated-callback", log.Fields{"argsLen": len(args)})
877
878 agent.lockDevice.Lock()
879 defer agent.lockDevice.Unlock()
880
881 var previousData *voltha.FlowGroups
882 var latestData *voltha.FlowGroups
883
884 var ok bool
885 if previousData, ok = args[0].(*ofp.FlowGroups); !ok {
886 log.Errorw("invalid-args", log.Fields{"args0": args[0]})
887 return nil
888 }
889 if latestData, ok = args[1].(*ofp.FlowGroups); !ok {
890 log.Errorw("invalid-args", log.Fields{"args1": args[1]})
891 return nil
892 }
893
894 // Sanity check - should not happen as this is already handled in logical device agent
895 if reflect.DeepEqual(previousData.Items, latestData.Items) {
896 log.Debugw("group-table-update-not-required", log.Fields{"previous": previousData.Items, "new": latestData.Items})
897 return nil
898 }
899
900 var device *voltha.Device
901 var err error
902 if device, err = agent.getDeviceWithoutLock(); err != nil {
903 log.Errorw("no-device", log.Fields{"id": agent.deviceId, "error": err})
904 return nil
905 }
906 flows := device.Flows
907
908 // Send update to adapters
khenaidoo43c82122018-11-22 18:38:28 -0500909 // TODO: Check whether the device supports incremental flow changes
khenaidoo19d7b632018-10-30 10:49:50 -0400910 // Assume false for test
911 acceptsAddRemoveFlowUpdates := false
912 if !acceptsAddRemoveFlowUpdates {
913 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, latestData); err != nil {
914 log.Debugw("update-flows-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
915 return err
916 }
917 return nil
918 }
919
920 // Incremental group changes accepted
921 var toAdd []*ofp.OfpGroupEntry
922 var toDelete []*ofp.OfpGroupEntry
923 var toUpdate []*ofp.OfpGroupEntry
924
925 for _, group := range latestData.Items {
926 if idx := fu.FindGroup(previousData.Items, group.Desc.GroupId); idx == -1 { // did not exist before
927 toAdd = append(toAdd, group)
928 } else { // existed before
929 if previousData.Items[idx].String() != group.String() { // there is a change
930 toUpdate = append(toUpdate, group)
931 }
932 }
933 }
934 for _, group := range previousData.Items {
935 if fu.FindGroup(latestData.Items, group.Desc.GroupId) == -1 { // does not exist now
936 toDelete = append(toDelete, group)
937 }
938 }
939 groupChanges := &ofp.FlowGroupChanges{
940 ToAdd: &voltha.FlowGroups{Items: toAdd},
941 ToRemove: &voltha.FlowGroups{Items: toDelete},
942 ToUpdate: &voltha.FlowGroups{Items: toUpdate},
943 }
944 // Send an empty flow changes as it should have been dealt with a call to flowTableUpdated
945 flowChanges := &ofp.FlowChanges{}
946
947 // Send changes only
948 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flowChanges, groupChanges); err != nil {
949 log.Debugw("update-incremental-group-error", log.Fields{"id": agent.lastData.Id, "error": err})
950 return err
951 }
952 return nil
953}
954
khenaidoob9203542018-09-17 22:56:37 -0400955// TODO: A generic device update by attribute
956func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -0400957 agent.lockDevice.Lock()
958 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400959 if value == nil {
960 return
961 }
962 var storeDevice *voltha.Device
963 var err error
khenaidoo92e62c52018-10-03 14:02:54 -0400964 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400965 return
966 }
967 updated := false
968 s := reflect.ValueOf(storeDevice).Elem()
969 if s.Kind() == reflect.Struct {
970 // exported field
971 f := s.FieldByName(name)
972 if f.IsValid() && f.CanSet() {
973 switch f.Kind() {
974 case reflect.String:
975 f.SetString(value.(string))
976 updated = true
977 case reflect.Uint32:
978 f.SetUint(uint64(value.(uint32)))
979 updated = true
980 case reflect.Bool:
981 f.SetBool(value.(bool))
982 updated = true
983 }
984 }
985 }
khenaidoo92e62c52018-10-03 14:02:54 -0400986 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -0400987 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -0400988 cloned := proto.Clone(storeDevice).(*voltha.Device)
989 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400990 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
991 }
992 return
993}