blob: 8bf866455d4aba937d92b07e8e4f3cacbfa906c5 [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
khenaidoo21d51152019-02-01 13:48:37 -050039 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040040 deviceMgr *DeviceManager
41 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040042 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040043 exitChannel chan int
khenaidoo19d7b632018-10-30 10:49:50 -040044 flowProxy *model.Proxy
45 groupProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040046 lockDevice sync.RWMutex
khenaidoob9203542018-09-17 22:56:37 -040047}
48
khenaidoo4d4802d2018-10-04 21:59:49 -040049//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
50//preprovisioning
khenaidoo9a468962018-09-19 15:33:13 -040051func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040052 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040053 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040054 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050055 if cloned.Id == "" {
56 cloned.Id = CreateDeviceId()
57 }
khenaidoo92e62c52018-10-03 14:02:54 -040058 cloned.AdminState = voltha.AdminState_PREPROVISIONED
khenaidoo19d7b632018-10-30 10:49:50 -040059 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
60 cloned.Flows = &ofp.Flows{Items: nil}
61 if !device.GetRoot() && device.ProxyAddress != nil {
62 // Set the default vlan ID to the one specified by the parent adapter. It can be
63 // overwritten by the child adapter during a device update request
64 cloned.Vlan = device.ProxyAddress.ChannelId
65 }
khenaidoo92e62c52018-10-03 14:02:54 -040066 agent.deviceId = cloned.Id
khenaidoofdbad6e2018-11-06 22:26:38 -050067 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040068 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040069 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050070 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040071 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040072 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040073 agent.lockDevice = sync.RWMutex{}
khenaidoob9203542018-09-17 22:56:37 -040074 return &agent
75}
76
khenaidoo4d4802d2018-10-04 21:59:49 -040077// start save the device to the data model and registers for callbacks on that device
khenaidoob9203542018-09-17 22:56:37 -040078func (agent *DeviceAgent) start(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -040079 agent.lockDevice.Lock()
80 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -040081 log.Debugw("starting-device-agent", log.Fields{"device": agent.lastData})
82 // Add the initial device to the local model
Stephane Barbarie933b09b2019-01-09 11:12:09 -050083 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoob9203542018-09-17 22:56:37 -040084 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
85 }
khenaidoo43c82122018-11-22 18:38:28 -050086 agent.deviceProxy = agent.clusterDataProxy.Root.CreateProxy("/devices/"+agent.deviceId, false)
87 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -040088
khenaidoo43c82122018-11-22 18:38:28 -050089 agent.flowProxy = agent.clusterDataProxy.Root.CreateProxy(
khenaidoo19d7b632018-10-30 10:49:50 -040090 fmt.Sprintf("/devices/%s/flows", agent.deviceId),
91 false)
khenaidoo43c82122018-11-22 18:38:28 -050092 agent.groupProxy = agent.clusterDataProxy.Root.CreateProxy(
khenaidoo19d7b632018-10-30 10:49:50 -040093 fmt.Sprintf("/devices/%s/flow_groups", agent.deviceId),
94 false)
95
96 agent.flowProxy.RegisterCallback(model.POST_UPDATE, agent.flowTableUpdated)
khenaidoo43c82122018-11-22 18:38:28 -050097 agent.groupProxy.RegisterCallback(model.POST_UPDATE, agent.groupTableUpdated)
khenaidoo19d7b632018-10-30 10:49:50 -040098
khenaidoob9203542018-09-17 22:56:37 -040099 log.Debug("device-agent-started")
100}
101
khenaidoo4d4802d2018-10-04 21:59:49 -0400102// stop stops the device agent. Not much to do for now
103func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400104 agent.lockDevice.Lock()
105 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400106 log.Debug("stopping-device-agent")
107 agent.exitChannel <- 1
108 log.Debug("device-agent-stopped")
109}
110
khenaidoo19d7b632018-10-30 10:49:50 -0400111// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400112func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
113 agent.lockDevice.Lock()
114 defer agent.lockDevice.Unlock()
115 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
116 if d, ok := device.(*voltha.Device); ok {
117 cloned := proto.Clone(d).(*voltha.Device)
118 return cloned, nil
119 }
120 }
121 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
122}
123
khenaidoo4d4802d2018-10-04 21:59:49 -0400124// 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 -0400125// This function is meant so that we do not have duplicate code all over the device agent functions
126func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
127 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
128 if d, ok := device.(*voltha.Device); ok {
129 cloned := proto.Clone(d).(*voltha.Device)
130 return cloned, nil
131 }
132 }
133 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
134}
135
khenaidoo4d4802d2018-10-04 21:59:49 -0400136// enableDevice activates a preprovisioned or disable device
khenaidoob9203542018-09-17 22:56:37 -0400137func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400138 agent.lockDevice.Lock()
139 defer agent.lockDevice.Unlock()
140 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500141
khenaidoo92e62c52018-10-03 14:02:54 -0400142 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400143 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
144 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500145 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
146 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
147 // with the adapter then we need to know the adapter that will handle this request
148 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
149 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
150 return err
151 } else {
152 device.Adapter = adapterName
153 }
154
khenaidoo92e62c52018-10-03 14:02:54 -0400155 if device.AdminState == voltha.AdminState_ENABLED {
156 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
157 //TODO: Needs customized error message
158 return nil
159 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400160 //TODO: if parent device is disabled then do not enable device
khenaidoo92e62c52018-10-03 14:02:54 -0400161 // Verify whether we need to adopt the device the first time
162 // TODO: A state machine for these state transitions would be better (we just have to handle
163 // a limited set of states now or it may be an overkill)
164 if device.AdminState == voltha.AdminState_PREPROVISIONED {
165 // First send the request to an Adapter and wait for a response
166 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
167 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400168 return err
169 }
khenaidoo92e62c52018-10-03 14:02:54 -0400170 } else {
171 // First send the request to an Adapter and wait for a response
172 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
173 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
174 return err
175 }
176 }
177 // Received an Ack (no error found above). Now update the device in the model to the expected state
178 cloned := proto.Clone(device).(*voltha.Device)
179 cloned.AdminState = voltha.AdminState_ENABLED
180 cloned.OperStatus = voltha.OperStatus_ACTIVATING
181 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
182 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
khenaidoob9203542018-09-17 22:56:37 -0400183 }
184 }
185 return nil
186}
187
khenaidoo19d7b632018-10-30 10:49:50 -0400188func (agent *DeviceAgent) updateFlows(flows []*ofp.OfpFlowStats) error {
189 agent.lockDevice.Lock()
190 defer agent.lockDevice.Unlock()
191 log.Debugw("updateFlows", log.Fields{"deviceId": agent.deviceId, "flows": flows})
192 var oldData *voltha.Flows
193 if storedData, err := agent.getDeviceWithoutLock(); err != nil {
194 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
195 } else {
196 oldData = proto.Clone(storedData.Flows).(*voltha.Flows)
197 log.Debugw("updateFlows", log.Fields{"deviceId": agent.deviceId, "flows": flows, "old": oldData})
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500198
khenaidoo19d7b632018-10-30 10:49:50 -0400199 // store the changed data
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500200 afterUpdate := agent.flowProxy.Update("/", &ofp.Flows{Items: flows}, false, "")
khenaidoo19d7b632018-10-30 10:49:50 -0400201 if afterUpdate == nil {
202 return status.Errorf(codes.Internal, "%s", agent.deviceId)
203 }
204
khenaidoo19d7b632018-10-30 10:49:50 -0400205 return nil
206 }
207}
208
209func (agent *DeviceAgent) updateGroups(groups []*ofp.OfpGroupEntry) error {
210 agent.lockDevice.Lock()
211 defer agent.lockDevice.Unlock()
khenaidoo19d7b632018-10-30 10:49:50 -0400212 log.Debugw("updateGroups", log.Fields{"deviceId": agent.deviceId, "groups": groups})
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500213 if _, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo19d7b632018-10-30 10:49:50 -0400214 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
215 } else {
khenaidoo19d7b632018-10-30 10:49:50 -0400216 // store the changed data
Stephane Barbarie1ab43272018-12-08 21:42:13 -0500217 afterUpdate := agent.groupProxy.Update("/", &ofp.FlowGroups{Items: groups}, false, "")
khenaidoo19d7b632018-10-30 10:49:50 -0400218 if afterUpdate == nil {
219 return status.Errorf(codes.Internal, "%s", agent.deviceId)
220 }
221
khenaidoo19d7b632018-10-30 10:49:50 -0400222 return nil
223 }
224}
225
khenaidoo4d4802d2018-10-04 21:59:49 -0400226//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400227func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
228 agent.lockDevice.Lock()
229 //defer agent.lockDevice.Unlock()
230 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
231 // Get the most up to date the device info
232 if device, err := agent.getDeviceWithoutLock(); err != nil {
233 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
234 } else {
235 if device.AdminState == voltha.AdminState_DISABLED {
236 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
237 //TODO: Needs customized error message
238 agent.lockDevice.Unlock()
239 return nil
240 }
241 // First send the request to an Adapter and wait for a response
242 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
243 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
244 agent.lockDevice.Unlock()
245 return err
246 }
247 // Received an Ack (no error found above). Now update the device in the model to the expected state
248 cloned := proto.Clone(device).(*voltha.Device)
249 cloned.AdminState = voltha.AdminState_DISABLED
250 // Set the state of all ports on that device to disable
251 for _, port := range cloned.Ports {
252 port.AdminState = voltha.AdminState_DISABLED
253 port.OperStatus = voltha.OperStatus_UNKNOWN
254 }
255 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
256 agent.lockDevice.Unlock()
257 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
258 }
259 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400260 }
261 return nil
262}
263
khenaidoo4d4802d2018-10-04 21:59:49 -0400264func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
265 agent.lockDevice.Lock()
266 defer agent.lockDevice.Unlock()
267 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
268 // Get the most up to date the device info
269 if device, err := agent.getDeviceWithoutLock(); err != nil {
270 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
271 } else {
272 if device.AdminState != voltha.AdminState_DISABLED {
273 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
274 //TODO: Needs customized error message
275 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
276 }
277 // First send the request to an Adapter and wait for a response
278 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
279 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
280 return err
281 }
282 }
283 return nil
284}
285
286func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
287 agent.lockDevice.Lock()
288 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
289 // Get the most up to date the device info
290 if device, err := agent.getDeviceWithoutLock(); err != nil {
291 agent.lockDevice.Unlock()
292 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
293 } else {
khenaidoo43c82122018-11-22 18:38:28 -0500294 if (device.AdminState != voltha.AdminState_DISABLED) &&
295 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400296 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
297 //TODO: Needs customized error message
298 agent.lockDevice.Unlock()
299 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
300 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500301 if device.AdminState != voltha.AdminState_PREPROVISIONED {
302 // Send the request to an Adapter and wait for a response
303 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
304 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
305 agent.lockDevice.Unlock()
306 return err
307 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400308 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500309 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400310 agent.lockDevice.Unlock()
311 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
312 }
313 agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400314 }
315 return nil
316}
317
khenaidoof5a5bfa2019-01-23 22:20:29 -0500318func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
319 agent.lockDevice.Lock()
320 defer agent.lockDevice.Unlock()
321 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
322 // Get the most up to date the device info
323 if device, err := agent.getDeviceWithoutLock(); err != nil {
324 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
325 } else {
326 if device.AdminState != voltha.AdminState_ENABLED {
327 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
328 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
329 }
330 // Save the image
331 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500332 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500333 cloned := proto.Clone(device).(*voltha.Device)
334 if cloned.ImageDownloads == nil {
335 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
336 } else {
337 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
338 }
339 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
340 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
341 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
342 }
343 // Send the request to the adapter
344 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
345 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
346 return nil, err
347 }
348 }
349 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
350}
351
352// isImageRegistered is a helper method to figure out if an image is already registered
353func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
354 for _, image := range device.ImageDownloads {
355 if image.Id == img.Id && image.Name == img.Name {
356 return true
357 }
358 }
359 return false
360}
361
362func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
363 agent.lockDevice.Lock()
364 defer agent.lockDevice.Unlock()
365 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
366 // Get the most up to date the device info
367 if device, err := agent.getDeviceWithoutLock(); err != nil {
368 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
369 } else {
370 // Verify whether the Image is in the list of image being downloaded
371 if !isImageRegistered(img, device) {
372 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
373 }
374
375 // Update image download state
376 cloned := proto.Clone(device).(*voltha.Device)
377 for _, image := range cloned.ImageDownloads {
378 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500379 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500380 }
381 }
382
383 //If device is in downloading state, send the request to cancel the download
384 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
385 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
386 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
387 return nil, err
388 }
389 // Set the device to Enabled
390 cloned.AdminState = voltha.AdminState_ENABLED
391 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
392 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
393 }
394 }
395 }
396 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
397 }
398
399func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
400 agent.lockDevice.Lock()
401 defer agent.lockDevice.Unlock()
402 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
403 // Get the most up to date the device info
404 if device, err := agent.getDeviceWithoutLock(); err != nil {
405 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
406 } else {
407 // Verify whether the Image is in the list of image being downloaded
408 if !isImageRegistered(img, device) {
409 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
410 }
411
412 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
413 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
414 }
415 // Update image download state
416 cloned := proto.Clone(device).(*voltha.Device)
417 for _, image := range cloned.ImageDownloads {
418 if image.Id == img.Id && image.Name == img.Name {
419 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
420 }
421 }
422 // Set the device to downloading_image
423 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
424 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
425 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
426 }
427
428 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
429 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
430 return nil, err
431 }
432 // The status of the AdminState will be changed following the update_download_status response from the adapter
433 // The image name will also be removed from the device list
434 }
435 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil}
436
437
438func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
439 agent.lockDevice.Lock()
440 defer agent.lockDevice.Unlock()
441 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
442 // Get the most up to date the device info
443 if device, err := agent.getDeviceWithoutLock(); err != nil {
444 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
445 } else {
446 // Verify whether the Image is in the list of image being downloaded
447 if !isImageRegistered(img, device) {
448 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
449 }
450
451 if device.AdminState != voltha.AdminState_ENABLED {
452 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
453 }
454 // Update image download state
455 cloned := proto.Clone(device).(*voltha.Device)
456 for _, image := range cloned.ImageDownloads {
457 if image.Id == img.Id && image.Name == img.Name {
458 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
459 }
460 }
461 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
462 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
463 }
464
465 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
466 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
467 return nil, err
468 }
469 }
470 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
471 }
472
473
474func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
475 agent.lockDevice.Lock()
476 defer agent.lockDevice.Unlock()
477 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
478 // Get the most up to date the device info
479 if device, err := agent.getDeviceWithoutLock(); err != nil {
480 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
481 } else {
482 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
483 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
484 return nil, err
485 } else {
486 return resp, nil
487 }
488 }
489}
490
491func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error{
492 agent.lockDevice.Lock()
493 defer agent.lockDevice.Unlock()
494 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
495 // Get the most up to date the device info
496 if device, err := agent.getDeviceWithoutLock(); err != nil {
497 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
498 } else {
499 // Update the image as well as remove it if the download was cancelled
500 cloned := proto.Clone(device).(*voltha.Device)
501 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
502 for _, image := range cloned.ImageDownloads {
503 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500504 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500505 clonedImages = append(clonedImages, img)
506 }
507 }
508 }
509 cloned.ImageDownloads = clonedImages
510 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500511 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
512 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
khenaidoof5a5bfa2019-01-23 22:20:29 -0500513 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING){
514 cloned.AdminState = voltha.AdminState_ENABLED
515 }
516
517 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
518 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
519 }
520 }
521 return nil
522}
523
524func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
525 agent.lockDevice.Lock()
526 defer agent.lockDevice.Unlock()
527 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
528 // Get the most up to date the device info
529 if device, err := agent.getDeviceWithoutLock(); err != nil {
530 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
531 } else {
532 for _, image := range device.ImageDownloads {
533 if image.Id == img.Id && image.Name == img.Name {
534 return image, nil
535 }
536 }
537 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
538 }
539}
540
541func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
542 agent.lockDevice.Lock()
543 defer agent.lockDevice.Unlock()
544 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
545 // Get the most up to date the device info
546 if device, err := agent.getDeviceWithoutLock(); err != nil {
547 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
548 } else {
549 return &voltha.ImageDownloads{Items:device.ImageDownloads}, nil
550 }
551}
552
khenaidoo4d4802d2018-10-04 21:59:49 -0400553// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400554func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
555 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400556 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400557 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400558 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400559 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400560 ports.Items = append(ports.Items, port)
561 }
562 }
563 }
564 return ports
565}
566
khenaidoo4d4802d2018-10-04 21:59:49 -0400567// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
568// parent device
khenaidoo79232702018-12-04 11:00:41 -0500569func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400570 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400571 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400572 return nil, err
573 } else {
khenaidoo79232702018-12-04 11:00:41 -0500574 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400575 var err error
576 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
577 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
578 return nil, err
579 }
580 return switchCap, nil
581 }
582}
583
khenaidoo4d4802d2018-10-04 21:59:49 -0400584// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
585// device
khenaidoo79232702018-12-04 11:00:41 -0500586func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400587 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400588 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400589 return nil, err
590 } else {
khenaidoo79232702018-12-04 11:00:41 -0500591 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400592 var err error
593 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
594 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
595 return nil, err
596 }
597 return portCap, nil
598 }
599}
600
khenaidoofdbad6e2018-11-06 22:26:38 -0500601func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
602 // Send packet to adapter
603 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
604 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
605 return err
606 }
607 return nil
608}
609
khenaidoo4d4802d2018-10-04 21:59:49 -0400610// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400611func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500612 //// Run this callback in its own go routine
613 go func(args ...interface{}) interface{} {
614 var previous *voltha.Device
615 var current *voltha.Device
616 var ok bool
617 if len(args) == 2 {
618 if previous, ok = args[0].(*voltha.Device); !ok {
619 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
620 return nil
621 }
622 if current, ok = args[1].(*voltha.Device); !ok {
623 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
624 return nil
625 }
626 } else {
627 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
628 return nil
629 }
630 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500631 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
632 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
633 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
634 }
khenaidoo43c82122018-11-22 18:38:28 -0500635 return nil
636 }(args...)
637
khenaidoo92e62c52018-10-03 14:02:54 -0400638 return nil
639}
640
khenaidoob9203542018-09-17 22:56:37 -0400641func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400642 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500643 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400644 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500645 cloned := proto.Clone(device).(*voltha.Device)
646 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
647 if afterUpdate == nil {
648 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400649 }
khenaidoo43c82122018-11-22 18:38:28 -0500650 return nil
651}
652
653func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
654 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
655 cloned := proto.Clone(device).(*voltha.Device)
656 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
657 if afterUpdate == nil {
658 return status.Errorf(codes.Internal, "%s", device.Id)
659 }
660 return nil
khenaidoob9203542018-09-17 22:56:37 -0400661}
662
khenaidoo92e62c52018-10-03 14:02:54 -0400663func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
664 agent.lockDevice.Lock()
665 //defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400666 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400667 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
668 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400669 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
670 } else {
671 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400672 cloned := proto.Clone(storeDevice).(*voltha.Device)
673 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
674 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
675 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
676 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400677 }
khenaidoo92e62c52018-10-03 14:02:54 -0400678 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
679 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
680 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400681 }
khenaidoo92e62c52018-10-03 14:02:54 -0400682 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400683 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400684 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
685 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400686 return status.Errorf(codes.Internal, "%s", agent.deviceId)
687 }
khenaidoo92e62c52018-10-03 14:02:54 -0400688 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400689 return nil
690 }
691}
692
693func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
694 agent.lockDevice.Lock()
695 //defer agent.lockDevice.Unlock()
696 // Work only on latest data
697 // TODO: Get list of ports from device directly instead of the entire device
698 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
699 agent.lockDevice.Unlock()
700 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
701 } else {
702 // clone the device
703 cloned := proto.Clone(storeDevice).(*voltha.Device)
704 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
705 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
706 agent.lockDevice.Unlock()
707 return status.Errorf(codes.InvalidArgument, "%s", portType)
708 }
709 for _, port := range cloned.Ports {
710 if port.Type == portType && port.PortNo == portNo {
711 port.OperStatus = operStatus
712 // Set the admin status to ENABLED if the operational status is ACTIVE
713 // TODO: Set by northbound system?
714 if operStatus == voltha.OperStatus_ACTIVE {
715 port.AdminState = voltha.AdminState_ENABLED
716 }
717 break
718 }
719 }
720 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
721 // Store the device
722 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
723 agent.lockDevice.Unlock()
724 return status.Errorf(codes.Internal, "%s", agent.deviceId)
725 }
726 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400727 return nil
728 }
729}
730
731func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400732 agent.lockDevice.Lock()
733 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400734 log.Debug("updatePmConfigs")
735 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400736 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400737 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
738 } else {
739 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400740 cloned := proto.Clone(storeDevice).(*voltha.Device)
741 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400742 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400743 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400744 if afterUpdate == nil {
745 return status.Errorf(codes.Internal, "%s", agent.deviceId)
746 }
747 return nil
748 }
749}
750
751func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400752 agent.lockDevice.Lock()
753 defer agent.lockDevice.Unlock()
754 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400755 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400756 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400757 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
758 } else {
759 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400760 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400761 if cloned.Ports == nil {
762 // First port
khenaidoo92e62c52018-10-03 14:02:54 -0400763 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400764 cloned.Ports = make([]*voltha.Port, 0)
765 }
khenaidoo92e62c52018-10-03 14:02:54 -0400766 cp := proto.Clone(port).(*voltha.Port)
767 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
768 // TODO: Set by northbound system?
769 if cp.OperStatus == voltha.OperStatus_ACTIVE {
770 cp.AdminState = voltha.AdminState_ENABLED
771 }
772 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400773 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400774 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
775 if afterUpdate == nil {
776 return status.Errorf(codes.Internal, "%s", agent.deviceId)
777 }
778 return nil
779 }
780}
781
782func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
783 agent.lockDevice.Lock()
784 defer agent.lockDevice.Unlock()
785 log.Debug("addPeerPort")
786 // Work only on latest data
787 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
788 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
789 } else {
790 // clone the device
791 cloned := proto.Clone(storeDevice).(*voltha.Device)
792 // Get the peer port on the device based on the port no
793 for _, peerPort := range cloned.Ports {
794 if peerPort.PortNo == port.PortNo { // found port
795 cp := proto.Clone(port).(*voltha.Port_PeerPort)
796 peerPort.Peers = append(peerPort.Peers, cp)
797 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
798 break
799 }
800 }
801 // Store the device
802 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400803 if afterUpdate == nil {
804 return status.Errorf(codes.Internal, "%s", agent.deviceId)
805 }
806 return nil
807 }
808}
809
khenaidoo19d7b632018-10-30 10:49:50 -0400810//flowTableUpdated is the callback after flows have been updated in the model to push them
khenaidoo21d51152019-02-01 13:48:37 -0500811//to the adapterAgents
khenaidoo19d7b632018-10-30 10:49:50 -0400812func (agent *DeviceAgent) flowTableUpdated(args ...interface{}) interface{} {
813 log.Debugw("flowTableUpdated-callback", log.Fields{"argsLen": len(args)})
814
815 agent.lockDevice.Lock()
816 defer agent.lockDevice.Unlock()
817
818 var previousData *voltha.Flows
819 var latestData *voltha.Flows
820
821 var ok bool
822 if previousData, ok = args[0].(*ofp.Flows); !ok {
823 log.Errorw("invalid-args", log.Fields{"args0": args[0]})
824 return nil
825 }
826 if latestData, ok = args[1].(*ofp.Flows); !ok {
827 log.Errorw("invalid-args", log.Fields{"args1": args[1]})
828 return nil
829 }
830
831 // Sanity check - should not happen as this is already handled in logical device agent
832 if reflect.DeepEqual(previousData.Items, latestData.Items) {
833 log.Debugw("flow-update-not-required", log.Fields{"previous": previousData.Items, "new": latestData.Items})
834 return nil
835 }
836
837 var device *voltha.Device
838 var err error
839 if device, err = agent.getDeviceWithoutLock(); err != nil {
840 log.Errorw("no-device", log.Fields{"id": agent.deviceId, "error": err})
841 return nil
842 }
843 groups := device.FlowGroups
844
khenaidoo21d51152019-02-01 13:48:37 -0500845 // Send update to adapterAgents
846 dType := agent.adapterMgr.getDeviceType(device.Type)
847 if !dType.AcceptsAddRemoveFlowUpdates {
khenaidoo19d7b632018-10-30 10:49:50 -0400848 if err := agent.adapterProxy.UpdateFlowsBulk(device, latestData, groups); err != nil {
849 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
850 return err
851 }
852 return nil
853 }
854 // Incremental flow changes accepted
855 var toAdd []*ofp.OfpFlowStats
856 var toDelete []*ofp.OfpFlowStats
857
858 for _, flow := range latestData.Items {
859 if fu.FindFlowById(previousData.Items, flow) == -1 { // did not exist before
860 toAdd = append(toAdd, flow)
861 }
862 }
863 for _, flow := range previousData.Items {
864 if fu.FindFlowById(latestData.Items, flow) == -1 { // does not exist now
865 toDelete = append(toDelete, flow)
866 }
867 }
868 flowChanges := &ofp.FlowChanges{
869 ToAdd: &voltha.Flows{Items: toAdd},
870 ToRemove: &voltha.Flows{Items: toDelete},
871 }
872 // Send an empty group changes as it would be dealt with a call to groupTableUpdated
873 groupChanges := &ofp.FlowGroupChanges{}
874
875 // Send changes only
876 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flowChanges, groupChanges); err != nil {
877 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
878 return err
879 }
880
881 return nil
882}
883
884//groupTableUpdated is the callback after group table has been updated in the model to push them
khenaidoo21d51152019-02-01 13:48:37 -0500885//to the adapterAgents
khenaidoo19d7b632018-10-30 10:49:50 -0400886func (agent *DeviceAgent) groupTableUpdated(args ...interface{}) interface{} {
887 log.Debugw("groupTableUpdated-callback", log.Fields{"argsLen": len(args)})
888
889 agent.lockDevice.Lock()
890 defer agent.lockDevice.Unlock()
891
892 var previousData *voltha.FlowGroups
893 var latestData *voltha.FlowGroups
894
895 var ok bool
896 if previousData, ok = args[0].(*ofp.FlowGroups); !ok {
897 log.Errorw("invalid-args", log.Fields{"args0": args[0]})
898 return nil
899 }
900 if latestData, ok = args[1].(*ofp.FlowGroups); !ok {
901 log.Errorw("invalid-args", log.Fields{"args1": args[1]})
902 return nil
903 }
904
905 // Sanity check - should not happen as this is already handled in logical device agent
906 if reflect.DeepEqual(previousData.Items, latestData.Items) {
907 log.Debugw("group-table-update-not-required", log.Fields{"previous": previousData.Items, "new": latestData.Items})
908 return nil
909 }
910
911 var device *voltha.Device
912 var err error
913 if device, err = agent.getDeviceWithoutLock(); err != nil {
914 log.Errorw("no-device", log.Fields{"id": agent.deviceId, "error": err})
915 return nil
916 }
917 flows := device.Flows
918
khenaidoo21d51152019-02-01 13:48:37 -0500919 // Send update to adapterAgents
khenaidoo43c82122018-11-22 18:38:28 -0500920 // TODO: Check whether the device supports incremental flow changes
khenaidoo19d7b632018-10-30 10:49:50 -0400921 // Assume false for test
922 acceptsAddRemoveFlowUpdates := false
923 if !acceptsAddRemoveFlowUpdates {
924 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, latestData); err != nil {
925 log.Debugw("update-flows-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
926 return err
927 }
928 return nil
929 }
930
931 // Incremental group changes accepted
932 var toAdd []*ofp.OfpGroupEntry
933 var toDelete []*ofp.OfpGroupEntry
934 var toUpdate []*ofp.OfpGroupEntry
935
936 for _, group := range latestData.Items {
937 if idx := fu.FindGroup(previousData.Items, group.Desc.GroupId); idx == -1 { // did not exist before
938 toAdd = append(toAdd, group)
939 } else { // existed before
940 if previousData.Items[idx].String() != group.String() { // there is a change
941 toUpdate = append(toUpdate, group)
942 }
943 }
944 }
945 for _, group := range previousData.Items {
946 if fu.FindGroup(latestData.Items, group.Desc.GroupId) == -1 { // does not exist now
947 toDelete = append(toDelete, group)
948 }
949 }
950 groupChanges := &ofp.FlowGroupChanges{
951 ToAdd: &voltha.FlowGroups{Items: toAdd},
952 ToRemove: &voltha.FlowGroups{Items: toDelete},
953 ToUpdate: &voltha.FlowGroups{Items: toUpdate},
954 }
955 // Send an empty flow changes as it should have been dealt with a call to flowTableUpdated
956 flowChanges := &ofp.FlowChanges{}
957
958 // Send changes only
959 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flowChanges, groupChanges); err != nil {
960 log.Debugw("update-incremental-group-error", log.Fields{"id": agent.lastData.Id, "error": err})
961 return err
962 }
963 return nil
964}
965
khenaidoob9203542018-09-17 22:56:37 -0400966// TODO: A generic device update by attribute
967func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -0400968 agent.lockDevice.Lock()
969 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400970 if value == nil {
971 return
972 }
973 var storeDevice *voltha.Device
974 var err error
khenaidoo92e62c52018-10-03 14:02:54 -0400975 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400976 return
977 }
978 updated := false
979 s := reflect.ValueOf(storeDevice).Elem()
980 if s.Kind() == reflect.Struct {
981 // exported field
982 f := s.FieldByName(name)
983 if f.IsValid() && f.CanSet() {
984 switch f.Kind() {
985 case reflect.String:
986 f.SetString(value.(string))
987 updated = true
988 case reflect.Uint32:
989 f.SetUint(uint64(value.(uint32)))
990 updated = true
991 case reflect.Bool:
992 f.SetBool(value.(bool))
993 updated = true
994 }
995 }
996 }
khenaidoo92e62c52018-10-03 14:02:54 -0400997 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -0400998 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -0400999 cloned := proto.Clone(storeDevice).(*voltha.Device)
1000 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001001 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1002 }
1003 return
1004}