blob: 0f4c177fb58da1efb0ca9ed5509bfbf71d2f1fd1 [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
khenaidoo2c6a0992019-04-29 13:46:56 -040052 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040053}
54
Scott Baker80678602019-11-14 16:57:36 -080055//newDeviceAgent creates a new device agent. The device will be initialized when start() is called.
khenaidoo2c6a0992019-04-29 13:46:56 -040056func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040057 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040058 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080059 if device.Id == "" {
npujar1d86a522019-11-14 17:11:16 +053060 agent.deviceID = CreateDeviceID()
Scott Baker80678602019-11-14 16:57:36 -080061 } else {
npujar1d86a522019-11-14 17:11:16 +053062 agent.deviceID = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050063 }
Scott Baker80678602019-11-14 16:57:36 -080064
khenaidoo2c6a0992019-04-29 13:46:56 -040065 agent.isRootdevice = device.Root
npujar1d86a522019-11-14 17:11:16 +053066 agent.parentID = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080067 agent.deviceType = device.Type
khenaidoob9203542018-09-17 22:56:37 -040068 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050069 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040070 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040071 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040072 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040073 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040074 return &agent
75}
76
Scott Baker80678602019-11-14 16:57:36 -080077// start()
78// save the device to the data model and registers for callbacks on that device if deviceToCreate!=nil. Otherwise,
npujar1d86a522019-11-14 17:11:16 +053079// 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 -080080// was started.
81func (agent *DeviceAgent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
82 var device *voltha.Device
83
khenaidoo92e62c52018-10-03 14:02:54 -040084 agent.lockDevice.Lock()
85 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +053086 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceID})
Scott Baker80678602019-11-14 16:57:36 -080087 if deviceToCreate == nil {
88 // Load the existing device
npujar1d86a522019-11-14 17:11:16 +053089 if loadedDevice := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, ""); loadedDevice != nil {
Scott Baker80678602019-11-14 16:57:36 -080090 var ok bool
91 if device, ok = loadedDevice.(*voltha.Device); ok {
92 agent.deviceType = device.Adapter
93 } else {
npujar1d86a522019-11-14 17:11:16 +053094 log.Errorw("failed-to-convert-device", log.Fields{"deviceId": agent.deviceID})
95 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -050096 }
97 } else {
npujar1d86a522019-11-14 17:11:16 +053098 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceID})
99 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500100 }
npujar1d86a522019-11-14 17:11:16 +0530101 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500102 } else {
Scott Baker80678602019-11-14 16:57:36 -0800103 // Create a new device
104 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
105 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
106 // agent.deviceId will also have been set during newDeviceAgent().
107 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530108 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800109 device.AdminState = voltha.AdminState_PREPROVISIONED
110 device.FlowGroups = &ofp.FlowGroups{Items: nil}
111 device.Flows = &ofp.Flows{Items: nil}
112 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
113 // Set the default vlan ID to the one specified by the parent adapter. It can be
114 // overwritten by the child adapter during a device update request
115 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
116 }
117
khenaidoo297cd252019-02-07 22:10:23 -0500118 // Add the initial device to the local model
npujar1d86a522019-11-14 17:11:16 +0530119 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceID, device, ""); added == nil {
120 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceID})
121 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500122 }
khenaidoob9203542018-09-17 22:56:37 -0400123 }
khenaidoo297cd252019-02-07 22:10:23 -0500124
npujar1d86a522019-11-14 17:11:16 +0530125 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceID, false)
khenaidoo43c82122018-11-22 18:38:28 -0500126 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400127
npujar1d86a522019-11-14 17:11:16 +0530128 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceID})
Scott Baker80678602019-11-14 16:57:36 -0800129 return device, nil
khenaidoob9203542018-09-17 22:56:37 -0400130}
131
khenaidoo4d4802d2018-10-04 21:59:49 -0400132// stop stops the device agent. Not much to do for now
133func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400134 agent.lockDevice.Lock()
135 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400136 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400137 // Remove the device from the KV store
npujar1d86a522019-11-14 17:11:16 +0530138 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceID, ""); removed == nil {
139 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -0400140 }
khenaidoob9203542018-09-17 22:56:37 -0400141 agent.exitChannel <- 1
142 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400143
khenaidoob9203542018-09-17 22:56:37 -0400144}
145
Scott Baker80678602019-11-14 16:57:36 -0800146// Load the most recent state from the KVStore for the device.
147func (agent *DeviceAgent) reconcileWithKVStore() {
148 agent.lockDevice.Lock()
149 defer agent.lockDevice.Unlock()
150 log.Debug("reconciling-device-agent-devicetype")
151 // TODO: context timeout
npujar1d86a522019-11-14 17:11:16 +0530152 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceID, 1, true, ""); device != nil {
Scott Baker80678602019-11-14 16:57:36 -0800153 if d, ok := device.(*voltha.Device); ok {
154 agent.deviceType = d.Adapter
npujar1d86a522019-11-14 17:11:16 +0530155 log.Debugw("reconciled-device-agent-devicetype", log.Fields{"Id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800156 }
157 }
158}
159
khenaidoo19d7b632018-10-30 10:49:50 -0400160// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400161func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400162 agent.lockDevice.RLock()
163 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530164 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceID, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400165 if d, ok := device.(*voltha.Device); ok {
166 cloned := proto.Clone(d).(*voltha.Device)
167 return cloned, nil
168 }
169 }
npujar1d86a522019-11-14 17:11:16 +0530170 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo92e62c52018-10-03 14:02:54 -0400171}
172
khenaidoo4d4802d2018-10-04 21:59:49 -0400173// getDeviceWithoutLock is a helper function to be used ONLY by any device agent function AFTER it has acquired the device lock.
khenaidoo92e62c52018-10-03 14:02:54 -0400174// This function is meant so that we do not have duplicate code all over the device agent functions
175func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
npujar1d86a522019-11-14 17:11:16 +0530176 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceID, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400177 if d, ok := device.(*voltha.Device); ok {
178 cloned := proto.Clone(d).(*voltha.Device)
179 return cloned, nil
180 }
181 }
npujar1d86a522019-11-14 17:11:16 +0530182 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo92e62c52018-10-03 14:02:54 -0400183}
184
khenaidoo3ab34882019-05-02 21:33:30 -0400185// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400186func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400187 agent.lockDevice.Lock()
188 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530189 log.Debugw("enableDevice", log.Fields{"id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500190
npujar1d86a522019-11-14 17:11:16 +0530191 device, err := agent.getDeviceWithoutLock()
192 if err != nil {
193 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
194 }
195 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
196 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
197 // with the adapter then we need to know the adapter that will handle this request
198 adapterName, err := agent.adapterMgr.getAdapterName(device.Type)
199 if err != nil {
200 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
201 return err
202 }
203 device.Adapter = adapterName
204
205 if device.AdminState == voltha.AdminState_ENABLED {
206 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceID})
207 return nil
208 }
209
210 if device.AdminState == voltha.AdminState_DELETED {
211 // This is a temporary state when a device is deleted before it gets removed from the model.
212 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
213 log.Warnw("invalid-state", log.Fields{"id": agent.deviceID, "state": device.AdminState, "error": err})
214 return err
215 }
216
217 previousAdminState := device.AdminState
218
219 // Update the Admin State and set the operational state to activating before sending the request to the
220 // Adapters
221 cloned := proto.Clone(device).(*voltha.Device)
222 cloned.AdminState = voltha.AdminState_ENABLED
223 cloned.OperStatus = voltha.OperStatus_ACTIVATING
224
225 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
226 return err
227 }
228
229 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
230 if previousAdminState == voltha.AdminState_PREPROVISIONED {
231 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
232 log.Debugw("adoptDevice-error", log.Fields{"id": agent.deviceID, "error": err})
233 return err
234 }
khenaidoob9203542018-09-17 22:56:37 -0400235 } else {
npujar1d86a522019-11-14 17:11:16 +0530236 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
237 log.Debugw("renableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
khenaidoo21d51152019-02-01 13:48:37 -0500238 return err
khenaidoob9203542018-09-17 22:56:37 -0400239 }
240 }
241 return nil
242}
243
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500244func (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 -0400245 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530246 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500247 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400248 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500249 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400250}
251
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500252func (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 -0400253 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530254 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.deviceID, "error": err})
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500255 response.Error(err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400256 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500257 response.Done()
khenaidoo2c6a0992019-04-29 13:46:56 -0400258}
259
khenaidoo0458db62019-06-20 08:50:36 -0400260//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
261//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400262func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar1d86a522019-11-14 17:11:16 +0530263 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400264
khenaidoo2c6a0992019-04-29 13:46:56 -0400265 if (len(newFlows) | len(newGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530266 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400267 return nil
268 }
269
khenaidoo19d7b632018-10-30 10:49:50 -0400270 agent.lockDevice.Lock()
271 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400272
khenaidoo0458db62019-06-20 08:50:36 -0400273 var device *voltha.Device
274 var err error
275 if device, err = agent.getDeviceWithoutLock(); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530276 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400277 }
278
279 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
280 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
281
282 var updatedFlows []*ofp.OfpFlowStats
283 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400284 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400285 var updatedGroups []*ofp.OfpGroupEntry
286
287 // Process flows
npujar1d86a522019-11-14 17:11:16 +0530288 updatedFlows = append(updatedFlows, newFlows...)
khenaidoo0458db62019-06-20 08:50:36 -0400289 for _, flow := range existingFlows.Items {
290 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400291 updatedFlows = append(updatedFlows, flow)
khenaidoo0458db62019-06-20 08:50:36 -0400292 } else {
293 flowsToDelete = append(flowsToDelete, flow)
294 }
295 }
296
297 // Process groups
npujar1d86a522019-11-14 17:11:16 +0530298 updatedGroups = append(updatedGroups, newGroups...)
khenaidoo0458db62019-06-20 08:50:36 -0400299 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400300 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
301 updatedGroups = append(updatedGroups, group)
302 } else {
303 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400304 }
305 }
306
307 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400308 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530309 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400310 return nil
311 }
312
313 // Send update to adapters
314 // Create two channels to receive responses from the dB and from the adapters.
315 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
316 // to send their responses. These channels will be garbage collected once all the responses are
317 // received
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500318 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400319 dType := agent.adapterMgr.getDeviceType(device.Type)
320 if !dType.AcceptsAddRemoveFlowUpdates {
321
322 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530323 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400324 return nil
325 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500326 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400327
328 } else {
329 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400330 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400331 ToRemove: &voltha.Flows{Items: flowsToDelete},
332 }
333 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400334 ToAdd: &voltha.FlowGroups{Items: newGroups},
335 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400336 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
337 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500338 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400339 }
340
341 // store the changed data
342 device.Flows = &voltha.Flows{Items: updatedFlows}
343 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500344 if err := agent.updateDeviceWithoutLock(device); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530345 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500346 }
khenaidoo0458db62019-06-20 08:50:36 -0400347
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500348 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400349 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400350 return status.Errorf(codes.Aborted, "errors-%s", res)
351 }
352
353 return nil
354}
355
356//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
357//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400358func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar1d86a522019-11-14 17:11:16 +0530359 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400360
361 if (len(flowsToDel) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530362 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400363 return nil
364 }
365
366 agent.lockDevice.Lock()
367 defer agent.lockDevice.Unlock()
368
369 var device *voltha.Device
370 var err error
371
372 if device, err = agent.getDeviceWithoutLock(); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530373 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400374 }
375
376 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
377 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
378
379 var flowsToKeep []*ofp.OfpFlowStats
380 var groupsToKeep []*ofp.OfpGroupEntry
381
382 // Process flows
383 for _, flow := range existingFlows.Items {
384 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
385 flowsToKeep = append(flowsToKeep, flow)
386 }
387 }
388
389 // Process groups
390 for _, group := range existingGroups.Items {
391 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
392 groupsToKeep = append(groupsToKeep, group)
393 }
394 }
395
396 log.Debugw("deleteFlowsAndGroups",
397 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530398 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400399 "flowsToDel": len(flowsToDel),
400 "flowsToKeep": len(flowsToKeep),
401 "groupsToDel": len(groupsToDel),
402 "groupsToKeep": len(groupsToKeep),
403 })
404
405 // Sanity check
406 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530407 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400408 return nil
409 }
410
411 // Send update to adapters
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500412 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400413 dType := agent.adapterMgr.getDeviceType(device.Type)
414 if !dType.AcceptsAddRemoveFlowUpdates {
415 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
npujar1d86a522019-11-14 17:11:16 +0530416 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400417 return nil
418 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500419 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400420 } else {
421 flowChanges := &ofp.FlowChanges{
422 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
423 ToRemove: &voltha.Flows{Items: flowsToDel},
424 }
425 groupChanges := &ofp.FlowGroupChanges{
426 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
427 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
428 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
429 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500430 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo0458db62019-06-20 08:50:36 -0400431 }
432
433 // store the changed data
434 device.Flows = &voltha.Flows{Items: flowsToKeep}
435 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
Kent Hagerman3c513972019-11-25 13:49:41 -0500436 if err := agent.updateDeviceWithoutLock(device); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530437 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500438 }
khenaidoo0458db62019-06-20 08:50:36 -0400439
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
444
445}
446
447//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
448//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400449func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar1d86a522019-11-14 17:11:16 +0530450 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400451
452 if (len(updatedFlows) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530453 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400454 return nil
455 }
456
457 agent.lockDevice.Lock()
458 defer agent.lockDevice.Unlock()
459 var device *voltha.Device
460 var err error
461 if device, err = agent.getDeviceWithoutLock(); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530462 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400463 }
464 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
465 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
466
467 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
npujar1d86a522019-11-14 17:11:16 +0530468 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400469 return nil
470 }
471
472 log.Debugw("updating-flows-and-groups",
473 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530474 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400475 "updatedFlows": updatedFlows,
476 "updatedGroups": updatedGroups,
477 })
478
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500479 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400480 dType := agent.adapterMgr.getDeviceType(device.Type)
481
482 // Process bulk flow update differently than incremental update
483 if !dType.AcceptsAddRemoveFlowUpdates {
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500484 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, response)
khenaidoo0458db62019-06-20 08:50:36 -0400485 } else {
486 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400487 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400488 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400489 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400490
491 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400492 for _, flow := range updatedFlows {
493 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
494 flowsToAdd = append(flowsToAdd, flow)
495 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400496 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400497 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400498 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400499 flowsToDelete = append(flowsToDelete, flow)
500 }
501 }
502
503 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400504 for _, g := range updatedGroups {
505 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
506 groupsToAdd = append(groupsToAdd, g)
507 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400508 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400509 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400510 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400511 groupsToDelete = append(groupsToDelete, group)
512 }
513 }
514
khenaidoo0458db62019-06-20 08:50:36 -0400515 log.Debugw("updating-flows-and-groups",
516 log.Fields{
npujar1d86a522019-11-14 17:11:16 +0530517 "deviceId": agent.deviceID,
khenaidoo0458db62019-06-20 08:50:36 -0400518 "flowsToAdd": flowsToAdd,
519 "flowsToDelete": flowsToDelete,
520 "groupsToAdd": groupsToAdd,
521 "groupsToDelete": groupsToDelete,
522 })
523
khenaidoo2c6a0992019-04-29 13:46:56 -0400524 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400525 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
npujar1d86a522019-11-14 17:11:16 +0530526 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400527 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400528 }
529
khenaidoo0458db62019-06-20 08:50:36 -0400530 flowChanges := &ofp.FlowChanges{
531 ToAdd: &voltha.Flows{Items: flowsToAdd},
532 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400533 }
khenaidoo0458db62019-06-20 08:50:36 -0400534 groupChanges := &ofp.FlowGroupChanges{
535 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
536 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
537 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
538 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500539 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, response)
khenaidoo19d7b632018-10-30 10:49:50 -0400540 }
khenaidoo0458db62019-06-20 08:50:36 -0400541
542 // store the updated data
543 device.Flows = &voltha.Flows{Items: updatedFlows}
544 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500545 if err := agent.updateDeviceWithoutLock(device); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530546 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
Kent Hagerman3c513972019-11-25 13:49:41 -0500547 }
khenaidoo0458db62019-06-20 08:50:36 -0400548
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500549 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400550 return status.Errorf(codes.Aborted, "errors-%s", res)
551 }
552 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400553}
554
khenaidoo4d4802d2018-10-04 21:59:49 -0400555//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400556func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400557 agent.lockDevice.Lock()
558 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530559 log.Debugw("disableDevice", log.Fields{"id": agent.deviceID})
khenaidoo92e62c52018-10-03 14:02:54 -0400560 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530561 device, err := agent.getDeviceWithoutLock()
562 if err != nil {
563 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
564 }
565 if device.AdminState == voltha.AdminState_DISABLED {
566 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
567 return nil
568 }
569 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
570 device.AdminState == voltha.AdminState_DELETED {
571 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
572 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, device.AdminState)
573 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400574
npujar1d86a522019-11-14 17:11:16 +0530575 // Update the Admin State and operational state before sending the request out
576 cloned := proto.Clone(device).(*voltha.Device)
577 cloned.AdminState = voltha.AdminState_DISABLED
578 cloned.OperStatus = voltha.OperStatus_UNKNOWN
579 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
580 return err
581 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400582
npujar1d86a522019-11-14 17:11:16 +0530583 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
584 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceID, "error": err})
585 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400586 }
587 return nil
588}
589
590func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
591 agent.lockDevice.Lock()
592 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530593 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -0400594 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530595 device, err := agent.getDeviceWithoutLock()
596 if err != nil {
597 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
598 }
599 if device.AdminState == adminState {
600 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceID, "state": adminState})
601 return nil
602 }
603 // Received an Ack (no error found above). Now update the device in the model to the expected state
604 cloned := proto.Clone(device).(*voltha.Device)
605 cloned.AdminState = adminState
606 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
607 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400608 }
609 return nil
610}
611
khenaidoo4d4802d2018-10-04 21:59:49 -0400612func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
613 agent.lockDevice.Lock()
614 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530615 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceID})
khenaidoo4d4802d2018-10-04 21:59:49 -0400616 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530617 device, err := agent.getDeviceWithoutLock()
618 if err != nil {
619 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
620 }
621 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
622 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceID, "error": err})
623 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400624 }
625 return nil
626}
627
628func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
629 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400630 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530631 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceID})
khenaidoo4d4802d2018-10-04 21:59:49 -0400632 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530633 device, err := agent.getDeviceWithoutLock()
634 if err != nil {
635 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
636 }
637 if device.AdminState == voltha.AdminState_DELETED {
638 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceID})
639 return nil
640 }
641 if (device.AdminState != voltha.AdminState_DISABLED) &&
642 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
643 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceID})
644 //TODO: Needs customized error message
645 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_DISABLED)
646 }
647 if device.AdminState != voltha.AdminState_PREPROVISIONED {
648 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
649 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
650 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceID, "error": err})
Mahir Gunyelb5851672019-07-24 10:46:26 +0300651 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400652 }
npujar1d86a522019-11-14 17:11:16 +0530653 }
654 // Set the state to deleted after we receive an Ack - this will trigger some background process to clean up
655 // the device as well as its association with the logical device
656 cloned := proto.Clone(device).(*voltha.Device)
657 cloned.AdminState = voltha.AdminState_DELETED
658 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
659 return err
660 }
661 // If this is a child device then remove the associated peer ports on the parent device
662 if !device.Root {
663 go func() {
664 err := agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
665 if err != nil {
666 log.Errorw("unable-to-delete-peer-ports", log.Fields{"error": err})
667 }
668 }()
khenaidoo4d4802d2018-10-04 21:59:49 -0400669 }
670 return nil
671}
672
npujar1d86a522019-11-14 17:11:16 +0530673func (agent *DeviceAgent) setParentID(device *voltha.Device, parentID string) error {
khenaidooad06fd72019-10-28 12:26:05 -0400674 agent.lockDevice.Lock()
675 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530676 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentID})
677 storeDevice, err := agent.getDeviceWithoutLock()
678 if err != nil {
679 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidooad06fd72019-10-28 12:26:05 -0400680 }
npujar1d86a522019-11-14 17:11:16 +0530681 // clone the device
682 cloned := proto.Clone(storeDevice).(*voltha.Device)
683 cloned.ParentId = parentID
684 // Store the device
685 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
686 return err
687 }
688 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400689}
690
khenaidoob3127472019-07-24 21:04:55 -0400691func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
692 agent.lockDevice.Lock()
693 defer agent.lockDevice.Unlock()
694 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
695 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +0530696 storeDevice, err := agent.getDeviceWithoutLock()
697 if err != nil {
698 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoob3127472019-07-24 21:04:55 -0400699 }
npujar1d86a522019-11-14 17:11:16 +0530700 // clone the device
701 cloned := proto.Clone(storeDevice).(*voltha.Device)
702 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
703 // Store the device
704 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
705 return err
706 }
707 // Send the request to the adapter
708 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
709 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceID, "error": err})
710 return err
711 }
712 return nil
khenaidoob3127472019-07-24 21:04:55 -0400713}
714
715func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
716 agent.lockDevice.Lock()
717 defer agent.lockDevice.Unlock()
718 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
719 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +0530720 storeDevice, err := agent.getDeviceWithoutLock()
721 if err != nil {
722 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoob3127472019-07-24 21:04:55 -0400723 }
npujar1d86a522019-11-14 17:11:16 +0530724 // clone the device
725 cloned := proto.Clone(storeDevice).(*voltha.Device)
726 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
727 // Store the device
728 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
729 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, cloned, false, "")
730 if afterUpdate == nil {
731 return status.Errorf(codes.Internal, "%s", agent.deviceID)
732 }
733 return nil
khenaidoob3127472019-07-24 21:04:55 -0400734}
735
736func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
737 agent.lockDevice.RLock()
738 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530739 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceID})
khenaidoob3127472019-07-24 21:04:55 -0400740 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530741 device, err := agent.getDeviceWithoutLock()
742 if err != nil {
743 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoob3127472019-07-24 21:04:55 -0400744 }
npujar1d86a522019-11-14 17:11:16 +0530745 cloned := proto.Clone(device).(*voltha.Device)
746 return cloned.PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400747}
748
khenaidoof5a5bfa2019-01-23 22:20:29 -0500749func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
750 agent.lockDevice.Lock()
751 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530752 log.Debugw("downloadImage", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500753 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530754 device, err := agent.getDeviceWithoutLock()
755 if err != nil {
756 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
757 }
758 if device.AdminState != voltha.AdminState_ENABLED {
759 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
760 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
761 }
762 // Save the image
763 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
764 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
765 cloned := proto.Clone(device).(*voltha.Device)
766 if cloned.ImageDownloads == nil {
767 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500768 } else {
769 if device.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +0530770 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
771 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500772 }
773 // Save the image
774 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500775 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500776 cloned := proto.Clone(device).(*voltha.Device)
777 if cloned.ImageDownloads == nil {
778 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
779 } else {
780 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
781 }
782 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300783 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
784 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500785 }
786 // Send the request to the adapter
787 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530788 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500789 return nil, err
790 }
791 }
792 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
793}
794
795// isImageRegistered is a helper method to figure out if an image is already registered
796func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
797 for _, image := range device.ImageDownloads {
798 if image.Id == img.Id && image.Name == img.Name {
799 return true
800 }
801 }
802 return false
803}
804
805func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
806 agent.lockDevice.Lock()
807 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530808 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500809 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530810 device, err := agent.getDeviceWithoutLock()
811 if err != nil {
812 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
813 }
814 // Verify whether the Image is in the list of image being downloaded
815 if !isImageRegistered(img, device) {
816 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
817 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500818
npujar1d86a522019-11-14 17:11:16 +0530819 // Update image download state
820 cloned := proto.Clone(device).(*voltha.Device)
821 for _, image := range cloned.ImageDownloads {
822 if image.Id == img.Id && image.Name == img.Name {
823 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500824 }
npujar1d86a522019-11-14 17:11:16 +0530825 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500826
npujar1d86a522019-11-14 17:11:16 +0530827 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
828 // Set the device to Enabled
829 cloned.AdminState = voltha.AdminState_ENABLED
830 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
831 return nil, err
832 }
833 // Send the request to the adapter
834 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
835 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
836 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500837 }
838 }
839 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700840}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500841
842func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
843 agent.lockDevice.Lock()
844 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530845 log.Debugw("activateImage", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500846 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530847 device, err := agent.getDeviceWithoutLock()
848 if err != nil {
849 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500850 }
npujar1d86a522019-11-14 17:11:16 +0530851 // Verify whether the Image is in the list of image being downloaded
852 if !isImageRegistered(img, device) {
853 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
854 }
855
856 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
857 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
858 }
859 // Update image download state
860 cloned := proto.Clone(device).(*voltha.Device)
861 for _, image := range cloned.ImageDownloads {
862 if image.Id == img.Id && image.Name == img.Name {
863 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
864 }
865 }
866 // Set the device to downloading_image
867 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
868 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
869 return nil, err
870 }
871
872 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
873 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
874 return nil, err
875 }
876 // The status of the AdminState will be changed following the update_download_status response from the adapter
877 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -0700878 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
879}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500880
881func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
882 agent.lockDevice.Lock()
883 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530884 log.Debugw("revertImage", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500885 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530886 device, err := agent.getDeviceWithoutLock()
887 if err != nil {
888 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
889 }
890 // Verify whether the Image is in the list of image being downloaded
891 if !isImageRegistered(img, device) {
892 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
893 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500894
npujar1d86a522019-11-14 17:11:16 +0530895 if device.AdminState != voltha.AdminState_ENABLED {
896 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
897 }
898 // Update image download state
899 cloned := proto.Clone(device).(*voltha.Device)
900 for _, image := range cloned.ImageDownloads {
901 if image.Id == img.Id && image.Name == img.Name {
902 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -0500903 }
npujar1d86a522019-11-14 17:11:16 +0530904 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300905
npujar1d86a522019-11-14 17:11:16 +0530906 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
907 return nil, err
908 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500909
npujar1d86a522019-11-14 17:11:16 +0530910 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
911 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
912 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500913 }
914 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700915}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500916
917func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
918 agent.lockDevice.Lock()
919 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530920 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500921 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530922 device, err := agent.getDeviceWithoutLock()
923 if err != nil {
924 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500925 }
npujar1d86a522019-11-14 17:11:16 +0530926 resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img)
927 if err != nil {
928 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceID, "error": err, "image": img.Name})
929 return nil, err
930 }
931 return resp, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500932}
933
serkant.uluderya334479d2019-04-10 08:26:15 -0700934func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500935 agent.lockDevice.Lock()
936 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +0530937 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500938 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530939 device, err := agent.getDeviceWithoutLock()
940 if err != nil {
941 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
942 }
943 // Update the image as well as remove it if the download was cancelled
944 cloned := proto.Clone(device).(*voltha.Device)
945 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
946 for _, image := range cloned.ImageDownloads {
947 if image.Id == img.Id && image.Name == img.Name {
948 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
949 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500950 }
951 }
npujar1d86a522019-11-14 17:11:16 +0530952 }
953 cloned.ImageDownloads = clonedImages
954 // Set the Admin state to enabled if required
955 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
956 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
957 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
958 cloned.AdminState = voltha.AdminState_ENABLED
959 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500960
npujar1d86a522019-11-14 17:11:16 +0530961 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
962 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500963 }
964 return nil
965}
966
967func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400968 agent.lockDevice.RLock()
969 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530970 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500971 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530972 device, err := agent.getDeviceWithoutLock()
973 if err != nil {
974 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500975 }
npujar1d86a522019-11-14 17:11:16 +0530976 for _, image := range device.ImageDownloads {
977 if image.Id == img.Id && image.Name == img.Name {
978 return image, nil
979 }
980 }
981 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500982}
983
npujar1d86a522019-11-14 17:11:16 +0530984func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400985 agent.lockDevice.RLock()
986 defer agent.lockDevice.RUnlock()
npujar1d86a522019-11-14 17:11:16 +0530987 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceID})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500988 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +0530989 device, err := agent.getDeviceWithoutLock()
990 if err != nil {
991 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500992 }
npujar1d86a522019-11-14 17:11:16 +0530993 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500994}
995
khenaidoo4d4802d2018-10-04 21:59:49 -0400996// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400997func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
npujar1d86a522019-11-14 17:11:16 +0530998 log.Debugw("getPorts", log.Fields{"id": agent.deviceID, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400999 ports := &voltha.Ports{}
npujar1d86a522019-11-14 17:11:16 +05301000 if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -04001001 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -04001002 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -04001003 ports.Items = append(ports.Items, port)
1004 }
1005 }
1006 }
1007 return ports
1008}
1009
khenaidoo4d4802d2018-10-04 21:59:49 -04001010// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
1011// parent device
khenaidoo79232702018-12-04 11:00:41 -05001012func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301013 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceID})
1014 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
1015 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001016 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001017 }
npujar1d86a522019-11-14 17:11:16 +05301018 var switchCap *ic.SwitchCapability
1019 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
1020 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
1021 return nil, err
1022 }
1023 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001024}
1025
khenaidoo4d4802d2018-10-04 21:59:49 -04001026// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
1027// device
khenaidoo79232702018-12-04 11:00:41 -05001028func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
npujar1d86a522019-11-14 17:11:16 +05301029 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceID})
1030 device, err := agent.deviceMgr.GetDevice(agent.deviceID)
1031 if device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001032 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001033 }
npujar1d86a522019-11-14 17:11:16 +05301034 var portCap *ic.PortCapability
1035 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
1036 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1037 return nil, err
1038 }
1039 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001040}
1041
khenaidoofdbad6e2018-11-06 22:26:38 -05001042func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001043 // If deviceType=="" then we must have taken ownership of this device.
1044 // Fixes VOL-2226 where a core would take ownership and have stale data
1045 if agent.deviceType == "" {
1046 agent.reconcileWithKVStore()
1047 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001048 // Send packet to adapter
npujar1d86a522019-11-14 17:11:16 +05301049 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceID, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001050 log.Debugw("packet-out-error", log.Fields{
npujar1d86a522019-11-14 17:11:16 +05301051 "id": agent.deviceID,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001052 "error": err,
1053 "packet": hex.EncodeToString(packet.Data),
1054 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001055 return err
1056 }
1057 return nil
1058}
1059
khenaidoo4d4802d2018-10-04 21:59:49 -04001060// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001061func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001062 //// Run this callback in its own go routine
1063 go func(args ...interface{}) interface{} {
1064 var previous *voltha.Device
1065 var current *voltha.Device
1066 var ok bool
1067 if len(args) == 2 {
1068 if previous, ok = args[0].(*voltha.Device); !ok {
1069 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1070 return nil
1071 }
1072 if current, ok = args[1].(*voltha.Device); !ok {
1073 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1074 return nil
1075 }
1076 } else {
1077 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1078 return nil
1079 }
1080 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001081 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1082 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1083 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1084 }
khenaidoo43c82122018-11-22 18:38:28 -05001085 return nil
1086 }(args...)
1087
khenaidoo92e62c52018-10-03 14:02:54 -04001088 return nil
1089}
1090
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001091// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1092// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1093func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1094 // First retrieve the most up to date device info
1095 var currentDevice *voltha.Device
1096 var err error
1097 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1098 return nil, err
1099 }
1100 cloned := proto.Clone(currentDevice).(*voltha.Device)
1101 cloned.Root = device.Root
1102 cloned.Vendor = device.Vendor
1103 cloned.Model = device.Model
1104 cloned.SerialNumber = device.SerialNumber
1105 cloned.MacAddress = device.MacAddress
1106 cloned.Vlan = device.Vlan
1107 cloned.Reason = device.Reason
1108 return cloned, nil
1109}
1110func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001111 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001112 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001113 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
npujar1d86a522019-11-14 17:11:16 +05301114 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1115 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001116 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1117 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001118 }
npujar1d86a522019-11-14 17:11:16 +05301119 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1120 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001121}
1122
1123func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1124 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1125 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001126 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001127}
1128
khenaidoo92e62c52018-10-03 14:02:54 -04001129func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1130 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001131 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001132 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301133 storeDevice, err := agent.getDeviceWithoutLock()
1134 if err != nil {
1135 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo92e62c52018-10-03 14:02:54 -04001136 }
npujar1d86a522019-11-14 17:11:16 +05301137 // clone the device
1138 cloned := proto.Clone(storeDevice).(*voltha.Device)
1139 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1140 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1141 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1142 cloned.ConnectStatus = connStatus
1143 }
1144 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1145 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1146 cloned.OperStatus = operStatus
1147 }
1148 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
1149 // Store the device
1150 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001151}
1152
khenaidoo3ab34882019-05-02 21:33:30 -04001153func (agent *DeviceAgent) enablePorts() error {
1154 agent.lockDevice.Lock()
1155 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301156 storeDevice, err := agent.getDeviceWithoutLock()
1157 if err != nil {
1158 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo3ab34882019-05-02 21:33:30 -04001159 }
npujar1d86a522019-11-14 17:11:16 +05301160 // clone the device
1161 cloned := proto.Clone(storeDevice).(*voltha.Device)
1162 for _, port := range cloned.Ports {
1163 port.AdminState = voltha.AdminState_ENABLED
1164 port.OperStatus = voltha.OperStatus_ACTIVE
1165 }
1166 // Store the device
1167 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001168}
1169
1170func (agent *DeviceAgent) disablePorts() error {
npujar1d86a522019-11-14 17:11:16 +05301171 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceID})
khenaidoo3ab34882019-05-02 21:33:30 -04001172 agent.lockDevice.Lock()
1173 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301174 storeDevice, err := agent.getDeviceWithoutLock()
1175 if err != nil {
1176 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo3ab34882019-05-02 21:33:30 -04001177 }
npujar1d86a522019-11-14 17:11:16 +05301178 // clone the device
1179 cloned := proto.Clone(storeDevice).(*voltha.Device)
1180 for _, port := range cloned.Ports {
1181 port.AdminState = voltha.AdminState_DISABLED
1182 port.OperStatus = voltha.OperStatus_UNKNOWN
1183 }
1184 // Store the device
1185 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001186}
1187
khenaidoo92e62c52018-10-03 14:02:54 -04001188func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1189 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001190 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001191 // Work only on latest data
1192 // TODO: Get list of ports from device directly instead of the entire device
npujar1d86a522019-11-14 17:11:16 +05301193 storeDevice, err := agent.getDeviceWithoutLock()
1194 if err != nil {
1195 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoob9203542018-09-17 22:56:37 -04001196 }
npujar1d86a522019-11-14 17:11:16 +05301197 // clone the device
1198 cloned := proto.Clone(storeDevice).(*voltha.Device)
1199 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1200 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1201 return status.Errorf(codes.InvalidArgument, "%s", portType)
1202 }
1203 for _, port := range cloned.Ports {
1204 if port.Type == portType && port.PortNo == portNo {
1205 port.OperStatus = operStatus
1206 // Set the admin status to ENABLED if the operational status is ACTIVE
1207 // TODO: Set by northbound system?
1208 if operStatus == voltha.OperStatus_ACTIVE {
1209 port.AdminState = voltha.AdminState_ENABLED
1210 }
1211 break
1212 }
1213 }
1214 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1215 // Store the device
1216 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001217}
1218
khenaidoo0a822f92019-05-08 15:15:57 -04001219func (agent *DeviceAgent) deleteAllPorts() error {
npujar1d86a522019-11-14 17:11:16 +05301220 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -04001221 agent.lockDevice.Lock()
1222 defer agent.lockDevice.Unlock()
1223 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301224 storeDevice, err := agent.getDeviceWithoutLock()
1225 if err != nil {
1226 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo0a822f92019-05-08 15:15:57 -04001227 }
npujar1d86a522019-11-14 17:11:16 +05301228 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1229 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1230 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1231 return err
1232 }
1233 if len(storeDevice.Ports) == 0 {
1234 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
1235 return nil
1236 }
1237 // clone the device & set the fields to empty
1238 cloned := proto.Clone(storeDevice).(*voltha.Device)
1239 cloned.Ports = []*voltha.Port{}
1240 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1241 // Store the device
1242 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001243}
1244
khenaidoob9203542018-09-17 22:56:37 -04001245func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001246 agent.lockDevice.Lock()
1247 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301248 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoob9203542018-09-17 22:56:37 -04001249 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301250 storeDevice, err := agent.getDeviceWithoutLock()
1251 if err != nil {
1252 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
1253 }
1254 // clone the device
1255 cloned := proto.Clone(storeDevice).(*voltha.Device)
1256 if cloned.Ports == nil {
1257 // First port
1258 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
1259 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001260 } else {
npujar1d86a522019-11-14 17:11:16 +05301261 for _, p := range cloned.Ports {
1262 if p.Type == port.Type && p.PortNo == port.PortNo {
1263 log.Debugw("port already exists", log.Fields{"port": *port})
1264 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001265 }
khenaidoob9203542018-09-17 22:56:37 -04001266 }
khenaidoo92e62c52018-10-03 14:02:54 -04001267 }
npujar1d86a522019-11-14 17:11:16 +05301268 cp := proto.Clone(port).(*voltha.Port)
1269 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1270 // TODO: Set by northbound system?
1271 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1272 cp.AdminState = voltha.AdminState_ENABLED
1273 }
1274 cloned.Ports = append(cloned.Ports, cp)
1275 // Store the device
1276 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001277}
1278
1279func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1280 agent.lockDevice.Lock()
1281 defer agent.lockDevice.Unlock()
1282 log.Debug("addPeerPort")
1283 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301284 storeDevice, err := agent.getDeviceWithoutLock()
1285 if err != nil {
1286 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoob9203542018-09-17 22:56:37 -04001287 }
npujar1d86a522019-11-14 17:11:16 +05301288 // clone the device
1289 cloned := proto.Clone(storeDevice).(*voltha.Device)
1290 // Get the peer port on the device based on the port no
1291 for _, peerPort := range cloned.Ports {
1292 if peerPort.PortNo == port.PortNo { // found port
1293 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1294 peerPort.Peers = append(peerPort.Peers, cp)
1295 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceID})
1296 break
1297 }
1298 }
1299 // Store the device
1300 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001301}
1302
npujar1d86a522019-11-14 17:11:16 +05301303func (agent *DeviceAgent) deletePeerPorts(deviceID string) error {
khenaidoo0a822f92019-05-08 15:15:57 -04001304 agent.lockDevice.Lock()
1305 defer agent.lockDevice.Unlock()
1306 log.Debug("deletePeerPorts")
1307 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301308 storeDevice, err := agent.getDeviceWithoutLock()
1309 if err != nil {
1310 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
khenaidoo0a822f92019-05-08 15:15:57 -04001311 }
npujar1d86a522019-11-14 17:11:16 +05301312 // clone the device
1313 cloned := proto.Clone(storeDevice).(*voltha.Device)
1314 var updatedPeers []*voltha.Port_PeerPort
1315 for _, port := range cloned.Ports {
1316 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1317 for _, peerPort := range port.Peers {
1318 if peerPort.DeviceId != deviceID {
1319 updatedPeers = append(updatedPeers, peerPort)
1320 }
1321 }
1322 port.Peers = updatedPeers
1323 }
1324
1325 // Store the device with updated peer ports
1326 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001327}
1328
khenaidoob9203542018-09-17 22:56:37 -04001329// TODO: A generic device update by attribute
1330func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001331 agent.lockDevice.Lock()
1332 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001333 if value == nil {
1334 return
1335 }
1336 var storeDevice *voltha.Device
1337 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001338 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001339 return
1340 }
1341 updated := false
1342 s := reflect.ValueOf(storeDevice).Elem()
1343 if s.Kind() == reflect.Struct {
1344 // exported field
1345 f := s.FieldByName(name)
1346 if f.IsValid() && f.CanSet() {
1347 switch f.Kind() {
1348 case reflect.String:
1349 f.SetString(value.(string))
1350 updated = true
1351 case reflect.Uint32:
1352 f.SetUint(uint64(value.(uint32)))
1353 updated = true
1354 case reflect.Bool:
1355 f.SetBool(value.(bool))
1356 updated = true
1357 }
1358 }
1359 }
khenaidoo92e62c52018-10-03 14:02:54 -04001360 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001361 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001362 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001363 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001364 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1365 }
khenaidoob9203542018-09-17 22:56:37 -04001366}
serkant.uluderya334479d2019-04-10 08:26:15 -07001367
1368func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1369 agent.lockDevice.Lock()
1370 defer agent.lockDevice.Unlock()
npujar1d86a522019-11-14 17:11:16 +05301371 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
serkant.uluderya334479d2019-04-10 08:26:15 -07001372 // Get the most up to date the device info
npujar1d86a522019-11-14 17:11:16 +05301373 device, err := agent.getDeviceWithoutLock()
1374 if err != nil {
1375 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
1376 }
1377 // First send the request to an Adapter and wait for a response
1378 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1379 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceID, "error": err})
1380 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001381 }
1382 return nil
1383}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001384
1385//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.
1386// It is an internal helper function.
1387func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1388 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
npujar1d86a522019-11-14 17:11:16 +05301389 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, device, strict, txid); afterUpdate == nil {
1390 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001391 }
npujar1d86a522019-11-14 17:11:16 +05301392 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001393
1394 return nil
1395}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001396
1397func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1398 agent.lockDevice.Lock()
1399 defer agent.lockDevice.Unlock()
1400 // Work only on latest data
npujar1d86a522019-11-14 17:11:16 +05301401 storeDevice, err := agent.getDeviceWithoutLock()
1402 if err != nil {
1403 return status.Errorf(codes.NotFound, "%s", agent.deviceID)
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001404 }
npujar1d86a522019-11-14 17:11:16 +05301405 // clone the device
1406 cloned := proto.Clone(storeDevice).(*voltha.Device)
1407 cloned.Reason = reason
1408 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1409 // Store the device
1410 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001411}