blob: 4e31ff88fbbeefdc959be92d0c57aa98b405e0af [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 {
119 log.Errorw("failed-removing-device", log.Fields{"id": agent.deviceId})
120 }
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 }
351 // First send the request to an Adapter and wait for a response
352 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
353 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400354 return err
355 }
khenaidoo0a822f92019-05-08 15:15:57 -0400356 if err = agent.updateAdminState(voltha.AdminState_DISABLED); err != nil {
357 log.Errorw("failed-update-device", log.Fields{"deviceId": device.Id, "currentState": device.AdminState, "expectedState": voltha.AdminState_DISABLED})
358 }
359 }
360 return nil
361}
362
363func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
364 agent.lockDevice.Lock()
365 defer agent.lockDevice.Unlock()
366 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
367 // Get the most up to date the device info
368 if device, err := agent.getDeviceWithoutLock(); err != nil {
369 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
370 } else {
371 if device.AdminState == adminState {
372 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
373 return nil
374 }
khenaidoo92e62c52018-10-03 14:02:54 -0400375 // Received an Ack (no error found above). Now update the device in the model to the expected state
376 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400377 cloned.AdminState = adminState
khenaidoo92e62c52018-10-03 14:02:54 -0400378 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400379 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
380 }
khenaidoo92e62c52018-10-03 14:02:54 -0400381 }
382 return nil
383}
384
khenaidoo4d4802d2018-10-04 21:59:49 -0400385func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
386 agent.lockDevice.Lock()
387 defer agent.lockDevice.Unlock()
388 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
389 // Get the most up to date the device info
390 if device, err := agent.getDeviceWithoutLock(); err != nil {
391 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
392 } else {
393 if device.AdminState != voltha.AdminState_DISABLED {
394 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
395 //TODO: Needs customized error message
396 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
397 }
398 // First send the request to an Adapter and wait for a response
399 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
400 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
401 return err
402 }
403 }
404 return nil
405}
406
407func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
408 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400409 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400410 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
411 // Get the most up to date the device info
412 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400413 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
414 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400415 if device.AdminState == voltha.AdminState_DELETED {
416 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
417 return nil
418 }
khenaidoo43c82122018-11-22 18:38:28 -0500419 if (device.AdminState != voltha.AdminState_DISABLED) &&
420 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400421 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
422 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400423 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
424 }
khenaidoo0a822f92019-05-08 15:15:57 -0400425 // Send the request to an Adapter and wait for a response
426 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
427 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
428 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400429 }
khenaidoo0a822f92019-05-08 15:15:57 -0400430
431 // Set the state to deleted - this will trigger some background process to clean up the device as well
432 // as its association with the logical device
433 cloned := proto.Clone(device).(*voltha.Device)
434 cloned.AdminState = voltha.AdminState_DELETED
435 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400436 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
437 }
khenaidoo0a822f92019-05-08 15:15:57 -0400438
439 // If this is a child device then remove the associated peer ports on the parent device
440 if !device.Root {
441 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
442 }
443
khenaidoo4d4802d2018-10-04 21:59:49 -0400444 }
445 return nil
446}
447
khenaidoof5a5bfa2019-01-23 22:20:29 -0500448func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
449 agent.lockDevice.Lock()
450 defer agent.lockDevice.Unlock()
451 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
452 // Get the most up to date the device info
453 if device, err := agent.getDeviceWithoutLock(); err != nil {
454 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
455 } else {
456 if device.AdminState != voltha.AdminState_ENABLED {
457 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
458 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
459 }
460 // Save the image
461 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500462 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500463 cloned := proto.Clone(device).(*voltha.Device)
464 if cloned.ImageDownloads == nil {
465 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
466 } else {
467 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
468 }
469 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
470 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
471 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
472 }
473 // Send the request to the adapter
474 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
475 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
476 return nil, err
477 }
478 }
479 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
480}
481
482// isImageRegistered is a helper method to figure out if an image is already registered
483func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
484 for _, image := range device.ImageDownloads {
485 if image.Id == img.Id && image.Name == img.Name {
486 return true
487 }
488 }
489 return false
490}
491
492func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
493 agent.lockDevice.Lock()
494 defer agent.lockDevice.Unlock()
495 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
496 // Get the most up to date the device info
497 if device, err := agent.getDeviceWithoutLock(); err != nil {
498 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
499 } else {
500 // Verify whether the Image is in the list of image being downloaded
501 if !isImageRegistered(img, device) {
502 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
503 }
504
505 // Update image download state
506 cloned := proto.Clone(device).(*voltha.Device)
507 for _, image := range cloned.ImageDownloads {
508 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500509 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500510 }
511 }
512
513 //If device is in downloading state, send the request to cancel the download
514 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
515 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
516 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
517 return nil, err
518 }
519 // Set the device to Enabled
520 cloned.AdminState = voltha.AdminState_ENABLED
521 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
522 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
523 }
524 }
525 }
526 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700527}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500528
529func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
530 agent.lockDevice.Lock()
531 defer agent.lockDevice.Unlock()
532 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
533 // Get the most up to date the device info
534 if device, err := agent.getDeviceWithoutLock(); err != nil {
535 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
536 } else {
537 // Verify whether the Image is in the list of image being downloaded
538 if !isImageRegistered(img, device) {
539 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
540 }
541
542 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
543 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
544 }
545 // Update image download state
546 cloned := proto.Clone(device).(*voltha.Device)
547 for _, image := range cloned.ImageDownloads {
548 if image.Id == img.Id && image.Name == img.Name {
549 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
550 }
551 }
552 // Set the device to downloading_image
553 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
554 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
555 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
556 }
557
558 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
559 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
560 return nil, err
561 }
562 // The status of the AdminState will be changed following the update_download_status response from the adapter
563 // The image name will also be removed from the device list
564 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700565 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
566}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500567
568func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
569 agent.lockDevice.Lock()
570 defer agent.lockDevice.Unlock()
571 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
572 // Get the most up to date the device info
573 if device, err := agent.getDeviceWithoutLock(); err != nil {
574 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
575 } else {
576 // Verify whether the Image is in the list of image being downloaded
577 if !isImageRegistered(img, device) {
578 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
579 }
580
581 if device.AdminState != voltha.AdminState_ENABLED {
582 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
583 }
584 // Update image download state
585 cloned := proto.Clone(device).(*voltha.Device)
586 for _, image := range cloned.ImageDownloads {
587 if image.Id == img.Id && image.Name == img.Name {
588 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
589 }
590 }
591 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
592 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
593 }
594
595 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
596 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
597 return nil, err
598 }
599 }
600 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700601}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500602
603func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
604 agent.lockDevice.Lock()
605 defer agent.lockDevice.Unlock()
606 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
607 // Get the most up to date the device info
608 if device, err := agent.getDeviceWithoutLock(); err != nil {
609 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
610 } else {
611 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
612 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
613 return nil, err
614 } else {
615 return resp, nil
616 }
617 }
618}
619
serkant.uluderya334479d2019-04-10 08:26:15 -0700620func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500621 agent.lockDevice.Lock()
622 defer agent.lockDevice.Unlock()
623 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
624 // Get the most up to date the device info
625 if device, err := agent.getDeviceWithoutLock(); err != nil {
626 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
627 } else {
628 // Update the image as well as remove it if the download was cancelled
629 cloned := proto.Clone(device).(*voltha.Device)
630 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
631 for _, image := range cloned.ImageDownloads {
632 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500633 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500634 clonedImages = append(clonedImages, img)
635 }
636 }
637 }
638 cloned.ImageDownloads = clonedImages
639 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500640 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
641 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700642 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500643 cloned.AdminState = voltha.AdminState_ENABLED
644 }
645
646 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
647 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
648 }
649 }
650 return nil
651}
652
653func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400654 agent.lockDevice.RLock()
655 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500656 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
657 // Get the most up to date the device info
658 if device, err := agent.getDeviceWithoutLock(); err != nil {
659 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
660 } else {
661 for _, image := range device.ImageDownloads {
662 if image.Id == img.Id && image.Name == img.Name {
663 return image, nil
664 }
665 }
666 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
667 }
668}
669
670func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400671 agent.lockDevice.RLock()
672 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500673 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
674 // Get the most up to date the device info
675 if device, err := agent.getDeviceWithoutLock(); err != nil {
676 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
677 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700678 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500679 }
680}
681
khenaidoo4d4802d2018-10-04 21:59:49 -0400682// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400683func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
684 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400685 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400686 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400687 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400688 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400689 ports.Items = append(ports.Items, port)
690 }
691 }
692 }
693 return ports
694}
695
khenaidoo4d4802d2018-10-04 21:59:49 -0400696// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
697// parent device
khenaidoo79232702018-12-04 11:00:41 -0500698func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400699 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400700 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400701 return nil, err
702 } else {
khenaidoo79232702018-12-04 11:00:41 -0500703 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400704 var err error
705 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
706 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
707 return nil, err
708 }
709 return switchCap, nil
710 }
711}
712
khenaidoo4d4802d2018-10-04 21:59:49 -0400713// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
714// device
khenaidoo79232702018-12-04 11:00:41 -0500715func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400716 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400717 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400718 return nil, err
719 } else {
khenaidoo79232702018-12-04 11:00:41 -0500720 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400721 var err error
722 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
723 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
724 return nil, err
725 }
726 return portCap, nil
727 }
728}
729
khenaidoofdbad6e2018-11-06 22:26:38 -0500730func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
731 // Send packet to adapter
732 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
733 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
734 return err
735 }
736 return nil
737}
738
khenaidoo4d4802d2018-10-04 21:59:49 -0400739// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400740func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500741 //// Run this callback in its own go routine
742 go func(args ...interface{}) interface{} {
743 var previous *voltha.Device
744 var current *voltha.Device
745 var ok bool
746 if len(args) == 2 {
747 if previous, ok = args[0].(*voltha.Device); !ok {
748 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
749 return nil
750 }
751 if current, ok = args[1].(*voltha.Device); !ok {
752 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
753 return nil
754 }
755 } else {
756 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
757 return nil
758 }
759 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -0500760 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
761 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
762 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
763 }
khenaidoo43c82122018-11-22 18:38:28 -0500764 return nil
765 }(args...)
766
khenaidoo92e62c52018-10-03 14:02:54 -0400767 return nil
768}
769
khenaidoob9203542018-09-17 22:56:37 -0400770func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400771 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -0500772 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400773 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -0500774 cloned := proto.Clone(device).(*voltha.Device)
775 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
776 if afterUpdate == nil {
777 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -0400778 }
khenaidoo43c82122018-11-22 18:38:28 -0500779 return nil
780}
781
782func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
783 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
784 cloned := proto.Clone(device).(*voltha.Device)
785 afterUpdate := agent.clusterDataProxy.Update("/devices/"+device.Id, cloned, false, "")
786 if afterUpdate == nil {
787 return status.Errorf(codes.Internal, "%s", device.Id)
788 }
789 return nil
khenaidoob9203542018-09-17 22:56:37 -0400790}
791
khenaidoo92e62c52018-10-03 14:02:54 -0400792func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
793 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400794 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400795 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400796 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400797 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
798 } else {
799 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400800 cloned := proto.Clone(storeDevice).(*voltha.Device)
801 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
802 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
803 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
804 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -0400805 }
khenaidoo92e62c52018-10-03 14:02:54 -0400806 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
807 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
808 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -0400809 }
khenaidoo92e62c52018-10-03 14:02:54 -0400810 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -0400811 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400812 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -0400813 return status.Errorf(codes.Internal, "%s", agent.deviceId)
814 }
khenaidoo92e62c52018-10-03 14:02:54 -0400815 return nil
816 }
817}
818
khenaidoo3ab34882019-05-02 21:33:30 -0400819func (agent *DeviceAgent) enablePorts() error {
820 agent.lockDevice.Lock()
821 defer agent.lockDevice.Unlock()
822 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
823 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
824 } else {
825 // clone the device
826 cloned := proto.Clone(storeDevice).(*voltha.Device)
827 for _, port := range cloned.Ports {
828 port.AdminState = voltha.AdminState_ENABLED
829 port.OperStatus = voltha.OperStatus_ACTIVE
830 }
831 // Store the device
832 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
833 return status.Errorf(codes.Internal, "%s", agent.deviceId)
834 }
835 return nil
836 }
837}
838
839func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -0400840 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -0400841 agent.lockDevice.Lock()
842 defer agent.lockDevice.Unlock()
843 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
844 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
845 } else {
846 // clone the device
847 cloned := proto.Clone(storeDevice).(*voltha.Device)
848 for _, port := range cloned.Ports {
849 port.AdminState = voltha.AdminState_DISABLED
850 port.OperStatus = voltha.OperStatus_UNKNOWN
851 }
852 // Store the device
853 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
854 return status.Errorf(codes.Internal, "%s", agent.deviceId)
855 }
856 return nil
857 }
858}
859
khenaidoo92e62c52018-10-03 14:02:54 -0400860func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
861 agent.lockDevice.Lock()
khenaidoo92e62c52018-10-03 14:02:54 -0400862 // Work only on latest data
863 // TODO: Get list of ports from device directly instead of the entire device
864 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
865 agent.lockDevice.Unlock()
866 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
867 } else {
868 // clone the device
869 cloned := proto.Clone(storeDevice).(*voltha.Device)
870 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
871 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
872 agent.lockDevice.Unlock()
873 return status.Errorf(codes.InvalidArgument, "%s", portType)
874 }
875 for _, port := range cloned.Ports {
876 if port.Type == portType && port.PortNo == portNo {
877 port.OperStatus = operStatus
878 // Set the admin status to ENABLED if the operational status is ACTIVE
879 // TODO: Set by northbound system?
880 if operStatus == voltha.OperStatus_ACTIVE {
881 port.AdminState = voltha.AdminState_ENABLED
882 }
883 break
884 }
885 }
886 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
887 // Store the device
888 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
889 agent.lockDevice.Unlock()
890 return status.Errorf(codes.Internal, "%s", agent.deviceId)
891 }
892 agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400893 return nil
894 }
895}
896
khenaidoo0a822f92019-05-08 15:15:57 -0400897func (agent *DeviceAgent) deleteAllPorts() error {
898 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
899 agent.lockDevice.Lock()
900 defer agent.lockDevice.Unlock()
901 // Work only on latest data
902 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
903 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
904 } else {
905 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
906 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
907 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
908 return err
909 }
910 if len(storeDevice.Ports) == 0 {
911 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
912 return nil
913 }
914 // clone the device & set the fields to empty
915 cloned := proto.Clone(storeDevice).(*voltha.Device)
916 cloned.Ports = []*voltha.Port{}
917 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
918 // Store the device
919 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
920 return status.Errorf(codes.Internal, "%s", agent.deviceId)
921 }
922 return nil
923 }
924}
925
khenaidoob9203542018-09-17 22:56:37 -0400926func (agent *DeviceAgent) updatePmConfigs(pmConfigs *voltha.PmConfigs) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400927 agent.lockDevice.Lock()
928 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400929 log.Debug("updatePmConfigs")
930 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400931 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400932 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
933 } else {
934 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400935 cloned := proto.Clone(storeDevice).(*voltha.Device)
936 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
khenaidoob9203542018-09-17 22:56:37 -0400937 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400938 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -0400939 if afterUpdate == nil {
940 return status.Errorf(codes.Internal, "%s", agent.deviceId)
941 }
942 return nil
943 }
944}
945
946func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400947 agent.lockDevice.Lock()
948 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -0400949 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400950 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -0400951 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400952 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
953 } else {
954 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -0400955 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -0400956 if cloned.Ports == nil {
957 // First port
khenaidoo0a822f92019-05-08 15:15:57 -0400958 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -0400959 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -0400960 } else {
961 for _, p := range cloned.Ports {
962 if p.Type == port.Type && p.PortNo == port.PortNo {
963 log.Debugw("port already exists", log.Fields{"port": *port})
964 return nil
965 }
966 }
khenaidoob9203542018-09-17 22:56:37 -0400967 }
khenaidoo92e62c52018-10-03 14:02:54 -0400968 cp := proto.Clone(port).(*voltha.Port)
969 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
970 // TODO: Set by northbound system?
971 if cp.OperStatus == voltha.OperStatus_ACTIVE {
972 cp.AdminState = voltha.AdminState_ENABLED
973 }
974 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -0400975 // Store the device
khenaidoo92e62c52018-10-03 14:02:54 -0400976 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
977 if afterUpdate == nil {
978 return status.Errorf(codes.Internal, "%s", agent.deviceId)
979 }
980 return nil
981 }
982}
983
984func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
985 agent.lockDevice.Lock()
986 defer agent.lockDevice.Unlock()
987 log.Debug("addPeerPort")
988 // Work only on latest data
989 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
990 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
991 } else {
992 // clone the device
993 cloned := proto.Clone(storeDevice).(*voltha.Device)
994 // Get the peer port on the device based on the port no
995 for _, peerPort := range cloned.Ports {
996 if peerPort.PortNo == port.PortNo { // found port
997 cp := proto.Clone(port).(*voltha.Port_PeerPort)
998 peerPort.Peers = append(peerPort.Peers, cp)
999 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1000 break
1001 }
1002 }
1003 // Store the device
1004 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001005 if afterUpdate == nil {
1006 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1007 }
1008 return nil
1009 }
1010}
1011
khenaidoo0a822f92019-05-08 15:15:57 -04001012func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1013 agent.lockDevice.Lock()
1014 defer agent.lockDevice.Unlock()
1015 log.Debug("deletePeerPorts")
1016 // Work only on latest data
1017 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1018 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1019 } else {
1020 // clone the device
1021 cloned := proto.Clone(storeDevice).(*voltha.Device)
1022 var updatedPeers []*voltha.Port_PeerPort
1023 for _, port := range cloned.Ports {
1024 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1025 for _, peerPort := range port.Peers {
1026 if peerPort.DeviceId != deviceId {
1027 updatedPeers = append(updatedPeers, peerPort)
1028 }
1029 }
1030 port.Peers = updatedPeers
1031 }
1032
1033 // Store the device with updated peer ports
1034 afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, "")
1035 if afterUpdate == nil {
1036 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1037 }
1038 return nil
1039 }
1040}
1041
khenaidoob9203542018-09-17 22:56:37 -04001042// TODO: A generic device update by attribute
1043func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001044 agent.lockDevice.Lock()
1045 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001046 if value == nil {
1047 return
1048 }
1049 var storeDevice *voltha.Device
1050 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001051 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001052 return
1053 }
1054 updated := false
1055 s := reflect.ValueOf(storeDevice).Elem()
1056 if s.Kind() == reflect.Struct {
1057 // exported field
1058 f := s.FieldByName(name)
1059 if f.IsValid() && f.CanSet() {
1060 switch f.Kind() {
1061 case reflect.String:
1062 f.SetString(value.(string))
1063 updated = true
1064 case reflect.Uint32:
1065 f.SetUint(uint64(value.(uint32)))
1066 updated = true
1067 case reflect.Bool:
1068 f.SetBool(value.(bool))
1069 updated = true
1070 }
1071 }
1072 }
khenaidoo92e62c52018-10-03 14:02:54 -04001073 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001074 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001075 cloned := proto.Clone(storeDevice).(*voltha.Device)
1076 if afterUpdate := agent.clusterDataProxy.Update("/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001077 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1078 }
1079 return
1080}
serkant.uluderya334479d2019-04-10 08:26:15 -07001081
1082func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1083 agent.lockDevice.Lock()
1084 defer agent.lockDevice.Unlock()
1085 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1086 // Get the most up to date the device info
1087 if device, err := agent.getDeviceWithoutLock(); err != nil {
1088 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1089 } else {
1090 // First send the request to an Adapter and wait for a response
1091 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1092 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1093 return err
1094 }
1095 }
1096 return nil
1097}