blob: b7599b73d1c9c89e3f3d1f30ff770d8a2c721c7a [file] [log] [blame]
khenaidoob9203542018-09-17 22:56:37 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package core
17
18import (
19 "context"
Matteo Scandolo360605d2019-11-05 18:29:17 -080020 "encoding/hex"
khenaidoo3ab34882019-05-02 21:33:30 -040021 "fmt"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040022 "reflect"
23 "sync"
24 "time"
25
khenaidoob9203542018-09-17 22:56:37 -040026 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050027 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070028 coreutils "github.com/opencord/voltha-go/rw_core/utils"
Scott Baker807addd2019-10-24 15:16:21 -070029 fu "github.com/opencord/voltha-lib-go/v2/pkg/flows"
30 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Baker555307d2019-11-04 08:58:01 -080031 ic "github.com/opencord/voltha-protos/v2/go/inter_container"
32 ofp "github.com/opencord/voltha-protos/v2/go/openflow_13"
33 "github.com/opencord/voltha-protos/v2/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040034 "google.golang.org/grpc/codes"
35 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040036)
37
38type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040039 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040040 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050041 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040042 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040043 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070044 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040045 deviceMgr *DeviceManager
46 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040047 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040048 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040049 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040050 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040051}
52
Scott Baker80678602019-11-14 16:57:36 -080053//newDeviceAgent creates a new device agent. The device will be initialized when start() is called.
khenaidoo2c6a0992019-04-29 13:46:56 -040054func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040055 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040056 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080057 if device.Id == "" {
58 agent.deviceId = CreateDeviceId()
59 } else {
60 agent.deviceId = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050061 }
Scott Baker80678602019-11-14 16:57:36 -080062
khenaidoo2c6a0992019-04-29 13:46:56 -040063 agent.isRootdevice = device.Root
khenaidoo6d62c002019-05-15 21:57:03 -040064 agent.parentId = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080065 agent.deviceType = device.Type
khenaidoob9203542018-09-17 22:56:37 -040066 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050067 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040068 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040069 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040070 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040071 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040072 return &agent
73}
74
Scott Baker80678602019-11-14 16:57:36 -080075// start()
76// save the device to the data model and registers for callbacks on that device if deviceToCreate!=nil. Otherwise,
77// it will load the data from the dB and setup teh necessary callbacks and proxies. Returns the device that
78// was started.
79func (agent *DeviceAgent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
80 var device *voltha.Device
81
khenaidoo92e62c52018-10-03 14:02:54 -040082 agent.lockDevice.Lock()
83 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050084 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
Scott Baker80678602019-11-14 16:57:36 -080085 if deviceToCreate == nil {
86 // Load the existing device
87 if loadedDevice := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, true, ""); loadedDevice != nil {
88 var ok bool
89 if device, ok = loadedDevice.(*voltha.Device); ok {
90 agent.deviceType = device.Adapter
91 } else {
92 log.Errorw("failed-to-convert-device", log.Fields{"deviceId": agent.deviceId})
93 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -050094 }
95 } else {
96 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
Scott Baker80678602019-11-14 16:57:36 -080097 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -050098 }
khenaidoo4c9e5592019-09-09 16:20:41 -040099 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500100 } else {
Scott Baker80678602019-11-14 16:57:36 -0800101 // Create a new device
102 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
103 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
104 // agent.deviceId will also have been set during newDeviceAgent().
105 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
106 device.Id = agent.deviceId
107 device.AdminState = voltha.AdminState_PREPROVISIONED
108 device.FlowGroups = &ofp.FlowGroups{Items: nil}
109 device.Flows = &ofp.Flows{Items: nil}
110 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
111 // Set the default vlan ID to the one specified by the parent adapter. It can be
112 // overwritten by the child adapter during a device update request
113 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
114 }
115
khenaidoo297cd252019-02-07 22:10:23 -0500116 // Add the initial device to the local model
Scott Baker80678602019-11-14 16:57:36 -0800117 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, device, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500118 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
Scott Baker80678602019-11-14 16:57:36 -0800119 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -0500120 }
khenaidoob9203542018-09-17 22:56:37 -0400121 }
khenaidoo297cd252019-02-07 22:10:23 -0500122
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400123 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500124 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400125
khenaidoo4c9e5592019-09-09 16:20:41 -0400126 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceId})
Scott Baker80678602019-11-14 16:57:36 -0800127 return device, nil
khenaidoob9203542018-09-17 22:56:37 -0400128}
129
khenaidoo4d4802d2018-10-04 21:59:49 -0400130// stop stops the device agent. Not much to do for now
131func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400132 agent.lockDevice.Lock()
133 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400134 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400135 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400136 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400137 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400138 }
khenaidoob9203542018-09-17 22:56:37 -0400139 agent.exitChannel <- 1
140 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400141
khenaidoob9203542018-09-17 22:56:37 -0400142}
143
Scott Baker80678602019-11-14 16:57:36 -0800144// Load the most recent state from the KVStore for the device.
145func (agent *DeviceAgent) reconcileWithKVStore() {
146 agent.lockDevice.Lock()
147 defer agent.lockDevice.Unlock()
148 log.Debug("reconciling-device-agent-devicetype")
149 // TODO: context timeout
150 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 1, true, ""); device != nil {
151 if d, ok := device.(*voltha.Device); ok {
152 agent.deviceType = d.Adapter
153 log.Debugw("reconciled-device-agent-devicetype", log.Fields{"Id": agent.deviceId, "type": agent.deviceType})
154 }
155 }
156}
157
khenaidoo19d7b632018-10-30 10:49:50 -0400158// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400159func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400160 agent.lockDevice.RLock()
161 defer agent.lockDevice.RUnlock()
Stephane Barbarieb6b68c42019-10-10 16:05:13 -0400162 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400163 if d, ok := device.(*voltha.Device); ok {
164 cloned := proto.Clone(d).(*voltha.Device)
165 return cloned, nil
166 }
167 }
168 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
169}
170
khenaidoo4d4802d2018-10-04 21:59:49 -0400171// 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 -0400172// This function is meant so that we do not have duplicate code all over the device agent functions
173func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400174 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400175 if d, ok := device.(*voltha.Device); ok {
176 cloned := proto.Clone(d).(*voltha.Device)
177 return cloned, nil
178 }
179 }
180 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
181}
182
khenaidoo3ab34882019-05-02 21:33:30 -0400183// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400184func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400185 agent.lockDevice.Lock()
186 defer agent.lockDevice.Unlock()
187 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500188
khenaidoo92e62c52018-10-03 14:02:54 -0400189 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400190 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
191 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500192 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
193 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
194 // with the adapter then we need to know the adapter that will handle this request
195 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
196 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
197 return err
198 } else {
199 device.Adapter = adapterName
200 }
201
khenaidoo92e62c52018-10-03 14:02:54 -0400202 if device.AdminState == voltha.AdminState_ENABLED {
203 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400204 return nil
205 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400206
207 if device.AdminState == voltha.AdminState_DELETED {
208 // This is a temporary state when a device is deleted before it gets removed from the model.
209 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
210 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
211 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400212 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400213
214 previousAdminState := device.AdminState
215
216 // Update the Admin State and set the operational state to activating before sending the request to the
217 // Adapters
218 cloned := proto.Clone(device).(*voltha.Device)
219 cloned.AdminState = voltha.AdminState_ENABLED
220 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400221
Mahir Gunyelb5851672019-07-24 10:46:26 +0300222 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
223 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400224 }
225
226 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
227 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400228 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800229 log.Debugw("adoptDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400230 return err
231 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400232 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400233 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800234 log.Debugw("renableDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400235 return err
236 }
khenaidoob9203542018-09-17 22:56:37 -0400237 }
238 }
239 return nil
240}
241
Manikkaraj kb1a10922019-07-29 12:10:34 -0400242func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
243 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800244 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo2c6a0992019-04-29 13:46:56 -0400245 ch <- err
246 }
247 ch <- nil
248}
249
Manikkaraj kb1a10922019-07-29 12:10:34 -0400250func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
251 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800252 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo2c6a0992019-04-29 13:46:56 -0400253 ch <- err
254 }
255 ch <- nil
256}
257
khenaidoo0458db62019-06-20 08:50:36 -0400258//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
259//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400260func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
261 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400262
khenaidoo2c6a0992019-04-29 13:46:56 -0400263 if (len(newFlows) | len(newGroups)) == 0 {
264 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
265 return nil
266 }
267
khenaidoo19d7b632018-10-30 10:49:50 -0400268 agent.lockDevice.Lock()
269 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400270
khenaidoo0458db62019-06-20 08:50:36 -0400271 var device *voltha.Device
272 var err error
273 if device, err = agent.getDeviceWithoutLock(); err != nil {
274 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
275 }
276
277 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
278 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
279
280 var updatedFlows []*ofp.OfpFlowStats
281 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400282 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400283 var updatedGroups []*ofp.OfpGroupEntry
284
285 // Process flows
286 for _, flow := range newFlows {
287 updatedFlows = append(updatedFlows, flow)
288 }
289 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
298 for _, g := range newGroups {
299 updatedGroups = append(updatedGroups, g)
300 }
301 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400302 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
303 updatedGroups = append(updatedGroups, group)
304 } else {
305 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400306 }
307 }
308
309 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400310 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
khenaidoo0458db62019-06-20 08:50:36 -0400311 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
312 return nil
313 }
314
315 // Send update to adapters
316 // Create two channels to receive responses from the dB and from the adapters.
317 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
318 // to send their responses. These channels will be garbage collected once all the responses are
319 // received
320 chAdapters := make(chan interface{})
khenaidoo0458db62019-06-20 08:50:36 -0400321 dType := agent.adapterMgr.getDeviceType(device.Type)
322 if !dType.AcceptsAddRemoveFlowUpdates {
323
324 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
325 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
326 return nil
327 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400328 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400329
330 } else {
331 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400332 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400333 ToRemove: &voltha.Flows{Items: flowsToDelete},
334 }
335 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400336 ToAdd: &voltha.FlowGroups{Items: newGroups},
337 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400338 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
339 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400340 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400341 }
342
343 // store the changed data
344 device.Flows = &voltha.Flows{Items: updatedFlows}
345 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500346 if err := agent.updateDeviceWithoutLock(device); err != nil {
347 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
348 }
khenaidoo0458db62019-06-20 08:50:36 -0400349
Kent Hagerman3c513972019-11-25 13:49:41 -0500350 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400351 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400352 return status.Errorf(codes.Aborted, "errors-%s", res)
353 }
354
355 return nil
356}
357
358//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
359//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400360func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400361 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
362
363 if (len(flowsToDel) | len(groupsToDel)) == 0 {
364 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
365 return nil
366 }
367
368 agent.lockDevice.Lock()
369 defer agent.lockDevice.Unlock()
370
371 var device *voltha.Device
372 var err error
373
374 if device, err = agent.getDeviceWithoutLock(); err != nil {
375 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
376 }
377
378 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
379 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
380
381 var flowsToKeep []*ofp.OfpFlowStats
382 var groupsToKeep []*ofp.OfpGroupEntry
383
384 // Process flows
385 for _, flow := range existingFlows.Items {
386 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
387 flowsToKeep = append(flowsToKeep, flow)
388 }
389 }
390
391 // Process groups
392 for _, group := range existingGroups.Items {
393 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
394 groupsToKeep = append(groupsToKeep, group)
395 }
396 }
397
398 log.Debugw("deleteFlowsAndGroups",
399 log.Fields{
400 "deviceId": agent.deviceId,
401 "flowsToDel": len(flowsToDel),
402 "flowsToKeep": len(flowsToKeep),
403 "groupsToDel": len(groupsToDel),
404 "groupsToKeep": len(groupsToKeep),
405 })
406
407 // Sanity check
408 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
409 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
410 return nil
411 }
412
413 // Send update to adapters
414 chAdapters := make(chan interface{})
khenaidoo0458db62019-06-20 08:50:36 -0400415 dType := agent.adapterMgr.getDeviceType(device.Type)
416 if !dType.AcceptsAddRemoveFlowUpdates {
417 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
418 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
419 return nil
420 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400421 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400422 } else {
423 flowChanges := &ofp.FlowChanges{
424 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
425 ToRemove: &voltha.Flows{Items: flowsToDel},
426 }
427 groupChanges := &ofp.FlowGroupChanges{
428 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
429 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
430 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
431 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400432 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400433 }
434
435 // store the changed data
436 device.Flows = &voltha.Flows{Items: flowsToKeep}
437 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
Kent Hagerman3c513972019-11-25 13:49:41 -0500438 if err := agent.updateDeviceWithoutLock(device); err != nil {
439 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
440 }
khenaidoo0458db62019-06-20 08:50:36 -0400441
Kent Hagerman3c513972019-11-25 13:49:41 -0500442 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400443 return status.Errorf(codes.Aborted, "errors-%s", res)
444 }
445 return nil
446
447}
448
449//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
450//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400451func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400452 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
453
454 if (len(updatedFlows) | len(updatedGroups)) == 0 {
455 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
456 return nil
457 }
458
459 agent.lockDevice.Lock()
460 defer agent.lockDevice.Unlock()
461 var device *voltha.Device
462 var err error
463 if device, err = agent.getDeviceWithoutLock(); err != nil {
464 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
465 }
466 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
467 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
468
469 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
470 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
471 return nil
472 }
473
474 log.Debugw("updating-flows-and-groups",
475 log.Fields{
476 "deviceId": agent.deviceId,
477 "updatedFlows": updatedFlows,
478 "updatedGroups": updatedGroups,
479 })
480
481 chAdapters := make(chan interface{})
khenaidoo0458db62019-06-20 08:50:36 -0400482 dType := agent.adapterMgr.getDeviceType(device.Type)
483
484 // Process bulk flow update differently than incremental update
485 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400486 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400487 } else {
488 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400489 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400490 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400491 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400492
493 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400494 for _, flow := range updatedFlows {
495 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
496 flowsToAdd = append(flowsToAdd, flow)
497 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400498 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400499 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400500 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400501 flowsToDelete = append(flowsToDelete, flow)
502 }
503 }
504
505 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400506 for _, g := range updatedGroups {
507 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
508 groupsToAdd = append(groupsToAdd, g)
509 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400510 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400511 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400512 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400513 groupsToDelete = append(groupsToDelete, group)
514 }
515 }
516
khenaidoo0458db62019-06-20 08:50:36 -0400517 log.Debugw("updating-flows-and-groups",
518 log.Fields{
519 "deviceId": agent.deviceId,
520 "flowsToAdd": flowsToAdd,
521 "flowsToDelete": flowsToDelete,
522 "groupsToAdd": groupsToAdd,
523 "groupsToDelete": groupsToDelete,
524 })
525
khenaidoo2c6a0992019-04-29 13:46:56 -0400526 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400527 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
528 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400529 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400530 }
531
khenaidoo0458db62019-06-20 08:50:36 -0400532 flowChanges := &ofp.FlowChanges{
533 ToAdd: &voltha.Flows{Items: flowsToAdd},
534 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400535 }
khenaidoo0458db62019-06-20 08:50:36 -0400536 groupChanges := &ofp.FlowGroupChanges{
537 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
538 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
539 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
540 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400541 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400542 }
khenaidoo0458db62019-06-20 08:50:36 -0400543
544 // store the updated data
545 device.Flows = &voltha.Flows{Items: updatedFlows}
546 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
Kent Hagerman3c513972019-11-25 13:49:41 -0500547 if err := agent.updateDeviceWithoutLock(device); err != nil {
548 return status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
549 }
khenaidoo0458db62019-06-20 08:50:36 -0400550
Kent Hagerman3c513972019-11-25 13:49:41 -0500551 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400552 return status.Errorf(codes.Aborted, "errors-%s", res)
553 }
554 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400555}
556
khenaidoo4d4802d2018-10-04 21:59:49 -0400557//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400558func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400559 agent.lockDevice.Lock()
560 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400561 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
562 // Get the most up to date the device info
563 if device, err := agent.getDeviceWithoutLock(); err != nil {
564 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
565 } else {
566 if device.AdminState == voltha.AdminState_DISABLED {
567 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400568 return nil
569 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400570 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
571 device.AdminState == voltha.AdminState_DELETED {
572 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
573 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
574 }
575
khenaidoo59ef7be2019-06-21 12:40:28 -0400576 // Update the Admin State and operational state before sending the request out
577 cloned := proto.Clone(device).(*voltha.Device)
578 cloned.AdminState = voltha.AdminState_DISABLED
579 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300580 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
581 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400582 }
583
khenaidoo92e62c52018-10-03 14:02:54 -0400584 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800585 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400586 return err
587 }
khenaidoo0a822f92019-05-08 15:15:57 -0400588 }
589 return nil
590}
591
592func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
593 agent.lockDevice.Lock()
594 defer agent.lockDevice.Unlock()
595 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
596 // Get the most up to date the device info
597 if device, err := agent.getDeviceWithoutLock(); err != nil {
598 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
599 } else {
600 if device.AdminState == adminState {
601 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
602 return nil
603 }
khenaidoo92e62c52018-10-03 14:02:54 -0400604 // Received an Ack (no error found above). Now update the device in the model to the expected state
605 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400606 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300607 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
608 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400609 }
khenaidoo92e62c52018-10-03 14:02:54 -0400610 }
611 return nil
612}
613
khenaidoo4d4802d2018-10-04 21:59:49 -0400614func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
615 agent.lockDevice.Lock()
616 defer agent.lockDevice.Unlock()
617 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
618 // Get the most up to date the device info
619 if device, err := agent.getDeviceWithoutLock(); err != nil {
620 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
621 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400622 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800623 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo4d4802d2018-10-04 21:59:49 -0400624 return err
625 }
626 }
627 return nil
628}
629
630func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
631 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400632 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400633 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
634 // Get the most up to date the device info
635 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400636 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
637 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400638 if device.AdminState == voltha.AdminState_DELETED {
639 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
640 return nil
641 }
khenaidoo43c82122018-11-22 18:38:28 -0500642 if (device.AdminState != voltha.AdminState_DISABLED) &&
643 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400644 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
645 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400646 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
647 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400648 if device.AdminState != voltha.AdminState_PREPROVISIONED {
649 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
650 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800651 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo4554f7c2019-05-29 22:13:15 -0400652 return err
653 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400654 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400655 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
656 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400657 cloned := proto.Clone(device).(*voltha.Device)
658 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300659 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
660 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400661 }
khenaidoo0a822f92019-05-08 15:15:57 -0400662 // If this is a child device then remove the associated peer ports on the parent device
663 if !device.Root {
664 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
665 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400666 }
667 return nil
668}
669
khenaidooad06fd72019-10-28 12:26:05 -0400670func (agent *DeviceAgent) setParentId(device *voltha.Device, parentId string) error {
671 agent.lockDevice.Lock()
672 defer agent.lockDevice.Unlock()
673 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentId})
674 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
675 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
676 } else {
677 // clone the device
678 cloned := proto.Clone(storeDevice).(*voltha.Device)
679 cloned.ParentId = parentId
680 // Store the device
681 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
682 return err
683 }
684 return nil
685 }
686}
687
khenaidoob3127472019-07-24 21:04:55 -0400688func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
689 agent.lockDevice.Lock()
690 defer agent.lockDevice.Unlock()
691 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
692 // Work only on latest data
693 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
694 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
695 } else {
696 // clone the device
697 cloned := proto.Clone(storeDevice).(*voltha.Device)
698 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
699 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300700 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
701 return err
khenaidoob3127472019-07-24 21:04:55 -0400702 }
703 // Send the request to the adapter
704 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800705 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoob3127472019-07-24 21:04:55 -0400706 return err
707 }
708 return nil
709 }
710}
711
712func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
713 agent.lockDevice.Lock()
714 defer agent.lockDevice.Unlock()
715 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
716 // Work only on latest data
717 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
718 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
719 } else {
720 // clone the device
721 cloned := proto.Clone(storeDevice).(*voltha.Device)
722 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
723 // Store the device
724 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
725 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
726 if afterUpdate == nil {
727 return status.Errorf(codes.Internal, "%s", agent.deviceId)
728 }
729 return nil
730 }
731}
732
733func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
734 agent.lockDevice.RLock()
735 defer agent.lockDevice.RUnlock()
736 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
737 // Get the most up to date the device info
738 if device, err := agent.getDeviceWithoutLock(); err != nil {
739 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
740 } else {
741 cloned := proto.Clone(device).(*voltha.Device)
742 return cloned.PmConfigs, nil
743 }
744}
745
khenaidoof5a5bfa2019-01-23 22:20:29 -0500746func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
747 agent.lockDevice.Lock()
748 defer agent.lockDevice.Unlock()
749 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
750 // Get the most up to date the device info
751 if device, err := agent.getDeviceWithoutLock(); err != nil {
752 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
753 } else {
754 if device.AdminState != voltha.AdminState_ENABLED {
755 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
756 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
757 }
758 // Save the image
759 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500760 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500761 cloned := proto.Clone(device).(*voltha.Device)
762 if cloned.ImageDownloads == nil {
763 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
764 } else {
765 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
766 }
767 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300768 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
769 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500770 }
771 // Send the request to the adapter
772 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800773 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500774 return nil, err
775 }
776 }
777 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
778}
779
780// isImageRegistered is a helper method to figure out if an image is already registered
781func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
782 for _, image := range device.ImageDownloads {
783 if image.Id == img.Id && image.Name == img.Name {
784 return true
785 }
786 }
787 return false
788}
789
790func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
791 agent.lockDevice.Lock()
792 defer agent.lockDevice.Unlock()
793 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
794 // Get the most up to date the device info
795 if device, err := agent.getDeviceWithoutLock(); err != nil {
796 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
797 } else {
798 // Verify whether the Image is in the list of image being downloaded
799 if !isImageRegistered(img, device) {
800 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
801 }
802
803 // Update image download state
804 cloned := proto.Clone(device).(*voltha.Device)
805 for _, image := range cloned.ImageDownloads {
806 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500807 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500808 }
809 }
810
khenaidoof5a5bfa2019-01-23 22:20:29 -0500811 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500812 // Set the device to Enabled
813 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300814 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
815 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500816 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400817 // Send the request to teh adapter
818 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800819 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoo59ef7be2019-06-21 12:40:28 -0400820 return nil, err
821 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500822 }
823 }
824 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700825}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500826
827func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
828 agent.lockDevice.Lock()
829 defer agent.lockDevice.Unlock()
830 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
831 // Get the most up to date the device info
832 if device, err := agent.getDeviceWithoutLock(); err != nil {
833 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
834 } else {
835 // Verify whether the Image is in the list of image being downloaded
836 if !isImageRegistered(img, device) {
837 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
838 }
839
840 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
841 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
842 }
843 // Update image download state
844 cloned := proto.Clone(device).(*voltha.Device)
845 for _, image := range cloned.ImageDownloads {
846 if image.Id == img.Id && image.Name == img.Name {
847 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
848 }
849 }
850 // Set the device to downloading_image
851 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300852 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
853 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500854 }
855
856 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800857 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500858 return nil, err
859 }
860 // The status of the AdminState will be changed following the update_download_status response from the adapter
861 // The image name will also be removed from the device list
862 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700863 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
864}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500865
866func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
867 agent.lockDevice.Lock()
868 defer agent.lockDevice.Unlock()
869 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
870 // Get the most up to date the device info
871 if device, err := agent.getDeviceWithoutLock(); err != nil {
872 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
873 } else {
874 // Verify whether the Image is in the list of image being downloaded
875 if !isImageRegistered(img, device) {
876 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
877 }
878
879 if device.AdminState != voltha.AdminState_ENABLED {
880 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
881 }
882 // Update image download state
883 cloned := proto.Clone(device).(*voltha.Device)
884 for _, image := range cloned.ImageDownloads {
885 if image.Id == img.Id && image.Name == img.Name {
886 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
887 }
888 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300889
890 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
891 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500892 }
893
894 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800895 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500896 return nil, err
897 }
898 }
899 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700900}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500901
902func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
903 agent.lockDevice.Lock()
904 defer agent.lockDevice.Unlock()
905 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
906 // Get the most up to date the device info
907 if device, err := agent.getDeviceWithoutLock(); err != nil {
908 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
909 } else {
910 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800911 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500912 return nil, err
913 } else {
914 return resp, nil
915 }
916 }
917}
918
serkant.uluderya334479d2019-04-10 08:26:15 -0700919func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500920 agent.lockDevice.Lock()
921 defer agent.lockDevice.Unlock()
922 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
923 // Get the most up to date the device info
924 if device, err := agent.getDeviceWithoutLock(); err != nil {
925 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
926 } else {
927 // Update the image as well as remove it if the download was cancelled
928 cloned := proto.Clone(device).(*voltha.Device)
929 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
930 for _, image := range cloned.ImageDownloads {
931 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500932 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500933 clonedImages = append(clonedImages, img)
934 }
935 }
936 }
937 cloned.ImageDownloads = clonedImages
938 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500939 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
940 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700941 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500942 cloned.AdminState = voltha.AdminState_ENABLED
943 }
944
Mahir Gunyelb5851672019-07-24 10:46:26 +0300945 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
946 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500947 }
948 }
949 return nil
950}
951
952func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400953 agent.lockDevice.RLock()
954 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500955 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
956 // Get the most up to date the device info
957 if device, err := agent.getDeviceWithoutLock(); err != nil {
958 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
959 } else {
960 for _, image := range device.ImageDownloads {
961 if image.Id == img.Id && image.Name == img.Name {
962 return image, nil
963 }
964 }
965 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
966 }
967}
968
969func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400970 agent.lockDevice.RLock()
971 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500972 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
973 // Get the most up to date the device info
974 if device, err := agent.getDeviceWithoutLock(); err != nil {
975 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
976 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700977 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500978 }
979}
980
khenaidoo4d4802d2018-10-04 21:59:49 -0400981// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400982func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
983 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400984 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400985 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400986 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400987 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400988 ports.Items = append(ports.Items, port)
989 }
990 }
991 }
992 return ports
993}
994
khenaidoo4d4802d2018-10-04 21:59:49 -0400995// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
996// parent device
khenaidoo79232702018-12-04 11:00:41 -0500997func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400998 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400999 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001000 return nil, err
1001 } else {
khenaidoo79232702018-12-04 11:00:41 -05001002 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -04001003 var err error
1004 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
1005 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
1006 return nil, err
1007 }
1008 return switchCap, nil
1009 }
1010}
1011
khenaidoo4d4802d2018-10-04 21:59:49 -04001012// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
1013// device
khenaidoo79232702018-12-04 11:00:41 -05001014func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -04001015 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -04001016 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001017 return nil, err
1018 } else {
khenaidoo79232702018-12-04 11:00:41 -05001019 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -04001020 var err error
1021 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
1022 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1023 return nil, err
1024 }
1025 return portCap, nil
1026 }
1027}
1028
khenaidoofdbad6e2018-11-06 22:26:38 -05001029func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001030 // If deviceType=="" then we must have taken ownership of this device.
1031 // Fixes VOL-2226 where a core would take ownership and have stale data
1032 if agent.deviceType == "" {
1033 agent.reconcileWithKVStore()
1034 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001035 // Send packet to adapter
1036 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001037 log.Debugw("packet-out-error", log.Fields{
Scott Baker80678602019-11-14 16:57:36 -08001038 "id": agent.deviceId,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001039 "error": err,
1040 "packet": hex.EncodeToString(packet.Data),
1041 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001042 return err
1043 }
1044 return nil
1045}
1046
khenaidoo4d4802d2018-10-04 21:59:49 -04001047// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001048func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001049 //// Run this callback in its own go routine
1050 go func(args ...interface{}) interface{} {
1051 var previous *voltha.Device
1052 var current *voltha.Device
1053 var ok bool
1054 if len(args) == 2 {
1055 if previous, ok = args[0].(*voltha.Device); !ok {
1056 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1057 return nil
1058 }
1059 if current, ok = args[1].(*voltha.Device); !ok {
1060 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1061 return nil
1062 }
1063 } else {
1064 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1065 return nil
1066 }
1067 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001068 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1069 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1070 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1071 }
khenaidoo43c82122018-11-22 18:38:28 -05001072 return nil
1073 }(args...)
1074
khenaidoo92e62c52018-10-03 14:02:54 -04001075 return nil
1076}
1077
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001078// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1079// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1080func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1081 // First retrieve the most up to date device info
1082 var currentDevice *voltha.Device
1083 var err error
1084 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1085 return nil, err
1086 }
1087 cloned := proto.Clone(currentDevice).(*voltha.Device)
1088 cloned.Root = device.Root
1089 cloned.Vendor = device.Vendor
1090 cloned.Model = device.Model
1091 cloned.SerialNumber = device.SerialNumber
1092 cloned.MacAddress = device.MacAddress
1093 cloned.Vlan = device.Vlan
1094 cloned.Reason = device.Reason
1095 return cloned, nil
1096}
1097func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001098 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001099 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001100 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1101 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1102 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1103 return status.Errorf(codes.Internal, "%s", err.Error())
1104 } else {
1105 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1106 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1107 }
khenaidoo43c82122018-11-22 18:38:28 -05001108}
1109
1110func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1111 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1112 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001113 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001114}
1115
khenaidoo92e62c52018-10-03 14:02:54 -04001116func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1117 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001118 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001119 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001120 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001121 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1122 } else {
1123 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001124 cloned := proto.Clone(storeDevice).(*voltha.Device)
1125 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1126 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1127 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1128 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001129 }
khenaidoo92e62c52018-10-03 14:02:54 -04001130 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1131 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1132 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001133 }
khenaidoo92e62c52018-10-03 14:02:54 -04001134 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001135 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001136 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001137 }
1138}
1139
khenaidoo3ab34882019-05-02 21:33:30 -04001140func (agent *DeviceAgent) enablePorts() error {
1141 agent.lockDevice.Lock()
1142 defer agent.lockDevice.Unlock()
1143 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1144 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1145 } else {
1146 // clone the device
1147 cloned := proto.Clone(storeDevice).(*voltha.Device)
1148 for _, port := range cloned.Ports {
1149 port.AdminState = voltha.AdminState_ENABLED
1150 port.OperStatus = voltha.OperStatus_ACTIVE
1151 }
1152 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001153 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001154 }
1155}
1156
1157func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001158 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001159 agent.lockDevice.Lock()
1160 defer agent.lockDevice.Unlock()
1161 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1162 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1163 } else {
1164 // clone the device
1165 cloned := proto.Clone(storeDevice).(*voltha.Device)
1166 for _, port := range cloned.Ports {
1167 port.AdminState = voltha.AdminState_DISABLED
1168 port.OperStatus = voltha.OperStatus_UNKNOWN
1169 }
1170 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001171 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001172 }
1173}
1174
khenaidoo92e62c52018-10-03 14:02:54 -04001175func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1176 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001177 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001178 // Work only on latest data
1179 // TODO: Get list of ports from device directly instead of the entire device
1180 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001181 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1182 } else {
1183 // clone the device
1184 cloned := proto.Clone(storeDevice).(*voltha.Device)
1185 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1186 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001187 return status.Errorf(codes.InvalidArgument, "%s", portType)
1188 }
1189 for _, port := range cloned.Ports {
1190 if port.Type == portType && port.PortNo == portNo {
1191 port.OperStatus = operStatus
1192 // Set the admin status to ENABLED if the operational status is ACTIVE
1193 // TODO: Set by northbound system?
1194 if operStatus == voltha.OperStatus_ACTIVE {
1195 port.AdminState = voltha.AdminState_ENABLED
1196 }
1197 break
1198 }
1199 }
1200 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1201 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001202 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001203 }
1204}
1205
khenaidoo0a822f92019-05-08 15:15:57 -04001206func (agent *DeviceAgent) deleteAllPorts() error {
1207 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1208 agent.lockDevice.Lock()
1209 defer agent.lockDevice.Unlock()
1210 // Work only on latest data
1211 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1212 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1213 } else {
1214 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1215 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1216 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1217 return err
1218 }
1219 if len(storeDevice.Ports) == 0 {
1220 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1221 return nil
1222 }
1223 // clone the device & set the fields to empty
1224 cloned := proto.Clone(storeDevice).(*voltha.Device)
1225 cloned.Ports = []*voltha.Port{}
1226 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1227 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001228 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001229 }
1230}
1231
khenaidoob9203542018-09-17 22:56:37 -04001232func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001233 agent.lockDevice.Lock()
1234 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001235 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001236 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001237 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001238 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1239 } else {
1240 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001241 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001242 if cloned.Ports == nil {
1243 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001244 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001245 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001246 } else {
1247 for _, p := range cloned.Ports {
1248 if p.Type == port.Type && p.PortNo == port.PortNo {
1249 log.Debugw("port already exists", log.Fields{"port": *port})
1250 return nil
1251 }
1252 }
khenaidoob9203542018-09-17 22:56:37 -04001253 }
khenaidoo92e62c52018-10-03 14:02:54 -04001254 cp := proto.Clone(port).(*voltha.Port)
1255 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1256 // TODO: Set by northbound system?
1257 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1258 cp.AdminState = voltha.AdminState_ENABLED
1259 }
1260 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001261 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001262 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001263 }
1264}
1265
1266func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1267 agent.lockDevice.Lock()
1268 defer agent.lockDevice.Unlock()
1269 log.Debug("addPeerPort")
1270 // Work only on latest data
1271 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1272 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1273 } else {
1274 // clone the device
1275 cloned := proto.Clone(storeDevice).(*voltha.Device)
1276 // Get the peer port on the device based on the port no
1277 for _, peerPort := range cloned.Ports {
1278 if peerPort.PortNo == port.PortNo { // found port
1279 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1280 peerPort.Peers = append(peerPort.Peers, cp)
1281 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1282 break
1283 }
1284 }
1285 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001286 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001287 }
1288}
1289
khenaidoo0a822f92019-05-08 15:15:57 -04001290func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1291 agent.lockDevice.Lock()
1292 defer agent.lockDevice.Unlock()
1293 log.Debug("deletePeerPorts")
1294 // Work only on latest data
1295 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1296 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1297 } else {
1298 // clone the device
1299 cloned := proto.Clone(storeDevice).(*voltha.Device)
1300 var updatedPeers []*voltha.Port_PeerPort
1301 for _, port := range cloned.Ports {
1302 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1303 for _, peerPort := range port.Peers {
1304 if peerPort.DeviceId != deviceId {
1305 updatedPeers = append(updatedPeers, peerPort)
1306 }
1307 }
1308 port.Peers = updatedPeers
1309 }
1310
1311 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001312 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001313 }
1314}
1315
khenaidoob9203542018-09-17 22:56:37 -04001316// TODO: A generic device update by attribute
1317func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001318 agent.lockDevice.Lock()
1319 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001320 if value == nil {
1321 return
1322 }
1323 var storeDevice *voltha.Device
1324 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001325 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001326 return
1327 }
1328 updated := false
1329 s := reflect.ValueOf(storeDevice).Elem()
1330 if s.Kind() == reflect.Struct {
1331 // exported field
1332 f := s.FieldByName(name)
1333 if f.IsValid() && f.CanSet() {
1334 switch f.Kind() {
1335 case reflect.String:
1336 f.SetString(value.(string))
1337 updated = true
1338 case reflect.Uint32:
1339 f.SetUint(uint64(value.(uint32)))
1340 updated = true
1341 case reflect.Bool:
1342 f.SetBool(value.(bool))
1343 updated = true
1344 }
1345 }
1346 }
khenaidoo92e62c52018-10-03 14:02:54 -04001347 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001348 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001349 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001350 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001351 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1352 }
1353 return
1354}
serkant.uluderya334479d2019-04-10 08:26:15 -07001355
1356func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1357 agent.lockDevice.Lock()
1358 defer agent.lockDevice.Unlock()
1359 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1360 // Get the most up to date the device info
1361 if device, err := agent.getDeviceWithoutLock(); err != nil {
1362 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1363 } else {
1364 // First send the request to an Adapter and wait for a response
1365 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
Scott Baker80678602019-11-14 16:57:36 -08001366 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceId, "error": err})
serkant.uluderya334479d2019-04-10 08:26:15 -07001367 return err
1368 }
1369 }
1370 return nil
1371}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001372
1373//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.
1374// It is an internal helper function.
1375func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1376 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1377 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1378 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1379 }
1380 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1381
1382 return nil
1383}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001384
1385func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1386 agent.lockDevice.Lock()
1387 defer agent.lockDevice.Unlock()
1388 // Work only on latest data
1389 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1390 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1391 } else {
1392 // clone the device
1393 cloned := proto.Clone(storeDevice).(*voltha.Device)
1394 cloned.Reason = reason
1395 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1396 // Store the device
1397 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1398 }
1399}