blob: ca3ffbbf094de99f4a2be1f46f362622ace0e7fa [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
khenaidoob2121e52019-12-16 17:17:22 -0500254//deleteFlowWithoutPreservingOrder removes a flow specified by index from the flows slice. This function will
255//panic if the index is out of range.
256func deleteFlowWithoutPreservingOrder(flows []*ofp.OfpFlowStats, index int) []*ofp.OfpFlowStats {
257 flows[index] = flows[len(flows)-1]
258 flows[len(flows)-1] = nil
259 return flows[:len(flows)-1]
260}
261
262//deleteGroupWithoutPreservingOrder removes a group specified by index from the groups slice. This function will
263//panic if the index is out of range.
264func deleteGroupWithoutPreservingOrder(groups []*ofp.OfpGroupEntry, index int) []*ofp.OfpGroupEntry {
265 groups[index] = groups[len(groups)-1]
266 groups[len(groups)-1] = nil
267 return groups[:len(groups)-1]
268}
269
270func flowsToUpdateToDelete(newFlows, existingFlows []*ofp.OfpFlowStats) (updatedNewFlows, flowsToDelete, updatedAllFlows []*ofp.OfpFlowStats) {
271 // Process flows
272 for _, flow := range existingFlows {
273 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
274 updatedAllFlows = append(updatedAllFlows, flow)
275 } else {
276 // We have a matching flow (i.e. the following field matches: "TableId", "Priority", "Flags", "Cookie",
277 // "Match". If this is an exact match (i.e. all other fields matches as well) then this flow will be
278 // ignored. Otherwise, the previous flow will be deleted and the new one added
279 if proto.Equal(newFlows[idx], flow) {
280 // Flow already exist, remove it from the new flows but keep it in the updated flows slice
281 newFlows = deleteFlowWithoutPreservingOrder(newFlows, idx)
282 updatedAllFlows = append(updatedAllFlows, flow)
283 } else {
284 // Minor change to flow, delete old and add new one
285 flowsToDelete = append(flowsToDelete, flow)
286 }
287 }
288 }
289 updatedAllFlows = append(updatedAllFlows, newFlows...)
290 return newFlows, flowsToDelete, updatedAllFlows
291}
292
293func groupsToUpdateToDelete(newGroups, existingGroups []*ofp.OfpGroupEntry) (updatedNewGroups, groupsToDelete, updatedAllGroups []*ofp.OfpGroupEntry) {
294 for _, group := range existingGroups {
295 if idx := fu.FindGroup(newGroups, group.Desc.GroupId); idx == -1 { // does not exist now
296 updatedAllGroups = append(updatedAllGroups, group)
297 } else {
298 // Follow same logic as flows
299 if proto.Equal(newGroups[idx], group) {
300 // Group already exist, remove it from the new groups
301 newGroups = deleteGroupWithoutPreservingOrder(newGroups, idx)
302 updatedAllGroups = append(updatedAllGroups, group)
303 } else {
304 // Minor change to group, delete old and add new one
305 groupsToDelete = append(groupsToDelete, group)
306 }
307 }
308 }
309 updatedAllGroups = append(updatedAllGroups, newGroups...)
310 return newGroups, groupsToDelete, updatedAllGroups
311}
312
A R Karthick5c28f552019-12-11 22:47:44 -0800313func (agent *DeviceAgent) addFlowsAndGroupsToAdapter(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530314 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400315
khenaidoo2c6a0992019-04-29 13:46:56 -0400316 if (len(newFlows) | len(newGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530317 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800318 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400319 }
320
khenaidoo19d7b632018-10-30 10:49:50 -0400321 agent.lockDevice.Lock()
322 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400323
khenaidoo6e55d9e2019-12-12 18:26:26 -0500324 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400325 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
326 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
327
khenaidoo0458db62019-06-20 08:50:36 -0400328 // Process flows
khenaidoob2121e52019-12-16 17:17:22 -0500329 newFlows, flowsToDelete, updatedAllFlows := flowsToUpdateToDelete(newFlows, existingFlows.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400330
331 // Process groups
khenaidoob2121e52019-12-16 17:17:22 -0500332 newGroups, groupsToDelete, updatedAllGroups := groupsToUpdateToDelete(newGroups, existingGroups.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400333
334 // Sanity check
khenaidoob2121e52019-12-16 17:17:22 -0500335 if (len(updatedAllFlows) | len(flowsToDelete) | len(updatedAllGroups) | len(groupsToDelete)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530336 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800337 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400338 }
339
340 // Send update to adapters
341 // Create two channels to receive responses from the dB and from the adapters.
342 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
343 // to send their responses. These channels will be garbage collected once all the responses are
344 // received
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500345 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400346 dType := agent.adapterMgr.getDeviceType(device.Type)
347 if !dType.AcceptsAddRemoveFlowUpdates {
348
khenaidoob2121e52019-12-16 17:17:22 -0500349 if len(updatedAllGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedAllGroups) && len(updatedAllFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedAllFlows) {
npujar1d86a522019-11-14 17:11:16 +0530350 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800351 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400352 }
khenaidoob2121e52019-12-16 17:17:22 -0500353 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedAllFlows}, &voltha.FlowGroups{Items: updatedAllGroups}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400354
355 } else {
356 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400357 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400358 ToRemove: &voltha.Flows{Items: flowsToDelete},
359 }
360 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400361 ToAdd: &voltha.FlowGroups{Items: newGroups},
362 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400363 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
364 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500365 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400366 }
367
368 // store the changed data
khenaidoob2121e52019-12-16 17:17:22 -0500369 device.Flows = &voltha.Flows{Items: updatedAllFlows}
370 device.FlowGroups = &voltha.FlowGroups{Items: updatedAllGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500371 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800372 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500373 }
khenaidoo0458db62019-06-20 08:50:36 -0400374
A R Karthick5c28f552019-12-11 22:47:44 -0800375 return response, nil
376}
377
378//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
379//adapters
380func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
381 response, err := agent.addFlowsAndGroupsToAdapter(newFlows, newGroups, flowMetadata)
382 if err != nil {
383 return err
384 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500385 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400386 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400387 return status.Errorf(codes.Aborted, "errors-%s", res)
388 }
khenaidoo0458db62019-06-20 08:50:36 -0400389 return nil
390}
391
A R Karthick5c28f552019-12-11 22:47:44 -0800392func (agent *DeviceAgent) deleteFlowsAndGroupsFromAdapter(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530393 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400394
395 if (len(flowsToDel) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530396 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800397 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400398 }
399
400 agent.lockDevice.Lock()
401 defer agent.lockDevice.Unlock()
402
khenaidoo6e55d9e2019-12-12 18:26:26 -0500403 device := agent.getDeviceWithoutLock()
khenaidoo0458db62019-06-20 08:50:36 -0400404
405 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
406 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
407
408 var flowsToKeep []*ofp.OfpFlowStats
409 var groupsToKeep []*ofp.OfpGroupEntry
410
411 // Process flows
412 for _, flow := range existingFlows.Items {
413 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
414 flowsToKeep = append(flowsToKeep, flow)
415 }
416 }
417
418 // Process groups
419 for _, group := range existingGroups.Items {
420 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
421 groupsToKeep = append(groupsToKeep, group)
422 }
423 }
424
425 log.Debugw("deleteFlowsAndGroups",
426 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530427 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400428 "flowsToDel": len(flowsToDel),
429 "flowsToKeep": len(flowsToKeep),
430 "groupsToDel": len(groupsToDel),
431 "groupsToKeep": len(groupsToKeep),
432 })
433
434 // Sanity check
435 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530436 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800437 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400438 }
439
440 // Send update to adapters
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500441 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400442 dType := agent.adapterMgr.getDeviceType(device.Type)
443 if !dType.AcceptsAddRemoveFlowUpdates {
444 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
npujar1d86a522019-11-14 17:11:16 +0530445 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800446 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400447 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500448 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400449 } else {
450 flowChanges := &ofp.FlowChanges{
451 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
452 ToRemove: &voltha.Flows{Items: flowsToDel},
453 }
454 groupChanges := &ofp.FlowGroupChanges{
455 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
456 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
457 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
458 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500459 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400460 }
461
462 // store the changed data
463 device.Flows = &voltha.Flows{Items: flowsToKeep}
464 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
Kent Hagerman3c513972019-11-25 13:49:41 -0500465 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800466 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500467 }
khenaidoo0458db62019-06-20 08:50:36 -0400468
A R Karthick5c28f552019-12-11 22:47:44 -0800469 return response, nil
470
471}
472
473//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
474//adapters
475func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
476 response, err := agent.deleteFlowsAndGroupsFromAdapter(flowsToDel, groupsToDel, flowMetadata)
477 if err != nil {
478 return err
479 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500480 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400481 return status.Errorf(codes.Aborted, "errors-%s", res)
482 }
483 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400484}
485
A R Karthick5c28f552019-12-11 22:47:44 -0800486func (agent *DeviceAgent) updateFlowsAndGroupsToAdapter(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
npujar1d86a522019-11-14 17:11:16 +0530487 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400488
489 if (len(updatedFlows) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530490 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800491 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400492 }
493
494 agent.lockDevice.Lock()
495 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500496
497 device := agent.getDeviceWithoutLock()
498
khenaidoo0458db62019-06-20 08:50:36 -0400499 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
500 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
501
502 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530503 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800504 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400505 }
506
507 log.Debugw("updating-flows-and-groups",
508 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530509 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400510 "updatedFlows": updatedFlows,
511 "updatedGroups": updatedGroups,
512 })
513
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500514 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400515 dType := agent.adapterMgr.getDeviceType(device.Type)
516
517 // Process bulk flow update differently than incremental update
518 if !dType.AcceptsAddRemoveFlowUpdates {
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500519 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, response)
khenaidoo0458db62019-06-20 08:50:36 -0400520 } else {
521 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400522 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400523 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400524 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400525
526 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400527 for _, flow := range updatedFlows {
528 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
529 flowsToAdd = append(flowsToAdd, flow)
530 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400531 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400532 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400533 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400534 flowsToDelete = append(flowsToDelete, flow)
535 }
536 }
537
538 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400539 for _, g := range updatedGroups {
540 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
541 groupsToAdd = append(groupsToAdd, g)
542 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400543 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400544 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400545 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400546 groupsToDelete = append(groupsToDelete, group)
547 }
548 }
549
khenaidoo0458db62019-06-20 08:50:36 -0400550 log.Debugw("updating-flows-and-groups",
551 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530552 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400553 "flowsToAdd": flowsToAdd,
554 "flowsToDelete": flowsToDelete,
555 "groupsToAdd": groupsToAdd,
556 "groupsToDelete": groupsToDelete,
557 })
558
khenaidoo2c6a0992019-04-29 13:46:56 -0400559 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400560 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530561 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800562 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400563 }
564
khenaidoo0458db62019-06-20 08:50:36 -0400565 flowChanges := &ofp.FlowChanges{
566 ToAdd: &voltha.Flows{Items: flowsToAdd},
567 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400568 }
khenaidoo0458db62019-06-20 08:50:36 -0400569 groupChanges := &ofp.FlowGroupChanges{
570 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
571 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
572 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
573 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500574 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo19d7b632018-10-30 10:49:50 -0400575 }
khenaidoo0458db62019-06-20 08:50:36 -0400576
577 // store the updated data
578 device.Flows = &voltha.Flows{Items: updatedFlows}
579 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500580 if err := agent.updateDeviceWithoutLock(device); err != nil {
A R Karthick5c28f552019-12-11 22:47:44 -0800581 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500582 }
khenaidoo0458db62019-06-20 08:50:36 -0400583
A R Karthick5c28f552019-12-11 22:47:44 -0800584 return response, nil
585}
586
587//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
588//also sends the updates to the adapters
589func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
590 response, err := agent.updateFlowsAndGroupsToAdapter(updatedFlows, updatedGroups, flowMetadata)
591 if err != nil {
592 return err
593 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500594 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400595 return status.Errorf(codes.Aborted, "errors-%s", res)
596 }
597 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400598}
599
khenaidoo4d4802d2018-10-04 21:59:49 -0400600//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400601func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400602 agent.lockDevice.Lock()
603 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530604 log.Debugw("disableDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500605
606 cloned := agent.getDeviceWithoutLock()
607
608 if cloned.AdminState == voltha.AdminState_DISABLED {
npujar1d86a522019-11-14 17:11:16 +0530609 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
610 return nil
611 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500612 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
613 cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530614 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500615 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530616 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400617
npujar1d86a522019-11-14 17:11:16 +0530618 // Update the Admin State and operational state before sending the request out
npujar1d86a522019-11-14 17:11:16 +0530619 cloned.AdminState = voltha.AdminState_DISABLED
620 cloned.OperStatus = voltha.OperStatus_UNKNOWN
621 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
622 return err
623 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500624 if err := agent.adapterProxy.DisableDevice(ctx, proto.Clone(cloned).(*voltha.Device)); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530625 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
626 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400627 }
628 return nil
629}
630
631func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
632 agent.lockDevice.Lock()
633 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530634 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500635
636 cloned := agent.getDeviceWithoutLock()
637
638 if cloned.AdminState == adminState {
npujar1d86a522019-11-14 17:11:16 +0530639 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceID, "state": adminState})
640 return nil
641 }
642 // Received an Ack (no error found above). Now update the device in the model to the expected state
npujar1d86a522019-11-14 17:11:16 +0530643 cloned.AdminState = adminState
644 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
645 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400646 }
647 return nil
648}
649
khenaidoo4d4802d2018-10-04 21:59:49 -0400650func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
651 agent.lockDevice.Lock()
652 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530653 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500654
655 device := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530656 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
657 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceID, "error": err})
658 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400659 }
660 return nil
661}
662
663func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
664 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400665 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530666 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500667
668 cloned := agent.getDeviceWithoutLock()
669 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530670 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceID})
671 return nil
672 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500673 if (cloned.AdminState != voltha.AdminState_DISABLED) &&
674 (cloned.AdminState != voltha.AdminState_PREPROVISIONED) {
npujar1d86a522019-11-14 17:11:16 +0530675 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceID})
676 //TODO: Needs customized error message
677 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_DISABLED)
678 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500679 if cloned.AdminState != voltha.AdminState_PREPROVISIONED {
npujar1d86a522019-11-14 17:11:16 +0530680 // 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 -0500681 if err := agent.adapterProxy.DeleteDevice(ctx, cloned); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530682 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceID, "error": err})
Mahir Gunyelb5851672019-07-24 10:46:26 +0300683 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400684 }
npujar1d86a522019-11-14 17:11:16 +0530685 }
686 // Set the state to deleted after we receive an Ack - this will trigger some background process to clean up
687 // the device as well as its association with the logical device
npujar1d86a522019-11-14 17:11:16 +0530688 cloned.AdminState = voltha.AdminState_DELETED
689 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
690 return err
691 }
692 // If this is a child device then remove the associated peer ports on the parent device
khenaidoo6e55d9e2019-12-12 18:26:26 -0500693 if !cloned.Root {
npujar1d86a522019-11-14 17:11:16 +0530694 go func() {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500695 err := agent.deviceMgr.deletePeerPorts(cloned.ParentId, cloned.Id)
npujar1d86a522019-11-14 17:11:16 +0530696 if err != nil {
697 log.Errorw("unable-to-delete-peer-ports", log.Fields{"error": err})
698 }
699 }()
khenaidoo4d4802d2018-10-04 21:59:49 -0400700 }
701 return nil
702}
703
npujar1d86a522019-11-14 17:11:16 +0530704func (agent *DeviceAgent) setParentID(device *voltha.Device, parentID string) error {
khenaidooad06fd72019-10-28 12:26:05 -0400705 agent.lockDevice.Lock()
706 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530707 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500708
709 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530710 cloned.ParentId = parentID
711 // Store the device
712 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
713 return err
714 }
715 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400716}
717
khenaidoob3127472019-07-24 21:04:55 -0400718func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
719 agent.lockDevice.Lock()
720 defer agent.lockDevice.Unlock()
721 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500722
723 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530724 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
725 // Store the device
726 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
727 return err
728 }
729 // Send the request to the adapter
730 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
731 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceID, "error": err})
732 return err
733 }
734 return nil
khenaidoob3127472019-07-24 21:04:55 -0400735}
736
737func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
738 agent.lockDevice.Lock()
739 defer agent.lockDevice.Unlock()
740 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500741
742 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530743 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
744 // Store the device
745 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
746 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, cloned, false, "")
747 if afterUpdate == nil {
748 return status.Errorf(codes.Internal, "%s", agent.deviceID)
749 }
750 return nil
khenaidoob3127472019-07-24 21:04:55 -0400751}
752
753func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
754 agent.lockDevice.RLock()
755 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530756 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500757
758 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400759}
760
khenaidoof5a5bfa2019-01-23 22:20:29 -0500761func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
762 agent.lockDevice.Lock()
763 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530764 log.Debugw("downloadImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500765
766 device := agent.getDeviceWithoutLock()
767
npujar1d86a522019-11-14 17:11:16 +0530768 if device.AdminState != voltha.AdminState_ENABLED {
769 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
770 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
771 }
772 // Save the image
773 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
774 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
775 cloned := proto.Clone(device).(*voltha.Device)
776 if cloned.ImageDownloads == nil {
777 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500778 } else {
779 if device.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530780 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
781 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500782 }
783 // Save the image
784 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500785 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500786 cloned := proto.Clone(device).(*voltha.Device)
787 if cloned.ImageDownloads == nil {
788 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
789 } else {
790 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
791 }
792 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300793 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
794 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500795 }
796 // Send the request to the adapter
797 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530798 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500799 return nil, err
800 }
801 }
802 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
803}
804
805// isImageRegistered is a helper method to figure out if an image is already registered
806func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
807 for _, image := range device.ImageDownloads {
808 if image.Id == img.Id && image.Name == img.Name {
809 return true
810 }
811 }
812 return false
813}
814
815func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
816 agent.lockDevice.Lock()
817 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530818 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500819
820 device := agent.getDeviceWithoutLock()
821
npujar1d86a522019-11-14 17:11:16 +0530822 // Verify whether the Image is in the list of image being downloaded
823 if !isImageRegistered(img, device) {
824 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
825 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500826
npujar1d86a522019-11-14 17:11:16 +0530827 // Update image download state
828 cloned := proto.Clone(device).(*voltha.Device)
829 for _, image := range cloned.ImageDownloads {
830 if image.Id == img.Id && image.Name == img.Name {
831 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500832 }
npujar1d86a522019-11-14 17:11:16 +0530833 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500834
npujar1d86a522019-11-14 17:11:16 +0530835 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
836 // Set the device to Enabled
837 cloned.AdminState = voltha.AdminState_ENABLED
838 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
839 return nil, err
840 }
841 // Send the request to the adapter
842 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
843 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
844 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500845 }
846 }
847 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700848}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500849
850func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
851 agent.lockDevice.Lock()
852 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530853 log.Debugw("activateImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500854 cloned := agent.getDeviceWithoutLock()
855
npujar1d86a522019-11-14 17:11:16 +0530856 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500857 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530858 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
859 }
860
khenaidoo6e55d9e2019-12-12 18:26:26 -0500861 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
npujar1d86a522019-11-14 17:11:16 +0530862 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
863 }
864 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530865 for _, image := range cloned.ImageDownloads {
866 if image.Id == img.Id && image.Name == img.Name {
867 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
868 }
869 }
870 // Set the device to downloading_image
871 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
872 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
873 return nil, err
874 }
875
khenaidoo6e55d9e2019-12-12 18:26:26 -0500876 if err := agent.adapterProxy.ActivateImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530877 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
878 return nil, err
879 }
880 // The status of the AdminState will be changed following the update_download_status response from the adapter
881 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -0700882 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
883}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500884
885func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
886 agent.lockDevice.Lock()
887 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530888 log.Debugw("revertImage", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500889
890 cloned := agent.getDeviceWithoutLock()
891
npujar1d86a522019-11-14 17:11:16 +0530892 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -0500893 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +0530894 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
895 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500896
khenaidoo6e55d9e2019-12-12 18:26:26 -0500897 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530898 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
899 }
900 // Update image download state
npujar1d86a522019-11-14 17:11:16 +0530901 for _, image := range cloned.ImageDownloads {
902 if image.Id == img.Id && image.Name == img.Name {
903 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -0500904 }
npujar1d86a522019-11-14 17:11:16 +0530905 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300906
npujar1d86a522019-11-14 17:11:16 +0530907 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
908 return nil, err
909 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500910
khenaidoo6e55d9e2019-12-12 18:26:26 -0500911 if err := agent.adapterProxy.RevertImageUpdate(ctx, proto.Clone(cloned).(*voltha.Device), img); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530912 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
913 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500914 }
915 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700916}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500917
918func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
919 agent.lockDevice.Lock()
920 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530921 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500922
923 cloned := agent.getDeviceWithoutLock()
924 resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, cloned, img)
npujar1d86a522019-11-14 17:11:16 +0530925 if err != nil {
926 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
927 return nil, err
928 }
929 return resp, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500930}
931
serkant.uluderya334479d2019-04-10 08:26:15 -0700932func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500933 agent.lockDevice.Lock()
934 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530935 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500936
937 cloned := agent.getDeviceWithoutLock()
938
npujar1d86a522019-11-14 17:11:16 +0530939 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +0530940 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
941 for _, image := range cloned.ImageDownloads {
942 if image.Id == img.Id && image.Name == img.Name {
943 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
944 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500945 }
946 }
npujar1d86a522019-11-14 17:11:16 +0530947 }
948 cloned.ImageDownloads = clonedImages
949 // Set the Admin state to enabled if required
950 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
951 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
952 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
953 cloned.AdminState = voltha.AdminState_ENABLED
954 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500955
npujar1d86a522019-11-14 17:11:16 +0530956 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
957 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500958 }
959 return nil
960}
961
962func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400963 agent.lockDevice.RLock()
964 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530965 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500966
967 cloned := agent.getDeviceWithoutLock()
968 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +0530969 if image.Id == img.Id && image.Name == img.Name {
970 return image, nil
971 }
972 }
973 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500974}
975
npujar1d86a522019-11-14 17:11:16 +0530976func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400977 agent.lockDevice.RLock()
978 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530979 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500980
981 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500982}
983
khenaidoo4d4802d2018-10-04 21:59:49 -0400984// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400985func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
npujar1d86a522019-11-14 17:11:16 +0530986 log.Debugw("getPorts", log.Fields{"id": agent.deviceID, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400987 ports := &voltha.Ports{}
npujar1d86a522019-11-14 17:11:16 +0530988 if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400989 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400990 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400991 ports.Items = append(ports.Items, port)
992 }
993 }
994 }
995 return ports
996}
997
khenaidoo4d4802d2018-10-04 21:59:49 -0400998// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
999// parent device
khenaidoo79232702018-12-04 11:00:41 -05001000func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301001 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceID})
1002 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
1003 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001004 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001005 }
npujar1d86a522019-11-14 17:11:16 +05301006 var switchCap *ic.SwitchCapability
1007 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
1008 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
1009 return nil, err
1010 }
1011 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001012}
1013
khenaidoo4d4802d2018-10-04 21:59:49 -04001014// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
1015// device
khenaidoo79232702018-12-04 11:00:41 -05001016func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301017 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceID})
1018 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
1019 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001020 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001021 }
npujar1d86a522019-11-14 17:11:16 +05301022 var portCap *ic.PortCapability
1023 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
1024 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1025 return nil, err
1026 }
1027 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001028}
1029
khenaidoofdbad6e2018-11-06 22:26:38 -05001030func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001031 // If deviceType=="" then we must have taken ownership of this device.
1032 // Fixes VOL-2226 where a core would take ownership and have stale data
1033 if agent.deviceType == "" {
1034 agent.reconcileWithKVStore()
1035 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001036 // Send packet to adapter
npujar1d86a522019-11-14 17:11:16 +05301037 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceID, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001038 log.Debugw("packet-out-error", log.Fields{
npujar1d86a522019-11-14 17:11:16 +05301039 "id": agent.deviceID,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001040 "error": err,
1041 "packet": hex.EncodeToString(packet.Data),
1042 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001043 return err
1044 }
1045 return nil
1046}
1047
khenaidoo4d4802d2018-10-04 21:59:49 -04001048// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001049func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001050 //// Run this callback in its own go routine
1051 go func(args ...interface{}) interface{} {
1052 var previous *voltha.Device
1053 var current *voltha.Device
1054 var ok bool
1055 if len(args) == 2 {
1056 if previous, ok = args[0].(*voltha.Device); !ok {
1057 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1058 return nil
1059 }
1060 if current, ok = args[1].(*voltha.Device); !ok {
1061 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1062 return nil
1063 }
1064 } else {
1065 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1066 return nil
1067 }
1068 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001069 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1070 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1071 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1072 }
khenaidoo43c82122018-11-22 18:38:28 -05001073 return nil
1074 }(args...)
1075
khenaidoo92e62c52018-10-03 14:02:54 -04001076 return nil
1077}
1078
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001079// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1080// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1081func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001082 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001083 cloned.Root = device.Root
1084 cloned.Vendor = device.Vendor
1085 cloned.Model = device.Model
1086 cloned.SerialNumber = device.SerialNumber
1087 cloned.MacAddress = device.MacAddress
1088 cloned.Vlan = device.Vlan
1089 cloned.Reason = device.Reason
1090 return cloned, nil
1091}
1092func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001093 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001094 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001095 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
npujar1d86a522019-11-14 17:11:16 +05301096 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1097 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001098 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1099 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001100 }
npujar1d86a522019-11-14 17:11:16 +05301101 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1102 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001103}
1104
1105func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1106 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1107 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001108 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001109}
1110
khenaidoo92e62c52018-10-03 14:02:54 -04001111func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1112 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001113 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001114
1115 cloned := agent.getDeviceWithoutLock()
1116
npujar1d86a522019-11-14 17:11:16 +05301117 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1118 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1119 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1120 cloned.ConnectStatus = connStatus
1121 }
1122 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1123 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1124 cloned.OperStatus = operStatus
1125 }
1126 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
1127 // Store the device
1128 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001129}
1130
khenaidoo3ab34882019-05-02 21:33:30 -04001131func (agent *DeviceAgent) enablePorts() error {
1132 agent.lockDevice.Lock()
1133 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001134
1135 cloned := agent.getDeviceWithoutLock()
1136
npujar1d86a522019-11-14 17:11:16 +05301137 for _, port := range cloned.Ports {
1138 port.AdminState = voltha.AdminState_ENABLED
1139 port.OperStatus = voltha.OperStatus_ACTIVE
1140 }
1141 // Store the device
1142 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001143}
1144
1145func (agent *DeviceAgent) disablePorts() error {
npujar1d86a522019-11-14 17:11:16 +05301146 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceID})
khenaidoo3ab34882019-05-02 21:33:30 -04001147 agent.lockDevice.Lock()
1148 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001149 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301150 for _, port := range cloned.Ports {
1151 port.AdminState = voltha.AdminState_DISABLED
1152 port.OperStatus = voltha.OperStatus_UNKNOWN
1153 }
1154 // Store the device
1155 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001156}
1157
khenaidoo92e62c52018-10-03 14:02:54 -04001158func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1159 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001160 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001161 // Work only on latest data
1162 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001163 cloned := agent.getDeviceWithoutLock()
1164
npujar1d86a522019-11-14 17:11:16 +05301165 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1166 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1167 return status.Errorf(codes.InvalidArgument, "%s", portType)
1168 }
1169 for _, port := range cloned.Ports {
1170 if port.Type == portType && port.PortNo == portNo {
1171 port.OperStatus = operStatus
1172 // Set the admin status to ENABLED if the operational status is ACTIVE
1173 // TODO: Set by northbound system?
1174 if operStatus == voltha.OperStatus_ACTIVE {
1175 port.AdminState = voltha.AdminState_ENABLED
1176 }
1177 break
1178 }
1179 }
1180 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1181 // Store the device
1182 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001183}
1184
khenaidoo0a822f92019-05-08 15:15:57 -04001185func (agent *DeviceAgent) deleteAllPorts() error {
npujar1d86a522019-11-14 17:11:16 +05301186 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -04001187 agent.lockDevice.Lock()
1188 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001189
1190 cloned := agent.getDeviceWithoutLock()
1191
1192 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1193 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
1194 log.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301195 return err
1196 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001197 if len(cloned.Ports) == 0 {
npujar1d86a522019-11-14 17:11:16 +05301198 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
1199 return nil
1200 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001201
npujar1d86a522019-11-14 17:11:16 +05301202 cloned.Ports = []*voltha.Port{}
1203 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1204 // Store the device
1205 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001206}
1207
khenaidoob9203542018-09-17 22:56:37 -04001208func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001209 agent.lockDevice.Lock()
1210 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301211 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001212
1213 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301214 if cloned.Ports == nil {
1215 // First port
1216 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
1217 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001218 } else {
npujar1d86a522019-11-14 17:11:16 +05301219 for _, p := range cloned.Ports {
1220 if p.Type == port.Type && p.PortNo == port.PortNo {
1221 log.Debugw("port already exists", log.Fields{"port": *port})
1222 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001223 }
khenaidoob9203542018-09-17 22:56:37 -04001224 }
khenaidoo92e62c52018-10-03 14:02:54 -04001225 }
npujar1d86a522019-11-14 17:11:16 +05301226 cp := proto.Clone(port).(*voltha.Port)
1227 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1228 // TODO: Set by northbound system?
1229 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1230 cp.AdminState = voltha.AdminState_ENABLED
1231 }
1232 cloned.Ports = append(cloned.Ports, cp)
1233 // Store the device
1234 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001235}
1236
1237func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1238 agent.lockDevice.Lock()
1239 defer agent.lockDevice.Unlock()
1240 log.Debug("addPeerPort")
khenaidoo6e55d9e2019-12-12 18:26:26 -05001241
1242 cloned := agent.getDeviceWithoutLock()
1243
npujar1d86a522019-11-14 17:11:16 +05301244 // Get the peer port on the device based on the port no
1245 for _, peerPort := range cloned.Ports {
1246 if peerPort.PortNo == port.PortNo { // found port
1247 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1248 peerPort.Peers = append(peerPort.Peers, cp)
1249 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceID})
1250 break
1251 }
1252 }
1253 // Store the device
1254 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001255}
1256
npujar1d86a522019-11-14 17:11:16 +05301257func (agent *DeviceAgent) deletePeerPorts(deviceID string) error {
khenaidoo0a822f92019-05-08 15:15:57 -04001258 agent.lockDevice.Lock()
1259 defer agent.lockDevice.Unlock()
1260 log.Debug("deletePeerPorts")
khenaidoo6e55d9e2019-12-12 18:26:26 -05001261
1262 cloned := agent.getDeviceWithoutLock()
1263
npujar1d86a522019-11-14 17:11:16 +05301264 var updatedPeers []*voltha.Port_PeerPort
1265 for _, port := range cloned.Ports {
1266 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1267 for _, peerPort := range port.Peers {
1268 if peerPort.DeviceId != deviceID {
1269 updatedPeers = append(updatedPeers, peerPort)
1270 }
1271 }
1272 port.Peers = updatedPeers
1273 }
1274
1275 // Store the device with updated peer ports
1276 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001277}
1278
khenaidoob9203542018-09-17 22:56:37 -04001279// TODO: A generic device update by attribute
1280func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001281 agent.lockDevice.Lock()
1282 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001283 if value == nil {
1284 return
1285 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001286
1287 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001288 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001289 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001290 if s.Kind() == reflect.Struct {
1291 // exported field
1292 f := s.FieldByName(name)
1293 if f.IsValid() && f.CanSet() {
1294 switch f.Kind() {
1295 case reflect.String:
1296 f.SetString(value.(string))
1297 updated = true
1298 case reflect.Uint32:
1299 f.SetUint(uint64(value.(uint32)))
1300 updated = true
1301 case reflect.Bool:
1302 f.SetBool(value.(bool))
1303 updated = true
1304 }
1305 }
1306 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001307 log.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001308 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001309
1310 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001311 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1312 }
khenaidoob9203542018-09-17 22:56:37 -04001313}
serkant.uluderya334479d2019-04-10 08:26:15 -07001314
1315func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1316 agent.lockDevice.Lock()
1317 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301318 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001319
1320 cloned := agent.getDeviceWithoutLock()
1321
npujar1d86a522019-11-14 17:11:16 +05301322 // First send the request to an Adapter and wait for a response
khenaidoo6e55d9e2019-12-12 18:26:26 -05001323 if err := agent.adapterProxy.SimulateAlarm(ctx, cloned, simulatereq); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301324 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceID, "error": err})
1325 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001326 }
1327 return nil
1328}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001329
1330//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.
1331// It is an internal helper function.
1332func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1333 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
npujar1d86a522019-11-14 17:11:16 +05301334 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, device, strict, txid); afterUpdate == nil {
1335 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001336 }
npujar1d86a522019-11-14 17:11:16 +05301337 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001338
khenaidoo6e55d9e2019-12-12 18:26:26 -05001339 agent.device = proto.Clone(device).(*voltha.Device)
1340
Mahir Gunyelb5851672019-07-24 10:46:26 +03001341 return nil
1342}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001343
1344func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1345 agent.lockDevice.Lock()
1346 defer agent.lockDevice.Unlock()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001347
1348 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301349 cloned.Reason = reason
1350 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1351 // Store the device
1352 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001353}