blob: 836269efb09f823094de38939b89d20d22009eab [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"
20 "github.com/gogo/protobuf/proto"
21 "github.com/opencord/voltha-go/common/log"
22 "github.com/opencord/voltha-go/db/model"
serkant.uluderya334479d2019-04-10 08:26:15 -070023 fu "github.com/opencord/voltha-go/rw_core/utils"
William Kurkiandaa6bb22019-03-07 12:26:28 -050024 ic "github.com/opencord/voltha-protos/go/inter_container"
25 ofp "github.com/opencord/voltha-protos/go/openflow_13"
26 "github.com/opencord/voltha-protos/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040027 "google.golang.org/grpc/codes"
28 "google.golang.org/grpc/status"
khenaidoo19d7b632018-10-30 10:49:50 -040029 "reflect"
30 "sync"
khenaidoob9203542018-09-17 22:56:37 -040031)
32
33type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040034 deviceId string
khenaidoo43c82122018-11-22 18:38:28 -050035 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040036 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040037 lastData *voltha.Device
38 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070039 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040040 deviceMgr *DeviceManager
41 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040042 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040043 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040044 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040045 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040046}
47
khenaidoo4d4802d2018-10-04 21:59:49 -040048//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
49//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040050func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040051 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040052 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040053 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050054 if cloned.Id == "" {
55 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050056 cloned.AdminState = voltha.AdminState_PREPROVISIONED
57 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
58 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050059 }
khenaidoo19d7b632018-10-30 10:49:50 -040060 if !device.GetRoot() && device.ProxyAddress != nil {
61 // Set the default vlan ID to the one specified by the parent adapter. It can be
62 // overwritten by the child adapter during a device update request
63 cloned.Vlan = device.ProxyAddress.ChannelId
64 }
khenaidoo2c6a0992019-04-29 13:46:56 -040065 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040066 agent.deviceId = cloned.Id
khenaidoofdbad6e2018-11-06 22:26:38 -050067 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040068 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040069 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050070 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040071 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040072 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040073 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040074 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040075 return &agent
76}
77
khenaidoo297cd252019-02-07 22:10:23 -050078// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
79// it will load the data from the dB and setup teh necessary callbacks and proxies.
80func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040081 agent.lockDevice.Lock()
82 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050083 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
84 if loadFromdB {
85 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
86 if d, ok := device.(*voltha.Device); ok {
87 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050088 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050089 }
90 } else {
91 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
92 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
93 }
94 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
95 } else {
96 // Add the initial device to the local model
97 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
98 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
99 }
khenaidoob9203542018-09-17 22:56:37 -0400100 }
khenaidoo297cd252019-02-07 22:10:23 -0500101
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400102 agent.deviceProxy = agent.clusterDataProxy.CreateProxy("/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500103 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400104
khenaidoob9203542018-09-17 22:56:37 -0400105 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500106 return nil
khenaidoob9203542018-09-17 22:56:37 -0400107}
108
khenaidoo4d4802d2018-10-04 21:59:49 -0400109// stop stops the device agent. Not much to do for now
110func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400111 agent.lockDevice.Lock()
112 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400113 log.Debug("stopping-device-agent")
114 agent.exitChannel <- 1
115 log.Debug("device-agent-stopped")
116}
117
khenaidoo19d7b632018-10-30 10:49:50 -0400118// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400119func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400120 agent.lockDevice.RLock()
121 defer agent.lockDevice.RUnlock()
khenaidoo297cd252019-02-07 22:10:23 -0500122 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400123 if d, ok := device.(*voltha.Device); ok {
124 cloned := proto.Clone(d).(*voltha.Device)
125 return cloned, nil
126 }
127 }
128 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
129}
130
khenaidoo4d4802d2018-10-04 21:59:49 -0400131// 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 -0400132// This function is meant so that we do not have duplicate code all over the device agent functions
133func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400134 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400135 if d, ok := device.(*voltha.Device); ok {
136 cloned := proto.Clone(d).(*voltha.Device)
137 return cloned, nil
138 }
139 }
140 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
141}
142
khenaidoo4d4802d2018-10-04 21:59:49 -0400143// enableDevice activates a preprovisioned or disable device
khenaidoob9203542018-09-17 22:56:37 -0400144func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400145 agent.lockDevice.Lock()
146 defer agent.lockDevice.Unlock()
147 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500148
khenaidoo92e62c52018-10-03 14:02:54 -0400149 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400150 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
151 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500152 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
153 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
154 // with the adapter then we need to know the adapter that will handle this request
155 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
156 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
157 return err
158 } else {
159 device.Adapter = adapterName
160 }
161
khenaidoo92e62c52018-10-03 14:02:54 -0400162 if device.AdminState == voltha.AdminState_ENABLED {
163 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
164 //TODO: Needs customized error message
165 return nil
166 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400167 //TODO: if parent device is disabled then do not enable device
khenaidoo92e62c52018-10-03 14:02:54 -0400168 // Verify whether we need to adopt the device the first time
169 // TODO: A state machine for these state transitions would be better (we just have to handle
170 // a limited set of states now or it may be an overkill)
171 if device.AdminState == voltha.AdminState_PREPROVISIONED {
172 // First send the request to an Adapter and wait for a response
173 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
174 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400175 return err
176 }
khenaidoo92e62c52018-10-03 14:02:54 -0400177 } else {
178 // First send the request to an Adapter and wait for a response
179 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
180 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
181 return err
182 }
183 }
184 // Received an Ack (no error found above). Now update the device in the model to the expected state
185 cloned := proto.Clone(device).(*voltha.Device)
186 cloned.AdminState = voltha.AdminState_ENABLED
187 cloned.OperStatus = voltha.OperStatus_ACTIVATING
188 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
189 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
khenaidoob9203542018-09-17 22:56:37 -0400190 }
191 }
192 return nil
193}
194
khenaidoo2c6a0992019-04-29 13:46:56 -0400195func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
196 if err := agent.updateDeviceWithoutLock(device); err != nil {
197 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400198 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400199 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400200}
201
khenaidoo2c6a0992019-04-29 13:46:56 -0400202func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
203 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
204 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
205 ch <- err
206 }
207 ch <- nil
208}
209
210func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
211 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
212 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
213 ch <- err
214 }
215 ch <- nil
216}
217
218func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
219 if (len(newFlows) | len(newGroups)) == 0 {
220 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
221 return nil
222 }
223
khenaidoo19d7b632018-10-30 10:49:50 -0400224 agent.lockDevice.Lock()
225 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400226 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
227 var existingFlows *voltha.Flows
228 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo19d7b632018-10-30 10:49:50 -0400229 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
230 } else {
khenaidoo2c6a0992019-04-29 13:46:56 -0400231 existingFlows = proto.Clone(device.Flows).(*voltha.Flows)
232 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
233 log.Debugw("addFlows", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "existingFlows": existingFlows, "groups": newGroups, "existingGroups": existingGroups})
234
235 var updatedFlows []*ofp.OfpFlowStats
236 var flowsToDelete []*ofp.OfpFlowStats
237 var groupsToDelete []*ofp.OfpGroupEntry
238 var updatedGroups []*ofp.OfpGroupEntry
239
240 // Process flows
241 for _, flow := range newFlows {
242 updatedFlows = append(updatedFlows, flow)
243 }
244
245 for _, flow := range existingFlows.Items {
246 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
247 updatedFlows = append(updatedFlows, flow)
248 } else {
249 flowsToDelete = append(flowsToDelete, flow)
250 }
251 }
252
253 // Process groups
254 for _, g := range newGroups {
255 updatedGroups = append(updatedGroups, g)
256 }
257
258 for _, group := range existingGroups.Items {
259 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
260 updatedGroups = append(updatedGroups, group)
261 } else {
262 groupsToDelete = append(groupsToDelete, group)
263 }
264 }
265
266 // Sanity check
267 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
268 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
269 return nil
270
271 }
272 // Send update to adapters
273 chAdapters := make(chan interface{})
274 defer close(chAdapters)
275 chdB := make(chan interface{})
276 defer close(chdB)
277 dType := agent.adapterMgr.getDeviceType(device.Type)
278 if !dType.AcceptsAddRemoveFlowUpdates {
279
280 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
281 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
282 return nil
283 }
284 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
285
286 } else {
287 flowChanges := &ofp.FlowChanges{
288 ToAdd: &voltha.Flows{Items: newFlows},
289 ToRemove: &voltha.Flows{Items: flowsToDelete},
290 }
291 groupChanges := &ofp.FlowGroupChanges{
292 ToAdd: &voltha.FlowGroups{Items: newGroups},
293 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
294 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
295 }
296 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
297 }
298
khenaidoo19d7b632018-10-30 10:49:50 -0400299 // store the changed data
khenaidoo2c6a0992019-04-29 13:46:56 -0400300 device.Flows = &voltha.Flows{Items: updatedFlows}
301 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
302 go agent.updateDeviceWithoutLockAsync(device, chdB)
303
304 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
305 return status.Errorf(codes.Aborted, "errors-%s", res)
khenaidoo19d7b632018-10-30 10:49:50 -0400306 }
307
khenaidoo19d7b632018-10-30 10:49:50 -0400308 return nil
309 }
310}
311
khenaidoo4d4802d2018-10-04 21:59:49 -0400312//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400313func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
314 agent.lockDevice.Lock()
315 //defer agent.lockDevice.Unlock()
316 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
317 // Get the most up to date the device info
318 if device, err := agent.getDeviceWithoutLock(); err != nil {
319 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
320 } else {
321 if device.AdminState == voltha.AdminState_DISABLED {
322 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
323 //TODO: Needs customized error message
324 agent.lockDevice.Unlock()
325 return nil
326 }
327 // First send the request to an Adapter and wait for a response
328 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
329 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
330 agent.lockDevice.Unlock()
331 return err
332 }
333 // Received an Ack (no error found above). Now update the device in the model to the expected state
334 cloned := proto.Clone(device).(*voltha.Device)
335 cloned.AdminState = voltha.AdminState_DISABLED
336 // Set the state of all ports on that device to disable
337 for _, port := range cloned.Ports {
338 port.AdminState = voltha.AdminState_DISABLED
339 port.OperStatus = voltha.OperStatus_UNKNOWN
340 }
341 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
342 agent.lockDevice.Unlock()
343 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
344 }
345 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400346 }
347 return nil
348}
349
khenaidoo4d4802d2018-10-04 21:59:49 -0400350func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
351 agent.lockDevice.Lock()
352 defer agent.lockDevice.Unlock()
353 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
354 // Get the most up to date the device info
355 if device, err := agent.getDeviceWithoutLock(); err != nil {
356 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
357 } else {
358 if device.AdminState != voltha.AdminState_DISABLED {
359 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
360 //TODO: Needs customized error message
361 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
362 }
363 // First send the request to an Adapter and wait for a response
364 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
365 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
366 return err
367 }
368 }
369 return nil
370}
371
372func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
373 agent.lockDevice.Lock()
374 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
375 // Get the most up to date the device info
376 if device, err := agent.getDeviceWithoutLock(); err != nil {
377 agent.lockDevice.Unlock()
378 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
379 } else {
khenaidoo43c82122018-11-22 18:38:28 -0500380 if (device.AdminState != voltha.AdminState_DISABLED) &&
381 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400382 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
383 //TODO: Needs customized error message
384 agent.lockDevice.Unlock()
385 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
386 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500387 if device.AdminState != voltha.AdminState_PREPROVISIONED {
388 // Send the request to an Adapter and wait for a response
389 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
390 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
391 agent.lockDevice.Unlock()
392 return err
393 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400394 }
khenaidoo7ccedd52018-12-14 16:48:54 -0500395 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400396 agent.lockDevice.Unlock()
397 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
398 }
399 agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400400 }
401 return nil
402}
403
khenaidoof5a5bfa2019-01-23 22:20:29 -0500404func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
405 agent.lockDevice.Lock()
406 defer agent.lockDevice.Unlock()
407 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
408 // Get the most up to date the device info
409 if device, err := agent.getDeviceWithoutLock(); err != nil {
410 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
411 } else {
412 if device.AdminState != voltha.AdminState_ENABLED {
413 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
414 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
415 }
416 // Save the image
417 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500418 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500419 cloned := proto.Clone(device).(*voltha.Device)
420 if cloned.ImageDownloads == nil {
421 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
422 } else {
423 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
424 }
425 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
426 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
427 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
428 }
429 // Send the request to the adapter
430 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
431 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
432 return nil, err
433 }
434 }
435 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
436}
437
438// isImageRegistered is a helper method to figure out if an image is already registered
439func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
440 for _, image := range device.ImageDownloads {
441 if image.Id == img.Id && image.Name == img.Name {
442 return true
443 }
444 }
445 return false
446}
447
448func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
449 agent.lockDevice.Lock()
450 defer agent.lockDevice.Unlock()
451 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
452 // Get the most up to date the device info
453 if device, err := agent.getDeviceWithoutLock(); err != nil {
454 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
455 } else {
456 // Verify whether the Image is in the list of image being downloaded
457 if !isImageRegistered(img, device) {
458 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
459 }
460
461 // Update image download state
462 cloned := proto.Clone(device).(*voltha.Device)
463 for _, image := range cloned.ImageDownloads {
464 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500465 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500466 }
467 }
468
469 //If device is in downloading state, send the request to cancel the download
470 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
471 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
472 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
473 return nil, err
474 }
475 // Set the device to Enabled
476 cloned.AdminState = voltha.AdminState_ENABLED
477 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
478 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
479 }
480 }
481 }
482 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700483}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500484
485func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
486 agent.lockDevice.Lock()
487 defer agent.lockDevice.Unlock()
488 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
489 // Get the most up to date the device info
490 if device, err := agent.getDeviceWithoutLock(); err != nil {
491 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
492 } else {
493 // Verify whether the Image is in the list of image being downloaded
494 if !isImageRegistered(img, device) {
495 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
496 }
497
498 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
499 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
500 }
501 // Update image download state
502 cloned := proto.Clone(device).(*voltha.Device)
503 for _, image := range cloned.ImageDownloads {
504 if image.Id == img.Id && image.Name == img.Name {
505 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
506 }
507 }
508 // Set the device to downloading_image
509 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
510 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
511 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
512 }
513
514 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
515 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
516 return nil, err
517 }
518 // The status of the AdminState will be changed following the update_download_status response from the adapter
519 // The image name will also be removed from the device list
520 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700521 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
522}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500523
524func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
525 agent.lockDevice.Lock()
526 defer agent.lockDevice.Unlock()
527 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
528 // Get the most up to date the device info
529 if device, err := agent.getDeviceWithoutLock(); err != nil {
530 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
531 } else {
532 // Verify whether the Image is in the list of image being downloaded
533 if !isImageRegistered(img, device) {
534 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
535 }
536
537 if device.AdminState != voltha.AdminState_ENABLED {
538 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
539 }
540 // Update image download state
541 cloned := proto.Clone(device).(*voltha.Device)
542 for _, image := range cloned.ImageDownloads {
543 if image.Id == img.Id && image.Name == img.Name {
544 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
545 }
546 }
547 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
548 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
549 }
550
551 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
552 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
553 return nil, err
554 }
555 }
556 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700557}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500558
559func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
560 agent.lockDevice.Lock()
561 defer agent.lockDevice.Unlock()
562 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
563 // Get the most up to date the device info
564 if device, err := agent.getDeviceWithoutLock(); err != nil {
565 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
566 } else {
567 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
568 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
569 return nil, err
570 } else {
571 return resp, nil
572 }
573 }
574}
575
serkant.uluderya334479d2019-04-10 08:26:15 -0700576func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500577 agent.lockDevice.Lock()
578 defer agent.lockDevice.Unlock()
579 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
580 // Get the most up to date the device info
581 if device, err := agent.getDeviceWithoutLock(); err != nil {
582 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
583 } else {
584 // Update the image as well as remove it if the download was cancelled
585 cloned := proto.Clone(device).(*voltha.Device)
586 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
587 for _, image := range cloned.ImageDownloads {
588 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500589 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500590 clonedImages = append(clonedImages, img)
591 }
592 }
593 }
594 cloned.ImageDownloads = clonedImages
595 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500596 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
597 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700598 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500599 cloned.AdminState = voltha.AdminState_ENABLED
600 }
601
602 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
603 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
604 }
605 }
606 return nil
607}
608
609func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400610 agent.lockDevice.RLock()
611 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500612 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
613 // Get the most up to date the device info
614 if device, err := agent.getDeviceWithoutLock(); err != nil {
615 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
616 } else {
617 for _, image := range device.ImageDownloads {
618 if image.Id == img.Id && image.Name == img.Name {
619 return image, nil
620 }
621 }
622 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
623 }
624}
625
626func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400627 agent.lockDevice.RLock()
628 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500629 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
630 // Get the most up to date the device info
631 if device, err := agent.getDeviceWithoutLock(); err != nil {
632 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
633 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700634 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500635 }
636}
637
khenaidoo4d4802d2018-10-04 21:59:49 -0400638// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400639func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
640 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400641 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400642 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400643 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400644 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400645 ports.Items = append(ports.Items, port)
646 }
647 }
648 }
649 return ports
650}
651
khenaidoo4d4802d2018-10-04 21:59:49 -0400652// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
653// parent device
khenaidoo79232702018-12-04 11:00:41 -0500654func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400655 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400656 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400657 return nil, err
658 } else {
khenaidoo79232702018-12-04 11:00:41 -0500659 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400660 var err error
661 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
662 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
663 return nil, err
664 }
665 return switchCap, nil
666 }
667}
668
khenaidoo4d4802d2018-10-04 21:59:49 -0400669// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
670// device
khenaidoo79232702018-12-04 11:00:41 -0500671func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400672 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400673 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400674 return nil, err
675 } else {
khenaidoo79232702018-12-04 11:00:41 -0500676 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400677 var err error
678 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
679 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
680 return nil, err
681 }
682 return portCap, nil
683 }
684}
685
khenaidoofdbad6e2018-11-06 22:26:38 -0500686func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
687 // Send packet to adapter
688 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
689 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
690 return err
691 }
692 return nil
693}
694
khenaidoo4d4802d2018-10-04 21:59:49 -0400695// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400696func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500697 //// Run this callback in its own go routine
698 go func(args ...interface{}) interface{} {
699 var previous *voltha.Device
700 var current *voltha.Device
701 var ok bool
702 if len(args) == 2 {
703 if previous, ok = args[0].(*voltha.Device); !ok {
704 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
705 return nil
706 }
707 if current, ok = args[1].(*voltha.Device); !ok {
708 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
709 return nil
710 }
711 } else {
712 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
713 return nil
714 }
715 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500716 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
717 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
718 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
719 }
khenaidoo43c82122018-11-22 18:38:28 -0500720 return nil
721 }(args...)
722
khenaidoo92e62c52018-10-03 14:02:54 -0400723 return nil
724}
725
khenaidoob9203542018-09-17 22:56:37 -0400726func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400727 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500728 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400729 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500730 cloned := proto.Clone(device).(*voltha.Device)
731 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
732 if afterUpdate == nil {
733 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400734 }
khenaidoo43c82122018-11-22 18:38:28 -0500735 return nil
736}
737
738func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
739 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
740 cloned := proto.Clone(device).(*voltha.Device)
741 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
742 if afterUpdate == nil {
743 return status.Errorf(codes.Internal, "%s", device.Id)
744 }
745 return nil
khenaidoob9203542018-09-17 22:56:37 -0400746}
747
khenaidoo92e62c52018-10-03 14:02:54 -0400748func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
749 agent.lockDevice.Lock()
khenaidoob9203542018-09-17 22:56:37 -0400750 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400751 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
752 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400753 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
754 } else {
755 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400756 cloned := proto.Clone(storeDevice).(*voltha.Device)
757 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
758 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
759 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
760 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400761 }
khenaidoo92e62c52018-10-03 14:02:54 -0400762 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
763 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
764 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400765 }
khenaidoo92e62c52018-10-03 14:02:54 -0400766 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400767 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400768 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
769 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400770 return status.Errorf(codes.Internal, "%s", agent.deviceId)
771 }
khenaidoo92e62c52018-10-03 14:02:54 -0400772 agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400773 return nil
774 }
775}
776
777func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
778 agent.lockDevice.Lock()
khenaidoo92e62c52018-10-03 14:02:54 -0400779 // Work only on latest data
780 // TODO: Get list of ports from device directly instead of the entire device
781 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
782 agent.lockDevice.Unlock()
783 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
784 } else {
785 // clone the device
786 cloned := proto.Clone(storeDevice).(*voltha.Device)
787 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
788 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
789 agent.lockDevice.Unlock()
790 return status.Errorf(codes.InvalidArgument, "%s", portType)
791 }
792 for _, port := range cloned.Ports {
793 if port.Type == portType && port.PortNo == portNo {
794 port.OperStatus = operStatus
795 // Set the admin status to ENABLED if the operational status is ACTIVE
796 // TODO: Set by northbound system?
797 if operStatus == voltha.OperStatus_ACTIVE {
798 port.AdminState = voltha.AdminState_ENABLED
799 }
800 break
801 }
802 }
803 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
804 // Store the device
805 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
806 agent.lockDevice.Unlock()
807 return status.Errorf(codes.Internal, "%s", agent.deviceId)
808 }
809 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400810 return nil
811 }
812}
813
814func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400815 agent.lockDevice.Lock()
816 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400817 log.Debug("updatePmConfigs")
818 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400819 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400820 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
821 } else {
822 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400823 cloned := proto.Clone(storeDevice).(*voltha.Device)
824 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400825 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400826 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400827 if afterUpdate == nil {
828 return status.Errorf(codes.Internal, "%s", agent.deviceId)
829 }
830 return nil
831 }
832}
833
834func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400835 agent.lockDevice.Lock()
836 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400837 log.Debugw("addLogicalPortToMap", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400838 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400839 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400840 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
841 } else {
842 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400843 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400844 if cloned.Ports == nil {
845 // First port
khenaidoo2c6a0992019-04-29 13:46:56 -0400846 log.Debugw("addLogicalPortToMap-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400847 cloned.Ports = make([]*voltha.Port, 0)
848 }
khenaidoo92e62c52018-10-03 14:02:54 -0400849 cp := proto.Clone(port).(*voltha.Port)
850 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
851 // TODO: Set by northbound system?
852 if cp.OperStatus == voltha.OperStatus_ACTIVE {
853 cp.AdminState = voltha.AdminState_ENABLED
854 }
855 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400856 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400857 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
858 if afterUpdate == nil {
859 return status.Errorf(codes.Internal, "%s", agent.deviceId)
860 }
861 return nil
862 }
863}
864
865func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
866 agent.lockDevice.Lock()
867 defer agent.lockDevice.Unlock()
868 log.Debug("addPeerPort")
869 // Work only on latest data
870 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
871 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
872 } else {
873 // clone the device
874 cloned := proto.Clone(storeDevice).(*voltha.Device)
875 // Get the peer port on the device based on the port no
876 for _, peerPort := range cloned.Ports {
877 if peerPort.PortNo == port.PortNo { // found port
878 cp := proto.Clone(port).(*voltha.Port_PeerPort)
879 peerPort.Peers = append(peerPort.Peers, cp)
880 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
881 break
882 }
883 }
884 // Store the device
885 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400886 if afterUpdate == nil {
887 return status.Errorf(codes.Internal, "%s", agent.deviceId)
888 }
889 return nil
890 }
891}
892
893// TODO: A generic device update by attribute
894func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -0400895 agent.lockDevice.Lock()
896 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400897 if value == nil {
898 return
899 }
900 var storeDevice *voltha.Device
901 var err error
khenaidoo92e62c52018-10-03 14:02:54 -0400902 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400903 return
904 }
905 updated := false
906 s := reflect.ValueOf(storeDevice).Elem()
907 if s.Kind() == reflect.Struct {
908 // exported field
909 f := s.FieldByName(name)
910 if f.IsValid() && f.CanSet() {
911 switch f.Kind() {
912 case reflect.String:
913 f.SetString(value.(string))
914 updated = true
915 case reflect.Uint32:
916 f.SetUint(uint64(value.(uint32)))
917 updated = true
918 case reflect.Bool:
919 f.SetBool(value.(bool))
920 updated = true
921 }
922 }
923 }
khenaidoo92e62c52018-10-03 14:02:54 -0400924 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -0400925 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -0400926 cloned := proto.Clone(storeDevice).(*voltha.Device)
927 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400928 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
929 }
930 return
931}
serkant.uluderya334479d2019-04-10 08:26:15 -0700932
933func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
934 agent.lockDevice.Lock()
935 defer agent.lockDevice.Unlock()
936 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
937 // Get the most up to date the device info
938 if device, err := agent.getDeviceWithoutLock(); err != nil {
939 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
940 } else {
941 // First send the request to an Adapter and wait for a response
942 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
943 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
944 return err
945 }
946 }
947 return nil
948}