blob: 06ba307f80e74e83eba84148ec3504f3dd7ff1af [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"
Scott Baker807addd2019-10-24 15:16:21 -070030 fu "github.com/opencord/voltha-lib-go/v2/pkg/flows"
31 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Baker555307d2019-11-04 08:58:01 -080032 ic "github.com/opencord/voltha-protos/v2/go/inter_container"
33 ofp "github.com/opencord/voltha-protos/v2/go/openflow_13"
34 "github.com/opencord/voltha-protos/v2/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
npujar1d86a522019-11-14 17:11:16 +053091 if loadedDevice := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, ""); loadedDevice != nil {
Scott Baker80678602019-11-14 16:57:36 -080092 var ok bool
93 if device, ok = loadedDevice.(*voltha.Device); ok {
94 agent.deviceType = device.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -050095 agent.device = proto.Clone(device).(*voltha.Device)
Scott Baker80678602019-11-14 16:57:36 -080096 } else {
npujar1d86a522019-11-14 17:11:16 +053097 log.Errorw("failed-to-convert-device", log.Fields{"deviceId": agent.deviceID})
98 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -050099 }
100 } else {
npujar1d86a522019-11-14 17:11:16 +0530101 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceID})
102 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500103 }
npujar1d86a522019-11-14 17:11:16 +0530104 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500105 } else {
Scott Baker80678602019-11-14 16:57:36 -0800106 // Create a new device
107 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
108 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
109 // agent.deviceId will also have been set during newDeviceAgent().
110 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530111 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800112 device.AdminState = voltha.AdminState_PREPROVISIONED
113 device.FlowGroups = &ofp.FlowGroups{Items: nil}
114 device.Flows = &ofp.Flows{Items: nil}
115 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
116 // Set the default vlan ID to the one specified by the parent adapter. It can be
117 // overwritten by the child adapter during a device update request
118 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
119 }
120
khenaidoo297cd252019-02-07 22:10:23 -0500121 // Add the initial device to the local model
npujar1d86a522019-11-14 17:11:16 +0530122 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceID, device, ""); added == nil {
123 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceID})
124 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500125 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500126 agent.device = proto.Clone(device).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400127 }
khenaidoo297cd252019-02-07 22:10:23 -0500128
npujar1d86a522019-11-14 17:11:16 +0530129 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceID, false)
khenaidoo43c82122018-11-22 18:38:28 -0500130 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400131
npujar1d86a522019-11-14 17:11:16 +0530132 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceID})
Scott Baker80678602019-11-14 16:57:36 -0800133 return device, nil
khenaidoob9203542018-09-17 22:56:37 -0400134}
135
khenaidoo4d4802d2018-10-04 21:59:49 -0400136// stop stops the device agent. Not much to do for now
137func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400138 agent.lockDevice.Lock()
139 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400140 log.Debug("stopping-device-agent")
khenaidoo6e55d9e2019-12-12 18:26:26 -0500141
142 // First unregister any callbacks
143 agent.deviceProxy.UnregisterCallback(model.POST_UPDATE, agent.processUpdate)
144
khenaidoo0a822f92019-05-08 15:15:57 -0400145 // Remove the device from the KV store
npujar1d86a522019-11-14 17:11:16 +0530146 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceID, ""); removed == nil {
147 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -0400148 }
khenaidoob9203542018-09-17 22:56:37 -0400149 agent.exitChannel <- 1
150 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400151
khenaidoob9203542018-09-17 22:56:37 -0400152}
153
Scott Baker80678602019-11-14 16:57:36 -0800154// Load the most recent state from the KVStore for the device.
155func (agent *DeviceAgent) reconcileWithKVStore() {
156 agent.lockDevice.Lock()
157 defer agent.lockDevice.Unlock()
158 log.Debug("reconciling-device-agent-devicetype")
159 // TODO: context timeout
npujar1d86a522019-11-14 17:11:16 +0530160 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceID, 1, true, ""); device != nil {
Scott Baker80678602019-11-14 16:57:36 -0800161 if d, ok := device.(*voltha.Device); ok {
162 agent.deviceType = d.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -0500163 agent.device = proto.Clone(d).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530164 log.Debugw("reconciled-device-agent-devicetype", log.Fields{"Id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800165 }
166 }
167}
168
khenaidoo6e55d9e2019-12-12 18:26:26 -0500169// getDevice returns the device data from cache
170func (agent *DeviceAgent) getDevice() *voltha.Device {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400171 agent.lockDevice.RLock()
172 defer agent.lockDevice.RUnlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500173 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400174}
175
khenaidoo4d4802d2018-10-04 21:59:49 -0400176// 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 -0500177func (agent *DeviceAgent) getDeviceWithoutLock() *voltha.Device {
178 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400179}
180
khenaidoo3ab34882019-05-02 21:33:30 -0400181// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400182func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400183 agent.lockDevice.Lock()
184 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530185 log.Debugw("enableDevice", log.Fields{"id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500186
khenaidoo6e55d9e2019-12-12 18:26:26 -0500187 cloned := agent.getDeviceWithoutLock()
188
npujar1d86a522019-11-14 17:11:16 +0530189 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
190 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
191 // with the adapter then we need to know the adapter that will handle this request
khenaidoo6e55d9e2019-12-12 18:26:26 -0500192 adapterName, err := agent.adapterMgr.getAdapterName(cloned.Type)
npujar1d86a522019-11-14 17:11:16 +0530193 if err != nil {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500194 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": cloned.Type, "deviceAdapter": cloned.Adapter})
npujar1d86a522019-11-14 17:11:16 +0530195 return err
196 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500197 cloned.Adapter = adapterName
npujar1d86a522019-11-14 17:11:16 +0530198
khenaidoo6e55d9e2019-12-12 18:26:26 -0500199 if cloned.AdminState == voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530200 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceID})
201 return nil
202 }
203
khenaidoo6e55d9e2019-12-12 18:26:26 -0500204 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530205 // This is a temporary state when a device is deleted before it gets removed from the model.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500206 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", cloned.Id))
207 log.Warnw("invalid-state", log.Fields{"id": agent.deviceID, "state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +0530208 return err
209 }
210
khenaidoo6e55d9e2019-12-12 18:26:26 -0500211 previousAdminState := cloned.AdminState
npujar1d86a522019-11-14 17:11:16 +0530212
213 // Update the Admin State and set the operational state to activating before sending the request to the
214 // Adapters
npujar1d86a522019-11-14 17:11:16 +0530215 cloned.AdminState = voltha.AdminState_ENABLED
216 cloned.OperStatus = voltha.OperStatus_ACTIVATING
217
218 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
219 return err
220 }
221
222 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500223 device := proto.Clone(cloned).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530224 if previousAdminState == voltha.AdminState_PREPROVISIONED {
225 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
226 log.Debugw("adoptDevice-error", log.Fields{"id": agent.deviceID, "error": err})
227 return err
228 }
khenaidoob9203542018-09-17 22:56:37 -0400229 } else {
npujar1d86a522019-11-14 17:11:16 +0530230 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
231 log.Debugw("renableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
khenaidoo21d51152019-02-01 13:48:37 -0500232 return err
khenaidoob9203542018-09-17 22:56:37 -0400233 }
234 }
235 return nil
236}
237
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500238func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, response coreutils.Response) {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400239 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530240 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500241 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400242 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500243 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400244}
245
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500246func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, response coreutils.Response) {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400247 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530248 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500249 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400250 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500251 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400252}
253
A R Karthick5c28f552019-12-11 22:47:44 -0800254func (agent *DeviceAgent) addFlowsAndGroupsToAdapter(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530255 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400256
khenaidoo2c6a0992019-04-29 13:46:56 -0400257 if (len(newFlows) | len(newGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530258 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800259 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400260 }
261
khenaidoo19d7b632018-10-30 10:49:50 -0400262 agent.lockDevice.Lock()
263 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400264
khenaidoo6e55d9e2019-12-12 18:26:26 -0500265 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400266 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
267 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
268
269 var updatedFlows []*ofp.OfpFlowStats
270 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400271 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400272 var updatedGroups []*ofp.OfpGroupEntry
273
274 // Process flows
npujar1d86a522019-11-14 17:11:16 +0530275 updatedFlows = append(updatedFlows, newFlows...)
khenaidoo0458db62019-06-20 08:50:36 -0400276 for _, flow := range existingFlows.Items {
277 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400278 updatedFlows = append(updatedFlows, flow)
khenaidoo0458db62019-06-20 08:50:36 -0400279 } else {
280 flowsToDelete = append(flowsToDelete, flow)
281 }
282 }
283
284 // Process groups
npujar1d86a522019-11-14 17:11:16 +0530285 updatedGroups = append(updatedGroups, newGroups...)
khenaidoo0458db62019-06-20 08:50:36 -0400286 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400287 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
288 updatedGroups = append(updatedGroups, group)
289 } else {
290 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400291 }
292 }
293
294 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400295 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530296 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800297 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400298 }
299
300 // Send update to adapters
301 // Create two channels to receive responses from the dB and from the adapters.
302 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
303 // to send their responses. These channels will be garbage collected once all the responses are
304 // received
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500305 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400306 dType := agent.adapterMgr.getDeviceType(device.Type)
307 if !dType.AcceptsAddRemoveFlowUpdates {
308
309 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530310 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800311 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400312 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500313 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400314
315 } else {
316 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400317 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400318 ToRemove: &voltha.Flows{Items: flowsToDelete},
319 }
320 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400321 ToAdd: &voltha.FlowGroups{Items: newGroups},
322 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400323 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
324 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500325 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400326 }
327
328 // store the changed data
329 device.Flows = &voltha.Flows{Items: updatedFlows}
330 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500331 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800332 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500333 }
khenaidoo0458db62019-06-20 08:50:36 -0400334
A R Karthick5c28f552019-12-11 22:47:44 -0800335 return response, nil
336}
337
338//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
339//adapters
340func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
341 response, err := agent.addFlowsAndGroupsToAdapter(newFlows, newGroups, flowMetadata)
342 if err != nil {
343 return err
344 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500345 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400346 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400347 return status.Errorf(codes.Aborted, "errors-%s", res)
348 }
khenaidoo0458db62019-06-20 08:50:36 -0400349 return nil
350}
351
A R Karthick5c28f552019-12-11 22:47:44 -0800352func (agent *DeviceAgent) deleteFlowsAndGroupsFromAdapter(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530353 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400354
355 if (len(flowsToDel) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530356 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800357 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400358 }
359
360 agent.lockDevice.Lock()
361 defer agent.lockDevice.Unlock()
362
khenaidoo6e55d9e2019-12-12 18:26:26 -0500363 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400364
365 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
366 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
367
368 var flowsToKeep []*ofp.OfpFlowStats
369 var groupsToKeep []*ofp.OfpGroupEntry
370
371 // Process flows
372 for _, flow := range existingFlows.Items {
373 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
374 flowsToKeep = append(flowsToKeep, flow)
375 }
376 }
377
378 // Process groups
379 for _, group := range existingGroups.Items {
380 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
381 groupsToKeep = append(groupsToKeep, group)
382 }
383 }
384
385 log.Debugw("deleteFlowsAndGroups",
386 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530387 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400388 "flowsToDel": len(flowsToDel),
389 "flowsToKeep": len(flowsToKeep),
390 "groupsToDel": len(groupsToDel),
391 "groupsToKeep": len(groupsToKeep),
392 })
393
394 // Sanity check
395 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530396 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800397 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400398 }
399
400 // Send update to adapters
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500401 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400402 dType := agent.adapterMgr.getDeviceType(device.Type)
403 if !dType.AcceptsAddRemoveFlowUpdates {
404 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
npujar1d86a522019-11-14 17:11:16 +0530405 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800406 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400407 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500408 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400409 } else {
410 flowChanges := &ofp.FlowChanges{
411 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
412 ToRemove: &voltha.Flows{Items: flowsToDel},
413 }
414 groupChanges := &ofp.FlowGroupChanges{
415 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
416 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
417 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
418 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500419 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400420 }
421
422 // store the changed data
423 device.Flows = &voltha.Flows{Items: flowsToKeep}
424 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
Kent Hagerman3c513972019-11-25 13:49:41 -0500425 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800426 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500427 }
khenaidoo0458db62019-06-20 08:50:36 -0400428
A R Karthick5c28f552019-12-11 22:47:44 -0800429 return response, nil
430
431}
432
433//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
434//adapters
435func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
436 response, err := agent.deleteFlowsAndGroupsFromAdapter(flowsToDel, groupsToDel, flowMetadata)
437 if err != nil {
438 return err
439 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500440 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400441 return status.Errorf(codes.Aborted, "errors-%s", res)
442 }
443 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400444}
445
A R Karthick5c28f552019-12-11 22:47:44 -0800446func (agent *DeviceAgent) updateFlowsAndGroupsToAdapter(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530447 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400448
449 if (len(updatedFlows) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530450 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800451 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400452 }
453
454 agent.lockDevice.Lock()
455 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500456
457 device := agent.getDeviceWithoutLock()
458
khenaidoo0458db62019-06-20 08:50:36 -0400459 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
460 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
461
462 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530463 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800464 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400465 }
466
467 log.Debugw("updating-flows-and-groups",
468 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530469 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400470 "updatedFlows": updatedFlows,
471 "updatedGroups": updatedGroups,
472 })
473
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500474 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400475 dType := agent.adapterMgr.getDeviceType(device.Type)
476
477 // Process bulk flow update differently than incremental update
478 if !dType.AcceptsAddRemoveFlowUpdates {
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500479 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, response)
khenaidoo0458db62019-06-20 08:50:36 -0400480 } else {
481 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400482 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400483 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400484 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400485
486 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400487 for _, flow := range updatedFlows {
488 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
489 flowsToAdd = append(flowsToAdd, flow)
490 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400491 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400492 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400493 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400494 flowsToDelete = append(flowsToDelete, flow)
495 }
496 }
497
498 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400499 for _, g := range updatedGroups {
500 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
501 groupsToAdd = append(groupsToAdd, g)
502 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400503 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400505 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400506 groupsToDelete = append(groupsToDelete, group)
507 }
508 }
509
khenaidoo0458db62019-06-20 08:50:36 -0400510 log.Debugw("updating-flows-and-groups",
511 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530512 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400513 "flowsToAdd": flowsToAdd,
514 "flowsToDelete": flowsToDelete,
515 "groupsToAdd": groupsToAdd,
516 "groupsToDelete": groupsToDelete,
517 })
518
khenaidoo2c6a0992019-04-29 13:46:56 -0400519 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400520 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | 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
khenaidoo2c6a0992019-04-29 13:46:56 -0400523 }
524
khenaidoo0458db62019-06-20 08:50:36 -0400525 flowChanges := &ofp.FlowChanges{
526 ToAdd: &voltha.Flows{Items: flowsToAdd},
527 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400528 }
khenaidoo0458db62019-06-20 08:50:36 -0400529 groupChanges := &ofp.FlowGroupChanges{
530 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
531 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
532 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
533 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500534 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo19d7b632018-10-30 10:49:50 -0400535 }
khenaidoo0458db62019-06-20 08:50:36 -0400536
537 // store the updated data
538 device.Flows = &voltha.Flows{Items: updatedFlows}
539 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500540 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800541 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500542 }
khenaidoo0458db62019-06-20 08:50:36 -0400543
A R Karthick5c28f552019-12-11 22:47:44 -0800544 return response, nil
545}
546
547//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
548//also sends the updates to the adapters
549func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
550 response, err := agent.updateFlowsAndGroupsToAdapter(updatedFlows, updatedGroups, flowMetadata)
551 if err != nil {
552 return err
553 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500554 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400555 return status.Errorf(codes.Aborted, "errors-%s", res)
556 }
557 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400558}
559
khenaidoo4d4802d2018-10-04 21:59:49 -0400560//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400561func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400562 agent.lockDevice.Lock()
563 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530564 log.Debugw("disableDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500565
566 cloned := agent.getDeviceWithoutLock()
567
568 if cloned.AdminState == voltha.AdminState_DISABLED {
npujar1d86a522019-11-14 17:11:16 +0530569 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
570 return nil
571 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500572 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
573 cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530574 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500575 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530576 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400577
npujar1d86a522019-11-14 17:11:16 +0530578 // Update the Admin State and operational state before sending the request out
npujar1d86a522019-11-14 17:11:16 +0530579 cloned.AdminState = voltha.AdminState_DISABLED
580 cloned.OperStatus = voltha.OperStatus_UNKNOWN
581 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
582 return err
583 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500584 if err := agent.adapterProxy.DisableDevice(ctx, proto.Clone(cloned).(*voltha.Device)); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530585 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
586 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400587 }
588 return nil
589}
590
591func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
592 agent.lockDevice.Lock()
593 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530594 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500595
596 cloned := agent.getDeviceWithoutLock()
597
598 if cloned.AdminState == adminState {
npujar1d86a522019-11-14 17:11:16 +0530599 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceID, "state": adminState})
600 return nil
601 }
602 // Received an Ack (no error found above). Now update the device in the model to the expected state
npujar1d86a522019-11-14 17:11:16 +0530603 cloned.AdminState = adminState
604 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
605 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400606 }
607 return nil
608}
609
khenaidoo4d4802d2018-10-04 21:59:49 -0400610func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
611 agent.lockDevice.Lock()
612 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530613 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500614
615 device := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530616 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
617 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceID, "error": err})
618 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400619 }
620 return nil
621}
622
623func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
624 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400625 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530626 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500627
628 cloned := agent.getDeviceWithoutLock()
629 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530630 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceID})
631 return nil
632 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500633 if (cloned.AdminState != voltha.AdminState_DISABLED) &&
634 (cloned.AdminState != voltha.AdminState_PREPROVISIONED) {
npujar1d86a522019-11-14 17:11:16 +0530635 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceID})
636 //TODO: Needs customized error message
637 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_DISABLED)
638 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500639 if cloned.AdminState != voltha.AdminState_PREPROVISIONED {
npujar1d86a522019-11-14 17:11:16 +0530640 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
khenaidoo6e55d9e2019-12-12 18:26:26 -0500641 if err := agent.adapterProxy.DeleteDevice(ctx, cloned); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530642 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceID, "error": err})
Mahir Gunyelb5851672019-07-24 10:46:26 +0300643 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400644 }
npujar1d86a522019-11-14 17:11:16 +0530645 }
646 // Set the state to deleted after we receive an Ack - this will trigger some background process to clean up
647 // the device as well as its association with the logical device
npujar1d86a522019-11-14 17:11:16 +0530648 cloned.AdminState = voltha.AdminState_DELETED
649 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
650 return err
651 }
652 // If this is a child device then remove the associated peer ports on the parent device
khenaidoo6e55d9e2019-12-12 18:26:26 -0500653 if !cloned.Root {
npujar1d86a522019-11-14 17:11:16 +0530654 go func() {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500655 err := agent.deviceMgr.deletePeerPorts(cloned.ParentId, cloned.Id)
npujar1d86a522019-11-14 17:11:16 +0530656 if err != nil {
657 log.Errorw("unable-to-delete-peer-ports", log.Fields{"error": err})
658 }
659 }()
khenaidoo4d4802d2018-10-04 21:59:49 -0400660 }
661 return nil
662}
663
npujar1d86a522019-11-14 17:11:16 +0530664func (agent *DeviceAgent) setParentID(device *voltha.Device, parentID string) error {
khenaidooad06fd72019-10-28 12:26:05 -0400665 agent.lockDevice.Lock()
666 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530667 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500668
669 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530670 cloned.ParentId = parentID
671 // Store the device
672 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
673 return err
674 }
675 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400676}
677
khenaidoob3127472019-07-24 21:04:55 -0400678func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
679 agent.lockDevice.Lock()
680 defer agent.lockDevice.Unlock()
681 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500682
683 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530684 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
685 // Store the device
686 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
687 return err
688 }
689 // Send the request to the adapter
690 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
691 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceID, "error": err})
692 return err
693 }
694 return nil
khenaidoob3127472019-07-24 21:04:55 -0400695}
696
697func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
698 agent.lockDevice.Lock()
699 defer agent.lockDevice.Unlock()
700 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500701
702 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530703 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
704 // Store the device
705 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
706 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, cloned, false, "")
707 if afterUpdate == nil {
708 return status.Errorf(codes.Internal, "%s", agent.deviceID)
709 }
710 return nil
khenaidoob3127472019-07-24 21:04:55 -0400711}
712
713func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
714 agent.lockDevice.RLock()
715 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530716 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500717
718 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400719}
720
khenaidoof5a5bfa2019-01-23 22:20:29 -0500721func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
722 agent.lockDevice.Lock()
723 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530724 log.Debugw("downloadImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500725
726 device := agent.getDeviceWithoutLock()
727
npujar1d86a522019-11-14 17:11:16 +0530728 if device.AdminState != voltha.AdminState_ENABLED {
729 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
730 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
731 }
732 // Save the image
733 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
734 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
735 cloned := proto.Clone(device).(*voltha.Device)
736 if cloned.ImageDownloads == nil {
737 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500738 } else {
739 if device.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530740 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
741 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500742 }
743 // Save the image
744 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500745 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500746 cloned := proto.Clone(device).(*voltha.Device)
747 if cloned.ImageDownloads == nil {
748 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
749 } else {
750 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
751 }
752 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300753 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
754 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500755 }
756 // Send the request to the adapter
757 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530758 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500759 return nil, err
760 }
761 }
762 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
763}
764
765// isImageRegistered is a helper method to figure out if an image is already registered
766func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
767 for _, image := range device.ImageDownloads {
768 if image.Id == img.Id && image.Name == img.Name {
769 return true
770 }
771 }
772 return false
773}
774
775func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
776 agent.lockDevice.Lock()
777 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530778 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500779
780 device := agent.getDeviceWithoutLock()
781
npujar1d86a522019-11-14 17:11:16 +0530782 // Verify whether the Image is in the list of image being downloaded
783 if !isImageRegistered(img, device) {
784 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
785 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500786
npujar1d86a522019-11-14 17:11:16 +0530787 // Update image download state
788 cloned := proto.Clone(device).(*voltha.Device)
789 for _, image := range cloned.ImageDownloads {
790 if image.Id == img.Id && image.Name == img.Name {
791 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500792 }
npujar1d86a522019-11-14 17:11:16 +0530793 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500794
npujar1d86a522019-11-14 17:11:16 +0530795 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
796 // Set the device to Enabled
797 cloned.AdminState = voltha.AdminState_ENABLED
798 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
799 return nil, err
800 }
801 // Send the request to the adapter
802 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
803 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
804 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500805 }
806 }
807 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700808}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500809
810func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
811 agent.lockDevice.Lock()
812 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530813 log.Debugw("activateImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500814 cloned := agent.getDeviceWithoutLock()
815
npujar1d86a522019-11-14 17:11:16 +0530816 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500817 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530818 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
819 }
820
khenaidoo6e55d9e2019-12-12 18:26:26 -0500821 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
npujar1d86a522019-11-14 17:11:16 +0530822 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
823 }
824 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530825 for _, image := range cloned.ImageDownloads {
826 if image.Id == img.Id && image.Name == img.Name {
827 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
828 }
829 }
830 // Set the device to downloading_image
831 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
832 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
833 return nil, err
834 }
835
khenaidoo6e55d9e2019-12-12 18:26:26 -0500836 if err := agent.adapterProxy.ActivateImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530837 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
838 return nil, err
839 }
840 // The status of the AdminState will be changed following the update_download_status response from the adapter
841 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -0700842 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
843}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500844
845func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
846 agent.lockDevice.Lock()
847 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530848 log.Debugw("revertImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500849
850 cloned := agent.getDeviceWithoutLock()
851
npujar1d86a522019-11-14 17:11:16 +0530852 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500853 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530854 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
855 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500856
khenaidoo6e55d9e2019-12-12 18:26:26 -0500857 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530858 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
859 }
860 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530861 for _, image := range cloned.ImageDownloads {
862 if image.Id == img.Id && image.Name == img.Name {
863 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -0500864 }
npujar1d86a522019-11-14 17:11:16 +0530865 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300866
npujar1d86a522019-11-14 17:11:16 +0530867 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
868 return nil, err
869 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500870
khenaidoo6e55d9e2019-12-12 18:26:26 -0500871 if err := agent.adapterProxy.RevertImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530872 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
873 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500874 }
875 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700876}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500877
878func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
879 agent.lockDevice.Lock()
880 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530881 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500882
883 cloned := agent.getDeviceWithoutLock()
884 resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, cloned, img)
npujar1d86a522019-11-14 17:11:16 +0530885 if err != nil {
886 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
887 return nil, err
888 }
889 return resp, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500890}
891
serkant.uluderya334479d2019-04-10 08:26:15 -0700892func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500893 agent.lockDevice.Lock()
894 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530895 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500896
897 cloned := agent.getDeviceWithoutLock()
898
npujar1d86a522019-11-14 17:11:16 +0530899 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +0530900 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
901 for _, image := range cloned.ImageDownloads {
902 if image.Id == img.Id && image.Name == img.Name {
903 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
904 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500905 }
906 }
npujar1d86a522019-11-14 17:11:16 +0530907 }
908 cloned.ImageDownloads = clonedImages
909 // Set the Admin state to enabled if required
910 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
911 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
912 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
913 cloned.AdminState = voltha.AdminState_ENABLED
914 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500915
npujar1d86a522019-11-14 17:11:16 +0530916 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
917 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500918 }
919 return nil
920}
921
922func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400923 agent.lockDevice.RLock()
924 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530925 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500926
927 cloned := agent.getDeviceWithoutLock()
928 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +0530929 if image.Id == img.Id && image.Name == img.Name {
930 return image, nil
931 }
932 }
933 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500934}
935
npujar1d86a522019-11-14 17:11:16 +0530936func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400937 agent.lockDevice.RLock()
938 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530939 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500940
941 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500942}
943
khenaidoo4d4802d2018-10-04 21:59:49 -0400944// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400945func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
npujar1d86a522019-11-14 17:11:16 +0530946 log.Debugw("getPorts", log.Fields{"id": agent.deviceID, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400947 ports := &voltha.Ports{}
npujar1d86a522019-11-14 17:11:16 +0530948 if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400949 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400950 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400951 ports.Items = append(ports.Items, port)
952 }
953 }
954 }
955 return ports
956}
957
khenaidoo4d4802d2018-10-04 21:59:49 -0400958// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
959// parent device
khenaidoo79232702018-12-04 11:00:41 -0500960func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
npujar1d86a522019-11-14 17:11:16 +0530961 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceID})
962 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
963 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400964 return nil, err
khenaidoob9203542018-09-17 22:56:37 -0400965 }
npujar1d86a522019-11-14 17:11:16 +0530966 var switchCap *ic.SwitchCapability
967 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
968 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
969 return nil, err
970 }
971 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -0400972}
973
khenaidoo4d4802d2018-10-04 21:59:49 -0400974// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
975// device
khenaidoo79232702018-12-04 11:00:41 -0500976func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
npujar1d86a522019-11-14 17:11:16 +0530977 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceID})
978 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
979 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400980 return nil, err
khenaidoob9203542018-09-17 22:56:37 -0400981 }
npujar1d86a522019-11-14 17:11:16 +0530982 var portCap *ic.PortCapability
983 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
984 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
985 return nil, err
986 }
987 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -0400988}
989
khenaidoofdbad6e2018-11-06 22:26:38 -0500990func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -0800991 // If deviceType=="" then we must have taken ownership of this device.
992 // Fixes VOL-2226 where a core would take ownership and have stale data
993 if agent.deviceType == "" {
994 agent.reconcileWithKVStore()
995 }
khenaidoofdbad6e2018-11-06 22:26:38 -0500996 // Send packet to adapter
npujar1d86a522019-11-14 17:11:16 +0530997 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceID, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -0800998 log.Debugw("packet-out-error", log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530999 "id": agent.deviceID,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001000 "error": err,
1001 "packet": hex.EncodeToString(packet.Data),
1002 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001003 return err
1004 }
1005 return nil
1006}
1007
khenaidoo4d4802d2018-10-04 21:59:49 -04001008// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001009func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001010 //// Run this callback in its own go routine
1011 go func(args ...interface{}) interface{} {
1012 var previous *voltha.Device
1013 var current *voltha.Device
1014 var ok bool
1015 if len(args) == 2 {
1016 if previous, ok = args[0].(*voltha.Device); !ok {
1017 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1018 return nil
1019 }
1020 if current, ok = args[1].(*voltha.Device); !ok {
1021 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1022 return nil
1023 }
1024 } else {
1025 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1026 return nil
1027 }
1028 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001029 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1030 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1031 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1032 }
khenaidoo43c82122018-11-22 18:38:28 -05001033 return nil
1034 }(args...)
1035
khenaidoo92e62c52018-10-03 14:02:54 -04001036 return nil
1037}
1038
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001039// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1040// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1041func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001042 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001043 cloned.Root = device.Root
1044 cloned.Vendor = device.Vendor
1045 cloned.Model = device.Model
1046 cloned.SerialNumber = device.SerialNumber
1047 cloned.MacAddress = device.MacAddress
1048 cloned.Vlan = device.Vlan
1049 cloned.Reason = device.Reason
1050 return cloned, nil
1051}
1052func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001053 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001054 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001055 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
npujar1d86a522019-11-14 17:11:16 +05301056 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1057 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001058 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1059 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001060 }
npujar1d86a522019-11-14 17:11:16 +05301061 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1062 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001063}
1064
1065func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1066 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1067 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001068 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001069}
1070
khenaidoo92e62c52018-10-03 14:02:54 -04001071func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1072 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001073 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001074
1075 cloned := agent.getDeviceWithoutLock()
1076
npujar1d86a522019-11-14 17:11:16 +05301077 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1078 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1079 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1080 cloned.ConnectStatus = connStatus
1081 }
1082 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1083 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1084 cloned.OperStatus = operStatus
1085 }
1086 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
1087 // Store the device
1088 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001089}
1090
khenaidoo3ab34882019-05-02 21:33:30 -04001091func (agent *DeviceAgent) enablePorts() error {
1092 agent.lockDevice.Lock()
1093 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001094
1095 cloned := agent.getDeviceWithoutLock()
1096
npujar1d86a522019-11-14 17:11:16 +05301097 for _, port := range cloned.Ports {
1098 port.AdminState = voltha.AdminState_ENABLED
1099 port.OperStatus = voltha.OperStatus_ACTIVE
1100 }
1101 // Store the device
1102 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001103}
1104
1105func (agent *DeviceAgent) disablePorts() error {
npujar1d86a522019-11-14 17:11:16 +05301106 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceID})
khenaidoo3ab34882019-05-02 21:33:30 -04001107 agent.lockDevice.Lock()
1108 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001109 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301110 for _, port := range cloned.Ports {
1111 port.AdminState = voltha.AdminState_DISABLED
1112 port.OperStatus = voltha.OperStatus_UNKNOWN
1113 }
1114 // Store the device
1115 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001116}
1117
khenaidoo92e62c52018-10-03 14:02:54 -04001118func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1119 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001120 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001121 // Work only on latest data
1122 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001123 cloned := agent.getDeviceWithoutLock()
1124
npujar1d86a522019-11-14 17:11:16 +05301125 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1126 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1127 return status.Errorf(codes.InvalidArgument, "%s", portType)
1128 }
1129 for _, port := range cloned.Ports {
1130 if port.Type == portType && port.PortNo == portNo {
1131 port.OperStatus = operStatus
1132 // Set the admin status to ENABLED if the operational status is ACTIVE
1133 // TODO: Set by northbound system?
1134 if operStatus == voltha.OperStatus_ACTIVE {
1135 port.AdminState = voltha.AdminState_ENABLED
1136 }
1137 break
1138 }
1139 }
1140 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1141 // Store the device
1142 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001143}
1144
khenaidoo0a822f92019-05-08 15:15:57 -04001145func (agent *DeviceAgent) deleteAllPorts() error {
npujar1d86a522019-11-14 17:11:16 +05301146 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -04001147 agent.lockDevice.Lock()
1148 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001149
1150 cloned := agent.getDeviceWithoutLock()
1151
1152 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1153 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
1154 log.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301155 return err
1156 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001157 if len(cloned.Ports) == 0 {
npujar1d86a522019-11-14 17:11:16 +05301158 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
1159 return nil
1160 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001161
npujar1d86a522019-11-14 17:11:16 +05301162 cloned.Ports = []*voltha.Port{}
1163 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1164 // Store the device
1165 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001166}
1167
khenaidoob9203542018-09-17 22:56:37 -04001168func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001169 agent.lockDevice.Lock()
1170 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301171 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001172
1173 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301174 if cloned.Ports == nil {
1175 // First port
1176 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
1177 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001178 } else {
npujar1d86a522019-11-14 17:11:16 +05301179 for _, p := range cloned.Ports {
1180 if p.Type == port.Type && p.PortNo == port.PortNo {
1181 log.Debugw("port already exists", log.Fields{"port": *port})
1182 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001183 }
khenaidoob9203542018-09-17 22:56:37 -04001184 }
khenaidoo92e62c52018-10-03 14:02:54 -04001185 }
npujar1d86a522019-11-14 17:11:16 +05301186 cp := proto.Clone(port).(*voltha.Port)
1187 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1188 // TODO: Set by northbound system?
1189 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1190 cp.AdminState = voltha.AdminState_ENABLED
1191 }
1192 cloned.Ports = append(cloned.Ports, cp)
1193 // Store the device
1194 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001195}
1196
1197func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1198 agent.lockDevice.Lock()
1199 defer agent.lockDevice.Unlock()
1200 log.Debug("addPeerPort")
khenaidoo6e55d9e2019-12-12 18:26:26 -05001201
1202 cloned := agent.getDeviceWithoutLock()
1203
npujar1d86a522019-11-14 17:11:16 +05301204 // Get the peer port on the device based on the port no
1205 for _, peerPort := range cloned.Ports {
1206 if peerPort.PortNo == port.PortNo { // found port
1207 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1208 peerPort.Peers = append(peerPort.Peers, cp)
1209 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceID})
1210 break
1211 }
1212 }
1213 // Store the device
1214 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001215}
1216
npujar1d86a522019-11-14 17:11:16 +05301217func (agent *DeviceAgent) deletePeerPorts(deviceID string) error {
khenaidoo0a822f92019-05-08 15:15:57 -04001218 agent.lockDevice.Lock()
1219 defer agent.lockDevice.Unlock()
1220 log.Debug("deletePeerPorts")
khenaidoo6e55d9e2019-12-12 18:26:26 -05001221
1222 cloned := agent.getDeviceWithoutLock()
1223
npujar1d86a522019-11-14 17:11:16 +05301224 var updatedPeers []*voltha.Port_PeerPort
1225 for _, port := range cloned.Ports {
1226 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1227 for _, peerPort := range port.Peers {
1228 if peerPort.DeviceId != deviceID {
1229 updatedPeers = append(updatedPeers, peerPort)
1230 }
1231 }
1232 port.Peers = updatedPeers
1233 }
1234
1235 // Store the device with updated peer ports
1236 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001237}
1238
khenaidoob9203542018-09-17 22:56:37 -04001239// TODO: A generic device update by attribute
1240func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001241 agent.lockDevice.Lock()
1242 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001243 if value == nil {
1244 return
1245 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001246
1247 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001248 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001249 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001250 if s.Kind() == reflect.Struct {
1251 // exported field
1252 f := s.FieldByName(name)
1253 if f.IsValid() && f.CanSet() {
1254 switch f.Kind() {
1255 case reflect.String:
1256 f.SetString(value.(string))
1257 updated = true
1258 case reflect.Uint32:
1259 f.SetUint(uint64(value.(uint32)))
1260 updated = true
1261 case reflect.Bool:
1262 f.SetBool(value.(bool))
1263 updated = true
1264 }
1265 }
1266 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001267 log.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001268 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001269
1270 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001271 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1272 }
khenaidoob9203542018-09-17 22:56:37 -04001273}
serkant.uluderya334479d2019-04-10 08:26:15 -07001274
1275func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1276 agent.lockDevice.Lock()
1277 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301278 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001279
1280 cloned := agent.getDeviceWithoutLock()
1281
npujar1d86a522019-11-14 17:11:16 +05301282 // First send the request to an Adapter and wait for a response
khenaidoo6e55d9e2019-12-12 18:26:26 -05001283 if err := agent.adapterProxy.SimulateAlarm(ctx, cloned, simulatereq); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301284 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceID, "error": err})
1285 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001286 }
1287 return nil
1288}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001289
1290//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.
1291// It is an internal helper function.
1292func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1293 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
npujar1d86a522019-11-14 17:11:16 +05301294 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, device, strict, txid); afterUpdate == nil {
1295 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001296 }
npujar1d86a522019-11-14 17:11:16 +05301297 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001298
khenaidoo6e55d9e2019-12-12 18:26:26 -05001299 agent.device = proto.Clone(device).(*voltha.Device)
1300
Mahir Gunyelb5851672019-07-24 10:46:26 +03001301 return nil
1302}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001303
1304func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1305 agent.lockDevice.Lock()
1306 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001307
1308 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301309 cloned.Reason = reason
1310 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1311 // Store the device
1312 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001313}