blob: 4a887792b49c715e9469a8f2644ad436c7c7706a [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
khenaidoo6d62c002019-05-15 21:57:03 -040036 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050037 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040038 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040039 lastData *voltha.Device
40 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070041 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040042 deviceMgr *DeviceManager
43 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040044 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040045 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040046 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040047 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040048}
49
khenaidoo4d4802d2018-10-04 21:59:49 -040050//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
51//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040052func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040053 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040054 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040055 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050056 if cloned.Id == "" {
57 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050058 cloned.AdminState = voltha.AdminState_PREPROVISIONED
59 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
60 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050061 }
khenaidoo19d7b632018-10-30 10:49:50 -040062 if !device.GetRoot() && device.ProxyAddress != nil {
63 // Set the default vlan ID to the one specified by the parent adapter. It can be
64 // overwritten by the child adapter during a device update request
65 cloned.Vlan = device.ProxyAddress.ChannelId
66 }
khenaidoo2c6a0992019-04-29 13:46:56 -040067 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040068 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040069 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050070 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040071 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040072 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050073 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040074 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040075 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040076 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040077 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040078 return &agent
79}
80
khenaidoo297cd252019-02-07 22:10:23 -050081// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
82// it will load the data from the dB and setup teh necessary callbacks and proxies.
83func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040084 agent.lockDevice.Lock()
85 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050086 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
87 if loadFromdB {
88 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 1, false, ""); device != nil {
89 if d, ok := device.(*voltha.Device); ok {
90 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050091 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050092 }
93 } else {
94 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
95 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
96 }
97 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
98 } else {
99 // Add the initial device to the local model
100 if added := agent.clusterDataProxy.AddWithID("/devices", agent.deviceId, agent.lastData, ""); added == nil {
101 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
102 }
khenaidoob9203542018-09-17 22:56:37 -0400103 }
khenaidoo297cd252019-02-07 22:10:23 -0500104
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400105 agent.deviceProxy = agent.clusterDataProxy.CreateProxy("/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500106 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400107
khenaidoob9203542018-09-17 22:56:37 -0400108 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500109 return nil
khenaidoob9203542018-09-17 22:56:37 -0400110}
111
khenaidoo4d4802d2018-10-04 21:59:49 -0400112// stop stops the device agent. Not much to do for now
113func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400114 agent.lockDevice.Lock()
115 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400116 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400117 // Remove the device from the KV store
118 if removed := agent.clusterDataProxy.Remove("/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400119 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400120 }
khenaidoob9203542018-09-17 22:56:37 -0400121 agent.exitChannel <- 1
122 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400123
khenaidoob9203542018-09-17 22:56:37 -0400124}
125
khenaidoo19d7b632018-10-30 10:49:50 -0400126// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400127func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400128 agent.lockDevice.RLock()
129 defer agent.lockDevice.RUnlock()
khenaidoo297cd252019-02-07 22:10:23 -0500130 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400131 if d, ok := device.(*voltha.Device); ok {
132 cloned := proto.Clone(d).(*voltha.Device)
133 return cloned, nil
134 }
135 }
136 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
137}
138
khenaidoo4d4802d2018-10-04 21:59:49 -0400139// 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 -0400140// This function is meant so that we do not have duplicate code all over the device agent functions
141func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarie40fd3b22019-04-23 21:50:47 -0400142 if device := agent.clusterDataProxy.Get("/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400143 if d, ok := device.(*voltha.Device); ok {
144 cloned := proto.Clone(d).(*voltha.Device)
145 return cloned, nil
146 }
147 }
148 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
149}
150
khenaidoo3ab34882019-05-02 21:33:30 -0400151// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400152func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400153 agent.lockDevice.Lock()
154 defer agent.lockDevice.Unlock()
155 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500156
khenaidoo92e62c52018-10-03 14:02:54 -0400157 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400158 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
159 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500160 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
161 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
162 // with the adapter then we need to know the adapter that will handle this request
163 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
164 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
165 return err
166 } else {
167 device.Adapter = adapterName
168 }
169
khenaidoo92e62c52018-10-03 14:02:54 -0400170 if device.AdminState == voltha.AdminState_ENABLED {
171 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400172 return nil
173 }
khenaidoo3ab34882019-05-02 21:33:30 -0400174 // If this is a child device then verify the parent state before proceeding
175 if !agent.isRootdevice {
176 if parent := agent.deviceMgr.getParentDevice(device); parent != nil {
177 if parent.AdminState == voltha.AdminState_DISABLED ||
178 parent.AdminState == voltha.AdminState_DELETED ||
179 parent.AdminState == voltha.AdminState_UNKNOWN {
180 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("incorrect-parent-state: %s %d", parent.Id, parent.AdminState))
181 log.Warnw("incorrect-parent-state", log.Fields{"id": agent.deviceId, "error": err})
182 return err
183 }
184 } else {
185 err = status.Error(codes.Unavailable, fmt.Sprintf("parent-not-existent: %s ", device.Id))
186 log.Warnw("parent-not-existent", log.Fields{"id": agent.deviceId, "error": err})
187 return err
188 }
189 }
khenaidoo92e62c52018-10-03 14:02:54 -0400190 if device.AdminState == voltha.AdminState_PREPROVISIONED {
191 // First send the request to an Adapter and wait for a response
192 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
193 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400194 return err
195 }
khenaidoo0a822f92019-05-08 15:15:57 -0400196 } else if device.AdminState == voltha.AdminState_DISABLED {
khenaidoo92e62c52018-10-03 14:02:54 -0400197 // First send the request to an Adapter and wait for a response
198 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
199 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
200 return err
201 }
khenaidoo0a822f92019-05-08 15:15:57 -0400202 } else {
203 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-delete-a-deleted-device: %s ", device.Id))
204 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
205 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400206 }
207 // Received an Ack (no error found above). Now update the device in the model to the expected state
208 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400209 cloned.OperStatus = voltha.OperStatus_ACTIVATING
210 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
211 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
khenaidoob9203542018-09-17 22:56:37 -0400212 }
213 }
214 return nil
215}
216
khenaidoo2c6a0992019-04-29 13:46:56 -0400217func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
218 if err := agent.updateDeviceWithoutLock(device); err != nil {
219 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400220 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400221 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400222}
223
khenaidoo2c6a0992019-04-29 13:46:56 -0400224func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
225 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
226 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
227 ch <- err
228 }
229 ch <- nil
230}
231
232func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
233 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
234 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
235 ch <- err
236 }
237 ch <- nil
238}
239
240func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
241 if (len(newFlows) | len(newGroups)) == 0 {
242 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
243 return nil
244 }
245
khenaidoo19d7b632018-10-30 10:49:50 -0400246 agent.lockDevice.Lock()
247 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400248 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
249 var existingFlows *voltha.Flows
250 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo19d7b632018-10-30 10:49:50 -0400251 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
252 } else {
khenaidoo2c6a0992019-04-29 13:46:56 -0400253 existingFlows = proto.Clone(device.Flows).(*voltha.Flows)
254 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
255 log.Debugw("addFlows", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "existingFlows": existingFlows, "groups": newGroups, "existingGroups": existingGroups})
256
257 var updatedFlows []*ofp.OfpFlowStats
258 var flowsToDelete []*ofp.OfpFlowStats
259 var groupsToDelete []*ofp.OfpGroupEntry
260 var updatedGroups []*ofp.OfpGroupEntry
261
262 // Process flows
263 for _, flow := range newFlows {
264 updatedFlows = append(updatedFlows, flow)
265 }
266
267 for _, flow := range existingFlows.Items {
268 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
269 updatedFlows = append(updatedFlows, flow)
270 } else {
271 flowsToDelete = append(flowsToDelete, flow)
272 }
273 }
274
275 // Process groups
276 for _, g := range newGroups {
277 updatedGroups = append(updatedGroups, g)
278 }
279
280 for _, group := range existingGroups.Items {
281 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
282 updatedGroups = append(updatedGroups, group)
283 } else {
284 groupsToDelete = append(groupsToDelete, group)
285 }
286 }
287
288 // Sanity check
289 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
290 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
291 return nil
292
293 }
294 // Send update to adapters
khenaidoo68c930b2019-05-13 11:46:51 -0400295
296 // Create two channels to receive responses from the dB and from the adapters.
297 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
298 // to send their responses. These channels will be garbage collected once all the responses are
299 // received
khenaidoo2c6a0992019-04-29 13:46:56 -0400300 chAdapters := make(chan interface{})
khenaidoo2c6a0992019-04-29 13:46:56 -0400301 chdB := make(chan interface{})
khenaidoo2c6a0992019-04-29 13:46:56 -0400302 dType := agent.adapterMgr.getDeviceType(device.Type)
303 if !dType.AcceptsAddRemoveFlowUpdates {
304
305 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
306 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
307 return nil
308 }
309 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
310
311 } else {
312 flowChanges := &ofp.FlowChanges{
313 ToAdd: &voltha.Flows{Items: newFlows},
314 ToRemove: &voltha.Flows{Items: flowsToDelete},
315 }
316 groupChanges := &ofp.FlowGroupChanges{
317 ToAdd: &voltha.FlowGroups{Items: newGroups},
318 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
319 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
320 }
321 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
322 }
323
khenaidoo19d7b632018-10-30 10:49:50 -0400324 // store the changed data
khenaidoo2c6a0992019-04-29 13:46:56 -0400325 device.Flows = &voltha.Flows{Items: updatedFlows}
326 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
327 go agent.updateDeviceWithoutLockAsync(device, chdB)
328
329 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
330 return status.Errorf(codes.Aborted, "errors-%s", res)
khenaidoo19d7b632018-10-30 10:49:50 -0400331 }
332
khenaidoo19d7b632018-10-30 10:49:50 -0400333 return nil
334 }
335}
336
khenaidoo4d4802d2018-10-04 21:59:49 -0400337//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400338func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo0a822f92019-05-08 15:15:57 -0400339 agent.lockDevice.RLock()
khenaidoo92e62c52018-10-03 14:02:54 -0400340 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
341 // Get the most up to date the device info
342 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo0a822f92019-05-08 15:15:57 -0400343 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400344 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
345 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400346 agent.lockDevice.RUnlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400347 if device.AdminState == voltha.AdminState_DISABLED {
348 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400349 return nil
350 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400351 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
352 device.AdminState == voltha.AdminState_DELETED {
353 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
354 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
355 }
356
khenaidoo92e62c52018-10-03 14:02:54 -0400357 // First send the request to an Adapter and wait for a response
358 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
359 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400360 return err
361 }
khenaidoo0a822f92019-05-08 15:15:57 -0400362 if err = agent.updateAdminState(voltha.AdminState_DISABLED); err != nil {
363 log.Errorw("failed-update-device", log.Fields{"deviceId": device.Id, "currentState": device.AdminState, "expectedState": voltha.AdminState_DISABLED})
364 }
365 }
366 return nil
367}
368
369func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
370 agent.lockDevice.Lock()
371 defer agent.lockDevice.Unlock()
372 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
373 // Get the most up to date the device info
374 if device, err := agent.getDeviceWithoutLock(); err != nil {
375 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
376 } else {
377 if device.AdminState == adminState {
378 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
379 return nil
380 }
khenaidoo92e62c52018-10-03 14:02:54 -0400381 // Received an Ack (no error found above). Now update the device in the model to the expected state
382 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400383 cloned.AdminState = adminState
khenaidoo92e62c52018-10-03 14:02:54 -0400384 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400385 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
386 }
khenaidoo92e62c52018-10-03 14:02:54 -0400387 }
388 return nil
389}
390
khenaidoo4d4802d2018-10-04 21:59:49 -0400391func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
392 agent.lockDevice.Lock()
393 defer agent.lockDevice.Unlock()
394 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
395 // Get the most up to date the device info
396 if device, err := agent.getDeviceWithoutLock(); err != nil {
397 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
398 } else {
399 if device.AdminState != voltha.AdminState_DISABLED {
400 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
401 //TODO: Needs customized error message
402 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
403 }
404 // First send the request to an Adapter and wait for a response
405 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
406 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
407 return err
408 }
409 }
410 return nil
411}
412
413func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
414 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400415 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400416 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
417 // Get the most up to date the device info
418 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400419 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
420 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400421 if device.AdminState == voltha.AdminState_DELETED {
422 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
423 return nil
424 }
khenaidoo43c82122018-11-22 18:38:28 -0500425 if (device.AdminState != voltha.AdminState_DISABLED) &&
426 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400427 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
428 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400429 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
430 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400431 if device.AdminState != voltha.AdminState_PREPROVISIONED {
432 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
433 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
434 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
435 return err
436 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400437 }
khenaidoo0a822f92019-05-08 15:15:57 -0400438 // Set the state to deleted - this will trigger some background process to clean up the device as well
439 // as its association with the logical device
440 cloned := proto.Clone(device).(*voltha.Device)
441 cloned.AdminState = voltha.AdminState_DELETED
442 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400443 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
444 }
khenaidoo0a822f92019-05-08 15:15:57 -0400445
446 // If this is a child device then remove the associated peer ports on the parent device
447 if !device.Root {
448 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
449 }
450
khenaidoo4d4802d2018-10-04 21:59:49 -0400451 }
452 return nil
453}
454
khenaidoof5a5bfa2019-01-23 22:20:29 -0500455func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
456 agent.lockDevice.Lock()
457 defer agent.lockDevice.Unlock()
458 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
459 // Get the most up to date the device info
460 if device, err := agent.getDeviceWithoutLock(); err != nil {
461 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
462 } else {
463 if device.AdminState != voltha.AdminState_ENABLED {
464 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
465 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
466 }
467 // Save the image
468 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500469 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500470 cloned := proto.Clone(device).(*voltha.Device)
471 if cloned.ImageDownloads == nil {
472 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
473 } else {
474 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
475 }
476 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
477 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
478 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
479 }
480 // Send the request to the adapter
481 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
482 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
483 return nil, err
484 }
485 }
486 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
487}
488
489// isImageRegistered is a helper method to figure out if an image is already registered
490func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
491 for _, image := range device.ImageDownloads {
492 if image.Id == img.Id && image.Name == img.Name {
493 return true
494 }
495 }
496 return false
497}
498
499func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
500 agent.lockDevice.Lock()
501 defer agent.lockDevice.Unlock()
502 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
503 // Get the most up to date the device info
504 if device, err := agent.getDeviceWithoutLock(); err != nil {
505 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
506 } else {
507 // Verify whether the Image is in the list of image being downloaded
508 if !isImageRegistered(img, device) {
509 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
510 }
511
512 // Update image download state
513 cloned := proto.Clone(device).(*voltha.Device)
514 for _, image := range cloned.ImageDownloads {
515 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500516 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500517 }
518 }
519
520 //If device is in downloading state, send the request to cancel the download
521 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
522 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
523 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
524 return nil, err
525 }
526 // Set the device to Enabled
527 cloned.AdminState = voltha.AdminState_ENABLED
528 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
529 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
530 }
531 }
532 }
533 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700534}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500535
536func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
537 agent.lockDevice.Lock()
538 defer agent.lockDevice.Unlock()
539 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
540 // Get the most up to date the device info
541 if device, err := agent.getDeviceWithoutLock(); err != nil {
542 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
543 } else {
544 // Verify whether the Image is in the list of image being downloaded
545 if !isImageRegistered(img, device) {
546 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
547 }
548
549 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
550 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
551 }
552 // Update image download state
553 cloned := proto.Clone(device).(*voltha.Device)
554 for _, image := range cloned.ImageDownloads {
555 if image.Id == img.Id && image.Name == img.Name {
556 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
557 }
558 }
559 // Set the device to downloading_image
560 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
561 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
562 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
563 }
564
565 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
566 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
567 return nil, err
568 }
569 // The status of the AdminState will be changed following the update_download_status response from the adapter
570 // The image name will also be removed from the device list
571 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700572 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
573}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500574
575func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
576 agent.lockDevice.Lock()
577 defer agent.lockDevice.Unlock()
578 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
579 // Get the most up to date the device info
580 if device, err := agent.getDeviceWithoutLock(); err != nil {
581 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
582 } else {
583 // Verify whether the Image is in the list of image being downloaded
584 if !isImageRegistered(img, device) {
585 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
586 }
587
588 if device.AdminState != voltha.AdminState_ENABLED {
589 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
590 }
591 // Update image download state
592 cloned := proto.Clone(device).(*voltha.Device)
593 for _, image := range cloned.ImageDownloads {
594 if image.Id == img.Id && image.Name == img.Name {
595 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
596 }
597 }
598 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
599 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
600 }
601
602 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
603 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
604 return nil, err
605 }
606 }
607 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700608}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500609
610func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
611 agent.lockDevice.Lock()
612 defer agent.lockDevice.Unlock()
613 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
614 // Get the most up to date the device info
615 if device, err := agent.getDeviceWithoutLock(); err != nil {
616 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
617 } else {
618 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
619 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
620 return nil, err
621 } else {
622 return resp, nil
623 }
624 }
625}
626
serkant.uluderya334479d2019-04-10 08:26:15 -0700627func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500628 agent.lockDevice.Lock()
629 defer agent.lockDevice.Unlock()
630 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
631 // Get the most up to date the device info
632 if device, err := agent.getDeviceWithoutLock(); err != nil {
633 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
634 } else {
635 // Update the image as well as remove it if the download was cancelled
636 cloned := proto.Clone(device).(*voltha.Device)
637 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
638 for _, image := range cloned.ImageDownloads {
639 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500640 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500641 clonedImages = append(clonedImages, img)
642 }
643 }
644 }
645 cloned.ImageDownloads = clonedImages
646 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500647 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
648 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700649 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500650 cloned.AdminState = voltha.AdminState_ENABLED
651 }
652
653 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
654 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
655 }
656 }
657 return nil
658}
659
660func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400661 agent.lockDevice.RLock()
662 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500663 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
664 // Get the most up to date the device info
665 if device, err := agent.getDeviceWithoutLock(); err != nil {
666 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
667 } else {
668 for _, image := range device.ImageDownloads {
669 if image.Id == img.Id && image.Name == img.Name {
670 return image, nil
671 }
672 }
673 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
674 }
675}
676
677func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400678 agent.lockDevice.RLock()
679 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500680 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
681 // Get the most up to date the device info
682 if device, err := agent.getDeviceWithoutLock(); err != nil {
683 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
684 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700685 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500686 }
687}
688
khenaidoo4d4802d2018-10-04 21:59:49 -0400689// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400690func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
691 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400692 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400693 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400694 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400695 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400696 ports.Items = append(ports.Items, port)
697 }
698 }
699 }
700 return ports
701}
702
khenaidoo4d4802d2018-10-04 21:59:49 -0400703// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
704// parent device
khenaidoo79232702018-12-04 11:00:41 -0500705func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400706 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400707 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400708 return nil, err
709 } else {
khenaidoo79232702018-12-04 11:00:41 -0500710 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400711 var err error
712 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
713 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
714 return nil, err
715 }
716 return switchCap, nil
717 }
718}
719
khenaidoo4d4802d2018-10-04 21:59:49 -0400720// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
721// device
khenaidoo79232702018-12-04 11:00:41 -0500722func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400723 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400724 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400725 return nil, err
726 } else {
khenaidoo79232702018-12-04 11:00:41 -0500727 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400728 var err error
729 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
730 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
731 return nil, err
732 }
733 return portCap, nil
734 }
735}
736
khenaidoofdbad6e2018-11-06 22:26:38 -0500737func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
738 // Send packet to adapter
739 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
740 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
741 return err
742 }
743 return nil
744}
745
khenaidoo4d4802d2018-10-04 21:59:49 -0400746// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400747func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500748 //// Run this callback in its own go routine
749 go func(args ...interface{}) interface{} {
750 var previous *voltha.Device
751 var current *voltha.Device
752 var ok bool
753 if len(args) == 2 {
754 if previous, ok = args[0].(*voltha.Device); !ok {
755 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
756 return nil
757 }
758 if current, ok = args[1].(*voltha.Device); !ok {
759 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
760 return nil
761 }
762 } else {
763 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
764 return nil
765 }
766 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500767 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
768 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
769 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
770 }
khenaidoo43c82122018-11-22 18:38:28 -0500771 return nil
772 }(args...)
773
khenaidoo92e62c52018-10-03 14:02:54 -0400774 return nil
775}
776
khenaidoob9203542018-09-17 22:56:37 -0400777func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400778 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500779 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400780 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500781 cloned := proto.Clone(device).(*voltha.Device)
782 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
783 if afterUpdate == nil {
784 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400785 }
khenaidoo43c82122018-11-22 18:38:28 -0500786 return nil
787}
788
789func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
790 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
791 cloned := proto.Clone(device).(*voltha.Device)
792 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
793 if afterUpdate == nil {
794 return status.Errorf(codes.Internal, "%s", device.Id)
795 }
796 return nil
khenaidoob9203542018-09-17 22:56:37 -0400797}
798
khenaidoo92e62c52018-10-03 14:02:54 -0400799func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
800 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400801 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400802 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400803 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400804 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
805 } else {
806 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400807 cloned := proto.Clone(storeDevice).(*voltha.Device)
808 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
809 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
810 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
811 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400812 }
khenaidoo92e62c52018-10-03 14:02:54 -0400813 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
814 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
815 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400816 }
khenaidoo92e62c52018-10-03 14:02:54 -0400817 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400818 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400819 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400820 return status.Errorf(codes.Internal, "%s", agent.deviceId)
821 }
khenaidoo92e62c52018-10-03 14:02:54 -0400822 return nil
823 }
824}
825
khenaidoo3ab34882019-05-02 21:33:30 -0400826func (agent *DeviceAgent) enablePorts() error {
827 agent.lockDevice.Lock()
828 defer agent.lockDevice.Unlock()
829 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
830 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
831 } else {
832 // clone the device
833 cloned := proto.Clone(storeDevice).(*voltha.Device)
834 for _, port := range cloned.Ports {
835 port.AdminState = voltha.AdminState_ENABLED
836 port.OperStatus = voltha.OperStatus_ACTIVE
837 }
838 // Store the device
839 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
840 return status.Errorf(codes.Internal, "%s", agent.deviceId)
841 }
842 return nil
843 }
844}
845
846func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -0400847 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -0400848 agent.lockDevice.Lock()
849 defer agent.lockDevice.Unlock()
850 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
851 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
852 } else {
853 // clone the device
854 cloned := proto.Clone(storeDevice).(*voltha.Device)
855 for _, port := range cloned.Ports {
856 port.AdminState = voltha.AdminState_DISABLED
857 port.OperStatus = voltha.OperStatus_UNKNOWN
858 }
859 // Store the device
860 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
861 return status.Errorf(codes.Internal, "%s", agent.deviceId)
862 }
863 return nil
864 }
865}
866
khenaidoo92e62c52018-10-03 14:02:54 -0400867func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
868 agent.lockDevice.Lock()
khenaidoo92e62c52018-10-03 14:02:54 -0400869 // Work only on latest data
870 // TODO: Get list of ports from device directly instead of the entire device
871 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
872 agent.lockDevice.Unlock()
873 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
874 } else {
875 // clone the device
876 cloned := proto.Clone(storeDevice).(*voltha.Device)
877 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
878 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
879 agent.lockDevice.Unlock()
880 return status.Errorf(codes.InvalidArgument, "%s", portType)
881 }
882 for _, port := range cloned.Ports {
883 if port.Type == portType && port.PortNo == portNo {
884 port.OperStatus = operStatus
885 // Set the admin status to ENABLED if the operational status is ACTIVE
886 // TODO: Set by northbound system?
887 if operStatus == voltha.OperStatus_ACTIVE {
888 port.AdminState = voltha.AdminState_ENABLED
889 }
890 break
891 }
892 }
893 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
894 // Store the device
895 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
896 agent.lockDevice.Unlock()
897 return status.Errorf(codes.Internal, "%s", agent.deviceId)
898 }
899 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400900 return nil
901 }
902}
903
khenaidoo0a822f92019-05-08 15:15:57 -0400904func (agent *DeviceAgent) deleteAllPorts() error {
905 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
906 agent.lockDevice.Lock()
907 defer agent.lockDevice.Unlock()
908 // Work only on latest data
909 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
910 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
911 } else {
912 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
913 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
914 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
915 return err
916 }
917 if len(storeDevice.Ports) == 0 {
918 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
919 return nil
920 }
921 // clone the device & set the fields to empty
922 cloned := proto.Clone(storeDevice).(*voltha.Device)
923 cloned.Ports = []*voltha.Port{}
924 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
925 // Store the device
926 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
927 return status.Errorf(codes.Internal, "%s", agent.deviceId)
928 }
929 return nil
930 }
931}
932
khenaidoob9203542018-09-17 22:56:37 -0400933func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400934 agent.lockDevice.Lock()
935 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400936 log.Debug("updatePmConfigs")
937 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400938 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400939 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
940 } else {
941 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400942 cloned := proto.Clone(storeDevice).(*voltha.Device)
943 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400944 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400945 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400946 if afterUpdate == nil {
947 return status.Errorf(codes.Internal, "%s", agent.deviceId)
948 }
949 return nil
950 }
951}
952
953func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400954 agent.lockDevice.Lock()
955 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -0400956 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400957 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400958 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400959 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
960 } else {
961 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400962 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400963 if cloned.Ports == nil {
964 // First port
khenaidoo0a822f92019-05-08 15:15:57 -0400965 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400966 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -0400967 } else {
968 for _, p := range cloned.Ports {
969 if p.Type == port.Type && p.PortNo == port.PortNo {
970 log.Debugw("port already exists", log.Fields{"port": *port})
971 return nil
972 }
973 }
khenaidoob9203542018-09-17 22:56:37 -0400974 }
khenaidoo92e62c52018-10-03 14:02:54 -0400975 cp := proto.Clone(port).(*voltha.Port)
976 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
977 // TODO: Set by northbound system?
978 if cp.OperStatus == voltha.OperStatus_ACTIVE {
979 cp.AdminState = voltha.AdminState_ENABLED
980 }
981 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400982 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400983 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
984 if afterUpdate == nil {
985 return status.Errorf(codes.Internal, "%s", agent.deviceId)
986 }
987 return nil
988 }
989}
990
991func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
992 agent.lockDevice.Lock()
993 defer agent.lockDevice.Unlock()
994 log.Debug("addPeerPort")
995 // Work only on latest data
996 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
997 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
998 } else {
999 // clone the device
1000 cloned := proto.Clone(storeDevice).(*voltha.Device)
1001 // Get the peer port on the device based on the port no
1002 for _, peerPort := range cloned.Ports {
1003 if peerPort.PortNo == port.PortNo { // found port
1004 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1005 peerPort.Peers = append(peerPort.Peers, cp)
1006 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1007 break
1008 }
1009 }
1010 // Store the device
1011 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001012 if afterUpdate == nil {
1013 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1014 }
1015 return nil
1016 }
1017}
1018
khenaidoo0a822f92019-05-08 15:15:57 -04001019func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1020 agent.lockDevice.Lock()
1021 defer agent.lockDevice.Unlock()
1022 log.Debug("deletePeerPorts")
1023 // Work only on latest data
1024 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1025 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1026 } else {
1027 // clone the device
1028 cloned := proto.Clone(storeDevice).(*voltha.Device)
1029 var updatedPeers []*voltha.Port_PeerPort
1030 for _, port := range cloned.Ports {
1031 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1032 for _, peerPort := range port.Peers {
1033 if peerPort.DeviceId != deviceId {
1034 updatedPeers = append(updatedPeers, peerPort)
1035 }
1036 }
1037 port.Peers = updatedPeers
1038 }
1039
1040 // Store the device with updated peer ports
1041 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1042 if afterUpdate == nil {
1043 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1044 }
1045 return nil
1046 }
1047}
1048
khenaidoob9203542018-09-17 22:56:37 -04001049// TODO: A generic device update by attribute
1050func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001051 agent.lockDevice.Lock()
1052 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001053 if value == nil {
1054 return
1055 }
1056 var storeDevice *voltha.Device
1057 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001058 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001059 return
1060 }
1061 updated := false
1062 s := reflect.ValueOf(storeDevice).Elem()
1063 if s.Kind() == reflect.Struct {
1064 // exported field
1065 f := s.FieldByName(name)
1066 if f.IsValid() && f.CanSet() {
1067 switch f.Kind() {
1068 case reflect.String:
1069 f.SetString(value.(string))
1070 updated = true
1071 case reflect.Uint32:
1072 f.SetUint(uint64(value.(uint32)))
1073 updated = true
1074 case reflect.Bool:
1075 f.SetBool(value.(bool))
1076 updated = true
1077 }
1078 }
1079 }
khenaidoo92e62c52018-10-03 14:02:54 -04001080 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001081 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001082 cloned := proto.Clone(storeDevice).(*voltha.Device)
1083 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001084 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1085 }
1086 return
1087}
serkant.uluderya334479d2019-04-10 08:26:15 -07001088
1089func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1090 agent.lockDevice.Lock()
1091 defer agent.lockDevice.Unlock()
1092 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1093 // Get the most up to date the device info
1094 if device, err := agent.getDeviceWithoutLock(); err != nil {
1095 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1096 } else {
1097 // First send the request to an Adapter and wait for a response
1098 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1099 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1100 return err
1101 }
1102 }
1103 return nil
1104}