blob: 7b9e00b806e0d1978135fd8a561660e94b04aeca [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"
khenaidoo3ab34882019-05-02 21:33:30 -040020 "fmt"
khenaidoob9203542018-09-17 22:56:37 -040021 "github.com/gogo/protobuf/proto"
22 "github.com/opencord/voltha-go/common/log"
23 "github.com/opencord/voltha-go/db/model"
serkant.uluderya334479d2019-04-10 08:26:15 -070024 fu "github.com/opencord/voltha-go/rw_core/utils"
William Kurkiandaa6bb22019-03-07 12:26:28 -050025 ic "github.com/opencord/voltha-protos/go/inter_container"
26 ofp "github.com/opencord/voltha-protos/go/openflow_13"
27 "github.com/opencord/voltha-protos/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040028 "google.golang.org/grpc/codes"
29 "google.golang.org/grpc/status"
khenaidoo19d7b632018-10-30 10:49:50 -040030 "reflect"
31 "sync"
Stephane Barbarieef6650d2019-07-18 12:15:09 -040032 "time"
khenaidoob9203542018-09-17 22:56:37 -040033)
34
35type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040036 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040037 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050038 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040039 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040040 lastData *voltha.Device
41 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070042 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040043 deviceMgr *DeviceManager
44 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040045 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040046 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040047 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040048 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040049}
50
khenaidoo4d4802d2018-10-04 21:59:49 -040051//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
52//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040053func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040054 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040055 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040056 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050057 if cloned.Id == "" {
58 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050059 cloned.AdminState = voltha.AdminState_PREPROVISIONED
60 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
61 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050062 }
khenaidoo19d7b632018-10-30 10:49:50 -040063 if !device.GetRoot() && device.ProxyAddress != nil {
64 // Set the default vlan ID to the one specified by the parent adapter. It can be
65 // overwritten by the child adapter during a device update request
66 cloned.Vlan = device.ProxyAddress.ChannelId
67 }
khenaidoo2c6a0992019-04-29 13:46:56 -040068 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040069 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040070 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050071 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040072 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040073 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050074 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040075 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040076 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040077 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040078 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040079 return &agent
80}
81
khenaidoo297cd252019-02-07 22:10:23 -050082// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
83// it will load the data from the dB and setup teh necessary callbacks and proxies.
84func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040085 agent.lockDevice.Lock()
86 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050087 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
88 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040089 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050090 if d, ok := device.(*voltha.Device); ok {
91 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050092 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050093 }
94 } else {
95 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
96 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
97 }
98 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
99 } else {
100 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400101 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500102 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
103 }
khenaidoob9203542018-09-17 22:56:37 -0400104 }
khenaidoo297cd252019-02-07 22:10:23 -0500105
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400106 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500107 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400108
khenaidoob9203542018-09-17 22:56:37 -0400109 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500110 return nil
khenaidoob9203542018-09-17 22:56:37 -0400111}
112
khenaidoo4d4802d2018-10-04 21:59:49 -0400113// stop stops the device agent. Not much to do for now
114func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400115 agent.lockDevice.Lock()
116 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400117 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400118 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400119 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400120 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400121 }
khenaidoob9203542018-09-17 22:56:37 -0400122 agent.exitChannel <- 1
123 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400124
khenaidoob9203542018-09-17 22:56:37 -0400125}
126
khenaidoo19d7b632018-10-30 10:49:50 -0400127// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400128func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400129 agent.lockDevice.RLock()
130 defer agent.lockDevice.RUnlock()
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400131 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, true, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400132 if d, ok := device.(*voltha.Device); ok {
133 cloned := proto.Clone(d).(*voltha.Device)
134 return cloned, nil
135 }
136 }
137 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
138}
139
khenaidoo4d4802d2018-10-04 21:59:49 -0400140// 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 -0400141// This function is meant so that we do not have duplicate code all over the device agent functions
142func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400143 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400144 if d, ok := device.(*voltha.Device); ok {
145 cloned := proto.Clone(d).(*voltha.Device)
146 return cloned, nil
147 }
148 }
149 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
150}
151
khenaidoo3ab34882019-05-02 21:33:30 -0400152// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400153func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400154 agent.lockDevice.Lock()
155 defer agent.lockDevice.Unlock()
156 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500157
khenaidoo92e62c52018-10-03 14:02:54 -0400158 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400159 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
160 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500161 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
162 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
163 // with the adapter then we need to know the adapter that will handle this request
164 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
165 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
166 return err
167 } else {
168 device.Adapter = adapterName
169 }
170
khenaidoo92e62c52018-10-03 14:02:54 -0400171 if device.AdminState == voltha.AdminState_ENABLED {
172 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400173 return nil
174 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400175
176 if device.AdminState == voltha.AdminState_DELETED {
177 // This is a temporary state when a device is deleted before it gets removed from the model.
178 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
179 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
180 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400181 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400182
183 previousAdminState := device.AdminState
184
185 // Update the Admin State and set the operational state to activating before sending the request to the
186 // Adapters
187 cloned := proto.Clone(device).(*voltha.Device)
188 cloned.AdminState = voltha.AdminState_ENABLED
189 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400190
Mahir Gunyelb5851672019-07-24 10:46:26 +0300191 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
192 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400193 }
194
195 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
196 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400197 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
198 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400199 return err
200 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400201 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400202 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
203 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
204 return err
205 }
khenaidoob9203542018-09-17 22:56:37 -0400206 }
207 }
208 return nil
209}
210
khenaidoo2c6a0992019-04-29 13:46:56 -0400211func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
212 if err := agent.updateDeviceWithoutLock(device); err != nil {
213 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400214 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400215 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400216}
217
khenaidoo2c6a0992019-04-29 13:46:56 -0400218func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
219 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
220 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
221 ch <- err
222 }
223 ch <- nil
224}
225
226func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
227 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
228 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
229 ch <- err
230 }
231 ch <- nil
232}
233
khenaidoo0458db62019-06-20 08:50:36 -0400234//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
235//adapters
khenaidoo2c6a0992019-04-29 13:46:56 -0400236func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
khenaidoo0458db62019-06-20 08:50:36 -0400237 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
238
khenaidoo2c6a0992019-04-29 13:46:56 -0400239 if (len(newFlows) | len(newGroups)) == 0 {
240 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
241 return nil
242 }
243
khenaidoo19d7b632018-10-30 10:49:50 -0400244 agent.lockDevice.Lock()
245 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400246
khenaidoo0458db62019-06-20 08:50:36 -0400247 var device *voltha.Device
248 var err error
249 if device, err = agent.getDeviceWithoutLock(); err != nil {
250 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
251 }
252
253 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
254 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
255
256 var updatedFlows []*ofp.OfpFlowStats
257 var flowsToDelete []*ofp.OfpFlowStats
258 var groupsToDelete []*ofp.OfpGroupEntry
259 var updatedGroups []*ofp.OfpGroupEntry
260
261 // Process flows
262 for _, flow := range newFlows {
263 updatedFlows = append(updatedFlows, flow)
264 }
265 for _, flow := range existingFlows.Items {
266 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
267 updatedFlows = append(updatedFlows, flow)
268 } else {
269 flowsToDelete = append(flowsToDelete, flow)
270 }
271 }
272
273 // Process groups
274 for _, g := range newGroups {
275 updatedGroups = append(updatedGroups, g)
276 }
277 for _, group := range existingGroups.Items {
278 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
279 updatedGroups = append(updatedGroups, group)
280 } else {
281 groupsToDelete = append(groupsToDelete, group)
282 }
283 }
284
285 // Sanity check
286 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
287 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
288 return nil
289 }
290
291 // Send update to adapters
292 // Create two channels to receive responses from the dB and from the adapters.
293 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
294 // to send their responses. These channels will be garbage collected once all the responses are
295 // received
296 chAdapters := make(chan interface{})
297 chdB := make(chan interface{})
298 dType := agent.adapterMgr.getDeviceType(device.Type)
299 if !dType.AcceptsAddRemoveFlowUpdates {
300
301 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
302 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
303 return nil
304 }
305 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
306
307 } else {
308 flowChanges := &ofp.FlowChanges{
309 ToAdd: &voltha.Flows{Items: newFlows},
310 ToRemove: &voltha.Flows{Items: flowsToDelete},
311 }
312 groupChanges := &ofp.FlowGroupChanges{
313 ToAdd: &voltha.FlowGroups{Items: newGroups},
314 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
315 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
316 }
317 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
318 }
319
320 // store the changed data
321 device.Flows = &voltha.Flows{Items: updatedFlows}
322 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
323 go agent.updateDeviceWithoutLockAsync(device, chdB)
324
325 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
326 return status.Errorf(codes.Aborted, "errors-%s", res)
327 }
328
329 return nil
330}
331
332//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
333//adapters
334func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry) error {
335 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
336
337 if (len(flowsToDel) | len(groupsToDel)) == 0 {
338 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
339 return nil
340 }
341
342 agent.lockDevice.Lock()
343 defer agent.lockDevice.Unlock()
344
345 var device *voltha.Device
346 var err error
347
348 if device, err = agent.getDeviceWithoutLock(); err != nil {
349 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
350 }
351
352 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
353 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
354
355 var flowsToKeep []*ofp.OfpFlowStats
356 var groupsToKeep []*ofp.OfpGroupEntry
357
358 // Process flows
359 for _, flow := range existingFlows.Items {
360 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
361 flowsToKeep = append(flowsToKeep, flow)
362 }
363 }
364
365 // Process groups
366 for _, group := range existingGroups.Items {
367 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
368 groupsToKeep = append(groupsToKeep, group)
369 }
370 }
371
372 log.Debugw("deleteFlowsAndGroups",
373 log.Fields{
374 "deviceId": agent.deviceId,
375 "flowsToDel": len(flowsToDel),
376 "flowsToKeep": len(flowsToKeep),
377 "groupsToDel": len(groupsToDel),
378 "groupsToKeep": len(groupsToKeep),
379 })
380
381 // Sanity check
382 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
383 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
384 return nil
385 }
386
387 // Send update to adapters
388 chAdapters := make(chan interface{})
389 chdB := make(chan interface{})
390 dType := agent.adapterMgr.getDeviceType(device.Type)
391 if !dType.AcceptsAddRemoveFlowUpdates {
392 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
393 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
394 return nil
395 }
396 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, chAdapters)
397 } else {
398 flowChanges := &ofp.FlowChanges{
399 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
400 ToRemove: &voltha.Flows{Items: flowsToDel},
401 }
402 groupChanges := &ofp.FlowGroupChanges{
403 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
404 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
405 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
406 }
407 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
408 }
409
410 // store the changed data
411 device.Flows = &voltha.Flows{Items: flowsToKeep}
412 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
413 go agent.updateDeviceWithoutLockAsync(device, chdB)
414
415 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
416 return status.Errorf(codes.Aborted, "errors-%s", res)
417 }
418 return nil
419
420}
421
422//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
423//also sends the updates to the adapters
424func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry) error {
425 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
426
427 if (len(updatedFlows) | len(updatedGroups)) == 0 {
428 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
429 return nil
430 }
431
432 agent.lockDevice.Lock()
433 defer agent.lockDevice.Unlock()
434 var device *voltha.Device
435 var err error
436 if device, err = agent.getDeviceWithoutLock(); err != nil {
437 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
438 }
439 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
440 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
441
442 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
443 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
444 return nil
445 }
446
447 log.Debugw("updating-flows-and-groups",
448 log.Fields{
449 "deviceId": agent.deviceId,
450 "updatedFlows": updatedFlows,
451 "updatedGroups": updatedGroups,
452 })
453
454 chAdapters := make(chan interface{})
455 chdB := make(chan interface{})
456 dType := agent.adapterMgr.getDeviceType(device.Type)
457
458 // Process bulk flow update differently than incremental update
459 if !dType.AcceptsAddRemoveFlowUpdates {
460 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
461 } else {
462 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400463 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400464 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400465 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400466
467 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400468 for _, flow := range updatedFlows {
469 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
470 flowsToAdd = append(flowsToAdd, flow)
471 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400472 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400473 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400474 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400475 flowsToDelete = append(flowsToDelete, flow)
476 }
477 }
478
479 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400480 for _, g := range updatedGroups {
481 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
482 groupsToAdd = append(groupsToAdd, g)
483 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400484 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400485 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400486 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400487 groupsToDelete = append(groupsToDelete, group)
488 }
489 }
490
khenaidoo0458db62019-06-20 08:50:36 -0400491 log.Debugw("updating-flows-and-groups",
492 log.Fields{
493 "deviceId": agent.deviceId,
494 "flowsToAdd": flowsToAdd,
495 "flowsToDelete": flowsToDelete,
496 "groupsToAdd": groupsToAdd,
497 "groupsToDelete": groupsToDelete,
498 })
499
khenaidoo2c6a0992019-04-29 13:46:56 -0400500 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400501 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
502 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400503 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 }
505
khenaidoo0458db62019-06-20 08:50:36 -0400506 flowChanges := &ofp.FlowChanges{
507 ToAdd: &voltha.Flows{Items: flowsToAdd},
508 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400509 }
khenaidoo0458db62019-06-20 08:50:36 -0400510 groupChanges := &ofp.FlowGroupChanges{
511 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
512 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
513 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
514 }
515 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400516 }
khenaidoo0458db62019-06-20 08:50:36 -0400517
518 // store the updated data
519 device.Flows = &voltha.Flows{Items: updatedFlows}
520 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
521 go agent.updateDeviceWithoutLockAsync(device, chdB)
522
523 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
524 return status.Errorf(codes.Aborted, "errors-%s", res)
525 }
526 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400527}
528
khenaidoo4d4802d2018-10-04 21:59:49 -0400529//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400530func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400531 agent.lockDevice.Lock()
532 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400533 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
534 // Get the most up to date the device info
535 if device, err := agent.getDeviceWithoutLock(); err != nil {
536 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
537 } else {
538 if device.AdminState == voltha.AdminState_DISABLED {
539 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400540 return nil
541 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400542 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
543 device.AdminState == voltha.AdminState_DELETED {
544 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
545 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
546 }
547
khenaidoo59ef7be2019-06-21 12:40:28 -0400548 // Update the Admin State and operational state before sending the request out
549 cloned := proto.Clone(device).(*voltha.Device)
550 cloned.AdminState = voltha.AdminState_DISABLED
551 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300552 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
553 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400554 }
555
khenaidoo92e62c52018-10-03 14:02:54 -0400556 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
557 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400558 return err
559 }
khenaidoo0a822f92019-05-08 15:15:57 -0400560 }
561 return nil
562}
563
564func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
565 agent.lockDevice.Lock()
566 defer agent.lockDevice.Unlock()
567 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
568 // Get the most up to date the device info
569 if device, err := agent.getDeviceWithoutLock(); err != nil {
570 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
571 } else {
572 if device.AdminState == adminState {
573 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
574 return nil
575 }
khenaidoo92e62c52018-10-03 14:02:54 -0400576 // Received an Ack (no error found above). Now update the device in the model to the expected state
577 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400578 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300579 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
580 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400581 }
khenaidoo92e62c52018-10-03 14:02:54 -0400582 }
583 return nil
584}
585
khenaidoo4d4802d2018-10-04 21:59:49 -0400586func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
587 agent.lockDevice.Lock()
588 defer agent.lockDevice.Unlock()
589 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
590 // Get the most up to date the device info
591 if device, err := agent.getDeviceWithoutLock(); err != nil {
592 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
593 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400594 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
595 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
596 return err
597 }
598 }
599 return nil
600}
601
602func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
603 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400604 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400605 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
606 // Get the most up to date the device info
607 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400608 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
609 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400610 if device.AdminState == voltha.AdminState_DELETED {
611 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
612 return nil
613 }
khenaidoo43c82122018-11-22 18:38:28 -0500614 if (device.AdminState != voltha.AdminState_DISABLED) &&
615 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400616 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
617 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400618 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
619 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400620 if device.AdminState != voltha.AdminState_PREPROVISIONED {
621 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
622 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
623 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
624 return err
625 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400626 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400627 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
628 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400629 cloned := proto.Clone(device).(*voltha.Device)
630 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300631 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
632 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400633 }
khenaidoo0a822f92019-05-08 15:15:57 -0400634 // If this is a child device then remove the associated peer ports on the parent device
635 if !device.Root {
636 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
637 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400638 }
639 return nil
640}
641
khenaidoob3127472019-07-24 21:04:55 -0400642func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
643 agent.lockDevice.Lock()
644 defer agent.lockDevice.Unlock()
645 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
646 // Work only on latest data
647 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
648 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
649 } else {
650 // clone the device
651 cloned := proto.Clone(storeDevice).(*voltha.Device)
652 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
653 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300654 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
655 return err
khenaidoob3127472019-07-24 21:04:55 -0400656 }
657 // Send the request to the adapter
658 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
659 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
660 return err
661 }
662 return nil
663 }
664}
665
666func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
667 agent.lockDevice.Lock()
668 defer agent.lockDevice.Unlock()
669 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
670 // Work only on latest data
671 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
672 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
673 } else {
674 // clone the device
675 cloned := proto.Clone(storeDevice).(*voltha.Device)
676 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
677 // Store the device
678 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
679 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
680 if afterUpdate == nil {
681 return status.Errorf(codes.Internal, "%s", agent.deviceId)
682 }
683 return nil
684 }
685}
686
687func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
688 agent.lockDevice.RLock()
689 defer agent.lockDevice.RUnlock()
690 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
691 // Get the most up to date the device info
692 if device, err := agent.getDeviceWithoutLock(); err != nil {
693 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
694 } else {
695 cloned := proto.Clone(device).(*voltha.Device)
696 return cloned.PmConfigs, nil
697 }
698}
699
khenaidoof5a5bfa2019-01-23 22:20:29 -0500700func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
701 agent.lockDevice.Lock()
702 defer agent.lockDevice.Unlock()
703 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
704 // Get the most up to date the device info
705 if device, err := agent.getDeviceWithoutLock(); err != nil {
706 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
707 } else {
708 if device.AdminState != voltha.AdminState_ENABLED {
709 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
710 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
711 }
712 // Save the image
713 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500714 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500715 cloned := proto.Clone(device).(*voltha.Device)
716 if cloned.ImageDownloads == nil {
717 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
718 } else {
719 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
720 }
721 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300722 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
723 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500724 }
725 // Send the request to the adapter
726 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
727 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
728 return nil, err
729 }
730 }
731 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
732}
733
734// isImageRegistered is a helper method to figure out if an image is already registered
735func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
736 for _, image := range device.ImageDownloads {
737 if image.Id == img.Id && image.Name == img.Name {
738 return true
739 }
740 }
741 return false
742}
743
744func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
745 agent.lockDevice.Lock()
746 defer agent.lockDevice.Unlock()
747 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
748 // Get the most up to date the device info
749 if device, err := agent.getDeviceWithoutLock(); err != nil {
750 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
751 } else {
752 // Verify whether the Image is in the list of image being downloaded
753 if !isImageRegistered(img, device) {
754 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
755 }
756
757 // Update image download state
758 cloned := proto.Clone(device).(*voltha.Device)
759 for _, image := range cloned.ImageDownloads {
760 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500761 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500762 }
763 }
764
khenaidoof5a5bfa2019-01-23 22:20:29 -0500765 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500766 // Set the device to Enabled
767 cloned.AdminState = voltha.AdminState_ENABLED
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 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400771 // Send the request to teh adapter
772 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
773 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
774 return nil, err
775 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500776 }
777 }
778 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700779}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500780
781func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
782 agent.lockDevice.Lock()
783 defer agent.lockDevice.Unlock()
784 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
785 // Get the most up to date the device info
786 if device, err := agent.getDeviceWithoutLock(); err != nil {
787 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
788 } else {
789 // Verify whether the Image is in the list of image being downloaded
790 if !isImageRegistered(img, device) {
791 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
792 }
793
794 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
795 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
796 }
797 // Update image download state
798 cloned := proto.Clone(device).(*voltha.Device)
799 for _, image := range cloned.ImageDownloads {
800 if image.Id == img.Id && image.Name == img.Name {
801 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
802 }
803 }
804 // Set the device to downloading_image
805 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300806 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
807 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500808 }
809
810 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
811 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
812 return nil, err
813 }
814 // The status of the AdminState will be changed following the update_download_status response from the adapter
815 // The image name will also be removed from the device list
816 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700817 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
818}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500819
820func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
821 agent.lockDevice.Lock()
822 defer agent.lockDevice.Unlock()
823 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
824 // Get the most up to date the device info
825 if device, err := agent.getDeviceWithoutLock(); err != nil {
826 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
827 } else {
828 // Verify whether the Image is in the list of image being downloaded
829 if !isImageRegistered(img, device) {
830 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
831 }
832
833 if device.AdminState != voltha.AdminState_ENABLED {
834 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
835 }
836 // Update image download state
837 cloned := proto.Clone(device).(*voltha.Device)
838 for _, image := range cloned.ImageDownloads {
839 if image.Id == img.Id && image.Name == img.Name {
840 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
841 }
842 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300843
844 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
845 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500846 }
847
848 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
849 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
850 return nil, err
851 }
852 }
853 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700854}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500855
856func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
857 agent.lockDevice.Lock()
858 defer agent.lockDevice.Unlock()
859 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
860 // Get the most up to date the device info
861 if device, err := agent.getDeviceWithoutLock(); err != nil {
862 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
863 } else {
864 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
865 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
866 return nil, err
867 } else {
868 return resp, nil
869 }
870 }
871}
872
serkant.uluderya334479d2019-04-10 08:26:15 -0700873func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500874 agent.lockDevice.Lock()
875 defer agent.lockDevice.Unlock()
876 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
877 // Get the most up to date the device info
878 if device, err := agent.getDeviceWithoutLock(); err != nil {
879 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
880 } else {
881 // Update the image as well as remove it if the download was cancelled
882 cloned := proto.Clone(device).(*voltha.Device)
883 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
884 for _, image := range cloned.ImageDownloads {
885 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500886 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500887 clonedImages = append(clonedImages, img)
888 }
889 }
890 }
891 cloned.ImageDownloads = clonedImages
892 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500893 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
894 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700895 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500896 cloned.AdminState = voltha.AdminState_ENABLED
897 }
898
Mahir Gunyelb5851672019-07-24 10:46:26 +0300899 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
900 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500901 }
902 }
903 return nil
904}
905
906func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400907 agent.lockDevice.RLock()
908 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500909 log.Debugw("getImageDownload", 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 for _, image := range device.ImageDownloads {
915 if image.Id == img.Id && image.Name == img.Name {
916 return image, nil
917 }
918 }
919 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
920 }
921}
922
923func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400924 agent.lockDevice.RLock()
925 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500926 log.Debugw("listImageDownloads", 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 nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
930 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700931 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500932 }
933}
934
khenaidoo4d4802d2018-10-04 21:59:49 -0400935// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400936func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
937 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400938 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400939 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400940 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400941 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400942 ports.Items = append(ports.Items, port)
943 }
944 }
945 }
946 return ports
947}
948
khenaidoo4d4802d2018-10-04 21:59:49 -0400949// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
950// parent device
khenaidoo79232702018-12-04 11:00:41 -0500951func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400952 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400953 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400954 return nil, err
955 } else {
khenaidoo79232702018-12-04 11:00:41 -0500956 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400957 var err error
958 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
959 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
960 return nil, err
961 }
962 return switchCap, nil
963 }
964}
965
khenaidoo4d4802d2018-10-04 21:59:49 -0400966// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
967// device
khenaidoo79232702018-12-04 11:00:41 -0500968func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400969 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400970 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400971 return nil, err
972 } else {
khenaidoo79232702018-12-04 11:00:41 -0500973 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400974 var err error
975 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
976 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
977 return nil, err
978 }
979 return portCap, nil
980 }
981}
982
khenaidoofdbad6e2018-11-06 22:26:38 -0500983func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
984 // Send packet to adapter
985 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
986 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
987 return err
988 }
989 return nil
990}
991
khenaidoo4d4802d2018-10-04 21:59:49 -0400992// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400993func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500994 //// Run this callback in its own go routine
995 go func(args ...interface{}) interface{} {
996 var previous *voltha.Device
997 var current *voltha.Device
998 var ok bool
999 if len(args) == 2 {
1000 if previous, ok = args[0].(*voltha.Device); !ok {
1001 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1002 return nil
1003 }
1004 if current, ok = args[1].(*voltha.Device); !ok {
1005 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1006 return nil
1007 }
1008 } else {
1009 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1010 return nil
1011 }
1012 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001013 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1014 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1015 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1016 }
khenaidoo43c82122018-11-22 18:38:28 -05001017 return nil
1018 }(args...)
1019
khenaidoo92e62c52018-10-03 14:02:54 -04001020 return nil
1021}
1022
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001023// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1024// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1025func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1026 // First retrieve the most up to date device info
1027 var currentDevice *voltha.Device
1028 var err error
1029 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1030 return nil, err
1031 }
1032 cloned := proto.Clone(currentDevice).(*voltha.Device)
1033 cloned.Root = device.Root
1034 cloned.Vendor = device.Vendor
1035 cloned.Model = device.Model
1036 cloned.SerialNumber = device.SerialNumber
1037 cloned.MacAddress = device.MacAddress
1038 cloned.Vlan = device.Vlan
1039 cloned.Reason = device.Reason
1040 return cloned, nil
1041}
1042func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001043 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001044 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001045 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1046 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1047 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1048 return status.Errorf(codes.Internal, "%s", err.Error())
1049 } else {
1050 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1051 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1052 }
khenaidoo43c82122018-11-22 18:38:28 -05001053}
1054
1055func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1056 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1057 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001058 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001059}
1060
khenaidoo92e62c52018-10-03 14:02:54 -04001061func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1062 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001063 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001064 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001065 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001066 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1067 } else {
1068 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001069 cloned := proto.Clone(storeDevice).(*voltha.Device)
1070 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1071 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1072 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1073 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001074 }
khenaidoo92e62c52018-10-03 14:02:54 -04001075 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1076 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1077 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001078 }
khenaidoo92e62c52018-10-03 14:02:54 -04001079 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001080 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001081 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001082 }
1083}
1084
khenaidoo3ab34882019-05-02 21:33:30 -04001085func (agent *DeviceAgent) enablePorts() error {
1086 agent.lockDevice.Lock()
1087 defer agent.lockDevice.Unlock()
1088 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1089 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1090 } else {
1091 // clone the device
1092 cloned := proto.Clone(storeDevice).(*voltha.Device)
1093 for _, port := range cloned.Ports {
1094 port.AdminState = voltha.AdminState_ENABLED
1095 port.OperStatus = voltha.OperStatus_ACTIVE
1096 }
1097 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001098 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001099 }
1100}
1101
1102func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001103 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001104 agent.lockDevice.Lock()
1105 defer agent.lockDevice.Unlock()
1106 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1107 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1108 } else {
1109 // clone the device
1110 cloned := proto.Clone(storeDevice).(*voltha.Device)
1111 for _, port := range cloned.Ports {
1112 port.AdminState = voltha.AdminState_DISABLED
1113 port.OperStatus = voltha.OperStatus_UNKNOWN
1114 }
1115 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001116 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001117 }
1118}
1119
khenaidoo92e62c52018-10-03 14:02:54 -04001120func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1121 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001122 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001123 // Work only on latest data
1124 // TODO: Get list of ports from device directly instead of the entire device
1125 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001126 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1127 } else {
1128 // clone the device
1129 cloned := proto.Clone(storeDevice).(*voltha.Device)
1130 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1131 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001132 return status.Errorf(codes.InvalidArgument, "%s", portType)
1133 }
1134 for _, port := range cloned.Ports {
1135 if port.Type == portType && port.PortNo == portNo {
1136 port.OperStatus = operStatus
1137 // Set the admin status to ENABLED if the operational status is ACTIVE
1138 // TODO: Set by northbound system?
1139 if operStatus == voltha.OperStatus_ACTIVE {
1140 port.AdminState = voltha.AdminState_ENABLED
1141 }
1142 break
1143 }
1144 }
1145 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1146 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001147 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001148 }
1149}
1150
khenaidoo0a822f92019-05-08 15:15:57 -04001151func (agent *DeviceAgent) deleteAllPorts() error {
1152 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1153 agent.lockDevice.Lock()
1154 defer agent.lockDevice.Unlock()
1155 // Work only on latest data
1156 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1157 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1158 } else {
1159 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1160 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1161 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1162 return err
1163 }
1164 if len(storeDevice.Ports) == 0 {
1165 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1166 return nil
1167 }
1168 // clone the device & set the fields to empty
1169 cloned := proto.Clone(storeDevice).(*voltha.Device)
1170 cloned.Ports = []*voltha.Port{}
1171 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1172 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001173 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001174 }
1175}
1176
khenaidoob9203542018-09-17 22:56:37 -04001177func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001178 agent.lockDevice.Lock()
1179 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001180 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001181 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001182 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001183 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1184 } else {
1185 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001186 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001187 if cloned.Ports == nil {
1188 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001189 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001190 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001191 } else {
1192 for _, p := range cloned.Ports {
1193 if p.Type == port.Type && p.PortNo == port.PortNo {
1194 log.Debugw("port already exists", log.Fields{"port": *port})
1195 return nil
1196 }
1197 }
khenaidoob9203542018-09-17 22:56:37 -04001198 }
khenaidoo92e62c52018-10-03 14:02:54 -04001199 cp := proto.Clone(port).(*voltha.Port)
1200 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1201 // TODO: Set by northbound system?
1202 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1203 cp.AdminState = voltha.AdminState_ENABLED
1204 }
1205 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001206 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001207 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001208 }
1209}
1210
1211func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1212 agent.lockDevice.Lock()
1213 defer agent.lockDevice.Unlock()
1214 log.Debug("addPeerPort")
1215 // Work only on latest data
1216 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1217 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1218 } else {
1219 // clone the device
1220 cloned := proto.Clone(storeDevice).(*voltha.Device)
1221 // Get the peer port on the device based on the port no
1222 for _, peerPort := range cloned.Ports {
1223 if peerPort.PortNo == port.PortNo { // found port
1224 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1225 peerPort.Peers = append(peerPort.Peers, cp)
1226 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1227 break
1228 }
1229 }
1230 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001231 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001232 }
1233}
1234
khenaidoo0a822f92019-05-08 15:15:57 -04001235func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1236 agent.lockDevice.Lock()
1237 defer agent.lockDevice.Unlock()
1238 log.Debug("deletePeerPorts")
1239 // Work only on latest data
1240 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1241 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1242 } else {
1243 // clone the device
1244 cloned := proto.Clone(storeDevice).(*voltha.Device)
1245 var updatedPeers []*voltha.Port_PeerPort
1246 for _, port := range cloned.Ports {
1247 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1248 for _, peerPort := range port.Peers {
1249 if peerPort.DeviceId != deviceId {
1250 updatedPeers = append(updatedPeers, peerPort)
1251 }
1252 }
1253 port.Peers = updatedPeers
1254 }
1255
1256 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001257 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001258 }
1259}
1260
khenaidoob9203542018-09-17 22:56:37 -04001261// TODO: A generic device update by attribute
1262func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001263 agent.lockDevice.Lock()
1264 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001265 if value == nil {
1266 return
1267 }
1268 var storeDevice *voltha.Device
1269 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001270 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001271 return
1272 }
1273 updated := false
1274 s := reflect.ValueOf(storeDevice).Elem()
1275 if s.Kind() == reflect.Struct {
1276 // exported field
1277 f := s.FieldByName(name)
1278 if f.IsValid() && f.CanSet() {
1279 switch f.Kind() {
1280 case reflect.String:
1281 f.SetString(value.(string))
1282 updated = true
1283 case reflect.Uint32:
1284 f.SetUint(uint64(value.(uint32)))
1285 updated = true
1286 case reflect.Bool:
1287 f.SetBool(value.(bool))
1288 updated = true
1289 }
1290 }
1291 }
khenaidoo92e62c52018-10-03 14:02:54 -04001292 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001293 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001294 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001295 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001296 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1297 }
1298 return
1299}
serkant.uluderya334479d2019-04-10 08:26:15 -07001300
1301func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1302 agent.lockDevice.Lock()
1303 defer agent.lockDevice.Unlock()
1304 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1305 // Get the most up to date the device info
1306 if device, err := agent.getDeviceWithoutLock(); err != nil {
1307 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1308 } else {
1309 // First send the request to an Adapter and wait for a response
1310 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1311 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1312 return err
1313 }
1314 }
1315 return nil
1316}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001317
1318//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.
1319// It is an internal helper function.
1320func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1321 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1322 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1323 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1324 }
1325 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1326
1327 return nil
1328}