blob: e01d419b0ceaea867b6972565681c063fb8627ad [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
khenaidoo2c6a0992019-04-29 13:46:56 -0400242func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
243 if err := agent.updateDeviceWithoutLock(device); err != nil {
244 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400245 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400246 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400247}
248
Manikkaraj kb1a10922019-07-29 12:10:34 -0400249func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
250 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800251 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo2c6a0992019-04-29 13:46:56 -0400252 ch <- err
253 }
254 ch <- nil
255}
256
Manikkaraj kb1a10922019-07-29 12:10:34 -0400257func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
258 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800259 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo2c6a0992019-04-29 13:46:56 -0400260 ch <- err
261 }
262 ch <- nil
263}
264
khenaidoo0458db62019-06-20 08:50:36 -0400265//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
266//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400267func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
268 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400269
khenaidoo2c6a0992019-04-29 13:46:56 -0400270 if (len(newFlows) | len(newGroups)) == 0 {
271 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
272 return nil
273 }
274
khenaidoo19d7b632018-10-30 10:49:50 -0400275 agent.lockDevice.Lock()
276 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400277
khenaidoo0458db62019-06-20 08:50:36 -0400278 var device *voltha.Device
279 var err error
280 if device, err = agent.getDeviceWithoutLock(); err != nil {
281 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
282 }
283
284 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
285 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
286
287 var updatedFlows []*ofp.OfpFlowStats
288 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400289 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400290 var updatedGroups []*ofp.OfpGroupEntry
291
292 // Process flows
293 for _, flow := range newFlows {
294 updatedFlows = append(updatedFlows, flow)
295 }
296 for _, flow := range existingFlows.Items {
297 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400298 updatedFlows = append(updatedFlows, flow)
khenaidoo0458db62019-06-20 08:50:36 -0400299 } else {
300 flowsToDelete = append(flowsToDelete, flow)
301 }
302 }
303
304 // Process groups
305 for _, g := range newGroups {
306 updatedGroups = append(updatedGroups, g)
307 }
308 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400309 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
310 updatedGroups = append(updatedGroups, group)
311 } else {
312 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400313 }
314 }
315
316 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400317 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
khenaidoo0458db62019-06-20 08:50:36 -0400318 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
319 return nil
320 }
321
322 // Send update to adapters
323 // Create two channels to receive responses from the dB and from the adapters.
324 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
325 // to send their responses. These channels will be garbage collected once all the responses are
326 // received
327 chAdapters := make(chan interface{})
328 chdB := make(chan interface{})
329 dType := agent.adapterMgr.getDeviceType(device.Type)
330 if !dType.AcceptsAddRemoveFlowUpdates {
331
332 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
333 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
334 return nil
335 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400336 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400337
338 } else {
339 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400340 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400341 ToRemove: &voltha.Flows{Items: flowsToDelete},
342 }
343 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400344 ToAdd: &voltha.FlowGroups{Items: newGroups},
345 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400346 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
347 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400348 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400349 }
350
351 // store the changed data
352 device.Flows = &voltha.Flows{Items: updatedFlows}
353 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
354 go agent.updateDeviceWithoutLockAsync(device, chdB)
355
Scott Bakerb671a862019-10-24 10:53:40 -0700356 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400357 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400358 return status.Errorf(codes.Aborted, "errors-%s", res)
359 }
360
361 return nil
362}
363
364//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
365//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400366func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400367 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
368
369 if (len(flowsToDel) | len(groupsToDel)) == 0 {
370 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
371 return nil
372 }
373
374 agent.lockDevice.Lock()
375 defer agent.lockDevice.Unlock()
376
377 var device *voltha.Device
378 var err error
379
380 if device, err = agent.getDeviceWithoutLock(); err != nil {
381 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
382 }
383
384 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
385 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
386
387 var flowsToKeep []*ofp.OfpFlowStats
388 var groupsToKeep []*ofp.OfpGroupEntry
389
390 // Process flows
391 for _, flow := range existingFlows.Items {
392 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
393 flowsToKeep = append(flowsToKeep, flow)
394 }
395 }
396
397 // Process groups
398 for _, group := range existingGroups.Items {
399 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
400 groupsToKeep = append(groupsToKeep, group)
401 }
402 }
403
404 log.Debugw("deleteFlowsAndGroups",
405 log.Fields{
406 "deviceId": agent.deviceId,
407 "flowsToDel": len(flowsToDel),
408 "flowsToKeep": len(flowsToKeep),
409 "groupsToDel": len(groupsToDel),
410 "groupsToKeep": len(groupsToKeep),
411 })
412
413 // Sanity check
414 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
415 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
416 return nil
417 }
418
419 // Send update to adapters
420 chAdapters := make(chan interface{})
421 chdB := make(chan interface{})
422 dType := agent.adapterMgr.getDeviceType(device.Type)
423 if !dType.AcceptsAddRemoveFlowUpdates {
424 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
425 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
426 return nil
427 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400428 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400429 } else {
430 flowChanges := &ofp.FlowChanges{
431 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
432 ToRemove: &voltha.Flows{Items: flowsToDel},
433 }
434 groupChanges := &ofp.FlowGroupChanges{
435 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
436 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
437 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
438 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400439 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400440 }
441
442 // store the changed data
443 device.Flows = &voltha.Flows{Items: flowsToKeep}
444 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
445 go agent.updateDeviceWithoutLockAsync(device, chdB)
446
Scott Bakerb671a862019-10-24 10:53:40 -0700447 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400448 return status.Errorf(codes.Aborted, "errors-%s", res)
449 }
450 return nil
451
452}
453
454//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
455//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400456func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400457 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
458
459 if (len(updatedFlows) | len(updatedGroups)) == 0 {
460 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
461 return nil
462 }
463
464 agent.lockDevice.Lock()
465 defer agent.lockDevice.Unlock()
466 var device *voltha.Device
467 var err error
468 if device, err = agent.getDeviceWithoutLock(); err != nil {
469 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
470 }
471 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
472 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
473
474 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
475 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
476 return nil
477 }
478
479 log.Debugw("updating-flows-and-groups",
480 log.Fields{
481 "deviceId": agent.deviceId,
482 "updatedFlows": updatedFlows,
483 "updatedGroups": updatedGroups,
484 })
485
486 chAdapters := make(chan interface{})
487 chdB := make(chan interface{})
488 dType := agent.adapterMgr.getDeviceType(device.Type)
489
490 // Process bulk flow update differently than incremental update
491 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400492 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400493 } else {
494 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400495 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400496 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400497 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400498
499 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400500 for _, flow := range updatedFlows {
501 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
502 flowsToAdd = append(flowsToAdd, flow)
503 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400505 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400506 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400507 flowsToDelete = append(flowsToDelete, flow)
508 }
509 }
510
511 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400512 for _, g := range updatedGroups {
513 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
514 groupsToAdd = append(groupsToAdd, g)
515 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400516 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400517 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400518 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400519 groupsToDelete = append(groupsToDelete, group)
520 }
521 }
522
khenaidoo0458db62019-06-20 08:50:36 -0400523 log.Debugw("updating-flows-and-groups",
524 log.Fields{
525 "deviceId": agent.deviceId,
526 "flowsToAdd": flowsToAdd,
527 "flowsToDelete": flowsToDelete,
528 "groupsToAdd": groupsToAdd,
529 "groupsToDelete": groupsToDelete,
530 })
531
khenaidoo2c6a0992019-04-29 13:46:56 -0400532 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400533 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
534 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400535 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400536 }
537
khenaidoo0458db62019-06-20 08:50:36 -0400538 flowChanges := &ofp.FlowChanges{
539 ToAdd: &voltha.Flows{Items: flowsToAdd},
540 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400541 }
khenaidoo0458db62019-06-20 08:50:36 -0400542 groupChanges := &ofp.FlowGroupChanges{
543 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
544 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
545 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
546 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400547 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400548 }
khenaidoo0458db62019-06-20 08:50:36 -0400549
550 // store the updated data
551 device.Flows = &voltha.Flows{Items: updatedFlows}
552 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
553 go agent.updateDeviceWithoutLockAsync(device, chdB)
554
Scott Bakerb671a862019-10-24 10:53:40 -0700555 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400556 return status.Errorf(codes.Aborted, "errors-%s", res)
557 }
558 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400559}
560
khenaidoo4d4802d2018-10-04 21:59:49 -0400561//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400562func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400563 agent.lockDevice.Lock()
564 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400565 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
566 // Get the most up to date the device info
567 if device, err := agent.getDeviceWithoutLock(); err != nil {
568 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
569 } else {
570 if device.AdminState == voltha.AdminState_DISABLED {
571 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400572 return nil
573 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400574 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
575 device.AdminState == voltha.AdminState_DELETED {
576 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
577 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
578 }
579
khenaidoo59ef7be2019-06-21 12:40:28 -0400580 // Update the Admin State and operational state before sending the request out
581 cloned := proto.Clone(device).(*voltha.Device)
582 cloned.AdminState = voltha.AdminState_DISABLED
583 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300584 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
585 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400586 }
587
khenaidoo92e62c52018-10-03 14:02:54 -0400588 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800589 log.Debugw("disableDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400590 return err
591 }
khenaidoo0a822f92019-05-08 15:15:57 -0400592 }
593 return nil
594}
595
596func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
597 agent.lockDevice.Lock()
598 defer agent.lockDevice.Unlock()
599 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
600 // Get the most up to date the device info
601 if device, err := agent.getDeviceWithoutLock(); err != nil {
602 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
603 } else {
604 if device.AdminState == adminState {
605 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
606 return nil
607 }
khenaidoo92e62c52018-10-03 14:02:54 -0400608 // Received an Ack (no error found above). Now update the device in the model to the expected state
609 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400610 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300611 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
612 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400613 }
khenaidoo92e62c52018-10-03 14:02:54 -0400614 }
615 return nil
616}
617
khenaidoo4d4802d2018-10-04 21:59:49 -0400618func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
619 agent.lockDevice.Lock()
620 defer agent.lockDevice.Unlock()
621 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
622 // Get the most up to date the device info
623 if device, err := agent.getDeviceWithoutLock(); err != nil {
624 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
625 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400626 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800627 log.Debugw("rebootDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo4d4802d2018-10-04 21:59:49 -0400628 return err
629 }
630 }
631 return nil
632}
633
634func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
635 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400636 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400637 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
638 // Get the most up to date the device info
639 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400640 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
641 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400642 if device.AdminState == voltha.AdminState_DELETED {
643 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
644 return nil
645 }
khenaidoo43c82122018-11-22 18:38:28 -0500646 if (device.AdminState != voltha.AdminState_DISABLED) &&
647 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400648 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
649 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400650 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
651 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400652 if device.AdminState != voltha.AdminState_PREPROVISIONED {
653 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
654 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800655 log.Debugw("deleteDevice-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoo4554f7c2019-05-29 22:13:15 -0400656 return err
657 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400658 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400659 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
660 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400661 cloned := proto.Clone(device).(*voltha.Device)
662 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300663 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
664 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400665 }
khenaidoo0a822f92019-05-08 15:15:57 -0400666 // If this is a child device then remove the associated peer ports on the parent device
667 if !device.Root {
668 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
669 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400670 }
671 return nil
672}
673
khenaidooad06fd72019-10-28 12:26:05 -0400674func (agent *DeviceAgent) setParentId(device *voltha.Device, parentId string) error {
675 agent.lockDevice.Lock()
676 defer agent.lockDevice.Unlock()
677 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentId})
678 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
679 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
680 } else {
681 // 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
689 }
690}
691
khenaidoob3127472019-07-24 21:04:55 -0400692func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
693 agent.lockDevice.Lock()
694 defer agent.lockDevice.Unlock()
695 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
696 // Work only on latest data
697 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
698 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
699 } else {
700 // clone the device
701 cloned := proto.Clone(storeDevice).(*voltha.Device)
702 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
703 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300704 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
705 return err
khenaidoob3127472019-07-24 21:04:55 -0400706 }
707 // Send the request to the adapter
708 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800709 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.deviceId, "error": err})
khenaidoob3127472019-07-24 21:04:55 -0400710 return err
711 }
712 return nil
713 }
714}
715
716func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
717 agent.lockDevice.Lock()
718 defer agent.lockDevice.Unlock()
719 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
720 // Work only on latest data
721 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
722 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
723 } else {
724 // 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
734 }
735}
736
737func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
738 agent.lockDevice.RLock()
739 defer agent.lockDevice.RUnlock()
740 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
741 // Get the most up to date the device info
742 if device, err := agent.getDeviceWithoutLock(); err != nil {
743 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
744 } else {
745 cloned := proto.Clone(device).(*voltha.Device)
746 return cloned.PmConfigs, nil
747 }
748}
749
khenaidoof5a5bfa2019-01-23 22:20:29 -0500750func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
751 agent.lockDevice.Lock()
752 defer agent.lockDevice.Unlock()
753 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
754 // Get the most up to date the device info
755 if device, err := agent.getDeviceWithoutLock(); err != nil {
756 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
757 } else {
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)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500764 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500765 cloned := proto.Clone(device).(*voltha.Device)
766 if cloned.ImageDownloads == nil {
767 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
768 } else {
769 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
770 }
771 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300772 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
773 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500774 }
775 // Send the request to the adapter
776 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800777 log.Debugw("downloadImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500778 return nil, err
779 }
780 }
781 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
782}
783
784// isImageRegistered is a helper method to figure out if an image is already registered
785func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
786 for _, image := range device.ImageDownloads {
787 if image.Id == img.Id && image.Name == img.Name {
788 return true
789 }
790 }
791 return false
792}
793
794func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
795 agent.lockDevice.Lock()
796 defer agent.lockDevice.Unlock()
797 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
798 // Get the most up to date the device info
799 if device, err := agent.getDeviceWithoutLock(); err != nil {
800 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
801 } else {
802 // Verify whether the Image is in the list of image being downloaded
803 if !isImageRegistered(img, device) {
804 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
805 }
806
807 // Update image download state
808 cloned := proto.Clone(device).(*voltha.Device)
809 for _, image := range cloned.ImageDownloads {
810 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500811 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500812 }
813 }
814
khenaidoof5a5bfa2019-01-23 22:20:29 -0500815 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500816 // Set the device to Enabled
817 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300818 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
819 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500820 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400821 // Send the request to teh adapter
822 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800823 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoo59ef7be2019-06-21 12:40:28 -0400824 return nil, err
825 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500826 }
827 }
828 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700829}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500830
831func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
832 agent.lockDevice.Lock()
833 defer agent.lockDevice.Unlock()
834 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
835 // Get the most up to date the device info
836 if device, err := agent.getDeviceWithoutLock(); err != nil {
837 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
838 } else {
839 // Verify whether the Image is in the list of image being downloaded
840 if !isImageRegistered(img, device) {
841 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
842 }
843
844 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
845 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
846 }
847 // Update image download state
848 cloned := proto.Clone(device).(*voltha.Device)
849 for _, image := range cloned.ImageDownloads {
850 if image.Id == img.Id && image.Name == img.Name {
851 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
852 }
853 }
854 // Set the device to downloading_image
855 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300856 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
857 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500858 }
859
860 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800861 log.Debugw("activateImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500862 return nil, err
863 }
864 // The status of the AdminState will be changed following the update_download_status response from the adapter
865 // The image name will also be removed from the device list
866 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700867 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
868}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500869
870func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
871 agent.lockDevice.Lock()
872 defer agent.lockDevice.Unlock()
873 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
874 // Get the most up to date the device info
875 if device, err := agent.getDeviceWithoutLock(); err != nil {
876 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
877 } else {
878 // Verify whether the Image is in the list of image being downloaded
879 if !isImageRegistered(img, device) {
880 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
881 }
882
883 if device.AdminState != voltha.AdminState_ENABLED {
884 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
885 }
886 // Update image download state
887 cloned := proto.Clone(device).(*voltha.Device)
888 for _, image := range cloned.ImageDownloads {
889 if image.Id == img.Id && image.Name == img.Name {
890 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
891 }
892 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300893
894 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
895 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500896 }
897
898 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800899 log.Debugw("revertImage-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500900 return nil, err
901 }
902 }
903 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700904}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500905
906func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
907 agent.lockDevice.Lock()
908 defer agent.lockDevice.Unlock()
909 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
910 // Get the most up to date the device info
911 if device, err := agent.getDeviceWithoutLock(); err != nil {
912 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
913 } else {
914 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
Scott Baker80678602019-11-14 16:57:36 -0800915 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.deviceId, "error": err, "image": img.Name})
khenaidoof5a5bfa2019-01-23 22:20:29 -0500916 return nil, err
917 } else {
918 return resp, nil
919 }
920 }
921}
922
serkant.uluderya334479d2019-04-10 08:26:15 -0700923func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500924 agent.lockDevice.Lock()
925 defer agent.lockDevice.Unlock()
926 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
927 // Get the most up to date the device info
928 if device, err := agent.getDeviceWithoutLock(); err != nil {
929 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
930 } else {
931 // Update the image as well as remove it if the download was cancelled
932 cloned := proto.Clone(device).(*voltha.Device)
933 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
934 for _, image := range cloned.ImageDownloads {
935 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500936 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500937 clonedImages = append(clonedImages, img)
938 }
939 }
940 }
941 cloned.ImageDownloads = clonedImages
942 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500943 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
944 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700945 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500946 cloned.AdminState = voltha.AdminState_ENABLED
947 }
948
Mahir Gunyelb5851672019-07-24 10:46:26 +0300949 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
950 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500951 }
952 }
953 return nil
954}
955
956func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400957 agent.lockDevice.RLock()
958 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500959 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
960 // Get the most up to date the device info
961 if device, err := agent.getDeviceWithoutLock(); err != nil {
962 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
963 } else {
964 for _, image := range device.ImageDownloads {
965 if image.Id == img.Id && image.Name == img.Name {
966 return image, nil
967 }
968 }
969 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
970 }
971}
972
973func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400974 agent.lockDevice.RLock()
975 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500976 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
977 // Get the most up to date the device info
978 if device, err := agent.getDeviceWithoutLock(); err != nil {
979 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
980 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700981 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500982 }
983}
984
khenaidoo4d4802d2018-10-04 21:59:49 -0400985// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400986func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
987 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400988 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400989 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400990 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400991 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400992 ports.Items = append(ports.Items, port)
993 }
994 }
995 }
996 return ports
997}
998
khenaidoo4d4802d2018-10-04 21:59:49 -0400999// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
1000// parent device
khenaidoo79232702018-12-04 11:00:41 -05001001func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -04001002 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -04001003 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001004 return nil, err
1005 } else {
khenaidoo79232702018-12-04 11:00:41 -05001006 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -04001007 var err error
1008 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
1009 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
1010 return nil, err
1011 }
1012 return switchCap, nil
1013 }
1014}
1015
khenaidoo4d4802d2018-10-04 21:59:49 -04001016// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
1017// device
khenaidoo79232702018-12-04 11:00:41 -05001018func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -04001019 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -04001020 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -04001021 return nil, err
1022 } else {
khenaidoo79232702018-12-04 11:00:41 -05001023 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -04001024 var err error
1025 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
1026 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1027 return nil, err
1028 }
1029 return portCap, nil
1030 }
1031}
1032
khenaidoofdbad6e2018-11-06 22:26:38 -05001033func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001034 // If deviceType=="" then we must have taken ownership of this device.
1035 // Fixes VOL-2226 where a core would take ownership and have stale data
1036 if agent.deviceType == "" {
1037 agent.reconcileWithKVStore()
1038 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001039 // Send packet to adapter
1040 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001041 log.Debugw("packet-out-error", log.Fields{
Scott Baker80678602019-11-14 16:57:36 -08001042 "id": agent.deviceId,
Matteo Scandolo360605d2019-11-05 18:29:17 -08001043 "error": err,
1044 "packet": hex.EncodeToString(packet.Data),
1045 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001046 return err
1047 }
1048 return nil
1049}
1050
khenaidoo4d4802d2018-10-04 21:59:49 -04001051// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001052func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001053 //// Run this callback in its own go routine
1054 go func(args ...interface{}) interface{} {
1055 var previous *voltha.Device
1056 var current *voltha.Device
1057 var ok bool
1058 if len(args) == 2 {
1059 if previous, ok = args[0].(*voltha.Device); !ok {
1060 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1061 return nil
1062 }
1063 if current, ok = args[1].(*voltha.Device); !ok {
1064 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1065 return nil
1066 }
1067 } else {
1068 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1069 return nil
1070 }
1071 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001072 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1073 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1074 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1075 }
khenaidoo43c82122018-11-22 18:38:28 -05001076 return nil
1077 }(args...)
1078
khenaidoo92e62c52018-10-03 14:02:54 -04001079 return nil
1080}
1081
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001082// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1083// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1084func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1085 // First retrieve the most up to date device info
1086 var currentDevice *voltha.Device
1087 var err error
1088 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1089 return nil, err
1090 }
1091 cloned := proto.Clone(currentDevice).(*voltha.Device)
1092 cloned.Root = device.Root
1093 cloned.Vendor = device.Vendor
1094 cloned.Model = device.Model
1095 cloned.SerialNumber = device.SerialNumber
1096 cloned.MacAddress = device.MacAddress
1097 cloned.Vlan = device.Vlan
1098 cloned.Reason = device.Reason
1099 return cloned, nil
1100}
1101func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001102 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001103 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001104 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1105 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1106 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1107 return status.Errorf(codes.Internal, "%s", err.Error())
1108 } else {
1109 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1110 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1111 }
khenaidoo43c82122018-11-22 18:38:28 -05001112}
1113
1114func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1115 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1116 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001117 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001118}
1119
khenaidoo92e62c52018-10-03 14:02:54 -04001120func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1121 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001122 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001123 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001124 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001125 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1126 } else {
1127 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001128 cloned := proto.Clone(storeDevice).(*voltha.Device)
1129 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1130 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1131 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1132 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001133 }
khenaidoo92e62c52018-10-03 14:02:54 -04001134 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1135 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1136 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001137 }
khenaidoo92e62c52018-10-03 14:02:54 -04001138 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001139 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001140 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001141 }
1142}
1143
khenaidoo3ab34882019-05-02 21:33:30 -04001144func (agent *DeviceAgent) enablePorts() error {
1145 agent.lockDevice.Lock()
1146 defer agent.lockDevice.Unlock()
1147 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1148 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1149 } else {
1150 // clone the device
1151 cloned := proto.Clone(storeDevice).(*voltha.Device)
1152 for _, port := range cloned.Ports {
1153 port.AdminState = voltha.AdminState_ENABLED
1154 port.OperStatus = voltha.OperStatus_ACTIVE
1155 }
1156 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001157 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001158 }
1159}
1160
1161func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001162 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001163 agent.lockDevice.Lock()
1164 defer agent.lockDevice.Unlock()
1165 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1166 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1167 } else {
1168 // clone the device
1169 cloned := proto.Clone(storeDevice).(*voltha.Device)
1170 for _, port := range cloned.Ports {
1171 port.AdminState = voltha.AdminState_DISABLED
1172 port.OperStatus = voltha.OperStatus_UNKNOWN
1173 }
1174 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001175 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001176 }
1177}
1178
khenaidoo92e62c52018-10-03 14:02:54 -04001179func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1180 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001181 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001182 // Work only on latest data
1183 // TODO: Get list of ports from device directly instead of the entire device
1184 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001185 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1186 } else {
1187 // clone the device
1188 cloned := proto.Clone(storeDevice).(*voltha.Device)
1189 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1190 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001191 return status.Errorf(codes.InvalidArgument, "%s", portType)
1192 }
1193 for _, port := range cloned.Ports {
1194 if port.Type == portType && port.PortNo == portNo {
1195 port.OperStatus = operStatus
1196 // Set the admin status to ENABLED if the operational status is ACTIVE
1197 // TODO: Set by northbound system?
1198 if operStatus == voltha.OperStatus_ACTIVE {
1199 port.AdminState = voltha.AdminState_ENABLED
1200 }
1201 break
1202 }
1203 }
1204 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1205 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001206 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001207 }
1208}
1209
khenaidoo0a822f92019-05-08 15:15:57 -04001210func (agent *DeviceAgent) deleteAllPorts() error {
1211 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1212 agent.lockDevice.Lock()
1213 defer agent.lockDevice.Unlock()
1214 // Work only on latest data
1215 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1216 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1217 } else {
1218 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1219 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1220 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1221 return err
1222 }
1223 if len(storeDevice.Ports) == 0 {
1224 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1225 return nil
1226 }
1227 // clone the device & set the fields to empty
1228 cloned := proto.Clone(storeDevice).(*voltha.Device)
1229 cloned.Ports = []*voltha.Port{}
1230 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1231 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001232 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001233 }
1234}
1235
khenaidoob9203542018-09-17 22:56:37 -04001236func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001237 agent.lockDevice.Lock()
1238 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001239 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001240 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001241 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001242 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1243 } else {
1244 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001245 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001246 if cloned.Ports == nil {
1247 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001248 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001249 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001250 } else {
1251 for _, p := range cloned.Ports {
1252 if p.Type == port.Type && p.PortNo == port.PortNo {
1253 log.Debugw("port already exists", log.Fields{"port": *port})
1254 return nil
1255 }
1256 }
khenaidoob9203542018-09-17 22:56:37 -04001257 }
khenaidoo92e62c52018-10-03 14:02:54 -04001258 cp := proto.Clone(port).(*voltha.Port)
1259 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1260 // TODO: Set by northbound system?
1261 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1262 cp.AdminState = voltha.AdminState_ENABLED
1263 }
1264 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001265 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001266 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001267 }
1268}
1269
1270func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1271 agent.lockDevice.Lock()
1272 defer agent.lockDevice.Unlock()
1273 log.Debug("addPeerPort")
1274 // Work only on latest data
1275 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1276 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1277 } else {
1278 // clone the device
1279 cloned := proto.Clone(storeDevice).(*voltha.Device)
1280 // Get the peer port on the device based on the port no
1281 for _, peerPort := range cloned.Ports {
1282 if peerPort.PortNo == port.PortNo { // found port
1283 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1284 peerPort.Peers = append(peerPort.Peers, cp)
1285 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1286 break
1287 }
1288 }
1289 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001290 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001291 }
1292}
1293
khenaidoo0a822f92019-05-08 15:15:57 -04001294func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1295 agent.lockDevice.Lock()
1296 defer agent.lockDevice.Unlock()
1297 log.Debug("deletePeerPorts")
1298 // Work only on latest data
1299 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1300 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1301 } else {
1302 // clone the device
1303 cloned := proto.Clone(storeDevice).(*voltha.Device)
1304 var updatedPeers []*voltha.Port_PeerPort
1305 for _, port := range cloned.Ports {
1306 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1307 for _, peerPort := range port.Peers {
1308 if peerPort.DeviceId != deviceId {
1309 updatedPeers = append(updatedPeers, peerPort)
1310 }
1311 }
1312 port.Peers = updatedPeers
1313 }
1314
1315 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001316 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001317 }
1318}
1319
khenaidoob9203542018-09-17 22:56:37 -04001320// TODO: A generic device update by attribute
1321func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001322 agent.lockDevice.Lock()
1323 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001324 if value == nil {
1325 return
1326 }
1327 var storeDevice *voltha.Device
1328 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001329 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001330 return
1331 }
1332 updated := false
1333 s := reflect.ValueOf(storeDevice).Elem()
1334 if s.Kind() == reflect.Struct {
1335 // exported field
1336 f := s.FieldByName(name)
1337 if f.IsValid() && f.CanSet() {
1338 switch f.Kind() {
1339 case reflect.String:
1340 f.SetString(value.(string))
1341 updated = true
1342 case reflect.Uint32:
1343 f.SetUint(uint64(value.(uint32)))
1344 updated = true
1345 case reflect.Bool:
1346 f.SetBool(value.(bool))
1347 updated = true
1348 }
1349 }
1350 }
khenaidoo92e62c52018-10-03 14:02:54 -04001351 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001352 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001353 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001354 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001355 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1356 }
1357 return
1358}
serkant.uluderya334479d2019-04-10 08:26:15 -07001359
1360func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1361 agent.lockDevice.Lock()
1362 defer agent.lockDevice.Unlock()
1363 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1364 // Get the most up to date the device info
1365 if device, err := agent.getDeviceWithoutLock(); err != nil {
1366 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1367 } else {
1368 // First send the request to an Adapter and wait for a response
1369 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
Scott Baker80678602019-11-14 16:57:36 -08001370 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.deviceId, "error": err})
serkant.uluderya334479d2019-04-10 08:26:15 -07001371 return err
1372 }
1373 }
1374 return nil
1375}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001376
1377//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.
1378// It is an internal helper function.
1379func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1380 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1381 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1382 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1383 }
1384 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1385
1386 return nil
1387}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001388
1389func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1390 agent.lockDevice.Lock()
1391 defer agent.lockDevice.Unlock()
1392 // Work only on latest data
1393 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1394 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1395 } else {
1396 // clone the device
1397 cloned := proto.Clone(storeDevice).(*voltha.Device)
1398 cloned.Reason = reason
1399 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1400 // Store the device
1401 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1402 }
1403}