blob: e7089cdb2d628673438dd822b31d5aee6414faf4 [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
khenaidoo68c930b2019-05-13 11:46:51 -0400293
294 // Create two channels to receive responses from the dB and from the adapters.
295 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
296 // to send their responses. These channels will be garbage collected once all the responses are
297 // received
khenaidoo2c6a0992019-04-29 13:46:56 -0400298 chAdapters := make(chan interface{})
khenaidoo2c6a0992019-04-29 13:46:56 -0400299 chdB := make(chan interface{})
khenaidoo2c6a0992019-04-29 13:46:56 -0400300 dType := agent.adapterMgr.getDeviceType(device.Type)
301 if !dType.AcceptsAddRemoveFlowUpdates {
302
303 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
304 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
305 return nil
306 }
307 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
308
309 } else {
310 flowChanges := &ofp.FlowChanges{
311 ToAdd: &voltha.Flows{Items: newFlows},
312 ToRemove: &voltha.Flows{Items: flowsToDelete},
313 }
314 groupChanges := &ofp.FlowGroupChanges{
315 ToAdd: &voltha.FlowGroups{Items: newGroups},
316 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
317 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
318 }
319 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
320 }
321
khenaidoo19d7b632018-10-30 10:49:50 -0400322 // store the changed data
khenaidoo2c6a0992019-04-29 13:46:56 -0400323 device.Flows = &voltha.Flows{Items: updatedFlows}
324 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
325 go agent.updateDeviceWithoutLockAsync(device, chdB)
326
327 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
328 return status.Errorf(codes.Aborted, "errors-%s", res)
khenaidoo19d7b632018-10-30 10:49:50 -0400329 }
330
khenaidoo19d7b632018-10-30 10:49:50 -0400331 return nil
332 }
333}
334
khenaidoo4d4802d2018-10-04 21:59:49 -0400335//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400336func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo0a822f92019-05-08 15:15:57 -0400337 agent.lockDevice.RLock()
khenaidoo92e62c52018-10-03 14:02:54 -0400338 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
339 // Get the most up to date the device info
340 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo0a822f92019-05-08 15:15:57 -0400341 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400342 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
343 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400344 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400345 if device.AdminState == voltha.AdminState_DISABLED {
346 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400347 return nil
348 }
349 // First send the request to an Adapter and wait for a response
350 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
351 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400352 return err
353 }
khenaidoo0a822f92019-05-08 15:15:57 -0400354 if err = agent.updateAdminState(voltha.AdminState_DISABLED); err != nil {
355 log.Errorw("failed-update-device", log.Fields{"deviceId": device.Id, "currentState": device.AdminState, "expectedState": voltha.AdminState_DISABLED})
356 }
357 }
358 return nil
359}
360
361func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
362 agent.lockDevice.Lock()
363 defer agent.lockDevice.Unlock()
364 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
365 // Get the most up to date the device info
366 if device, err := agent.getDeviceWithoutLock(); err != nil {
367 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
368 } else {
369 if device.AdminState == adminState {
370 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
371 return nil
372 }
khenaidoo92e62c52018-10-03 14:02:54 -0400373 // Received an Ack (no error found above). Now update the device in the model to the expected state
374 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400375 cloned.AdminState = adminState
khenaidoo92e62c52018-10-03 14:02:54 -0400376 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400377 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
378 }
khenaidoo92e62c52018-10-03 14:02:54 -0400379 }
380 return nil
381}
382
khenaidoo4d4802d2018-10-04 21:59:49 -0400383func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
384 agent.lockDevice.Lock()
385 defer agent.lockDevice.Unlock()
386 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
387 // Get the most up to date the device info
388 if device, err := agent.getDeviceWithoutLock(); err != nil {
389 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
390 } else {
391 if device.AdminState != voltha.AdminState_DISABLED {
392 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
393 //TODO: Needs customized error message
394 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
395 }
396 // First send the request to an Adapter and wait for a response
397 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
398 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
399 return err
400 }
401 }
402 return nil
403}
404
405func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
406 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400407 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400408 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
409 // Get the most up to date the device info
410 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400411 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
412 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400413 if device.AdminState == voltha.AdminState_DELETED {
414 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
415 return nil
416 }
khenaidoo43c82122018-11-22 18:38:28 -0500417 if (device.AdminState != voltha.AdminState_DISABLED) &&
418 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400419 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
420 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400421 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
422 }
khenaidoo0a822f92019-05-08 15:15:57 -0400423 // Send the request to an Adapter and wait for a response
424 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
425 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
426 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400427 }
khenaidoo0a822f92019-05-08 15:15:57 -0400428
429 // Set the state to deleted - this will trigger some background process to clean up the device as well
430 // as its association with the logical device
431 cloned := proto.Clone(device).(*voltha.Device)
432 cloned.AdminState = voltha.AdminState_DELETED
433 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400434 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
435 }
khenaidoo0a822f92019-05-08 15:15:57 -0400436
437 // If this is a child device then remove the associated peer ports on the parent device
438 if !device.Root {
439 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
440 }
441
khenaidoo4d4802d2018-10-04 21:59:49 -0400442 }
443 return nil
444}
445
khenaidoof5a5bfa2019-01-23 22:20:29 -0500446func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
447 agent.lockDevice.Lock()
448 defer agent.lockDevice.Unlock()
449 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
450 // Get the most up to date the device info
451 if device, err := agent.getDeviceWithoutLock(); err != nil {
452 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
453 } else {
454 if device.AdminState != voltha.AdminState_ENABLED {
455 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
456 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
457 }
458 // Save the image
459 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500460 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500461 cloned := proto.Clone(device).(*voltha.Device)
462 if cloned.ImageDownloads == nil {
463 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
464 } else {
465 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
466 }
467 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
468 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
469 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
470 }
471 // Send the request to the adapter
472 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
473 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
474 return nil, err
475 }
476 }
477 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
478}
479
480// isImageRegistered is a helper method to figure out if an image is already registered
481func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
482 for _, image := range device.ImageDownloads {
483 if image.Id == img.Id && image.Name == img.Name {
484 return true
485 }
486 }
487 return false
488}
489
490func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
491 agent.lockDevice.Lock()
492 defer agent.lockDevice.Unlock()
493 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
494 // Get the most up to date the device info
495 if device, err := agent.getDeviceWithoutLock(); err != nil {
496 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
497 } else {
498 // Verify whether the Image is in the list of image being downloaded
499 if !isImageRegistered(img, device) {
500 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
501 }
502
503 // Update image download state
504 cloned := proto.Clone(device).(*voltha.Device)
505 for _, image := range cloned.ImageDownloads {
506 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500507 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500508 }
509 }
510
511 //If device is in downloading state, send the request to cancel the download
512 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
513 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
514 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
515 return nil, err
516 }
517 // Set the device to Enabled
518 cloned.AdminState = voltha.AdminState_ENABLED
519 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
520 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
521 }
522 }
523 }
524 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700525}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500526
527func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
528 agent.lockDevice.Lock()
529 defer agent.lockDevice.Unlock()
530 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
531 // Get the most up to date the device info
532 if device, err := agent.getDeviceWithoutLock(); err != nil {
533 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
534 } else {
535 // Verify whether the Image is in the list of image being downloaded
536 if !isImageRegistered(img, device) {
537 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
538 }
539
540 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
541 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
542 }
543 // Update image download state
544 cloned := proto.Clone(device).(*voltha.Device)
545 for _, image := range cloned.ImageDownloads {
546 if image.Id == img.Id && image.Name == img.Name {
547 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
548 }
549 }
550 // Set the device to downloading_image
551 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
552 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
553 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
554 }
555
556 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
557 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
558 return nil, err
559 }
560 // The status of the AdminState will be changed following the update_download_status response from the adapter
561 // The image name will also be removed from the device list
562 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700563 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
564}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500565
566func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
567 agent.lockDevice.Lock()
568 defer agent.lockDevice.Unlock()
569 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
570 // Get the most up to date the device info
571 if device, err := agent.getDeviceWithoutLock(); err != nil {
572 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
573 } else {
574 // Verify whether the Image is in the list of image being downloaded
575 if !isImageRegistered(img, device) {
576 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
577 }
578
579 if device.AdminState != voltha.AdminState_ENABLED {
580 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
581 }
582 // Update image download state
583 cloned := proto.Clone(device).(*voltha.Device)
584 for _, image := range cloned.ImageDownloads {
585 if image.Id == img.Id && image.Name == img.Name {
586 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
587 }
588 }
589 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
590 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
591 }
592
593 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
594 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
595 return nil, err
596 }
597 }
598 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700599}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500600
601func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
602 agent.lockDevice.Lock()
603 defer agent.lockDevice.Unlock()
604 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
605 // Get the most up to date the device info
606 if device, err := agent.getDeviceWithoutLock(); err != nil {
607 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
608 } else {
609 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
610 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
611 return nil, err
612 } else {
613 return resp, nil
614 }
615 }
616}
617
serkant.uluderya334479d2019-04-10 08:26:15 -0700618func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500619 agent.lockDevice.Lock()
620 defer agent.lockDevice.Unlock()
621 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
622 // Get the most up to date the device info
623 if device, err := agent.getDeviceWithoutLock(); err != nil {
624 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
625 } else {
626 // Update the image as well as remove it if the download was cancelled
627 cloned := proto.Clone(device).(*voltha.Device)
628 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
629 for _, image := range cloned.ImageDownloads {
630 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500631 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500632 clonedImages = append(clonedImages, img)
633 }
634 }
635 }
636 cloned.ImageDownloads = clonedImages
637 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500638 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
639 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700640 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500641 cloned.AdminState = voltha.AdminState_ENABLED
642 }
643
644 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
645 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
646 }
647 }
648 return nil
649}
650
651func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400652 agent.lockDevice.RLock()
653 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500654 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
655 // Get the most up to date the device info
656 if device, err := agent.getDeviceWithoutLock(); err != nil {
657 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
658 } else {
659 for _, image := range device.ImageDownloads {
660 if image.Id == img.Id && image.Name == img.Name {
661 return image, nil
662 }
663 }
664 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
665 }
666}
667
668func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400669 agent.lockDevice.RLock()
670 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500671 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
672 // Get the most up to date the device info
673 if device, err := agent.getDeviceWithoutLock(); err != nil {
674 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
675 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700676 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500677 }
678}
679
khenaidoo4d4802d2018-10-04 21:59:49 -0400680// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400681func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
682 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400683 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400684 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400685 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400686 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400687 ports.Items = append(ports.Items, port)
688 }
689 }
690 }
691 return ports
692}
693
khenaidoo4d4802d2018-10-04 21:59:49 -0400694// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
695// parent device
khenaidoo79232702018-12-04 11:00:41 -0500696func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400697 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400698 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400699 return nil, err
700 } else {
khenaidoo79232702018-12-04 11:00:41 -0500701 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400702 var err error
703 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
704 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
705 return nil, err
706 }
707 return switchCap, nil
708 }
709}
710
khenaidoo4d4802d2018-10-04 21:59:49 -0400711// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
712// device
khenaidoo79232702018-12-04 11:00:41 -0500713func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400714 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400715 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400716 return nil, err
717 } else {
khenaidoo79232702018-12-04 11:00:41 -0500718 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400719 var err error
720 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
721 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
722 return nil, err
723 }
724 return portCap, nil
725 }
726}
727
khenaidoofdbad6e2018-11-06 22:26:38 -0500728func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
729 // Send packet to adapter
730 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
731 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
732 return err
733 }
734 return nil
735}
736
khenaidoo4d4802d2018-10-04 21:59:49 -0400737// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400738func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500739 //// Run this callback in its own go routine
740 go func(args ...interface{}) interface{} {
741 var previous *voltha.Device
742 var current *voltha.Device
743 var ok bool
744 if len(args) == 2 {
745 if previous, ok = args[0].(*voltha.Device); !ok {
746 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
747 return nil
748 }
749 if current, ok = args[1].(*voltha.Device); !ok {
750 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
751 return nil
752 }
753 } else {
754 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
755 return nil
756 }
757 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500758 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
759 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
760 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
761 }
khenaidoo43c82122018-11-22 18:38:28 -0500762 return nil
763 }(args...)
764
khenaidoo92e62c52018-10-03 14:02:54 -0400765 return nil
766}
767
khenaidoob9203542018-09-17 22:56:37 -0400768func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400769 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500770 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400771 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500772 cloned := proto.Clone(device).(*voltha.Device)
773 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
774 if afterUpdate == nil {
775 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400776 }
khenaidoo43c82122018-11-22 18:38:28 -0500777 return nil
778}
779
780func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
781 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
782 cloned := proto.Clone(device).(*voltha.Device)
783 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
784 if afterUpdate == nil {
785 return status.Errorf(codes.Internal, "%s", device.Id)
786 }
787 return nil
khenaidoob9203542018-09-17 22:56:37 -0400788}
789
khenaidoo92e62c52018-10-03 14:02:54 -0400790func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
791 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400792 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400793 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400794 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400795 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
796 } else {
797 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400798 cloned := proto.Clone(storeDevice).(*voltha.Device)
799 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
800 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
801 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
802 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400803 }
khenaidoo92e62c52018-10-03 14:02:54 -0400804 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
805 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
806 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400807 }
khenaidoo92e62c52018-10-03 14:02:54 -0400808 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400809 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400810 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400811 return status.Errorf(codes.Internal, "%s", agent.deviceId)
812 }
khenaidoo92e62c52018-10-03 14:02:54 -0400813 return nil
814 }
815}
816
khenaidoo3ab34882019-05-02 21:33:30 -0400817func (agent *DeviceAgent) enablePorts() error {
818 agent.lockDevice.Lock()
819 defer agent.lockDevice.Unlock()
820 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
821 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
822 } else {
823 // clone the device
824 cloned := proto.Clone(storeDevice).(*voltha.Device)
825 for _, port := range cloned.Ports {
826 port.AdminState = voltha.AdminState_ENABLED
827 port.OperStatus = voltha.OperStatus_ACTIVE
828 }
829 // Store the device
830 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
831 return status.Errorf(codes.Internal, "%s", agent.deviceId)
832 }
833 return nil
834 }
835}
836
837func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -0400838 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -0400839 agent.lockDevice.Lock()
840 defer agent.lockDevice.Unlock()
841 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
842 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
843 } else {
844 // clone the device
845 cloned := proto.Clone(storeDevice).(*voltha.Device)
846 for _, port := range cloned.Ports {
847 port.AdminState = voltha.AdminState_DISABLED
848 port.OperStatus = voltha.OperStatus_UNKNOWN
849 }
850 // Store the device
851 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
852 return status.Errorf(codes.Internal, "%s", agent.deviceId)
853 }
854 return nil
855 }
856}
857
khenaidoo92e62c52018-10-03 14:02:54 -0400858func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
859 agent.lockDevice.Lock()
khenaidoo92e62c52018-10-03 14:02:54 -0400860 // Work only on latest data
861 // TODO: Get list of ports from device directly instead of the entire device
862 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
863 agent.lockDevice.Unlock()
864 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
865 } else {
866 // clone the device
867 cloned := proto.Clone(storeDevice).(*voltha.Device)
868 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
869 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
870 agent.lockDevice.Unlock()
871 return status.Errorf(codes.InvalidArgument, "%s", portType)
872 }
873 for _, port := range cloned.Ports {
874 if port.Type == portType && port.PortNo == portNo {
875 port.OperStatus = operStatus
876 // Set the admin status to ENABLED if the operational status is ACTIVE
877 // TODO: Set by northbound system?
878 if operStatus == voltha.OperStatus_ACTIVE {
879 port.AdminState = voltha.AdminState_ENABLED
880 }
881 break
882 }
883 }
884 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
885 // Store the device
886 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
887 agent.lockDevice.Unlock()
888 return status.Errorf(codes.Internal, "%s", agent.deviceId)
889 }
890 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400891 return nil
892 }
893}
894
khenaidoo0a822f92019-05-08 15:15:57 -0400895func (agent *DeviceAgent) deleteAllPorts() error {
896 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
897 agent.lockDevice.Lock()
898 defer agent.lockDevice.Unlock()
899 // Work only on latest data
900 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
901 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
902 } else {
903 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
904 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
905 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
906 return err
907 }
908 if len(storeDevice.Ports) == 0 {
909 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
910 return nil
911 }
912 // clone the device & set the fields to empty
913 cloned := proto.Clone(storeDevice).(*voltha.Device)
914 cloned.Ports = []*voltha.Port{}
915 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
916 // Store the device
917 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
918 return status.Errorf(codes.Internal, "%s", agent.deviceId)
919 }
920 return nil
921 }
922}
923
khenaidoob9203542018-09-17 22:56:37 -0400924func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400925 agent.lockDevice.Lock()
926 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400927 log.Debug("updatePmConfigs")
928 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400929 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400930 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
931 } else {
932 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400933 cloned := proto.Clone(storeDevice).(*voltha.Device)
934 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400935 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400936 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400937 if afterUpdate == nil {
938 return status.Errorf(codes.Internal, "%s", agent.deviceId)
939 }
940 return nil
941 }
942}
943
944func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400945 agent.lockDevice.Lock()
946 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -0400947 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400948 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400949 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400950 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
951 } else {
952 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400953 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400954 if cloned.Ports == nil {
955 // First port
khenaidoo0a822f92019-05-08 15:15:57 -0400956 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400957 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -0400958 } else {
959 for _, p := range cloned.Ports {
960 if p.Type == port.Type && p.PortNo == port.PortNo {
961 log.Debugw("port already exists", log.Fields{"port": *port})
962 return nil
963 }
964 }
khenaidoob9203542018-09-17 22:56:37 -0400965 }
khenaidoo92e62c52018-10-03 14:02:54 -0400966 cp := proto.Clone(port).(*voltha.Port)
967 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
968 // TODO: Set by northbound system?
969 if cp.OperStatus == voltha.OperStatus_ACTIVE {
970 cp.AdminState = voltha.AdminState_ENABLED
971 }
972 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400973 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400974 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
975 if afterUpdate == nil {
976 return status.Errorf(codes.Internal, "%s", agent.deviceId)
977 }
978 return nil
979 }
980}
981
982func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
983 agent.lockDevice.Lock()
984 defer agent.lockDevice.Unlock()
985 log.Debug("addPeerPort")
986 // Work only on latest data
987 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
988 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
989 } else {
990 // clone the device
991 cloned := proto.Clone(storeDevice).(*voltha.Device)
992 // Get the peer port on the device based on the port no
993 for _, peerPort := range cloned.Ports {
994 if peerPort.PortNo == port.PortNo { // found port
995 cp := proto.Clone(port).(*voltha.Port_PeerPort)
996 peerPort.Peers = append(peerPort.Peers, cp)
997 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
998 break
999 }
1000 }
1001 // Store the device
1002 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001003 if afterUpdate == nil {
1004 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1005 }
1006 return nil
1007 }
1008}
1009
khenaidoo0a822f92019-05-08 15:15:57 -04001010func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1011 agent.lockDevice.Lock()
1012 defer agent.lockDevice.Unlock()
1013 log.Debug("deletePeerPorts")
1014 // Work only on latest data
1015 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1016 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1017 } else {
1018 // clone the device
1019 cloned := proto.Clone(storeDevice).(*voltha.Device)
1020 var updatedPeers []*voltha.Port_PeerPort
1021 for _, port := range cloned.Ports {
1022 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1023 for _, peerPort := range port.Peers {
1024 if peerPort.DeviceId != deviceId {
1025 updatedPeers = append(updatedPeers, peerPort)
1026 }
1027 }
1028 port.Peers = updatedPeers
1029 }
1030
1031 // Store the device with updated peer ports
1032 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1033 if afterUpdate == nil {
1034 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1035 }
1036 return nil
1037 }
1038}
1039
khenaidoob9203542018-09-17 22:56:37 -04001040// TODO: A generic device update by attribute
1041func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001042 agent.lockDevice.Lock()
1043 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001044 if value == nil {
1045 return
1046 }
1047 var storeDevice *voltha.Device
1048 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001049 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001050 return
1051 }
1052 updated := false
1053 s := reflect.ValueOf(storeDevice).Elem()
1054 if s.Kind() == reflect.Struct {
1055 // exported field
1056 f := s.FieldByName(name)
1057 if f.IsValid() && f.CanSet() {
1058 switch f.Kind() {
1059 case reflect.String:
1060 f.SetString(value.(string))
1061 updated = true
1062 case reflect.Uint32:
1063 f.SetUint(uint64(value.(uint32)))
1064 updated = true
1065 case reflect.Bool:
1066 f.SetBool(value.(bool))
1067 updated = true
1068 }
1069 }
1070 }
khenaidoo92e62c52018-10-03 14:02:54 -04001071 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001072 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001073 cloned := proto.Clone(storeDevice).(*voltha.Device)
1074 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001075 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1076 }
1077 return
1078}
serkant.uluderya334479d2019-04-10 08:26:15 -07001079
1080func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1081 agent.lockDevice.Lock()
1082 defer agent.lockDevice.Unlock()
1083 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1084 // Get the most up to date the device info
1085 if device, err := agent.getDeviceWithoutLock(); err != nil {
1086 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1087 } else {
1088 // First send the request to an Adapter and wait for a response
1089 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1090 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1091 return err
1092 }
1093 }
1094 return nil
1095}