blob: d45fca62516cfc1504b6268c94e6f88c950e8e6e [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"
khenaidoob9203542018-09-17 22:56:37 -040032)
33
34type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040035 deviceId string
khenaidoo43c82122018-11-22 18:38:28 -050036 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040037 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040038 lastData *voltha.Device
39 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070040 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040041 deviceMgr *DeviceManager
42 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040043 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040044 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040045 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040046 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040047}
48
khenaidoo4d4802d2018-10-04 21:59:49 -040049//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
50//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040051func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040052 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040053 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040054 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050055 if cloned.Id == "" {
56 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050057 cloned.AdminState = voltha.AdminState_PREPROVISIONED
58 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
59 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050060 }
khenaidoo19d7b632018-10-30 10:49:50 -040061 if !device.GetRoot() && device.ProxyAddress != nil {
62 // Set the default vlan ID to the one specified by the parent adapter. It can be
63 // overwritten by the child adapter during a device update request
64 cloned.Vlan = device.ProxyAddress.ChannelId
65 }
khenaidoo2c6a0992019-04-29 13:46:56 -040066 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040067 agent.deviceId = cloned.Id
khenaidoofdbad6e2018-11-06 22:26:38 -050068 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040069 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040070 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050071 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040072 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040073 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040074 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040075 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040076 return &agent
77}
78
khenaidoo297cd252019-02-07 22:10:23 -050079// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
80// it will load the data from the dB and setup teh necessary callbacks and proxies.
81func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040082 agent.lockDevice.Lock()
83 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050084 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
85 if loadFromdB {
86 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
87 if d, ok := device.(*voltha.Device); ok {
88 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050089 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050090 }
91 } else {
92 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
93 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
94 }
95 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
96 } else {
97 // Add the initial device to the local model
98 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
99 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
100 }
khenaidoob9203542018-09-17 22:56:37 -0400101 }
khenaidoo297cd252019-02-07 22:10:23 -0500102
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400103 agent.deviceProxy = agent.clusterDataProxy.CreateProxy("/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500104 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400105
khenaidoob9203542018-09-17 22:56:37 -0400106 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500107 return nil
khenaidoob9203542018-09-17 22:56:37 -0400108}
109
khenaidoo4d4802d2018-10-04 21:59:49 -0400110// stop stops the device agent. Not much to do for now
111func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400112 agent.lockDevice.Lock()
113 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400114 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400115 // Remove the device from the KV store
116 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
117 log.Errorw("failed-removing-device", log.Fields{"id": agent.deviceId})
118 }
khenaidoob9203542018-09-17 22:56:37 -0400119 agent.exitChannel <- 1
120 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400121
khenaidoob9203542018-09-17 22:56:37 -0400122}
123
khenaidoo19d7b632018-10-30 10:49:50 -0400124// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400125func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400126 agent.lockDevice.RLock()
127 defer agent.lockDevice.RUnlock()
khenaidoo297cd252019-02-07 22:10:23 -0500128 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400129 if d, ok := device.(*voltha.Device); ok {
130 cloned := proto.Clone(d).(*voltha.Device)
131 return cloned, nil
132 }
133 }
134 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
135}
136
khenaidoo4d4802d2018-10-04 21:59:49 -0400137// 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 -0400138// This function is meant so that we do not have duplicate code all over the device agent functions
139func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400140 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400141 if d, ok := device.(*voltha.Device); ok {
142 cloned := proto.Clone(d).(*voltha.Device)
143 return cloned, nil
144 }
145 }
146 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
147}
148
khenaidoo3ab34882019-05-02 21:33:30 -0400149// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400150func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400151 agent.lockDevice.Lock()
152 defer agent.lockDevice.Unlock()
153 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500154
khenaidoo92e62c52018-10-03 14:02:54 -0400155 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400156 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
157 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500158 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
159 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
160 // with the adapter then we need to know the adapter that will handle this request
161 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
162 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
163 return err
164 } else {
165 device.Adapter = adapterName
166 }
167
khenaidoo92e62c52018-10-03 14:02:54 -0400168 if device.AdminState == voltha.AdminState_ENABLED {
169 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400170 return nil
171 }
khenaidoo3ab34882019-05-02 21:33:30 -0400172 // If this is a child device then verify the parent state before proceeding
173 if !agent.isRootdevice {
174 if parent := agent.deviceMgr.getParentDevice(device); parent != nil {
175 if parent.AdminState == voltha.AdminState_DISABLED ||
176 parent.AdminState == voltha.AdminState_DELETED ||
177 parent.AdminState == voltha.AdminState_UNKNOWN {
178 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("incorrect-parent-state: %s %d", parent.Id, parent.AdminState))
179 log.Warnw("incorrect-parent-state", log.Fields{"id": agent.deviceId, "error": err})
180 return err
181 }
182 } else {
183 err = status.Error(codes.Unavailable, fmt.Sprintf("parent-not-existent: %s ", device.Id))
184 log.Warnw("parent-not-existent", log.Fields{"id": agent.deviceId, "error": err})
185 return err
186 }
187 }
khenaidoo92e62c52018-10-03 14:02:54 -0400188 if device.AdminState == voltha.AdminState_PREPROVISIONED {
189 // First send the request to an Adapter and wait for a response
190 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
191 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400192 return err
193 }
khenaidoo0a822f92019-05-08 15:15:57 -0400194 } else if device.AdminState == voltha.AdminState_DISABLED {
khenaidoo92e62c52018-10-03 14:02:54 -0400195 // First send the request to an Adapter and wait for a response
196 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
197 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
198 return err
199 }
khenaidoo0a822f92019-05-08 15:15:57 -0400200 } else {
201 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-delete-a-deleted-device: %s ", device.Id))
202 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
203 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400204 }
205 // Received an Ack (no error found above). Now update the device in the model to the expected state
206 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400207 cloned.OperStatus = voltha.OperStatus_ACTIVATING
208 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
209 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
khenaidoob9203542018-09-17 22:56:37 -0400210 }
211 }
212 return nil
213}
214
khenaidoo2c6a0992019-04-29 13:46:56 -0400215func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
216 if err := agent.updateDeviceWithoutLock(device); err != nil {
217 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400218 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400219 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400220}
221
khenaidoo2c6a0992019-04-29 13:46:56 -0400222func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
223 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
224 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
225 ch <- err
226 }
227 ch <- nil
228}
229
230func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
231 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
232 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
233 ch <- err
234 }
235 ch <- nil
236}
237
238func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
239 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 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
247 var existingFlows *voltha.Flows
248 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo19d7b632018-10-30 10:49:50 -0400249 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
250 } else {
khenaidoo2c6a0992019-04-29 13:46:56 -0400251 existingFlows = proto.Clone(device.Flows).(*voltha.Flows)
252 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
253 log.Debugw("addFlows", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "existingFlows": existingFlows, "groups": newGroups, "existingGroups": existingGroups})
254
255 var updatedFlows []*ofp.OfpFlowStats
256 var flowsToDelete []*ofp.OfpFlowStats
257 var groupsToDelete []*ofp.OfpGroupEntry
258 var updatedGroups []*ofp.OfpGroupEntry
259
260 // Process flows
261 for _, flow := range newFlows {
262 updatedFlows = append(updatedFlows, flow)
263 }
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
278 for _, group := range existingGroups.Items {
279 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
280 updatedGroups = append(updatedGroups, group)
281 } else {
282 groupsToDelete = append(groupsToDelete, group)
283 }
284 }
285
286 // Sanity check
287 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
288 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
289 return nil
290
291 }
292 // Send update to adapters
293 chAdapters := make(chan interface{})
294 defer close(chAdapters)
295 chdB := make(chan interface{})
296 defer close(chdB)
297 dType := agent.adapterMgr.getDeviceType(device.Type)
298 if !dType.AcceptsAddRemoveFlowUpdates {
299
300 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
301 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
302 return nil
303 }
304 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
305
306 } else {
307 flowChanges := &ofp.FlowChanges{
308 ToAdd: &voltha.Flows{Items: newFlows},
309 ToRemove: &voltha.Flows{Items: flowsToDelete},
310 }
311 groupChanges := &ofp.FlowGroupChanges{
312 ToAdd: &voltha.FlowGroups{Items: newGroups},
313 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
314 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
315 }
316 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
317 }
318
khenaidoo19d7b632018-10-30 10:49:50 -0400319 // store the changed data
khenaidoo2c6a0992019-04-29 13:46:56 -0400320 device.Flows = &voltha.Flows{Items: updatedFlows}
321 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
322 go agent.updateDeviceWithoutLockAsync(device, chdB)
323
324 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
325 return status.Errorf(codes.Aborted, "errors-%s", res)
khenaidoo19d7b632018-10-30 10:49:50 -0400326 }
327
khenaidoo19d7b632018-10-30 10:49:50 -0400328 return nil
329 }
330}
331
khenaidoo4d4802d2018-10-04 21:59:49 -0400332//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400333func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo0a822f92019-05-08 15:15:57 -0400334 agent.lockDevice.RLock()
khenaidoo92e62c52018-10-03 14:02:54 -0400335 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
336 // Get the most up to date the device info
337 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo0a822f92019-05-08 15:15:57 -0400338 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400339 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
340 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400341 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400342 if device.AdminState == voltha.AdminState_DISABLED {
343 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400344 return nil
345 }
346 // First send the request to an Adapter and wait for a response
347 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
348 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400349 return err
350 }
khenaidoo0a822f92019-05-08 15:15:57 -0400351 if err = agent.updateAdminState(voltha.AdminState_DISABLED); err != nil {
352 log.Errorw("failed-update-device", log.Fields{"deviceId": device.Id, "currentState": device.AdminState, "expectedState": voltha.AdminState_DISABLED})
353 }
354 }
355 return nil
356}
357
358func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
359 agent.lockDevice.Lock()
360 defer agent.lockDevice.Unlock()
361 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
362 // Get the most up to date the device info
363 if device, err := agent.getDeviceWithoutLock(); err != nil {
364 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
365 } else {
366 if device.AdminState == adminState {
367 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
368 return nil
369 }
khenaidoo92e62c52018-10-03 14:02:54 -0400370 // Received an Ack (no error found above). Now update the device in the model to the expected state
371 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400372 cloned.AdminState = adminState
khenaidoo92e62c52018-10-03 14:02:54 -0400373 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400374 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
375 }
khenaidoo92e62c52018-10-03 14:02:54 -0400376 }
377 return nil
378}
379
khenaidoo4d4802d2018-10-04 21:59:49 -0400380func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
381 agent.lockDevice.Lock()
382 defer agent.lockDevice.Unlock()
383 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
384 // Get the most up to date the device info
385 if device, err := agent.getDeviceWithoutLock(); err != nil {
386 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
387 } else {
388 if device.AdminState != voltha.AdminState_DISABLED {
389 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
390 //TODO: Needs customized error message
391 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
392 }
393 // First send the request to an Adapter and wait for a response
394 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
395 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
396 return err
397 }
398 }
399 return nil
400}
401
402func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
403 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400404 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400405 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
406 // Get the most up to date the device info
407 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400408 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
409 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400410 if device.AdminState == voltha.AdminState_DELETED {
411 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
412 return nil
413 }
khenaidoo43c82122018-11-22 18:38:28 -0500414 if (device.AdminState != voltha.AdminState_DISABLED) &&
415 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400416 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
417 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400418 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
419 }
khenaidoo0a822f92019-05-08 15:15:57 -0400420 // Send the request to an Adapter and wait for a response
421 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
422 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
423 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400424 }
khenaidoo0a822f92019-05-08 15:15:57 -0400425
426 // Set the state to deleted - this will trigger some background process to clean up the device as well
427 // as its association with the logical device
428 cloned := proto.Clone(device).(*voltha.Device)
429 cloned.AdminState = voltha.AdminState_DELETED
430 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400431 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
432 }
khenaidoo0a822f92019-05-08 15:15:57 -0400433
434 // If this is a child device then remove the associated peer ports on the parent device
435 if !device.Root {
436 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
437 }
438
khenaidoo4d4802d2018-10-04 21:59:49 -0400439 }
440 return nil
441}
442
khenaidoof5a5bfa2019-01-23 22:20:29 -0500443func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
444 agent.lockDevice.Lock()
445 defer agent.lockDevice.Unlock()
446 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
447 // Get the most up to date the device info
448 if device, err := agent.getDeviceWithoutLock(); err != nil {
449 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
450 } else {
451 if device.AdminState != voltha.AdminState_ENABLED {
452 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
453 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
454 }
455 // Save the image
456 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500457 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500458 cloned := proto.Clone(device).(*voltha.Device)
459 if cloned.ImageDownloads == nil {
460 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
461 } else {
462 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
463 }
464 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
465 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
466 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
467 }
468 // Send the request to the adapter
469 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
470 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
471 return nil, err
472 }
473 }
474 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
475}
476
477// isImageRegistered is a helper method to figure out if an image is already registered
478func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
479 for _, image := range device.ImageDownloads {
480 if image.Id == img.Id && image.Name == img.Name {
481 return true
482 }
483 }
484 return false
485}
486
487func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
488 agent.lockDevice.Lock()
489 defer agent.lockDevice.Unlock()
490 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
491 // Get the most up to date the device info
492 if device, err := agent.getDeviceWithoutLock(); err != nil {
493 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
494 } else {
495 // Verify whether the Image is in the list of image being downloaded
496 if !isImageRegistered(img, device) {
497 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
498 }
499
500 // Update image download state
501 cloned := proto.Clone(device).(*voltha.Device)
502 for _, image := range cloned.ImageDownloads {
503 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500504 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500505 }
506 }
507
508 //If device is in downloading state, send the request to cancel the download
509 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
510 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
511 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
512 return nil, err
513 }
514 // Set the device to Enabled
515 cloned.AdminState = voltha.AdminState_ENABLED
516 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
517 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
518 }
519 }
520 }
521 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700522}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500523
524func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
525 agent.lockDevice.Lock()
526 defer agent.lockDevice.Unlock()
527 log.Debugw("activateImage", 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_DOWNLOADING_IMAGE {
538 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-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_ACTIVATING
545 }
546 }
547 // Set the device to downloading_image
548 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
549 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
550 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
551 }
552
553 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
554 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
555 return nil, err
556 }
557 // The status of the AdminState will be changed following the update_download_status response from the adapter
558 // The image name will also be removed from the device list
559 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700560 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
561}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500562
563func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
564 agent.lockDevice.Lock()
565 defer agent.lockDevice.Unlock()
566 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
567 // Get the most up to date the device info
568 if device, err := agent.getDeviceWithoutLock(); err != nil {
569 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
570 } else {
571 // Verify whether the Image is in the list of image being downloaded
572 if !isImageRegistered(img, device) {
573 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
574 }
575
576 if device.AdminState != voltha.AdminState_ENABLED {
577 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
578 }
579 // Update image download state
580 cloned := proto.Clone(device).(*voltha.Device)
581 for _, image := range cloned.ImageDownloads {
582 if image.Id == img.Id && image.Name == img.Name {
583 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
584 }
585 }
586 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
587 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
588 }
589
590 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
591 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
592 return nil, err
593 }
594 }
595 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700596}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500597
598func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
599 agent.lockDevice.Lock()
600 defer agent.lockDevice.Unlock()
601 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
602 // Get the most up to date the device info
603 if device, err := agent.getDeviceWithoutLock(); err != nil {
604 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
605 } else {
606 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
607 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
608 return nil, err
609 } else {
610 return resp, nil
611 }
612 }
613}
614
serkant.uluderya334479d2019-04-10 08:26:15 -0700615func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500616 agent.lockDevice.Lock()
617 defer agent.lockDevice.Unlock()
618 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
619 // Get the most up to date the device info
620 if device, err := agent.getDeviceWithoutLock(); err != nil {
621 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
622 } else {
623 // Update the image as well as remove it if the download was cancelled
624 cloned := proto.Clone(device).(*voltha.Device)
625 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
626 for _, image := range cloned.ImageDownloads {
627 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500628 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500629 clonedImages = append(clonedImages, img)
630 }
631 }
632 }
633 cloned.ImageDownloads = clonedImages
634 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500635 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
636 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700637 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500638 cloned.AdminState = voltha.AdminState_ENABLED
639 }
640
641 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
642 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
643 }
644 }
645 return nil
646}
647
648func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400649 agent.lockDevice.RLock()
650 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500651 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
652 // Get the most up to date the device info
653 if device, err := agent.getDeviceWithoutLock(); err != nil {
654 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
655 } else {
656 for _, image := range device.ImageDownloads {
657 if image.Id == img.Id && image.Name == img.Name {
658 return image, nil
659 }
660 }
661 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
662 }
663}
664
665func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400666 agent.lockDevice.RLock()
667 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500668 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
669 // Get the most up to date the device info
670 if device, err := agent.getDeviceWithoutLock(); err != nil {
671 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
672 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700673 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500674 }
675}
676
khenaidoo4d4802d2018-10-04 21:59:49 -0400677// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400678func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
679 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400680 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400681 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400682 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400683 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400684 ports.Items = append(ports.Items, port)
685 }
686 }
687 }
688 return ports
689}
690
khenaidoo4d4802d2018-10-04 21:59:49 -0400691// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
692// parent device
khenaidoo79232702018-12-04 11:00:41 -0500693func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400694 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400695 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400696 return nil, err
697 } else {
khenaidoo79232702018-12-04 11:00:41 -0500698 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400699 var err error
700 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
701 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
702 return nil, err
703 }
704 return switchCap, nil
705 }
706}
707
khenaidoo4d4802d2018-10-04 21:59:49 -0400708// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
709// device
khenaidoo79232702018-12-04 11:00:41 -0500710func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400711 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400712 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400713 return nil, err
714 } else {
khenaidoo79232702018-12-04 11:00:41 -0500715 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400716 var err error
717 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
718 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
719 return nil, err
720 }
721 return portCap, nil
722 }
723}
724
khenaidoofdbad6e2018-11-06 22:26:38 -0500725func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
726 // Send packet to adapter
727 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
728 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
729 return err
730 }
731 return nil
732}
733
khenaidoo4d4802d2018-10-04 21:59:49 -0400734// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400735func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500736 //// Run this callback in its own go routine
737 go func(args ...interface{}) interface{} {
738 var previous *voltha.Device
739 var current *voltha.Device
740 var ok bool
741 if len(args) == 2 {
742 if previous, ok = args[0].(*voltha.Device); !ok {
743 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
744 return nil
745 }
746 if current, ok = args[1].(*voltha.Device); !ok {
747 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
748 return nil
749 }
750 } else {
751 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
752 return nil
753 }
754 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500755 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
756 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
757 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
758 }
khenaidoo43c82122018-11-22 18:38:28 -0500759 return nil
760 }(args...)
761
khenaidoo92e62c52018-10-03 14:02:54 -0400762 return nil
763}
764
khenaidoob9203542018-09-17 22:56:37 -0400765func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400766 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500767 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400768 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500769 cloned := proto.Clone(device).(*voltha.Device)
770 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
771 if afterUpdate == nil {
772 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400773 }
khenaidoo43c82122018-11-22 18:38:28 -0500774 return nil
775}
776
777func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
778 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
779 cloned := proto.Clone(device).(*voltha.Device)
780 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
781 if afterUpdate == nil {
782 return status.Errorf(codes.Internal, "%s", device.Id)
783 }
784 return nil
khenaidoob9203542018-09-17 22:56:37 -0400785}
786
khenaidoo92e62c52018-10-03 14:02:54 -0400787func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
788 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400789 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400790 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400791 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400792 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
793 } else {
794 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400795 cloned := proto.Clone(storeDevice).(*voltha.Device)
796 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
797 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
798 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
799 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400800 }
khenaidoo92e62c52018-10-03 14:02:54 -0400801 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
802 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
803 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400804 }
khenaidoo92e62c52018-10-03 14:02:54 -0400805 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400806 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400807 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400808 return status.Errorf(codes.Internal, "%s", agent.deviceId)
809 }
khenaidoo92e62c52018-10-03 14:02:54 -0400810 return nil
811 }
812}
813
khenaidoo3ab34882019-05-02 21:33:30 -0400814func (agent *DeviceAgent) enablePorts() error {
815 agent.lockDevice.Lock()
816 defer agent.lockDevice.Unlock()
817 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
818 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
819 } else {
820 // clone the device
821 cloned := proto.Clone(storeDevice).(*voltha.Device)
822 for _, port := range cloned.Ports {
823 port.AdminState = voltha.AdminState_ENABLED
824 port.OperStatus = voltha.OperStatus_ACTIVE
825 }
826 // Store the device
827 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
828 return status.Errorf(codes.Internal, "%s", agent.deviceId)
829 }
830 return nil
831 }
832}
833
834func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -0400835 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -0400836 agent.lockDevice.Lock()
837 defer agent.lockDevice.Unlock()
838 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
839 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
840 } else {
841 // clone the device
842 cloned := proto.Clone(storeDevice).(*voltha.Device)
843 for _, port := range cloned.Ports {
844 port.AdminState = voltha.AdminState_DISABLED
845 port.OperStatus = voltha.OperStatus_UNKNOWN
846 }
847 // Store the device
848 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
849 return status.Errorf(codes.Internal, "%s", agent.deviceId)
850 }
851 return nil
852 }
853}
854
khenaidoo92e62c52018-10-03 14:02:54 -0400855func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
856 agent.lockDevice.Lock()
khenaidoo92e62c52018-10-03 14:02:54 -0400857 // Work only on latest data
858 // TODO: Get list of ports from device directly instead of the entire device
859 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
860 agent.lockDevice.Unlock()
861 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
862 } else {
863 // clone the device
864 cloned := proto.Clone(storeDevice).(*voltha.Device)
865 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
866 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
867 agent.lockDevice.Unlock()
868 return status.Errorf(codes.InvalidArgument, "%s", portType)
869 }
870 for _, port := range cloned.Ports {
871 if port.Type == portType && port.PortNo == portNo {
872 port.OperStatus = operStatus
873 // Set the admin status to ENABLED if the operational status is ACTIVE
874 // TODO: Set by northbound system?
875 if operStatus == voltha.OperStatus_ACTIVE {
876 port.AdminState = voltha.AdminState_ENABLED
877 }
878 break
879 }
880 }
881 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
882 // Store the device
883 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
884 agent.lockDevice.Unlock()
885 return status.Errorf(codes.Internal, "%s", agent.deviceId)
886 }
887 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400888 return nil
889 }
890}
891
khenaidoo0a822f92019-05-08 15:15:57 -0400892func (agent *DeviceAgent) deleteAllPorts() error {
893 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
894 agent.lockDevice.Lock()
895 defer agent.lockDevice.Unlock()
896 // Work only on latest data
897 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
898 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
899 } else {
900 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
901 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
902 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
903 return err
904 }
905 if len(storeDevice.Ports) == 0 {
906 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
907 return nil
908 }
909 // clone the device & set the fields to empty
910 cloned := proto.Clone(storeDevice).(*voltha.Device)
911 cloned.Ports = []*voltha.Port{}
912 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
913 // Store the device
914 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
915 return status.Errorf(codes.Internal, "%s", agent.deviceId)
916 }
917 return nil
918 }
919}
920
khenaidoob9203542018-09-17 22:56:37 -0400921func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400922 agent.lockDevice.Lock()
923 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400924 log.Debug("updatePmConfigs")
925 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400926 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400927 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
928 } else {
929 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400930 cloned := proto.Clone(storeDevice).(*voltha.Device)
931 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400932 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400933 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400934 if afterUpdate == nil {
935 return status.Errorf(codes.Internal, "%s", agent.deviceId)
936 }
937 return nil
938 }
939}
940
941func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400942 agent.lockDevice.Lock()
943 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -0400944 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400945 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400946 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400947 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
948 } else {
949 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400950 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400951 if cloned.Ports == nil {
952 // First port
khenaidoo0a822f92019-05-08 15:15:57 -0400953 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400954 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -0400955 } else {
956 for _, p := range cloned.Ports {
957 if p.Type == port.Type && p.PortNo == port.PortNo {
958 log.Debugw("port already exists", log.Fields{"port": *port})
959 return nil
960 }
961 }
khenaidoob9203542018-09-17 22:56:37 -0400962 }
khenaidoo92e62c52018-10-03 14:02:54 -0400963 cp := proto.Clone(port).(*voltha.Port)
964 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
965 // TODO: Set by northbound system?
966 if cp.OperStatus == voltha.OperStatus_ACTIVE {
967 cp.AdminState = voltha.AdminState_ENABLED
968 }
969 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400970 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400971 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
972 if afterUpdate == nil {
973 return status.Errorf(codes.Internal, "%s", agent.deviceId)
974 }
975 return nil
976 }
977}
978
979func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
980 agent.lockDevice.Lock()
981 defer agent.lockDevice.Unlock()
982 log.Debug("addPeerPort")
983 // Work only on latest data
984 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
985 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
986 } else {
987 // clone the device
988 cloned := proto.Clone(storeDevice).(*voltha.Device)
989 // Get the peer port on the device based on the port no
990 for _, peerPort := range cloned.Ports {
991 if peerPort.PortNo == port.PortNo { // found port
992 cp := proto.Clone(port).(*voltha.Port_PeerPort)
993 peerPort.Peers = append(peerPort.Peers, cp)
994 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
995 break
996 }
997 }
998 // Store the device
999 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001000 if afterUpdate == nil {
1001 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1002 }
1003 return nil
1004 }
1005}
1006
khenaidoo0a822f92019-05-08 15:15:57 -04001007func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1008 agent.lockDevice.Lock()
1009 defer agent.lockDevice.Unlock()
1010 log.Debug("deletePeerPorts")
1011 // Work only on latest data
1012 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1013 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1014 } else {
1015 // clone the device
1016 cloned := proto.Clone(storeDevice).(*voltha.Device)
1017 var updatedPeers []*voltha.Port_PeerPort
1018 for _, port := range cloned.Ports {
1019 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1020 for _, peerPort := range port.Peers {
1021 if peerPort.DeviceId != deviceId {
1022 updatedPeers = append(updatedPeers, peerPort)
1023 }
1024 }
1025 port.Peers = updatedPeers
1026 }
1027
1028 // Store the device with updated peer ports
1029 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1030 if afterUpdate == nil {
1031 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1032 }
1033 return nil
1034 }
1035}
1036
khenaidoob9203542018-09-17 22:56:37 -04001037// TODO: A generic device update by attribute
1038func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001039 agent.lockDevice.Lock()
1040 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001041 if value == nil {
1042 return
1043 }
1044 var storeDevice *voltha.Device
1045 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001046 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001047 return
1048 }
1049 updated := false
1050 s := reflect.ValueOf(storeDevice).Elem()
1051 if s.Kind() == reflect.Struct {
1052 // exported field
1053 f := s.FieldByName(name)
1054 if f.IsValid() && f.CanSet() {
1055 switch f.Kind() {
1056 case reflect.String:
1057 f.SetString(value.(string))
1058 updated = true
1059 case reflect.Uint32:
1060 f.SetUint(uint64(value.(uint32)))
1061 updated = true
1062 case reflect.Bool:
1063 f.SetBool(value.(bool))
1064 updated = true
1065 }
1066 }
1067 }
khenaidoo92e62c52018-10-03 14:02:54 -04001068 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001069 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001070 cloned := proto.Clone(storeDevice).(*voltha.Device)
1071 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001072 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1073 }
1074 return
1075}
serkant.uluderya334479d2019-04-10 08:26:15 -07001076
1077func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1078 agent.lockDevice.Lock()
1079 defer agent.lockDevice.Unlock()
1080 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1081 // Get the most up to date the device info
1082 if device, err := agent.getDeviceWithoutLock(); err != nil {
1083 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1084 } else {
1085 // First send the request to an Adapter and wait for a response
1086 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1087 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1088 return err
1089 }
1090 }
1091 return nil
1092}