blob: a202c82ab928358068b20f652770c986e80c8552 [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"
Stephane Barbarieef6650d2019-07-18 12:15:09 -040032 "time"
khenaidoob9203542018-09-17 22:56:37 -040033)
34
35type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040036 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040037 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050038 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040039 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040040 lastData *voltha.Device
41 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070042 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040043 deviceMgr *DeviceManager
44 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040045 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040046 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040047 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040048 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040049}
50
khenaidoo4d4802d2018-10-04 21:59:49 -040051//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
52//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040053func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040054 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040055 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040056 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050057 if cloned.Id == "" {
58 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050059 cloned.AdminState = voltha.AdminState_PREPROVISIONED
60 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
61 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050062 }
khenaidoo19d7b632018-10-30 10:49:50 -040063 if !device.GetRoot() && device.ProxyAddress != nil {
64 // Set the default vlan ID to the one specified by the parent adapter. It can be
65 // overwritten by the child adapter during a device update request
66 cloned.Vlan = device.ProxyAddress.ChannelId
67 }
khenaidoo2c6a0992019-04-29 13:46:56 -040068 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040069 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040070 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050071 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040072 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040073 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050074 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040075 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040076 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040077 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040078 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040079 return &agent
80}
81
khenaidoo297cd252019-02-07 22:10:23 -050082// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
83// it will load the data from the dB and setup teh necessary callbacks and proxies.
84func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040085 agent.lockDevice.Lock()
86 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050087 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
88 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040089 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050090 if d, ok := device.(*voltha.Device); ok {
91 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050092 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050093 }
94 } else {
95 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
96 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
97 }
98 log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
99 } else {
100 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400101 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500102 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
103 }
khenaidoob9203542018-09-17 22:56:37 -0400104 }
khenaidoo297cd252019-02-07 22:10:23 -0500105
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400106 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500107 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400108
khenaidoob9203542018-09-17 22:56:37 -0400109 log.Debug("device-agent-started")
khenaidoo297cd252019-02-07 22:10:23 -0500110 return nil
khenaidoob9203542018-09-17 22:56:37 -0400111}
112
khenaidoo4d4802d2018-10-04 21:59:49 -0400113// stop stops the device agent. Not much to do for now
114func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400115 agent.lockDevice.Lock()
116 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400117 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400118 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400119 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400120 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400121 }
khenaidoob9203542018-09-17 22:56:37 -0400122 agent.exitChannel <- 1
123 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400124
khenaidoob9203542018-09-17 22:56:37 -0400125}
126
khenaidoo19d7b632018-10-30 10:49:50 -0400127// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400128func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400129 agent.lockDevice.RLock()
130 defer agent.lockDevice.RUnlock()
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400131 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, true, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400132 if d, ok := device.(*voltha.Device); ok {
133 cloned := proto.Clone(d).(*voltha.Device)
134 return cloned, nil
135 }
136 }
137 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
138}
139
khenaidoo4d4802d2018-10-04 21:59:49 -0400140// 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 -0400141// This function is meant so that we do not have duplicate code all over the device agent functions
142func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400143 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400144 if d, ok := device.(*voltha.Device); ok {
145 cloned := proto.Clone(d).(*voltha.Device)
146 return cloned, nil
147 }
148 }
149 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
150}
151
khenaidoo3ab34882019-05-02 21:33:30 -0400152// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400153func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400154 agent.lockDevice.Lock()
155 defer agent.lockDevice.Unlock()
156 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500157
khenaidoo92e62c52018-10-03 14:02:54 -0400158 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400159 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
160 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500161 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
162 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
163 // with the adapter then we need to know the adapter that will handle this request
164 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
165 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
166 return err
167 } else {
168 device.Adapter = adapterName
169 }
170
khenaidoo92e62c52018-10-03 14:02:54 -0400171 if device.AdminState == voltha.AdminState_ENABLED {
172 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400173 return nil
174 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400175
176 if device.AdminState == voltha.AdminState_DELETED {
177 // This is a temporary state when a device is deleted before it gets removed from the model.
178 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
179 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
180 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400181 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400182
183 previousAdminState := device.AdminState
184
185 // Update the Admin State and set the operational state to activating before sending the request to the
186 // Adapters
187 cloned := proto.Clone(device).(*voltha.Device)
188 cloned.AdminState = voltha.AdminState_ENABLED
189 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400190
191 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
192 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo59ef7be2019-06-21 12:40:28 -0400193 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
194 }
195
196 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
197 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400198 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
199 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400200 return err
201 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400202 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400203 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
204 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
205 return err
206 }
khenaidoob9203542018-09-17 22:56:37 -0400207 }
208 }
209 return nil
210}
211
khenaidoo2c6a0992019-04-29 13:46:56 -0400212func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
213 if err := agent.updateDeviceWithoutLock(device); err != nil {
214 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400215 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400216 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400217}
218
khenaidoo2c6a0992019-04-29 13:46:56 -0400219func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, ch chan interface{}) {
220 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups); err != nil {
221 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
222 ch <- err
223 }
224 ch <- nil
225}
226
227func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, ch chan interface{}) {
228 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups); err != nil {
229 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
230 ch <- err
231 }
232 ch <- nil
233}
234
khenaidoo0458db62019-06-20 08:50:36 -0400235//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
236//adapters
khenaidoo2c6a0992019-04-29 13:46:56 -0400237func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry) error {
khenaidoo0458db62019-06-20 08:50:36 -0400238 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
239
khenaidoo2c6a0992019-04-29 13:46:56 -0400240 if (len(newFlows) | len(newGroups)) == 0 {
241 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
242 return nil
243 }
244
khenaidoo19d7b632018-10-30 10:49:50 -0400245 agent.lockDevice.Lock()
246 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400247
khenaidoo0458db62019-06-20 08:50:36 -0400248 var device *voltha.Device
249 var err error
250 if device, err = agent.getDeviceWithoutLock(); err != nil {
251 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
252 }
253
254 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
255 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
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 for _, flow := range existingFlows.Items {
267 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
268 updatedFlows = append(updatedFlows, flow)
269 } else {
270 flowsToDelete = append(flowsToDelete, flow)
271 }
272 }
273
274 // Process groups
275 for _, g := range newGroups {
276 updatedGroups = append(updatedGroups, g)
277 }
278 for _, group := range existingGroups.Items {
279 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
280 updatedGroups = append(updatedGroups, group)
281 } else {
282 groupsToDelete = append(groupsToDelete, group)
283 }
284 }
285
286 // Sanity check
287 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
288 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
289 return nil
290 }
291
292 // Send update to adapters
293 // Create two channels to receive responses from the dB and from the adapters.
294 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
295 // to send their responses. These channels will be garbage collected once all the responses are
296 // received
297 chAdapters := make(chan interface{})
298 chdB := make(chan interface{})
299 dType := agent.adapterMgr.getDeviceType(device.Type)
300 if !dType.AcceptsAddRemoveFlowUpdates {
301
302 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
303 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
304 return nil
305 }
306 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
307
308 } else {
309 flowChanges := &ofp.FlowChanges{
310 ToAdd: &voltha.Flows{Items: newFlows},
311 ToRemove: &voltha.Flows{Items: flowsToDelete},
312 }
313 groupChanges := &ofp.FlowGroupChanges{
314 ToAdd: &voltha.FlowGroups{Items: newGroups},
315 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
316 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
317 }
318 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
319 }
320
321 // store the changed data
322 device.Flows = &voltha.Flows{Items: updatedFlows}
323 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
324 go agent.updateDeviceWithoutLockAsync(device, chdB)
325
326 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
327 return status.Errorf(codes.Aborted, "errors-%s", res)
328 }
329
330 return nil
331}
332
333//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
334//adapters
335func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry) error {
336 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
337
338 if (len(flowsToDel) | len(groupsToDel)) == 0 {
339 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
340 return nil
341 }
342
343 agent.lockDevice.Lock()
344 defer agent.lockDevice.Unlock()
345
346 var device *voltha.Device
347 var err error
348
349 if device, err = agent.getDeviceWithoutLock(); err != nil {
350 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
351 }
352
353 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
354 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
355
356 var flowsToKeep []*ofp.OfpFlowStats
357 var groupsToKeep []*ofp.OfpGroupEntry
358
359 // Process flows
360 for _, flow := range existingFlows.Items {
361 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
362 flowsToKeep = append(flowsToKeep, flow)
363 }
364 }
365
366 // Process groups
367 for _, group := range existingGroups.Items {
368 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
369 groupsToKeep = append(groupsToKeep, group)
370 }
371 }
372
373 log.Debugw("deleteFlowsAndGroups",
374 log.Fields{
375 "deviceId": agent.deviceId,
376 "flowsToDel": len(flowsToDel),
377 "flowsToKeep": len(flowsToKeep),
378 "groupsToDel": len(groupsToDel),
379 "groupsToKeep": len(groupsToKeep),
380 })
381
382 // Sanity check
383 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
384 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
385 return nil
386 }
387
388 // Send update to adapters
389 chAdapters := make(chan interface{})
390 chdB := make(chan interface{})
391 dType := agent.adapterMgr.getDeviceType(device.Type)
392 if !dType.AcceptsAddRemoveFlowUpdates {
393 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
394 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
395 return nil
396 }
397 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, chAdapters)
398 } else {
399 flowChanges := &ofp.FlowChanges{
400 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
401 ToRemove: &voltha.Flows{Items: flowsToDel},
402 }
403 groupChanges := &ofp.FlowGroupChanges{
404 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
405 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
406 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
407 }
408 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
409 }
410
411 // store the changed data
412 device.Flows = &voltha.Flows{Items: flowsToKeep}
413 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
414 go agent.updateDeviceWithoutLockAsync(device, chdB)
415
416 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
417 return status.Errorf(codes.Aborted, "errors-%s", res)
418 }
419 return nil
420
421}
422
423//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
424//also sends the updates to the adapters
425func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry) error {
426 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
427
428 if (len(updatedFlows) | len(updatedGroups)) == 0 {
429 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
430 return nil
431 }
432
433 agent.lockDevice.Lock()
434 defer agent.lockDevice.Unlock()
435 var device *voltha.Device
436 var err error
437 if device, err = agent.getDeviceWithoutLock(); err != nil {
438 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
439 }
440 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
441 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
442
443 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
444 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
445 return nil
446 }
447
448 log.Debugw("updating-flows-and-groups",
449 log.Fields{
450 "deviceId": agent.deviceId,
451 "updatedFlows": updatedFlows,
452 "updatedGroups": updatedGroups,
453 })
454
455 chAdapters := make(chan interface{})
456 chdB := make(chan interface{})
457 dType := agent.adapterMgr.getDeviceType(device.Type)
458
459 // Process bulk flow update differently than incremental update
460 if !dType.AcceptsAddRemoveFlowUpdates {
461 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, chAdapters)
462 } else {
463 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400464 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400465 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400466 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400467
468 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400469 for _, flow := range updatedFlows {
470 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
471 flowsToAdd = append(flowsToAdd, flow)
472 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400473 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400474 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400475 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400476 flowsToDelete = append(flowsToDelete, flow)
477 }
478 }
479
480 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400481 for _, g := range updatedGroups {
482 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
483 groupsToAdd = append(groupsToAdd, g)
484 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400485 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400486 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400487 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400488 groupsToDelete = append(groupsToDelete, group)
489 }
490 }
491
khenaidoo0458db62019-06-20 08:50:36 -0400492 log.Debugw("updating-flows-and-groups",
493 log.Fields{
494 "deviceId": agent.deviceId,
495 "flowsToAdd": flowsToAdd,
496 "flowsToDelete": flowsToDelete,
497 "groupsToAdd": groupsToAdd,
498 "groupsToDelete": groupsToDelete,
499 })
500
khenaidoo2c6a0992019-04-29 13:46:56 -0400501 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400502 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
503 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400505 }
506
khenaidoo0458db62019-06-20 08:50:36 -0400507 flowChanges := &ofp.FlowChanges{
508 ToAdd: &voltha.Flows{Items: flowsToAdd},
509 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400510 }
khenaidoo0458db62019-06-20 08:50:36 -0400511 groupChanges := &ofp.FlowGroupChanges{
512 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
513 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
514 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
515 }
516 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400517 }
khenaidoo0458db62019-06-20 08:50:36 -0400518
519 // store the updated data
520 device.Flows = &voltha.Flows{Items: updatedFlows}
521 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
522 go agent.updateDeviceWithoutLockAsync(device, chdB)
523
524 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
525 return status.Errorf(codes.Aborted, "errors-%s", res)
526 }
527 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400528}
529
khenaidoo4d4802d2018-10-04 21:59:49 -0400530//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400531func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400532 agent.lockDevice.Lock()
533 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400534 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
535 // Get the most up to date the device info
536 if device, err := agent.getDeviceWithoutLock(); err != nil {
537 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
538 } else {
539 if device.AdminState == voltha.AdminState_DISABLED {
540 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400541 return nil
542 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400543 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
544 device.AdminState == voltha.AdminState_DELETED {
545 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
546 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
547 }
548
khenaidoo59ef7be2019-06-21 12:40:28 -0400549 // Update the Admin State and operational state before sending the request out
550 cloned := proto.Clone(device).(*voltha.Device)
551 cloned.AdminState = voltha.AdminState_DISABLED
552 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400553 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
554 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo59ef7be2019-06-21 12:40:28 -0400555 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
556 }
557
khenaidoo92e62c52018-10-03 14:02:54 -0400558 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
559 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400560 return err
561 }
khenaidoo0a822f92019-05-08 15:15:57 -0400562 }
563 return nil
564}
565
566func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
567 agent.lockDevice.Lock()
568 defer agent.lockDevice.Unlock()
569 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
570 // Get the most up to date the device info
571 if device, err := agent.getDeviceWithoutLock(); err != nil {
572 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
573 } else {
574 if device.AdminState == adminState {
575 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
576 return nil
577 }
khenaidoo92e62c52018-10-03 14:02:54 -0400578 // Received an Ack (no error found above). Now update the device in the model to the expected state
579 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400580 cloned.AdminState = adminState
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400581 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
582 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400583 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
584 }
khenaidoo92e62c52018-10-03 14:02:54 -0400585 }
586 return nil
587}
588
khenaidoo4d4802d2018-10-04 21:59:49 -0400589func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
590 agent.lockDevice.Lock()
591 defer agent.lockDevice.Unlock()
592 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
593 // Get the most up to date the device info
594 if device, err := agent.getDeviceWithoutLock(); err != nil {
595 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
596 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400597 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
598 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
599 return err
600 }
601 }
602 return nil
603}
604
605func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
606 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400607 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400608 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
609 // Get the most up to date the device info
610 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400611 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
612 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400613 if device.AdminState == voltha.AdminState_DELETED {
614 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
615 return nil
616 }
khenaidoo43c82122018-11-22 18:38:28 -0500617 if (device.AdminState != voltha.AdminState_DISABLED) &&
618 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400619 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
620 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400621 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
622 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400623 if device.AdminState != voltha.AdminState_PREPROVISIONED {
624 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
625 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
626 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
627 return err
628 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400629 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400630 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
631 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400632 cloned := proto.Clone(device).(*voltha.Device)
633 cloned.AdminState = voltha.AdminState_DELETED
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400634 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
635 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400636 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
637 }
khenaidoo0a822f92019-05-08 15:15:57 -0400638
639 // If this is a child device then remove the associated peer ports on the parent device
640 if !device.Root {
641 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
642 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400643 }
644 return nil
645}
646
khenaidoob3127472019-07-24 21:04:55 -0400647func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
648 agent.lockDevice.Lock()
649 defer agent.lockDevice.Unlock()
650 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
651 // Work only on latest data
652 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
653 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
654 } else {
655 // clone the device
656 cloned := proto.Clone(storeDevice).(*voltha.Device)
657 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
658 // Store the device
659 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
660 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
661 if afterUpdate == nil {
662 return status.Errorf(codes.Internal, "%s", agent.deviceId)
663 }
664 // Send the request to the adapter
665 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
666 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
667 return err
668 }
669 return nil
670 }
671}
672
673func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
674 agent.lockDevice.Lock()
675 defer agent.lockDevice.Unlock()
676 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
677 // Work only on latest data
678 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
679 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
680 } else {
681 // clone the device
682 cloned := proto.Clone(storeDevice).(*voltha.Device)
683 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
684 // Store the device
685 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
686 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
687 if afterUpdate == nil {
688 return status.Errorf(codes.Internal, "%s", agent.deviceId)
689 }
690 return nil
691 }
692}
693
694func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
695 agent.lockDevice.RLock()
696 defer agent.lockDevice.RUnlock()
697 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
698 // Get the most up to date the device info
699 if device, err := agent.getDeviceWithoutLock(); err != nil {
700 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
701 } else {
702 cloned := proto.Clone(device).(*voltha.Device)
703 return cloned.PmConfigs, nil
704 }
705}
706
khenaidoof5a5bfa2019-01-23 22:20:29 -0500707func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
708 agent.lockDevice.Lock()
709 defer agent.lockDevice.Unlock()
710 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
711 // Get the most up to date the device info
712 if device, err := agent.getDeviceWithoutLock(); err != nil {
713 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
714 } else {
715 if device.AdminState != voltha.AdminState_ENABLED {
716 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
717 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
718 }
719 // Save the image
720 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500721 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500722 cloned := proto.Clone(device).(*voltha.Device)
723 if cloned.ImageDownloads == nil {
724 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
725 } else {
726 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
727 }
728 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400729 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
730 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500731 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
732 }
733 // Send the request to the adapter
734 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
735 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
736 return nil, err
737 }
738 }
739 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
740}
741
742// isImageRegistered is a helper method to figure out if an image is already registered
743func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
744 for _, image := range device.ImageDownloads {
745 if image.Id == img.Id && image.Name == img.Name {
746 return true
747 }
748 }
749 return false
750}
751
752func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
753 agent.lockDevice.Lock()
754 defer agent.lockDevice.Unlock()
755 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
756 // Get the most up to date the device info
757 if device, err := agent.getDeviceWithoutLock(); err != nil {
758 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
759 } else {
760 // Verify whether the Image is in the list of image being downloaded
761 if !isImageRegistered(img, device) {
762 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
763 }
764
765 // Update image download state
766 cloned := proto.Clone(device).(*voltha.Device)
767 for _, image := range cloned.ImageDownloads {
768 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500769 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500770 }
771 }
772
khenaidoof5a5bfa2019-01-23 22:20:29 -0500773 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500774 // Set the device to Enabled
775 cloned.AdminState = voltha.AdminState_ENABLED
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400776 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
777 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500778 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
779 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400780 // Send the request to teh adapter
781 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
782 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
783 return nil, err
784 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500785 }
786 }
787 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700788}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500789
790func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
791 agent.lockDevice.Lock()
792 defer agent.lockDevice.Unlock()
793 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
794 // Get the most up to date the device info
795 if device, err := agent.getDeviceWithoutLock(); err != nil {
796 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
797 } else {
798 // Verify whether the Image is in the list of image being downloaded
799 if !isImageRegistered(img, device) {
800 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
801 }
802
803 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
804 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
805 }
806 // Update image download state
807 cloned := proto.Clone(device).(*voltha.Device)
808 for _, image := range cloned.ImageDownloads {
809 if image.Id == img.Id && image.Name == img.Name {
810 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
811 }
812 }
813 // Set the device to downloading_image
814 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400815 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
816 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500817 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
818 }
819
820 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
821 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
822 return nil, err
823 }
824 // The status of the AdminState will be changed following the update_download_status response from the adapter
825 // The image name will also be removed from the device list
826 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700827 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
828}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500829
830func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
831 agent.lockDevice.Lock()
832 defer agent.lockDevice.Unlock()
833 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
834 // Get the most up to date the device info
835 if device, err := agent.getDeviceWithoutLock(); err != nil {
836 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
837 } else {
838 // Verify whether the Image is in the list of image being downloaded
839 if !isImageRegistered(img, device) {
840 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
841 }
842
843 if device.AdminState != voltha.AdminState_ENABLED {
844 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
845 }
846 // Update image download state
847 cloned := proto.Clone(device).(*voltha.Device)
848 for _, image := range cloned.ImageDownloads {
849 if image.Id == img.Id && image.Name == img.Name {
850 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
851 }
852 }
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400853 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
854 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500855 return nil, status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
856 }
857
858 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
859 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
860 return nil, err
861 }
862 }
863 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700864}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500865
866func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
867 agent.lockDevice.Lock()
868 defer agent.lockDevice.Unlock()
869 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
870 // Get the most up to date the device info
871 if device, err := agent.getDeviceWithoutLock(); err != nil {
872 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
873 } else {
874 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
875 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
876 return nil, err
877 } else {
878 return resp, nil
879 }
880 }
881}
882
serkant.uluderya334479d2019-04-10 08:26:15 -0700883func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500884 agent.lockDevice.Lock()
885 defer agent.lockDevice.Unlock()
886 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
887 // Get the most up to date the device info
888 if device, err := agent.getDeviceWithoutLock(); err != nil {
889 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
890 } else {
891 // Update the image as well as remove it if the download was cancelled
892 cloned := proto.Clone(device).(*voltha.Device)
893 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
894 for _, image := range cloned.ImageDownloads {
895 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500896 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500897 clonedImages = append(clonedImages, img)
898 }
899 }
900 }
901 cloned.ImageDownloads = clonedImages
902 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500903 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
904 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700905 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500906 cloned.AdminState = voltha.AdminState_ENABLED
907 }
908
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400909 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
910 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500911 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
912 }
913 }
914 return nil
915}
916
917func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400918 agent.lockDevice.RLock()
919 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500920 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
921 // Get the most up to date the device info
922 if device, err := agent.getDeviceWithoutLock(); err != nil {
923 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
924 } else {
925 for _, image := range device.ImageDownloads {
926 if image.Id == img.Id && image.Name == img.Name {
927 return image, nil
928 }
929 }
930 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
931 }
932}
933
934func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400935 agent.lockDevice.RLock()
936 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500937 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
938 // Get the most up to date the device info
939 if device, err := agent.getDeviceWithoutLock(); err != nil {
940 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
941 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700942 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500943 }
944}
945
khenaidoo4d4802d2018-10-04 21:59:49 -0400946// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400947func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
948 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400949 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400950 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400951 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400952 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400953 ports.Items = append(ports.Items, port)
954 }
955 }
956 }
957 return ports
958}
959
khenaidoo4d4802d2018-10-04 21:59:49 -0400960// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
961// parent device
khenaidoo79232702018-12-04 11:00:41 -0500962func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400963 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400964 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400965 return nil, err
966 } else {
khenaidoo79232702018-12-04 11:00:41 -0500967 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400968 var err error
969 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
970 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
971 return nil, err
972 }
973 return switchCap, nil
974 }
975}
976
khenaidoo4d4802d2018-10-04 21:59:49 -0400977// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
978// device
khenaidoo79232702018-12-04 11:00:41 -0500979func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400980 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400981 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400982 return nil, err
983 } else {
khenaidoo79232702018-12-04 11:00:41 -0500984 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400985 var err error
986 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
987 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
988 return nil, err
989 }
990 return portCap, nil
991 }
992}
993
khenaidoofdbad6e2018-11-06 22:26:38 -0500994func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
995 // Send packet to adapter
996 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
997 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
998 return err
999 }
1000 return nil
1001}
1002
khenaidoo4d4802d2018-10-04 21:59:49 -04001003// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001004func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001005 //// Run this callback in its own go routine
1006 go func(args ...interface{}) interface{} {
1007 var previous *voltha.Device
1008 var current *voltha.Device
1009 var ok bool
1010 if len(args) == 2 {
1011 if previous, ok = args[0].(*voltha.Device); !ok {
1012 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1013 return nil
1014 }
1015 if current, ok = args[1].(*voltha.Device); !ok {
1016 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1017 return nil
1018 }
1019 } else {
1020 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1021 return nil
1022 }
1023 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001024 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1025 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1026 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1027 }
khenaidoo43c82122018-11-22 18:38:28 -05001028 return nil
1029 }(args...)
1030
khenaidoo92e62c52018-10-03 14:02:54 -04001031 return nil
1032}
1033
khenaidoob9203542018-09-17 22:56:37 -04001034func (agent *DeviceAgent) updateDevice(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001035 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001036 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001037 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo43c82122018-11-22 18:38:28 -05001038 cloned := proto.Clone(device).(*voltha.Device)
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001039 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1040 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+device.Id, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001041 if afterUpdate == nil {
1042 return status.Errorf(codes.Internal, "%s", device.Id)
khenaidoob9203542018-09-17 22:56:37 -04001043 }
khenaidoo43c82122018-11-22 18:38:28 -05001044 return nil
1045}
1046
1047func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1048 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1049 cloned := proto.Clone(device).(*voltha.Device)
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001050 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1051 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+device.Id, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001052 if afterUpdate == nil {
1053 return status.Errorf(codes.Internal, "%s", device.Id)
1054 }
1055 return nil
khenaidoob9203542018-09-17 22:56:37 -04001056}
1057
khenaidoo92e62c52018-10-03 14:02:54 -04001058func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1059 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001060 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001061 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001062 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001063 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1064 } else {
1065 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001066 cloned := proto.Clone(storeDevice).(*voltha.Device)
1067 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1068 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1069 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1070 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001071 }
khenaidoo92e62c52018-10-03 14:02:54 -04001072 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1073 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1074 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001075 }
khenaidoo92e62c52018-10-03 14:02:54 -04001076 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001077 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001078 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1079 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001080 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1081 }
khenaidoo92e62c52018-10-03 14:02:54 -04001082 return nil
1083 }
1084}
1085
khenaidoo3ab34882019-05-02 21:33:30 -04001086func (agent *DeviceAgent) enablePorts() error {
1087 agent.lockDevice.Lock()
1088 defer agent.lockDevice.Unlock()
1089 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1090 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1091 } else {
1092 // clone the device
1093 cloned := proto.Clone(storeDevice).(*voltha.Device)
1094 for _, port := range cloned.Ports {
1095 port.AdminState = voltha.AdminState_ENABLED
1096 port.OperStatus = voltha.OperStatus_ACTIVE
1097 }
1098 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001099 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1100 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo3ab34882019-05-02 21:33:30 -04001101 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1102 }
1103 return nil
1104 }
1105}
1106
1107func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001108 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001109 agent.lockDevice.Lock()
1110 defer agent.lockDevice.Unlock()
1111 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1112 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1113 } else {
1114 // clone the device
1115 cloned := proto.Clone(storeDevice).(*voltha.Device)
1116 for _, port := range cloned.Ports {
1117 port.AdminState = voltha.AdminState_DISABLED
1118 port.OperStatus = voltha.OperStatus_UNKNOWN
1119 }
1120 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001121 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1122 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo3ab34882019-05-02 21:33:30 -04001123 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1124 }
1125 return nil
1126 }
1127}
1128
khenaidoo92e62c52018-10-03 14:02:54 -04001129func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1130 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001131 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001132 // Work only on latest data
1133 // TODO: Get list of ports from device directly instead of the entire device
1134 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001135 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1136 } else {
1137 // clone the device
1138 cloned := proto.Clone(storeDevice).(*voltha.Device)
1139 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1140 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001141 return status.Errorf(codes.InvalidArgument, "%s", portType)
1142 }
1143 for _, port := range cloned.Ports {
1144 if port.Type == portType && port.PortNo == portNo {
1145 port.OperStatus = operStatus
1146 // Set the admin status to ENABLED if the operational status is ACTIVE
1147 // TODO: Set by northbound system?
1148 if operStatus == voltha.OperStatus_ACTIVE {
1149 port.AdminState = voltha.AdminState_ENABLED
1150 }
1151 break
1152 }
1153 }
1154 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1155 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001156 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1157 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001158 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1159 }
khenaidoob9203542018-09-17 22:56:37 -04001160 return nil
1161 }
1162}
1163
khenaidoo0a822f92019-05-08 15:15:57 -04001164func (agent *DeviceAgent) deleteAllPorts() error {
1165 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1166 agent.lockDevice.Lock()
1167 defer agent.lockDevice.Unlock()
1168 // Work only on latest data
1169 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1170 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1171 } else {
1172 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1173 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1174 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1175 return err
1176 }
1177 if len(storeDevice.Ports) == 0 {
1178 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1179 return nil
1180 }
1181 // clone the device & set the fields to empty
1182 cloned := proto.Clone(storeDevice).(*voltha.Device)
1183 cloned.Ports = []*voltha.Port{}
1184 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1185 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001186 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1187 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoo0a822f92019-05-08 15:15:57 -04001188 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1189 }
1190 return nil
1191 }
1192}
1193
khenaidoob9203542018-09-17 22:56:37 -04001194func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001195 agent.lockDevice.Lock()
1196 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001197 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001198 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001199 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001200 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1201 } else {
1202 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001203 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001204 if cloned.Ports == nil {
1205 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001206 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001207 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001208 } else {
1209 for _, p := range cloned.Ports {
1210 if p.Type == port.Type && p.PortNo == port.PortNo {
1211 log.Debugw("port already exists", log.Fields{"port": *port})
1212 return nil
1213 }
1214 }
khenaidoob9203542018-09-17 22:56:37 -04001215 }
khenaidoo92e62c52018-10-03 14:02:54 -04001216 cp := proto.Clone(port).(*voltha.Port)
1217 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1218 // TODO: Set by northbound system?
1219 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1220 cp.AdminState = voltha.AdminState_ENABLED
1221 }
1222 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001223 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001224 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1225 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001226 if afterUpdate == nil {
1227 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1228 }
1229 return nil
1230 }
1231}
1232
1233func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1234 agent.lockDevice.Lock()
1235 defer agent.lockDevice.Unlock()
1236 log.Debug("addPeerPort")
1237 // Work only on latest data
1238 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1239 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1240 } else {
1241 // clone the device
1242 cloned := proto.Clone(storeDevice).(*voltha.Device)
1243 // Get the peer port on the device based on the port no
1244 for _, peerPort := range cloned.Ports {
1245 if peerPort.PortNo == port.PortNo { // found port
1246 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1247 peerPort.Peers = append(peerPort.Peers, cp)
1248 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1249 break
1250 }
1251 }
1252 // Store the device
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001253 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1254 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001255 if afterUpdate == nil {
1256 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1257 }
1258 return nil
1259 }
1260}
1261
khenaidoo0a822f92019-05-08 15:15:57 -04001262func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1263 agent.lockDevice.Lock()
1264 defer agent.lockDevice.Unlock()
1265 log.Debug("deletePeerPorts")
1266 // Work only on latest data
1267 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1268 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1269 } else {
1270 // clone the device
1271 cloned := proto.Clone(storeDevice).(*voltha.Device)
1272 var updatedPeers []*voltha.Port_PeerPort
1273 for _, port := range cloned.Ports {
1274 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1275 for _, peerPort := range port.Peers {
1276 if peerPort.DeviceId != deviceId {
1277 updatedPeers = append(updatedPeers, peerPort)
1278 }
1279 }
1280 port.Peers = updatedPeers
1281 }
1282
1283 // Store the device with updated peer ports
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001284 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1285 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001286 if afterUpdate == nil {
1287 return status.Errorf(codes.Internal, "%s", agent.deviceId)
1288 }
1289 return nil
1290 }
1291}
1292
khenaidoob9203542018-09-17 22:56:37 -04001293// TODO: A generic device update by attribute
1294func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001295 agent.lockDevice.Lock()
1296 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001297 if value == nil {
1298 return
1299 }
1300 var storeDevice *voltha.Device
1301 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001302 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001303 return
1304 }
1305 updated := false
1306 s := reflect.ValueOf(storeDevice).Elem()
1307 if s.Kind() == reflect.Struct {
1308 // exported field
1309 f := s.FieldByName(name)
1310 if f.IsValid() && f.CanSet() {
1311 switch f.Kind() {
1312 case reflect.String:
1313 f.SetString(value.(string))
1314 updated = true
1315 case reflect.Uint32:
1316 f.SetUint(uint64(value.(uint32)))
1317 updated = true
1318 case reflect.Bool:
1319 f.SetBool(value.(bool))
1320 updated = true
1321 }
1322 }
1323 }
khenaidoo92e62c52018-10-03 14:02:54 -04001324 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001325 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001326 cloned := proto.Clone(storeDevice).(*voltha.Device)
Stephane Barbarieef6650d2019-07-18 12:15:09 -04001327 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1328 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, ""); afterUpdate == nil {
khenaidoob9203542018-09-17 22:56:37 -04001329 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1330 }
1331 return
1332}
serkant.uluderya334479d2019-04-10 08:26:15 -07001333
1334func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1335 agent.lockDevice.Lock()
1336 defer agent.lockDevice.Unlock()
1337 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1338 // Get the most up to date the device info
1339 if device, err := agent.getDeviceWithoutLock(); err != nil {
1340 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1341 } else {
1342 // First send the request to an Adapter and wait for a response
1343 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1344 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1345 return err
1346 }
1347 }
1348 return nil
1349}