blob: 42d628a8edf4965b5b2b0ce105bfdfbbd4556599 [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 */
npujar1d86a522019-11-14 17:11:16 +053016
khenaidoob9203542018-09-17 22:56:37 -040017package core
18
19import (
20 "context"
Matteo Scandolo360605d2019-11-05 18:29:17 -080021 "encoding/hex"
khenaidoo3ab34882019-05-02 21:33:30 -040022 "fmt"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040023 "reflect"
24 "sync"
25 "time"
26
khenaidoob9203542018-09-17 22:56:37 -040027 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050028 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070029 coreutils "github.com/opencord/voltha-go/rw_core/utils"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080030 fu "github.com/opencord/voltha-lib-go/v3/pkg/flows"
31 "github.com/opencord/voltha-lib-go/v3/pkg/log"
32 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
33 ofp "github.com/opencord/voltha-protos/v3/go/openflow_13"
34 "github.com/opencord/voltha-protos/v3/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040035 "google.golang.org/grpc/codes"
36 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040037)
38
npujar1d86a522019-11-14 17:11:16 +053039// DeviceAgent represents device agent attributes
khenaidoob9203542018-09-17 22:56:37 -040040type DeviceAgent struct {
npujar1d86a522019-11-14 17:11:16 +053041 deviceID string
42 parentID string
khenaidoo43c82122018-11-22 18:38:28 -050043 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040044 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040045 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070046 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040047 deviceMgr *DeviceManager
48 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040049 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040050 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040051 lockDevice sync.RWMutex
khenaidoo6e55d9e2019-12-12 18:26:26 -050052 device *voltha.Device
khenaidoo2c6a0992019-04-29 13:46:56 -040053 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040054}
55
Scott Baker80678602019-11-14 16:57:36 -080056//newDeviceAgent creates a new device agent. The device will be initialized when start() is called.
khenaidoo2c6a0992019-04-29 13:46:56 -040057func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040058 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040059 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080060 if device.Id == "" {
npujar1d86a522019-11-14 17:11:16 +053061 agent.deviceID = CreateDeviceID()
Scott Baker80678602019-11-14 16:57:36 -080062 } else {
npujar1d86a522019-11-14 17:11:16 +053063 agent.deviceID = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050064 }
Scott Baker80678602019-11-14 16:57:36 -080065
khenaidoo2c6a0992019-04-29 13:46:56 -040066 agent.isRootdevice = device.Root
npujar1d86a522019-11-14 17:11:16 +053067 agent.parentID = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080068 agent.deviceType = device.Type
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{}
khenaidoo2c6a0992019-04-29 13:46:56 -040074 agent.defaultTimeout = timeout
khenaidoo6e55d9e2019-12-12 18:26:26 -050075 agent.device = proto.Clone(device).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -040076 return &agent
77}
78
Scott Baker80678602019-11-14 16:57:36 -080079// start()
80// save the device to the data model and registers for callbacks on that device if deviceToCreate!=nil. Otherwise,
npujar1d86a522019-11-14 17:11:16 +053081// it will load the data from the dB and setup the necessary callbacks and proxies. Returns the device that
Scott Baker80678602019-11-14 16:57:36 -080082// was started.
83func (agent *DeviceAgent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
84 var device *voltha.Device
85
khenaidoo92e62c52018-10-03 14:02:54 -040086 agent.lockDevice.Lock()
87 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +053088 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceID})
Scott Baker80678602019-11-14 16:57:36 -080089 if deviceToCreate == nil {
90 // Load the existing device
Thomas Lee Se5a44012019-11-07 20:32:24 +053091 loadedDevice, err := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, "")
92 if err != nil {
93 log.Errorw("failed-to-get-from-cluster-data-proxy", log.Fields{"error": err})
94 return nil, err
95 }
96 if loadedDevice != nil {
Scott Baker80678602019-11-14 16:57:36 -080097 var ok bool
98 if device, ok = loadedDevice.(*voltha.Device); ok {
99 agent.deviceType = device.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -0500100 agent.device = proto.Clone(device).(*voltha.Device)
Scott Baker80678602019-11-14 16:57:36 -0800101 } else {
npujar1d86a522019-11-14 17:11:16 +0530102 log.Errorw("failed-to-convert-device", log.Fields{"deviceId": agent.deviceID})
103 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500104 }
105 } else {
npujar1d86a522019-11-14 17:11:16 +0530106 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceID})
107 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500108 }
npujar1d86a522019-11-14 17:11:16 +0530109 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500110 } else {
Scott Baker80678602019-11-14 16:57:36 -0800111 // Create a new device
112 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
113 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
114 // agent.deviceId will also have been set during newDeviceAgent().
115 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530116 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800117 device.AdminState = voltha.AdminState_PREPROVISIONED
118 device.FlowGroups = &ofp.FlowGroups{Items: nil}
119 device.Flows = &ofp.Flows{Items: nil}
120 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
121 // Set the default vlan ID to the one specified by the parent adapter. It can be
122 // overwritten by the child adapter during a device update request
123 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
124 }
125
khenaidoo297cd252019-02-07 22:10:23 -0500126 // Add the initial device to the local model
Thomas Lee Se5a44012019-11-07 20:32:24 +0530127 added, err := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceID, device, "")
128 if err != nil {
129 log.Errorw("failed-to-save-devices-to-cluster-proxy", log.Fields{"error": err})
130 return nil, err
131 }
132 if added == nil {
npujar1d86a522019-11-14 17:11:16 +0530133 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceID})
134 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500135 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500136 agent.device = proto.Clone(device).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400137 }
Thomas Lee Se5a44012019-11-07 20:32:24 +0530138 var err error
139 if agent.deviceProxy, err = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceID, false); err != nil {
140 log.Errorw("failed-to-add-devices-to-cluster-proxy", log.Fields{"error": err})
141 return nil, err
142 }
npujar9a30c702019-11-14 17:06:39 +0530143 agent.deviceProxy.RegisterCallback(model.PostUpdate, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400144
npujar1d86a522019-11-14 17:11:16 +0530145 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceID})
Scott Baker80678602019-11-14 16:57:36 -0800146 return device, nil
khenaidoob9203542018-09-17 22:56:37 -0400147}
148
khenaidoo4d4802d2018-10-04 21:59:49 -0400149// stop stops the device agent. Not much to do for now
150func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400151 agent.lockDevice.Lock()
152 defer agent.lockDevice.Unlock()
khenaidoo49085352020-01-13 19:15:43 -0500153
154 log.Debugw("stopping-device-agent", log.Fields{"deviceId": agent.deviceID, "parentId": agent.parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500155
156 // First unregister any callbacks
npujar9a30c702019-11-14 17:06:39 +0530157 agent.deviceProxy.UnregisterCallback(model.PostUpdate, agent.processUpdate)
khenaidoo6e55d9e2019-12-12 18:26:26 -0500158
khenaidoo0a822f92019-05-08 15:15:57 -0400159 // Remove the device from the KV store
Thomas Lee Se5a44012019-11-07 20:32:24 +0530160 removed, err := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceID, "")
161 if err != nil {
162 log.Errorw("Failed-to-remove-device-from-cluster-data-proxy", log.Fields{"error": err})
163 return
164 }
165 if removed == nil {
npujar1d86a522019-11-14 17:11:16 +0530166 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -0400167 }
khenaidoob9203542018-09-17 22:56:37 -0400168 agent.exitChannel <- 1
khenaidoo49085352020-01-13 19:15:43 -0500169 log.Debugw("device-agent-stopped", log.Fields{"deviceId": agent.deviceID, "parentId": agent.parentID})
khenaidoob9203542018-09-17 22:56:37 -0400170}
171
Scott Baker80678602019-11-14 16:57:36 -0800172// Load the most recent state from the KVStore for the device.
npujar467fe752020-01-16 20:17:45 +0530173func (agent *DeviceAgent) reconcileWithKVStore(ctx context.Context) {
Scott Baker80678602019-11-14 16:57:36 -0800174 agent.lockDevice.Lock()
175 defer agent.lockDevice.Unlock()
176 log.Debug("reconciling-device-agent-devicetype")
177 // TODO: context timeout
npujar467fe752020-01-16 20:17:45 +0530178 device, err := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, "")
Thomas Lee Se5a44012019-11-07 20:32:24 +0530179 if err != nil {
180 log.Errorw("Failed to get device info from cluster data proxy", log.Fields{"error": err})
181 return
182 }
183 if device != nil {
Scott Baker80678602019-11-14 16:57:36 -0800184 if d, ok := device.(*voltha.Device); ok {
185 agent.deviceType = d.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -0500186 agent.device = proto.Clone(d).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530187 log.Debugw("reconciled-device-agent-devicetype", log.Fields{"Id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800188 }
189 }
190}
191
khenaidoo6e55d9e2019-12-12 18:26:26 -0500192// getDevice returns the device data from cache
193func (agent *DeviceAgent) getDevice() *voltha.Device {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400194 agent.lockDevice.RLock()
195 defer agent.lockDevice.RUnlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500196 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400197}
198
khenaidoo4d4802d2018-10-04 21:59:49 -0400199// getDeviceWithoutLock is a helper function to be used ONLY by any device agent function AFTER it has acquired the device lock.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500200func (agent *DeviceAgent) getDeviceWithoutLock() *voltha.Device {
201 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400202}
203
khenaidoo3ab34882019-05-02 21:33:30 -0400204// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400205func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400206 agent.lockDevice.Lock()
207 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530208 log.Debugw("enableDevice", log.Fields{"id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500209
khenaidoo6e55d9e2019-12-12 18:26:26 -0500210 cloned := agent.getDeviceWithoutLock()
211
npujar1d86a522019-11-14 17:11:16 +0530212 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
213 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
214 // with the adapter then we need to know the adapter that will handle this request
khenaidoo6e55d9e2019-12-12 18:26:26 -0500215 adapterName, err := agent.adapterMgr.getAdapterName(cloned.Type)
npujar1d86a522019-11-14 17:11:16 +0530216 if err != nil {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500217 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": cloned.Type, "deviceAdapter": cloned.Adapter})
npujar1d86a522019-11-14 17:11:16 +0530218 return err
219 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500220 cloned.Adapter = adapterName
npujar1d86a522019-11-14 17:11:16 +0530221
khenaidoo6e55d9e2019-12-12 18:26:26 -0500222 if cloned.AdminState == voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530223 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceID})
224 return nil
225 }
226
khenaidoo6e55d9e2019-12-12 18:26:26 -0500227 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530228 // This is a temporary state when a device is deleted before it gets removed from the model.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500229 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", cloned.Id))
230 log.Warnw("invalid-state", log.Fields{"id": agent.deviceID, "state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +0530231 return err
232 }
233
khenaidoo6e55d9e2019-12-12 18:26:26 -0500234 previousAdminState := cloned.AdminState
npujar1d86a522019-11-14 17:11:16 +0530235
236 // Update the Admin State and set the operational state to activating before sending the request to the
237 // Adapters
npujar1d86a522019-11-14 17:11:16 +0530238 cloned.AdminState = voltha.AdminState_ENABLED
239 cloned.OperStatus = voltha.OperStatus_ACTIVATING
240
npujar467fe752020-01-16 20:17:45 +0530241 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530242 return err
243 }
244
245 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500246 device := proto.Clone(cloned).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530247 if previousAdminState == voltha.AdminState_PREPROVISIONED {
248 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
249 log.Debugw("adoptDevice-error", log.Fields{"id": agent.deviceID, "error": err})
250 return err
251 }
khenaidoob9203542018-09-17 22:56:37 -0400252 } else {
npujar1d86a522019-11-14 17:11:16 +0530253 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
254 log.Debugw("renableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
khenaidoo21d51152019-02-01 13:48:37 -0500255 return err
khenaidoob9203542018-09-17 22:56:37 -0400256 }
257 }
258 return nil
259}
260
npujar467fe752020-01-16 20:17:45 +0530261func (agent *DeviceAgent) sendBulkFlowsToAdapters(ctx context.Context, device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, response coreutils.Response) {
262 if err := agent.adapterProxy.UpdateFlowsBulk(ctx, device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530263 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500264 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400265 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500266 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400267}
268
npujar467fe752020-01-16 20:17:45 +0530269func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(ctx context.Context, device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, response coreutils.Response) {
270 if err := agent.adapterProxy.UpdateFlowsIncremental(ctx, device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530271 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500272 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400273 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500274 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400275}
276
khenaidoob2121e52019-12-16 17:17:22 -0500277//deleteFlowWithoutPreservingOrder removes a flow specified by index from the flows slice. This function will
278//panic if the index is out of range.
279func deleteFlowWithoutPreservingOrder(flows []*ofp.OfpFlowStats, index int) []*ofp.OfpFlowStats {
280 flows[index] = flows[len(flows)-1]
281 flows[len(flows)-1] = nil
282 return flows[:len(flows)-1]
283}
284
285//deleteGroupWithoutPreservingOrder removes a group specified by index from the groups slice. This function will
286//panic if the index is out of range.
287func deleteGroupWithoutPreservingOrder(groups []*ofp.OfpGroupEntry, index int) []*ofp.OfpGroupEntry {
288 groups[index] = groups[len(groups)-1]
289 groups[len(groups)-1] = nil
290 return groups[:len(groups)-1]
291}
292
293func flowsToUpdateToDelete(newFlows, existingFlows []*ofp.OfpFlowStats) (updatedNewFlows, flowsToDelete, updatedAllFlows []*ofp.OfpFlowStats) {
294 // Process flows
295 for _, flow := range existingFlows {
296 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
297 updatedAllFlows = append(updatedAllFlows, flow)
298 } else {
299 // We have a matching flow (i.e. the following field matches: "TableId", "Priority", "Flags", "Cookie",
300 // "Match". If this is an exact match (i.e. all other fields matches as well) then this flow will be
301 // ignored. Otherwise, the previous flow will be deleted and the new one added
302 if proto.Equal(newFlows[idx], flow) {
303 // Flow already exist, remove it from the new flows but keep it in the updated flows slice
304 newFlows = deleteFlowWithoutPreservingOrder(newFlows, idx)
305 updatedAllFlows = append(updatedAllFlows, flow)
306 } else {
307 // Minor change to flow, delete old and add new one
308 flowsToDelete = append(flowsToDelete, flow)
309 }
310 }
311 }
312 updatedAllFlows = append(updatedAllFlows, newFlows...)
313 return newFlows, flowsToDelete, updatedAllFlows
314}
315
316func groupsToUpdateToDelete(newGroups, existingGroups []*ofp.OfpGroupEntry) (updatedNewGroups, groupsToDelete, updatedAllGroups []*ofp.OfpGroupEntry) {
317 for _, group := range existingGroups {
318 if idx := fu.FindGroup(newGroups, group.Desc.GroupId); idx == -1 { // does not exist now
319 updatedAllGroups = append(updatedAllGroups, group)
320 } else {
321 // Follow same logic as flows
322 if proto.Equal(newGroups[idx], group) {
323 // Group already exist, remove it from the new groups
324 newGroups = deleteGroupWithoutPreservingOrder(newGroups, idx)
325 updatedAllGroups = append(updatedAllGroups, group)
326 } else {
327 // Minor change to group, delete old and add new one
328 groupsToDelete = append(groupsToDelete, group)
329 }
330 }
331 }
332 updatedAllGroups = append(updatedAllGroups, newGroups...)
333 return newGroups, groupsToDelete, updatedAllGroups
334}
335
npujar467fe752020-01-16 20:17:45 +0530336func (agent *DeviceAgent) addFlowsAndGroupsToAdapter(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530337 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400338
khenaidoo2c6a0992019-04-29 13:46:56 -0400339 if (len(newFlows) | len(newGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530340 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800341 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400342 }
343
khenaidoo19d7b632018-10-30 10:49:50 -0400344 agent.lockDevice.Lock()
345 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400346
khenaidoo6e55d9e2019-12-12 18:26:26 -0500347 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400348 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
349 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
350
khenaidoo0458db62019-06-20 08:50:36 -0400351 // Process flows
khenaidoob2121e52019-12-16 17:17:22 -0500352 newFlows, flowsToDelete, updatedAllFlows := flowsToUpdateToDelete(newFlows, existingFlows.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400353
354 // Process groups
khenaidoob2121e52019-12-16 17:17:22 -0500355 newGroups, groupsToDelete, updatedAllGroups := groupsToUpdateToDelete(newGroups, existingGroups.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400356
357 // Sanity check
khenaidoob2121e52019-12-16 17:17:22 -0500358 if (len(updatedAllFlows) | len(flowsToDelete) | len(updatedAllGroups) | len(groupsToDelete)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530359 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800360 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400361 }
362
363 // Send update to adapters
364 // Create two channels to receive responses from the dB and from the adapters.
365 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
366 // to send their responses. These channels will be garbage collected once all the responses are
367 // received
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500368 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400369 dType := agent.adapterMgr.getDeviceType(device.Type)
khenaidooe7be1332020-01-24 18:58:33 -0500370 if dType == nil {
371 log.Errorw("non-existent device type", log.Fields{"deviceType": device.Type})
372 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent device type %s", device.Type)
373 }
khenaidoo0458db62019-06-20 08:50:36 -0400374 if !dType.AcceptsAddRemoveFlowUpdates {
375
khenaidoob2121e52019-12-16 17:17:22 -0500376 if len(updatedAllGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedAllGroups) && len(updatedAllFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedAllFlows) {
npujar1d86a522019-11-14 17:11:16 +0530377 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800378 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400379 }
npujar467fe752020-01-16 20:17:45 +0530380 go agent.sendBulkFlowsToAdapters(ctx, device, &voltha.Flows{Items: updatedAllFlows}, &voltha.FlowGroups{Items: updatedAllGroups}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400381
382 } else {
383 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400384 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400385 ToRemove: &voltha.Flows{Items: flowsToDelete},
386 }
387 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400388 ToAdd: &voltha.FlowGroups{Items: newGroups},
389 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400390 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
391 }
npujar467fe752020-01-16 20:17:45 +0530392 go agent.sendIncrementalFlowsToAdapters(ctx, device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400393 }
394
395 // store the changed data
khenaidoob2121e52019-12-16 17:17:22 -0500396 device.Flows = &voltha.Flows{Items: updatedAllFlows}
397 device.FlowGroups = &voltha.FlowGroups{Items: updatedAllGroups}
npujar467fe752020-01-16 20:17:45 +0530398 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800399 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500400 }
khenaidoo0458db62019-06-20 08:50:36 -0400401
A R Karthick5c28f552019-12-11 22:47:44 -0800402 return response, nil
403}
404
405//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
406//adapters
npujar467fe752020-01-16 20:17:45 +0530407func (agent *DeviceAgent) addFlowsAndGroups(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
408 response, err := agent.addFlowsAndGroupsToAdapter(ctx, newFlows, newGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800409 if err != nil {
410 return err
411 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500412 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400413 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400414 return status.Errorf(codes.Aborted, "errors-%s", res)
415 }
khenaidoo0458db62019-06-20 08:50:36 -0400416 return nil
417}
418
npujar467fe752020-01-16 20:17:45 +0530419func (agent *DeviceAgent) deleteFlowsAndGroupsFromAdapter(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530420 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400421
422 if (len(flowsToDel) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530423 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800424 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400425 }
426
427 agent.lockDevice.Lock()
428 defer agent.lockDevice.Unlock()
429
khenaidoo6e55d9e2019-12-12 18:26:26 -0500430 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400431
432 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
433 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
434
435 var flowsToKeep []*ofp.OfpFlowStats
436 var groupsToKeep []*ofp.OfpGroupEntry
437
438 // Process flows
439 for _, flow := range existingFlows.Items {
440 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
441 flowsToKeep = append(flowsToKeep, flow)
442 }
443 }
444
445 // Process groups
446 for _, group := range existingGroups.Items {
447 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
448 groupsToKeep = append(groupsToKeep, group)
449 }
450 }
451
452 log.Debugw("deleteFlowsAndGroups",
453 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530454 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400455 "flowsToDel": len(flowsToDel),
456 "flowsToKeep": len(flowsToKeep),
457 "groupsToDel": len(groupsToDel),
458 "groupsToKeep": len(groupsToKeep),
459 })
460
461 // Sanity check
462 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530463 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800464 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400465 }
466
467 // Send update to adapters
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500468 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400469 dType := agent.adapterMgr.getDeviceType(device.Type)
khenaidooe7be1332020-01-24 18:58:33 -0500470 if dType == nil {
471 log.Errorw("non-existent device type", log.Fields{"deviceType": device.Type})
472 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent device type %s", device.Type)
473 }
khenaidoo0458db62019-06-20 08:50:36 -0400474 if !dType.AcceptsAddRemoveFlowUpdates {
475 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
npujar1d86a522019-11-14 17:11:16 +0530476 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800477 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400478 }
npujar467fe752020-01-16 20:17:45 +0530479 go agent.sendBulkFlowsToAdapters(ctx, device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400480 } else {
481 flowChanges := &ofp.FlowChanges{
482 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
483 ToRemove: &voltha.Flows{Items: flowsToDel},
484 }
485 groupChanges := &ofp.FlowGroupChanges{
486 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
487 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
488 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
489 }
npujar467fe752020-01-16 20:17:45 +0530490 go agent.sendIncrementalFlowsToAdapters(ctx, device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400491 }
492
493 // store the changed data
494 device.Flows = &voltha.Flows{Items: flowsToKeep}
495 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
npujar467fe752020-01-16 20:17:45 +0530496 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800497 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500498 }
khenaidoo0458db62019-06-20 08:50:36 -0400499
A R Karthick5c28f552019-12-11 22:47:44 -0800500 return response, nil
501
502}
503
504//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
505//adapters
npujar467fe752020-01-16 20:17:45 +0530506func (agent *DeviceAgent) deleteFlowsAndGroups(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
507 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDel, groupsToDel, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800508 if err != nil {
509 return err
510 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500511 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400512 return status.Errorf(codes.Aborted, "errors-%s", res)
513 }
514 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400515}
516
npujar467fe752020-01-16 20:17:45 +0530517func (agent *DeviceAgent) updateFlowsAndGroupsToAdapter(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530518 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400519
520 if (len(updatedFlows) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530521 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800522 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400523 }
524
525 agent.lockDevice.Lock()
526 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500527
528 device := agent.getDeviceWithoutLock()
529
khenaidoo0458db62019-06-20 08:50:36 -0400530 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
531 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
532
533 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530534 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800535 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400536 }
537
538 log.Debugw("updating-flows-and-groups",
539 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530540 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400541 "updatedFlows": updatedFlows,
542 "updatedGroups": updatedGroups,
543 })
544
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500545 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400546 dType := agent.adapterMgr.getDeviceType(device.Type)
khenaidooe7be1332020-01-24 18:58:33 -0500547 if dType == nil {
548 log.Errorw("non-existent device type", log.Fields{"deviceType": device.Type})
549 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent device type %s", device.Type)
550 }
khenaidoo0458db62019-06-20 08:50:36 -0400551
552 // Process bulk flow update differently than incremental update
553 if !dType.AcceptsAddRemoveFlowUpdates {
npujar467fe752020-01-16 20:17:45 +0530554 go agent.sendBulkFlowsToAdapters(ctx, device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, response)
khenaidoo0458db62019-06-20 08:50:36 -0400555 } else {
556 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400557 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400558 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400559 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400560
561 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400562 for _, flow := range updatedFlows {
563 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
564 flowsToAdd = append(flowsToAdd, flow)
565 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400566 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400567 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400568 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400569 flowsToDelete = append(flowsToDelete, flow)
570 }
571 }
572
573 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400574 for _, g := range updatedGroups {
575 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
576 groupsToAdd = append(groupsToAdd, g)
577 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400578 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400579 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400580 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400581 groupsToDelete = append(groupsToDelete, group)
582 }
583 }
584
khenaidoo0458db62019-06-20 08:50:36 -0400585 log.Debugw("updating-flows-and-groups",
586 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530587 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400588 "flowsToAdd": flowsToAdd,
589 "flowsToDelete": flowsToDelete,
590 "groupsToAdd": groupsToAdd,
591 "groupsToDelete": groupsToDelete,
592 })
593
khenaidoo2c6a0992019-04-29 13:46:56 -0400594 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400595 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530596 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800597 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400598 }
599
khenaidoo0458db62019-06-20 08:50:36 -0400600 flowChanges := &ofp.FlowChanges{
601 ToAdd: &voltha.Flows{Items: flowsToAdd},
602 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400603 }
khenaidoo0458db62019-06-20 08:50:36 -0400604 groupChanges := &ofp.FlowGroupChanges{
605 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
606 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
607 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
608 }
npujar467fe752020-01-16 20:17:45 +0530609 go agent.sendIncrementalFlowsToAdapters(ctx, device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo19d7b632018-10-30 10:49:50 -0400610 }
khenaidoo0458db62019-06-20 08:50:36 -0400611
612 // store the updated data
613 device.Flows = &voltha.Flows{Items: updatedFlows}
614 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
npujar467fe752020-01-16 20:17:45 +0530615 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800616 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500617 }
khenaidoo0458db62019-06-20 08:50:36 -0400618
A R Karthick5c28f552019-12-11 22:47:44 -0800619 return response, nil
620}
621
622//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
623//also sends the updates to the adapters
npujar467fe752020-01-16 20:17:45 +0530624func (agent *DeviceAgent) updateFlowsAndGroups(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
625 response, err := agent.updateFlowsAndGroupsToAdapter(ctx, updatedFlows, updatedGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800626 if err != nil {
627 return err
628 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500629 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400630 return status.Errorf(codes.Aborted, "errors-%s", res)
631 }
632 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400633}
634
khenaidoo4d4802d2018-10-04 21:59:49 -0400635//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400636func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400637 agent.lockDevice.Lock()
638 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530639 log.Debugw("disableDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500640
641 cloned := agent.getDeviceWithoutLock()
642
643 if cloned.AdminState == voltha.AdminState_DISABLED {
npujar1d86a522019-11-14 17:11:16 +0530644 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
645 return nil
646 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500647 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
648 cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530649 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500650 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530651 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400652
npujar1d86a522019-11-14 17:11:16 +0530653 // Update the Admin State and operational state before sending the request out
npujar1d86a522019-11-14 17:11:16 +0530654 cloned.AdminState = voltha.AdminState_DISABLED
655 cloned.OperStatus = voltha.OperStatus_UNKNOWN
npujar467fe752020-01-16 20:17:45 +0530656 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530657 return err
658 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500659 if err := agent.adapterProxy.DisableDevice(ctx, proto.Clone(cloned).(*voltha.Device)); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530660 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
661 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400662 }
663 return nil
664}
665
npujar467fe752020-01-16 20:17:45 +0530666func (agent *DeviceAgent) updateAdminState(ctx context.Context, adminState voltha.AdminState_Types) error {
khenaidoo0a822f92019-05-08 15:15:57 -0400667 agent.lockDevice.Lock()
668 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530669 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500670
671 cloned := agent.getDeviceWithoutLock()
672
673 if cloned.AdminState == adminState {
npujar1d86a522019-11-14 17:11:16 +0530674 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceID, "state": adminState})
675 return nil
676 }
677 // Received an Ack (no error found above). Now update the device in the model to the expected state
npujar1d86a522019-11-14 17:11:16 +0530678 cloned.AdminState = adminState
npujar467fe752020-01-16 20:17:45 +0530679 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530680 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400681 }
682 return nil
683}
684
khenaidoo4d4802d2018-10-04 21:59:49 -0400685func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
686 agent.lockDevice.Lock()
687 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530688 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500689
690 device := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530691 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
692 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceID, "error": err})
693 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400694 }
695 return nil
696}
697
698func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
699 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400700 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530701 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500702
703 cloned := agent.getDeviceWithoutLock()
704 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530705 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceID})
706 return nil
707 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500708 if cloned.AdminState != voltha.AdminState_PREPROVISIONED {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500709 if err := agent.adapterProxy.DeleteDevice(ctx, cloned); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530710 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceID, "error": err})
Mahir Gunyelb5851672019-07-24 10:46:26 +0300711 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400712 }
npujar1d86a522019-11-14 17:11:16 +0530713 }
Chaitrashree G S543df3e2020-02-24 22:36:54 -0500714 //Set the state to deleted - this will trigger some background process to invoke parent adapter to delete child
715 //device and clean up the device as well as its association with the logical device
npujar1d86a522019-11-14 17:11:16 +0530716 cloned.AdminState = voltha.AdminState_DELETED
Chaitrashree G S543df3e2020-02-24 22:36:54 -0500717
npujar467fe752020-01-16 20:17:45 +0530718 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530719 return err
720 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400721 return nil
722}
723
npujar467fe752020-01-16 20:17:45 +0530724func (agent *DeviceAgent) setParentID(ctx context.Context, device *voltha.Device, parentID string) error {
khenaidooad06fd72019-10-28 12:26:05 -0400725 agent.lockDevice.Lock()
726 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530727 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500728
729 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530730 cloned.ParentId = parentID
731 // Store the device
npujar467fe752020-01-16 20:17:45 +0530732 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530733 return err
734 }
735 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400736}
737
khenaidoob3127472019-07-24 21:04:55 -0400738func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
739 agent.lockDevice.Lock()
740 defer agent.lockDevice.Unlock()
741 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500742
743 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530744 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
745 // Store the device
npujar467fe752020-01-16 20:17:45 +0530746 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530747 return err
748 }
749 // Send the request to the adapter
750 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
751 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceID, "error": err})
752 return err
753 }
754 return nil
khenaidoob3127472019-07-24 21:04:55 -0400755}
756
npujar467fe752020-01-16 20:17:45 +0530757func (agent *DeviceAgent) initPmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoob3127472019-07-24 21:04:55 -0400758 agent.lockDevice.Lock()
759 defer agent.lockDevice.Unlock()
760 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500761
762 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530763 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
764 // Store the device
npujar467fe752020-01-16 20:17:45 +0530765 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Thomas Lee Se5a44012019-11-07 20:32:24 +0530766 afterUpdate, err := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, cloned, false, "")
767 if err != nil {
768 return status.Errorf(codes.Internal, "%s", agent.deviceID)
769 }
npujar1d86a522019-11-14 17:11:16 +0530770 if afterUpdate == nil {
771 return status.Errorf(codes.Internal, "%s", agent.deviceID)
772 }
773 return nil
khenaidoob3127472019-07-24 21:04:55 -0400774}
775
776func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
777 agent.lockDevice.RLock()
778 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530779 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500780
781 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400782}
783
khenaidoof5a5bfa2019-01-23 22:20:29 -0500784func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
785 agent.lockDevice.Lock()
786 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530787 log.Debugw("downloadImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500788
789 device := agent.getDeviceWithoutLock()
790
npujar1d86a522019-11-14 17:11:16 +0530791 if device.AdminState != voltha.AdminState_ENABLED {
792 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
793 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
794 }
795 // Save the image
796 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
797 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
798 cloned := proto.Clone(device).(*voltha.Device)
799 if cloned.ImageDownloads == nil {
800 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500801 } else {
802 if device.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530803 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
804 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500805 }
806 // Save the image
807 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500808 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500809 cloned := proto.Clone(device).(*voltha.Device)
810 if cloned.ImageDownloads == nil {
811 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
812 } else {
813 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
814 }
815 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
npujar467fe752020-01-16 20:17:45 +0530816 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
Mahir Gunyelb5851672019-07-24 10:46:26 +0300817 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500818 }
819 // Send the request to the adapter
820 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530821 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500822 return nil, err
823 }
824 }
825 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
826}
827
828// isImageRegistered is a helper method to figure out if an image is already registered
829func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
830 for _, image := range device.ImageDownloads {
831 if image.Id == img.Id && image.Name == img.Name {
832 return true
833 }
834 }
835 return false
836}
837
838func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
839 agent.lockDevice.Lock()
840 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530841 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500842
843 device := agent.getDeviceWithoutLock()
844
npujar1d86a522019-11-14 17:11:16 +0530845 // Verify whether the Image is in the list of image being downloaded
846 if !isImageRegistered(img, device) {
847 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
848 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500849
npujar1d86a522019-11-14 17:11:16 +0530850 // Update image download state
851 cloned := proto.Clone(device).(*voltha.Device)
852 for _, image := range cloned.ImageDownloads {
853 if image.Id == img.Id && image.Name == img.Name {
854 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500855 }
npujar1d86a522019-11-14 17:11:16 +0530856 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500857
npujar1d86a522019-11-14 17:11:16 +0530858 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
859 // Set the device to Enabled
860 cloned.AdminState = voltha.AdminState_ENABLED
npujar467fe752020-01-16 20:17:45 +0530861 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530862 return nil, err
863 }
864 // Send the request to the adapter
865 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
866 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
867 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500868 }
869 }
870 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700871}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500872
873func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
874 agent.lockDevice.Lock()
875 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530876 log.Debugw("activateImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500877 cloned := agent.getDeviceWithoutLock()
878
npujar1d86a522019-11-14 17:11:16 +0530879 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500880 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530881 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
882 }
883
khenaidoo6e55d9e2019-12-12 18:26:26 -0500884 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
npujar1d86a522019-11-14 17:11:16 +0530885 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
886 }
887 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530888 for _, image := range cloned.ImageDownloads {
889 if image.Id == img.Id && image.Name == img.Name {
890 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
891 }
892 }
893 // Set the device to downloading_image
894 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
npujar467fe752020-01-16 20:17:45 +0530895 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530896 return nil, err
897 }
898
khenaidoo6e55d9e2019-12-12 18:26:26 -0500899 if err := agent.adapterProxy.ActivateImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530900 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
901 return nil, err
902 }
903 // The status of the AdminState will be changed following the update_download_status response from the adapter
904 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -0700905 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
906}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500907
908func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
909 agent.lockDevice.Lock()
910 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530911 log.Debugw("revertImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500912
913 cloned := agent.getDeviceWithoutLock()
914
npujar1d86a522019-11-14 17:11:16 +0530915 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500916 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530917 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
918 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500919
khenaidoo6e55d9e2019-12-12 18:26:26 -0500920 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530921 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
922 }
923 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530924 for _, image := range cloned.ImageDownloads {
925 if image.Id == img.Id && image.Name == img.Name {
926 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -0500927 }
npujar1d86a522019-11-14 17:11:16 +0530928 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300929
npujar467fe752020-01-16 20:17:45 +0530930 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530931 return nil, err
932 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500933
khenaidoo6e55d9e2019-12-12 18:26:26 -0500934 if err := agent.adapterProxy.RevertImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530935 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
936 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500937 }
938 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700939}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500940
941func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
942 agent.lockDevice.Lock()
943 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530944 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500945
946 cloned := agent.getDeviceWithoutLock()
947 resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, cloned, img)
npujar1d86a522019-11-14 17:11:16 +0530948 if err != nil {
949 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
950 return nil, err
951 }
952 return resp, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500953}
954
npujar467fe752020-01-16 20:17:45 +0530955func (agent *DeviceAgent) updateImageDownload(ctx context.Context, img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500956 agent.lockDevice.Lock()
957 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530958 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500959
960 cloned := agent.getDeviceWithoutLock()
961
npujar1d86a522019-11-14 17:11:16 +0530962 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +0530963 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
964 for _, image := range cloned.ImageDownloads {
965 if image.Id == img.Id && image.Name == img.Name {
966 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
967 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500968 }
969 }
npujar1d86a522019-11-14 17:11:16 +0530970 }
971 cloned.ImageDownloads = clonedImages
972 // Set the Admin state to enabled if required
973 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
974 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
975 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
976 cloned.AdminState = voltha.AdminState_ENABLED
977 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500978
npujar467fe752020-01-16 20:17:45 +0530979 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530980 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500981 }
982 return nil
983}
984
985func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400986 agent.lockDevice.RLock()
987 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530988 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500989
990 cloned := agent.getDeviceWithoutLock()
991 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +0530992 if image.Id == img.Id && image.Name == img.Name {
993 return image, nil
994 }
995 }
996 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500997}
998
npujar1d86a522019-11-14 17:11:16 +0530999func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -04001000 agent.lockDevice.RLock()
1001 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +05301002 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001003
1004 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001005}
1006
khenaidoo4d4802d2018-10-04 21:59:49 -04001007// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -04001008func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
npujar1d86a522019-11-14 17:11:16 +05301009 log.Debugw("getPorts", log.Fields{"id": agent.deviceID, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -04001010 ports := &voltha.Ports{}
npujar467fe752020-01-16 20:17:45 +05301011 if device, _ := agent.deviceMgr.GetDevice(ctx, agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -04001012 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -04001013 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -04001014 ports.Items = append(ports.Items, port)
1015 }
1016 }
1017 }
1018 return ports
1019}
1020
khenaidoo4d4802d2018-10-04 21:59:49 -04001021// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
1022// parent device
khenaidoo79232702018-12-04 11:00:41 -05001023func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301024 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceID})
npujar467fe752020-01-16 20:17:45 +05301025 device, err := agent.deviceMgr.GetDevice(ctx, agent.deviceID)
npujar1d86a522019-11-14 17:11:16 +05301026 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001027 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001028 }
npujar1d86a522019-11-14 17:11:16 +05301029 var switchCap *ic.SwitchCapability
1030 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
1031 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
1032 return nil, err
1033 }
1034 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001035}
1036
khenaidoo4d4802d2018-10-04 21:59:49 -04001037// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
1038// device
khenaidoo79232702018-12-04 11:00:41 -05001039func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301040 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceID})
npujar467fe752020-01-16 20:17:45 +05301041 device, err := agent.deviceMgr.GetDevice(ctx, agent.deviceID)
npujar1d86a522019-11-14 17:11:16 +05301042 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001043 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001044 }
npujar1d86a522019-11-14 17:11:16 +05301045 var portCap *ic.PortCapability
1046 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
1047 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1048 return nil, err
1049 }
1050 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001051}
1052
npujar467fe752020-01-16 20:17:45 +05301053func (agent *DeviceAgent) packetOut(ctx context.Context, outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001054 // If deviceType=="" then we must have taken ownership of this device.
1055 // Fixes VOL-2226 where a core would take ownership and have stale data
1056 if agent.deviceType == "" {
npujar467fe752020-01-16 20:17:45 +05301057 agent.reconcileWithKVStore(ctx)
Scott Baker80678602019-11-14 16:57:36 -08001058 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001059 // Send packet to adapter
npujar467fe752020-01-16 20:17:45 +05301060 if err := agent.adapterProxy.packetOut(ctx, agent.deviceType, agent.deviceID, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001061 log.Debugw("packet-out-error", log.Fields{
npujar1d86a522019-11-14 17:11:16 +05301062 "id": agent.deviceID,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001063 "error": err,
1064 "packet": hex.EncodeToString(packet.Data),
1065 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001066 return err
1067 }
1068 return nil
1069}
1070
khenaidoo4d4802d2018-10-04 21:59:49 -04001071// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
npujar467fe752020-01-16 20:17:45 +05301072func (agent *DeviceAgent) processUpdate(ctx context.Context, args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001073 //// Run this callback in its own go routine
1074 go func(args ...interface{}) interface{} {
1075 var previous *voltha.Device
1076 var current *voltha.Device
1077 var ok bool
1078 if len(args) == 2 {
1079 if previous, ok = args[0].(*voltha.Device); !ok {
1080 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1081 return nil
1082 }
1083 if current, ok = args[1].(*voltha.Device); !ok {
1084 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1085 return nil
1086 }
1087 } else {
1088 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1089 return nil
1090 }
npujar467fe752020-01-16 20:17:45 +05301091 // Perform the state transition in it's own go routine (since the caller doesn't wait for this, use a background context)
1092 if err := agent.deviceMgr.processTransition(context.Background(), previous, current); err != nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -05001093 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1094 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1095 }
khenaidoo43c82122018-11-22 18:38:28 -05001096 return nil
1097 }(args...)
1098
khenaidoo92e62c52018-10-03 14:02:54 -04001099 return nil
1100}
1101
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001102// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1103// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1104func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001105 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001106 cloned.Root = device.Root
1107 cloned.Vendor = device.Vendor
1108 cloned.Model = device.Model
1109 cloned.SerialNumber = device.SerialNumber
1110 cloned.MacAddress = device.MacAddress
1111 cloned.Vlan = device.Vlan
1112 cloned.Reason = device.Reason
1113 return cloned, nil
1114}
npujar467fe752020-01-16 20:17:45 +05301115func (agent *DeviceAgent) updateDeviceUsingAdapterData(ctx context.Context, device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001116 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001117 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001118 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
npujar1d86a522019-11-14 17:11:16 +05301119 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1120 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001121 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1122 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001123 }
npujar1d86a522019-11-14 17:11:16 +05301124 cloned := proto.Clone(updatedDevice).(*voltha.Device)
npujar467fe752020-01-16 20:17:45 +05301125 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001126}
1127
npujar467fe752020-01-16 20:17:45 +05301128func (agent *DeviceAgent) updateDeviceWithoutLock(ctx context.Context, device *voltha.Device) error {
khenaidoo43c82122018-11-22 18:38:28 -05001129 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1130 cloned := proto.Clone(device).(*voltha.Device)
npujar467fe752020-01-16 20:17:45 +05301131 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001132}
1133
npujar467fe752020-01-16 20:17:45 +05301134func (agent *DeviceAgent) updateDeviceStatus(ctx context.Context, operStatus voltha.OperStatus_Types, connStatus voltha.ConnectStatus_Types) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001135 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001136 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001137
1138 cloned := agent.getDeviceWithoutLock()
1139
npujar1d86a522019-11-14 17:11:16 +05301140 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001141 if s, ok := voltha.ConnectStatus_Types_value[connStatus.String()]; ok {
npujar1d86a522019-11-14 17:11:16 +05301142 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1143 cloned.ConnectStatus = connStatus
1144 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001145 if s, ok := voltha.OperStatus_Types_value[operStatus.String()]; ok {
npujar1d86a522019-11-14 17:11:16 +05301146 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1147 cloned.OperStatus = operStatus
1148 }
1149 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
1150 // Store the device
npujar467fe752020-01-16 20:17:45 +05301151 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001152}
1153
kesavandbc2d1622020-01-21 00:42:01 -05001154func (agent *DeviceAgent) updatePortsOperState(ctx context.Context, operStatus voltha.OperStatus_Types) error {
1155 log.Debugw("updatePortsOperState", log.Fields{"device-id": agent.deviceID})
khenaidoo3ab34882019-05-02 21:33:30 -04001156 agent.lockDevice.Lock()
1157 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001158 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301159 for _, port := range cloned.Ports {
kesavandbc2d1622020-01-21 00:42:01 -05001160 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301161 }
1162 // Store the device
npujar467fe752020-01-16 20:17:45 +05301163 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001164}
1165
npujar467fe752020-01-16 20:17:45 +05301166func (agent *DeviceAgent) updatePortState(ctx context.Context, portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_Types) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001167 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001168 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001169 // Work only on latest data
1170 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001171 cloned := agent.getDeviceWithoutLock()
1172
npujar1d86a522019-11-14 17:11:16 +05301173 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1174 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1175 return status.Errorf(codes.InvalidArgument, "%s", portType)
1176 }
1177 for _, port := range cloned.Ports {
1178 if port.Type == portType && port.PortNo == portNo {
1179 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301180 }
1181 }
1182 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1183 // Store the device
npujar467fe752020-01-16 20:17:45 +05301184 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001185}
1186
npujar467fe752020-01-16 20:17:45 +05301187func (agent *DeviceAgent) deleteAllPorts(ctx context.Context) error {
npujar1d86a522019-11-14 17:11:16 +05301188 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -04001189 agent.lockDevice.Lock()
1190 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001191
1192 cloned := agent.getDeviceWithoutLock()
1193
1194 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1195 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
1196 log.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301197 return err
1198 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001199 if len(cloned.Ports) == 0 {
npujar1d86a522019-11-14 17:11:16 +05301200 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
1201 return nil
1202 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001203
npujar1d86a522019-11-14 17:11:16 +05301204 cloned.Ports = []*voltha.Port{}
1205 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1206 // Store the device
npujar467fe752020-01-16 20:17:45 +05301207 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001208}
1209
npujar467fe752020-01-16 20:17:45 +05301210func (agent *DeviceAgent) addPort(ctx context.Context, port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001211 agent.lockDevice.Lock()
1212 defer agent.lockDevice.Unlock()
khenaidoo80b987d2020-02-20 10:52:52 -05001213 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceID, "port": port})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001214
1215 cloned := agent.getDeviceWithoutLock()
khenaidoo80b987d2020-02-20 10:52:52 -05001216 updatePort := false
npujar1d86a522019-11-14 17:11:16 +05301217 if cloned.Ports == nil {
1218 // First port
1219 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
1220 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001221 } else {
npujar1d86a522019-11-14 17:11:16 +05301222 for _, p := range cloned.Ports {
1223 if p.Type == port.Type && p.PortNo == port.PortNo {
khenaidoo80b987d2020-02-20 10:52:52 -05001224 if p.Label == "" && p.Type == voltha.Port_PON_OLT {
1225 //Creation of OLT PON port is being processed after a default PON port was created. Just update it.
1226 log.Infow("update-pon-port-created-by-default", log.Fields{"default-port": p, "port-to-add": port})
1227 p.Label = port.Label
1228 p.OperStatus = port.OperStatus
1229 updatePort = true
1230 break
1231 }
1232 log.Debugw("port already exists", log.Fields{"port": port})
npujar1d86a522019-11-14 17:11:16 +05301233 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001234 }
khenaidoob9203542018-09-17 22:56:37 -04001235 }
khenaidoo92e62c52018-10-03 14:02:54 -04001236 }
khenaidoo80b987d2020-02-20 10:52:52 -05001237 if !updatePort {
1238 cp := proto.Clone(port).(*voltha.Port)
1239 // Set the admin state of the port to ENABLE
1240 cp.AdminState = voltha.AdminState_ENABLED
1241 cloned.Ports = append(cloned.Ports, cp)
1242 }
npujar1d86a522019-11-14 17:11:16 +05301243 // Store the device
npujar467fe752020-01-16 20:17:45 +05301244 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001245}
1246
khenaidoo80b987d2020-02-20 10:52:52 -05001247func (agent *DeviceAgent) addPeerPort(ctx context.Context, peerPort *voltha.Port_PeerPort) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001248 agent.lockDevice.Lock()
1249 defer agent.lockDevice.Unlock()
khenaidoo80b987d2020-02-20 10:52:52 -05001250 log.Debugw("adding-peer-peerPort", log.Fields{"device-id": agent.deviceID, "peer-peerPort": peerPort})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001251
1252 cloned := agent.getDeviceWithoutLock()
1253
khenaidoo80b987d2020-02-20 10:52:52 -05001254 // Get the peer port on the device based on the peerPort no
1255 found := false
1256 for _, port := range cloned.Ports {
1257 if port.PortNo == peerPort.PortNo { // found peerPort
1258 cp := proto.Clone(peerPort).(*voltha.Port_PeerPort)
1259 port.Peers = append(port.Peers, cp)
1260 log.Debugw("found-peer", log.Fields{"device-id": agent.deviceID, "portNo": peerPort.PortNo, "deviceId": agent.deviceID})
1261 found = true
npujar1d86a522019-11-14 17:11:16 +05301262 break
1263 }
1264 }
khenaidoo80b987d2020-02-20 10:52:52 -05001265 if !found && agent.isRootdevice {
1266 // An ONU PON port has been created before the corresponding creation of the OLT PON port. Create the OLT PON port
1267 // with default values which will be updated once the OLT PON port creation is processed.
1268 ponPort := &voltha.Port{
1269 PortNo: peerPort.PortNo,
1270 Type: voltha.Port_PON_OLT,
1271 AdminState: voltha.AdminState_ENABLED,
1272 DeviceId: agent.deviceID,
1273 Peers: []*voltha.Port_PeerPort{proto.Clone(peerPort).(*voltha.Port_PeerPort)},
1274 }
1275 cloned.Ports = append(cloned.Ports, ponPort)
1276 log.Infow("adding-default-pon-port", log.Fields{"device-id": agent.deviceID, "peer": peerPort, "pon-port": ponPort})
1277 }
npujar1d86a522019-11-14 17:11:16 +05301278 // Store the device
npujar467fe752020-01-16 20:17:45 +05301279 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001280}
1281
npujar467fe752020-01-16 20:17:45 +05301282func (agent *DeviceAgent) deletePeerPorts(ctx context.Context, deviceID string) error {
khenaidoo0a822f92019-05-08 15:15:57 -04001283 log.Debug("deletePeerPorts")
khenaidoo6e55d9e2019-12-12 18:26:26 -05001284
1285 cloned := agent.getDeviceWithoutLock()
1286
npujar1d86a522019-11-14 17:11:16 +05301287 var updatedPeers []*voltha.Port_PeerPort
1288 for _, port := range cloned.Ports {
1289 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1290 for _, peerPort := range port.Peers {
1291 if peerPort.DeviceId != deviceID {
1292 updatedPeers = append(updatedPeers, peerPort)
1293 }
1294 }
1295 port.Peers = updatedPeers
1296 }
1297
1298 // Store the device with updated peer ports
npujar467fe752020-01-16 20:17:45 +05301299 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001300}
1301
khenaidoob9203542018-09-17 22:56:37 -04001302// TODO: A generic device update by attribute
npujar467fe752020-01-16 20:17:45 +05301303func (agent *DeviceAgent) updateDeviceAttribute(ctx context.Context, name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001304 agent.lockDevice.Lock()
1305 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001306 if value == nil {
1307 return
1308 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001309
1310 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001311 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001312 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001313 if s.Kind() == reflect.Struct {
1314 // exported field
1315 f := s.FieldByName(name)
1316 if f.IsValid() && f.CanSet() {
1317 switch f.Kind() {
1318 case reflect.String:
1319 f.SetString(value.(string))
1320 updated = true
1321 case reflect.Uint32:
1322 f.SetUint(uint64(value.(uint32)))
1323 updated = true
1324 case reflect.Bool:
1325 f.SetBool(value.(bool))
1326 updated = true
1327 }
1328 }
1329 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001330 log.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001331 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001332
npujar467fe752020-01-16 20:17:45 +05301333 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001334 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1335 }
khenaidoob9203542018-09-17 22:56:37 -04001336}
serkant.uluderya334479d2019-04-10 08:26:15 -07001337
1338func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1339 agent.lockDevice.Lock()
1340 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301341 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001342
1343 cloned := agent.getDeviceWithoutLock()
1344
npujar1d86a522019-11-14 17:11:16 +05301345 // First send the request to an Adapter and wait for a response
khenaidoo6e55d9e2019-12-12 18:26:26 -05001346 if err := agent.adapterProxy.SimulateAlarm(ctx, cloned, simulatereq); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301347 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceID, "error": err})
1348 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001349 }
1350 return nil
1351}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001352
1353//This is an update operation to model without Lock.This function must never be invoked by another function unless the latter holds a lock on the device.
1354// It is an internal helper function.
npujar467fe752020-01-16 20:17:45 +05301355func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(ctx context.Context, device *voltha.Device, strict bool, txid string) error {
1356 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Thomas Lee Se5a44012019-11-07 20:32:24 +05301357 afterUpdate, err := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, device, strict, txid)
1358 if err != nil {
1359 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
1360 }
1361 if afterUpdate == nil {
npujar1d86a522019-11-14 17:11:16 +05301362 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001363 }
npujar1d86a522019-11-14 17:11:16 +05301364 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001365
khenaidoo6e55d9e2019-12-12 18:26:26 -05001366 agent.device = proto.Clone(device).(*voltha.Device)
1367
Mahir Gunyelb5851672019-07-24 10:46:26 +03001368 return nil
1369}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001370
npujar467fe752020-01-16 20:17:45 +05301371func (agent *DeviceAgent) updateDeviceReason(ctx context.Context, reason string) error {
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001372 agent.lockDevice.Lock()
1373 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001374
1375 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301376 cloned.Reason = reason
1377 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1378 // Store the device
npujar467fe752020-01-16 20:17:45 +05301379 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001380}
kesavandbc2d1622020-01-21 00:42:01 -05001381
1382func (agent *DeviceAgent) disablePort(ctx context.Context, Port *voltha.Port) error {
1383 var cp *voltha.Port
1384 agent.lockDevice.Lock()
1385 defer agent.lockDevice.Unlock()
1386 log.Debugw("disablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
1387 // Get the most up to date the device info
1388 device := agent.getDeviceWithoutLock()
1389 for _, port := range device.Ports {
1390 if port.PortNo == Port.PortNo {
1391 port.AdminState = voltha.AdminState_DISABLED
1392 cp = proto.Clone(port).(*voltha.Port)
1393 break
1394
1395 }
1396 }
1397 if cp == nil {
1398 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1399 }
1400
1401 if cp.Type != voltha.Port_PON_OLT {
1402 return status.Errorf(codes.InvalidArgument, "Disabling of Port Type %v unimplemented", cp.Type)
1403 }
1404 // Store the device
1405 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
1406 log.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
1407 return err
1408 }
1409 //send request to adapter
1410 if err := agent.adapterProxy.disablePort(ctx, device, cp); err != nil {
1411 log.Debugw("DisablePort-error", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
1412 return err
1413 }
1414 return nil
1415}
1416
1417func (agent *DeviceAgent) enablePort(ctx context.Context, Port *voltha.Port) error {
1418 var cp *voltha.Port
1419 agent.lockDevice.Lock()
1420 defer agent.lockDevice.Unlock()
1421 log.Debugw("enablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
1422 // Get the most up to date the device info
1423 device := agent.getDeviceWithoutLock()
1424 for _, port := range device.Ports {
1425 if port.PortNo == Port.PortNo {
1426 port.AdminState = voltha.AdminState_ENABLED
1427 cp = proto.Clone(port).(*voltha.Port)
1428 break
1429 }
1430 }
1431
1432 if cp == nil {
1433 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1434 }
1435
1436 if cp.Type != voltha.Port_PON_OLT {
1437 return status.Errorf(codes.InvalidArgument, "Enabling of Port Type %v unimplemented", cp.Type)
1438 }
1439 // Store the device
1440 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
1441 log.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
1442 return err
1443 }
1444 //send request to adapter
1445 if err := agent.adapterProxy.enablePort(ctx, device, cp); err != nil {
1446 log.Debugw("EnablePort-error", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
1447 return err
1448 }
1449 return nil
1450}
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001451
1452func (agent *DeviceAgent) ChildDeviceLost(ctx context.Context, device *voltha.Device) error {
1453
1454 agent.lockDevice.Lock()
1455 defer agent.lockDevice.Unlock()
1456 log.Debugw("ChildDeviceLost", log.Fields{"id": device.Id})
1457
1458 //Remove the associated peer ports on the parent device
1459 if err := agent.deviceMgr.deletePeerPorts(ctx, device.ParentId, device.Id); err != nil {
khenaidoo67b22152020-03-02 16:01:25 -05001460 // At this stage, the parent device may also have been deleted. Just log and keep processing.
1461 log.Warnw("failure-deleting-peer-port", log.Fields{"error": err, "child-device-id": device.Id, "parent-device-id": device.ParentId})
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001462 }
1463
1464 if err := agent.adapterProxy.ChildDeviceLost(ctx, agent.deviceType, agent.deviceID, device.ParentPortNo, device.ProxyAddress.OnuId); err != nil {
1465 log.Warnw("ChildDeviceLost-error", log.Fields{"error": err})
1466 }
1467 return nil
1468
1469}