blob: 89b1fe9d9c713dba95197b4c908607c7e142b322 [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 }
khenaidooc3224532019-09-05 21:04:54 -040098 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -050099 } 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})
khenaidooc3224532019-09-05 21:04:54 -0400103 return status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -0500104 }
khenaidoob9203542018-09-17 22:56:37 -0400105 }
khenaidoo297cd252019-02-07 22:10:23 -0500106
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400107 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500108 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400109
khenaidooc3224532019-09-05 21:04:54 -0400110 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500111 return nil
khenaidoob9203542018-09-17 22:56:37 -0400112}
113
khenaidoo4d4802d2018-10-04 21:59:49 -0400114// stop stops the device agent. Not much to do for now
115func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400116 agent.lockDevice.Lock()
117 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400118 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400119 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400120 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400121 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400122 }
khenaidoob9203542018-09-17 22:56:37 -0400123 agent.exitChannel <- 1
124 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400125
khenaidoob9203542018-09-17 22:56:37 -0400126}
127
khenaidoo19d7b632018-10-30 10:49:50 -0400128// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400129func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400130 agent.lockDevice.RLock()
131 defer agent.lockDevice.RUnlock()
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400132 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, true, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400133 if d, ok := device.(*voltha.Device); ok {
134 cloned := proto.Clone(d).(*voltha.Device)
135 return cloned, nil
136 }
137 }
138 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
139}
140
khenaidoo4d4802d2018-10-04 21:59:49 -0400141// 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 -0400142// This function is meant so that we do not have duplicate code all over the device agent functions
143func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400144 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400145 if d, ok := device.(*voltha.Device); ok {
146 cloned := proto.Clone(d).(*voltha.Device)
147 return cloned, nil
148 }
149 }
150 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
151}
152
khenaidoo3ab34882019-05-02 21:33:30 -0400153// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400154func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400155 agent.lockDevice.Lock()
156 defer agent.lockDevice.Unlock()
157 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500158
khenaidoo92e62c52018-10-03 14:02:54 -0400159 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400160 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
161 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500162 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
163 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
164 // with the adapter then we need to know the adapter that will handle this request
165 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
166 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
167 return err
168 } else {
169 device.Adapter = adapterName
170 }
171
khenaidoo92e62c52018-10-03 14:02:54 -0400172 if device.AdminState == voltha.AdminState_ENABLED {
173 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400174 return nil
175 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400176
177 if device.AdminState == voltha.AdminState_DELETED {
178 // This is a temporary state when a device is deleted before it gets removed from the model.
179 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
180 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
181 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400182 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400183
184 previousAdminState := device.AdminState
185
186 // Update the Admin State and set the operational state to activating before sending the request to the
187 // Adapters
188 cloned := proto.Clone(device).(*voltha.Device)
189 cloned.AdminState = voltha.AdminState_ENABLED
190 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400191
Mahir Gunyelb5851672019-07-24 10:46:26 +0300192 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
193 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400194 }
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
Manikkaraj kb1a10922019-07-29 12:10:34 -0400219func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
220 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400221 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
222 ch <- err
223 }
224 ch <- nil
225}
226
Manikkaraj kb1a10922019-07-29 12:10:34 -0400227func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
228 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400229 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
Manikkaraj kb1a10922019-07-29 12:10:34 -0400237func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
238 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400239
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 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400306 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400307
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 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400318 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400319 }
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 {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400327 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400328 return status.Errorf(codes.Aborted, "errors-%s", res)
329 }
330
331 return nil
332}
333
334//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
335//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400336func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400337 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
338
339 if (len(flowsToDel) | len(groupsToDel)) == 0 {
340 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
341 return nil
342 }
343
344 agent.lockDevice.Lock()
345 defer agent.lockDevice.Unlock()
346
347 var device *voltha.Device
348 var err error
349
350 if device, err = agent.getDeviceWithoutLock(); err != nil {
351 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
352 }
353
354 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
355 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
356
357 var flowsToKeep []*ofp.OfpFlowStats
358 var groupsToKeep []*ofp.OfpGroupEntry
359
360 // Process flows
361 for _, flow := range existingFlows.Items {
362 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
363 flowsToKeep = append(flowsToKeep, flow)
364 }
365 }
366
367 // Process groups
368 for _, group := range existingGroups.Items {
369 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
370 groupsToKeep = append(groupsToKeep, group)
371 }
372 }
373
374 log.Debugw("deleteFlowsAndGroups",
375 log.Fields{
376 "deviceId": agent.deviceId,
377 "flowsToDel": len(flowsToDel),
378 "flowsToKeep": len(flowsToKeep),
379 "groupsToDel": len(groupsToDel),
380 "groupsToKeep": len(groupsToKeep),
381 })
382
383 // Sanity check
384 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
385 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
386 return nil
387 }
388
389 // Send update to adapters
390 chAdapters := make(chan interface{})
391 chdB := make(chan interface{})
392 dType := agent.adapterMgr.getDeviceType(device.Type)
393 if !dType.AcceptsAddRemoveFlowUpdates {
394 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
395 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
396 return nil
397 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400398 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400399 } else {
400 flowChanges := &ofp.FlowChanges{
401 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
402 ToRemove: &voltha.Flows{Items: flowsToDel},
403 }
404 groupChanges := &ofp.FlowGroupChanges{
405 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
406 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
407 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
408 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400409 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400410 }
411
412 // store the changed data
413 device.Flows = &voltha.Flows{Items: flowsToKeep}
414 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
415 go agent.updateDeviceWithoutLockAsync(device, chdB)
416
417 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
418 return status.Errorf(codes.Aborted, "errors-%s", res)
419 }
420 return nil
421
422}
423
424//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
425//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400426func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400427 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
428
429 if (len(updatedFlows) | len(updatedGroups)) == 0 {
430 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
431 return nil
432 }
433
434 agent.lockDevice.Lock()
435 defer agent.lockDevice.Unlock()
436 var device *voltha.Device
437 var err error
438 if device, err = agent.getDeviceWithoutLock(); err != nil {
439 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
440 }
441 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
442 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
443
444 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
445 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
446 return nil
447 }
448
449 log.Debugw("updating-flows-and-groups",
450 log.Fields{
451 "deviceId": agent.deviceId,
452 "updatedFlows": updatedFlows,
453 "updatedGroups": updatedGroups,
454 })
455
456 chAdapters := make(chan interface{})
457 chdB := make(chan interface{})
458 dType := agent.adapterMgr.getDeviceType(device.Type)
459
460 // Process bulk flow update differently than incremental update
461 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400462 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400463 } else {
464 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400465 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400466 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400467 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400468
469 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400470 for _, flow := range updatedFlows {
471 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
472 flowsToAdd = append(flowsToAdd, flow)
473 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400474 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400475 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400476 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400477 flowsToDelete = append(flowsToDelete, flow)
478 }
479 }
480
481 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400482 for _, g := range updatedGroups {
483 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
484 groupsToAdd = append(groupsToAdd, g)
485 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400486 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400487 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400488 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400489 groupsToDelete = append(groupsToDelete, group)
490 }
491 }
492
khenaidoo0458db62019-06-20 08:50:36 -0400493 log.Debugw("updating-flows-and-groups",
494 log.Fields{
495 "deviceId": agent.deviceId,
496 "flowsToAdd": flowsToAdd,
497 "flowsToDelete": flowsToDelete,
498 "groupsToAdd": groupsToAdd,
499 "groupsToDelete": groupsToDelete,
500 })
501
khenaidoo2c6a0992019-04-29 13:46:56 -0400502 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400503 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
504 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400505 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400506 }
507
khenaidoo0458db62019-06-20 08:50:36 -0400508 flowChanges := &ofp.FlowChanges{
509 ToAdd: &voltha.Flows{Items: flowsToAdd},
510 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400511 }
khenaidoo0458db62019-06-20 08:50:36 -0400512 groupChanges := &ofp.FlowGroupChanges{
513 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
514 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
515 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
516 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400517 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400518 }
khenaidoo0458db62019-06-20 08:50:36 -0400519
520 // store the updated data
521 device.Flows = &voltha.Flows{Items: updatedFlows}
522 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
523 go agent.updateDeviceWithoutLockAsync(device, chdB)
524
525 if res := fu.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
526 return status.Errorf(codes.Aborted, "errors-%s", res)
527 }
528 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400529}
530
khenaidoo4d4802d2018-10-04 21:59:49 -0400531//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400532func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400533 agent.lockDevice.Lock()
534 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400535 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
536 // Get the most up to date the device info
537 if device, err := agent.getDeviceWithoutLock(); err != nil {
538 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
539 } else {
540 if device.AdminState == voltha.AdminState_DISABLED {
541 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400542 return nil
543 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400544 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
545 device.AdminState == voltha.AdminState_DELETED {
546 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
547 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
548 }
549
khenaidoo59ef7be2019-06-21 12:40:28 -0400550 // Update the Admin State and operational state before sending the request out
551 cloned := proto.Clone(device).(*voltha.Device)
552 cloned.AdminState = voltha.AdminState_DISABLED
553 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300554 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
555 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400556 }
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
Mahir Gunyelb5851672019-07-24 10:46:26 +0300581 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
582 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400583 }
khenaidoo92e62c52018-10-03 14:02:54 -0400584 }
585 return nil
586}
587
khenaidoo4d4802d2018-10-04 21:59:49 -0400588func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
589 agent.lockDevice.Lock()
590 defer agent.lockDevice.Unlock()
591 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
592 // Get the most up to date the device info
593 if device, err := agent.getDeviceWithoutLock(); err != nil {
594 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
595 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400596 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
597 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
598 return err
599 }
600 }
601 return nil
602}
603
604func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
605 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400606 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400607 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
608 // Get the most up to date the device info
609 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400610 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
611 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400612 if device.AdminState == voltha.AdminState_DELETED {
613 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
614 return nil
615 }
khenaidoo43c82122018-11-22 18:38:28 -0500616 if (device.AdminState != voltha.AdminState_DISABLED) &&
617 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400618 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
619 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400620 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
621 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400622 if device.AdminState != voltha.AdminState_PREPROVISIONED {
623 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
624 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
625 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
626 return err
627 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400628 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400629 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
630 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400631 cloned := proto.Clone(device).(*voltha.Device)
632 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300633 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
634 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400635 }
khenaidoo0a822f92019-05-08 15:15:57 -0400636 // If this is a child device then remove the associated peer ports on the parent device
637 if !device.Root {
638 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
639 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400640 }
641 return nil
642}
643
khenaidoob3127472019-07-24 21:04:55 -0400644func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
645 agent.lockDevice.Lock()
646 defer agent.lockDevice.Unlock()
647 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
648 // Work only on latest data
649 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
650 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
651 } else {
652 // clone the device
653 cloned := proto.Clone(storeDevice).(*voltha.Device)
654 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
655 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300656 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
657 return err
khenaidoob3127472019-07-24 21:04:55 -0400658 }
659 // Send the request to the adapter
660 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
661 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
662 return err
663 }
664 return nil
665 }
666}
667
668func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
669 agent.lockDevice.Lock()
670 defer agent.lockDevice.Unlock()
671 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
672 // Work only on latest data
673 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
674 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
675 } else {
676 // clone the device
677 cloned := proto.Clone(storeDevice).(*voltha.Device)
678 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
679 // Store the device
680 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
681 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
682 if afterUpdate == nil {
683 return status.Errorf(codes.Internal, "%s", agent.deviceId)
684 }
685 return nil
686 }
687}
688
689func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
690 agent.lockDevice.RLock()
691 defer agent.lockDevice.RUnlock()
692 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
693 // Get the most up to date the device info
694 if device, err := agent.getDeviceWithoutLock(); err != nil {
695 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
696 } else {
697 cloned := proto.Clone(device).(*voltha.Device)
698 return cloned.PmConfigs, nil
699 }
700}
701
khenaidoof5a5bfa2019-01-23 22:20:29 -0500702func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
703 agent.lockDevice.Lock()
704 defer agent.lockDevice.Unlock()
705 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
706 // Get the most up to date the device info
707 if device, err := agent.getDeviceWithoutLock(); err != nil {
708 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
709 } else {
710 if device.AdminState != voltha.AdminState_ENABLED {
711 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
712 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
713 }
714 // Save the image
715 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500716 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500717 cloned := proto.Clone(device).(*voltha.Device)
718 if cloned.ImageDownloads == nil {
719 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
720 } else {
721 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
722 }
723 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300724 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
725 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500726 }
727 // Send the request to the adapter
728 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
729 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
730 return nil, err
731 }
732 }
733 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
734}
735
736// isImageRegistered is a helper method to figure out if an image is already registered
737func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
738 for _, image := range device.ImageDownloads {
739 if image.Id == img.Id && image.Name == img.Name {
740 return true
741 }
742 }
743 return false
744}
745
746func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
747 agent.lockDevice.Lock()
748 defer agent.lockDevice.Unlock()
749 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
750 // Get the most up to date the device info
751 if device, err := agent.getDeviceWithoutLock(); err != nil {
752 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
753 } else {
754 // Verify whether the Image is in the list of image being downloaded
755 if !isImageRegistered(img, device) {
756 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
757 }
758
759 // Update image download state
760 cloned := proto.Clone(device).(*voltha.Device)
761 for _, image := range cloned.ImageDownloads {
762 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500763 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500764 }
765 }
766
khenaidoof5a5bfa2019-01-23 22:20:29 -0500767 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500768 // Set the device to Enabled
769 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300770 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
771 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500772 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400773 // Send the request to teh adapter
774 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
775 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
776 return nil, err
777 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500778 }
779 }
780 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700781}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500782
783func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
784 agent.lockDevice.Lock()
785 defer agent.lockDevice.Unlock()
786 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
787 // Get the most up to date the device info
788 if device, err := agent.getDeviceWithoutLock(); err != nil {
789 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
790 } else {
791 // Verify whether the Image is in the list of image being downloaded
792 if !isImageRegistered(img, device) {
793 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
794 }
795
796 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
797 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
798 }
799 // Update image download state
800 cloned := proto.Clone(device).(*voltha.Device)
801 for _, image := range cloned.ImageDownloads {
802 if image.Id == img.Id && image.Name == img.Name {
803 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
804 }
805 }
806 // Set the device to downloading_image
807 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300808 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
809 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500810 }
811
812 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
813 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
814 return nil, err
815 }
816 // The status of the AdminState will be changed following the update_download_status response from the adapter
817 // The image name will also be removed from the device list
818 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700819 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
820}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500821
822func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
823 agent.lockDevice.Lock()
824 defer agent.lockDevice.Unlock()
825 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
826 // Get the most up to date the device info
827 if device, err := agent.getDeviceWithoutLock(); err != nil {
828 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
829 } else {
830 // Verify whether the Image is in the list of image being downloaded
831 if !isImageRegistered(img, device) {
832 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
833 }
834
835 if device.AdminState != voltha.AdminState_ENABLED {
836 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
837 }
838 // Update image download state
839 cloned := proto.Clone(device).(*voltha.Device)
840 for _, image := range cloned.ImageDownloads {
841 if image.Id == img.Id && image.Name == img.Name {
842 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
843 }
844 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300845
846 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
847 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500848 }
849
850 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
851 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
852 return nil, err
853 }
854 }
855 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700856}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500857
858func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
859 agent.lockDevice.Lock()
860 defer agent.lockDevice.Unlock()
861 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
862 // Get the most up to date the device info
863 if device, err := agent.getDeviceWithoutLock(); err != nil {
864 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
865 } else {
866 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
867 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
868 return nil, err
869 } else {
870 return resp, nil
871 }
872 }
873}
874
serkant.uluderya334479d2019-04-10 08:26:15 -0700875func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500876 agent.lockDevice.Lock()
877 defer agent.lockDevice.Unlock()
878 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
879 // Get the most up to date the device info
880 if device, err := agent.getDeviceWithoutLock(); err != nil {
881 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
882 } else {
883 // Update the image as well as remove it if the download was cancelled
884 cloned := proto.Clone(device).(*voltha.Device)
885 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
886 for _, image := range cloned.ImageDownloads {
887 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500888 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500889 clonedImages = append(clonedImages, img)
890 }
891 }
892 }
893 cloned.ImageDownloads = clonedImages
894 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500895 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
896 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700897 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500898 cloned.AdminState = voltha.AdminState_ENABLED
899 }
900
Mahir Gunyelb5851672019-07-24 10:46:26 +0300901 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
902 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500903 }
904 }
905 return nil
906}
907
908func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400909 agent.lockDevice.RLock()
910 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500911 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
912 // Get the most up to date the device info
913 if device, err := agent.getDeviceWithoutLock(); err != nil {
914 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
915 } else {
916 for _, image := range device.ImageDownloads {
917 if image.Id == img.Id && image.Name == img.Name {
918 return image, nil
919 }
920 }
921 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
922 }
923}
924
925func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400926 agent.lockDevice.RLock()
927 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500928 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
929 // Get the most up to date the device info
930 if device, err := agent.getDeviceWithoutLock(); err != nil {
931 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
932 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700933 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500934 }
935}
936
khenaidoo4d4802d2018-10-04 21:59:49 -0400937// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400938func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
939 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400940 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400941 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400942 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400943 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400944 ports.Items = append(ports.Items, port)
945 }
946 }
947 }
948 return ports
949}
950
khenaidoo4d4802d2018-10-04 21:59:49 -0400951// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
952// parent device
khenaidoo79232702018-12-04 11:00:41 -0500953func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400954 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400955 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400956 return nil, err
957 } else {
khenaidoo79232702018-12-04 11:00:41 -0500958 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400959 var err error
960 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
961 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
962 return nil, err
963 }
964 return switchCap, nil
965 }
966}
967
khenaidoo4d4802d2018-10-04 21:59:49 -0400968// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
969// device
khenaidoo79232702018-12-04 11:00:41 -0500970func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400971 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400972 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400973 return nil, err
974 } else {
khenaidoo79232702018-12-04 11:00:41 -0500975 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400976 var err error
977 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
978 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
979 return nil, err
980 }
981 return portCap, nil
982 }
983}
984
khenaidoofdbad6e2018-11-06 22:26:38 -0500985func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
986 // Send packet to adapter
987 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
988 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
989 return err
990 }
991 return nil
992}
993
khenaidoo4d4802d2018-10-04 21:59:49 -0400994// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -0400995func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -0500996 //// Run this callback in its own go routine
997 go func(args ...interface{}) interface{} {
998 var previous *voltha.Device
999 var current *voltha.Device
1000 var ok bool
1001 if len(args) == 2 {
1002 if previous, ok = args[0].(*voltha.Device); !ok {
1003 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1004 return nil
1005 }
1006 if current, ok = args[1].(*voltha.Device); !ok {
1007 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1008 return nil
1009 }
1010 } else {
1011 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1012 return nil
1013 }
1014 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001015 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1016 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1017 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1018 }
khenaidoo43c82122018-11-22 18:38:28 -05001019 return nil
1020 }(args...)
1021
khenaidoo92e62c52018-10-03 14:02:54 -04001022 return nil
1023}
1024
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001025// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1026// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1027func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1028 // First retrieve the most up to date device info
1029 var currentDevice *voltha.Device
1030 var err error
1031 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1032 return nil, err
1033 }
1034 cloned := proto.Clone(currentDevice).(*voltha.Device)
1035 cloned.Root = device.Root
1036 cloned.Vendor = device.Vendor
1037 cloned.Model = device.Model
1038 cloned.SerialNumber = device.SerialNumber
1039 cloned.MacAddress = device.MacAddress
1040 cloned.Vlan = device.Vlan
1041 cloned.Reason = device.Reason
1042 return cloned, nil
1043}
1044func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001045 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001046 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001047 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1048 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1049 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1050 return status.Errorf(codes.Internal, "%s", err.Error())
1051 } else {
1052 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1053 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1054 }
khenaidoo43c82122018-11-22 18:38:28 -05001055}
1056
1057func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1058 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1059 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001060 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001061}
1062
khenaidoo92e62c52018-10-03 14:02:54 -04001063func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1064 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001065 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001066 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001067 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001068 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1069 } else {
1070 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001071 cloned := proto.Clone(storeDevice).(*voltha.Device)
1072 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1073 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1074 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1075 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001076 }
khenaidoo92e62c52018-10-03 14:02:54 -04001077 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1078 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1079 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001080 }
khenaidoo92e62c52018-10-03 14:02:54 -04001081 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001082 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001083 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001084 }
1085}
1086
khenaidoo3ab34882019-05-02 21:33:30 -04001087func (agent *DeviceAgent) enablePorts() error {
1088 agent.lockDevice.Lock()
1089 defer agent.lockDevice.Unlock()
1090 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1091 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1092 } else {
1093 // clone the device
1094 cloned := proto.Clone(storeDevice).(*voltha.Device)
1095 for _, port := range cloned.Ports {
1096 port.AdminState = voltha.AdminState_ENABLED
1097 port.OperStatus = voltha.OperStatus_ACTIVE
1098 }
1099 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001100 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001101 }
1102}
1103
1104func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001105 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001106 agent.lockDevice.Lock()
1107 defer agent.lockDevice.Unlock()
1108 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1109 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1110 } else {
1111 // clone the device
1112 cloned := proto.Clone(storeDevice).(*voltha.Device)
1113 for _, port := range cloned.Ports {
1114 port.AdminState = voltha.AdminState_DISABLED
1115 port.OperStatus = voltha.OperStatus_UNKNOWN
1116 }
1117 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001118 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001119 }
1120}
1121
khenaidoo92e62c52018-10-03 14:02:54 -04001122func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1123 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001124 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001125 // Work only on latest data
1126 // TODO: Get list of ports from device directly instead of the entire device
1127 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001128 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1129 } else {
1130 // clone the device
1131 cloned := proto.Clone(storeDevice).(*voltha.Device)
1132 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1133 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001134 return status.Errorf(codes.InvalidArgument, "%s", portType)
1135 }
1136 for _, port := range cloned.Ports {
1137 if port.Type == portType && port.PortNo == portNo {
1138 port.OperStatus = operStatus
1139 // Set the admin status to ENABLED if the operational status is ACTIVE
1140 // TODO: Set by northbound system?
1141 if operStatus == voltha.OperStatus_ACTIVE {
1142 port.AdminState = voltha.AdminState_ENABLED
1143 }
1144 break
1145 }
1146 }
1147 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1148 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001149 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001150 }
1151}
1152
khenaidoo0a822f92019-05-08 15:15:57 -04001153func (agent *DeviceAgent) deleteAllPorts() error {
1154 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1155 agent.lockDevice.Lock()
1156 defer agent.lockDevice.Unlock()
1157 // Work only on latest data
1158 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1159 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1160 } else {
1161 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1162 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1163 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1164 return err
1165 }
1166 if len(storeDevice.Ports) == 0 {
1167 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1168 return nil
1169 }
1170 // clone the device & set the fields to empty
1171 cloned := proto.Clone(storeDevice).(*voltha.Device)
1172 cloned.Ports = []*voltha.Port{}
1173 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1174 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001175 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001176 }
1177}
1178
khenaidoob9203542018-09-17 22:56:37 -04001179func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001180 agent.lockDevice.Lock()
1181 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001182 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001183 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001184 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001185 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1186 } else {
1187 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001188 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001189 if cloned.Ports == nil {
1190 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001191 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001192 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001193 } else {
1194 for _, p := range cloned.Ports {
1195 if p.Type == port.Type && p.PortNo == port.PortNo {
1196 log.Debugw("port already exists", log.Fields{"port": *port})
1197 return nil
1198 }
1199 }
khenaidoob9203542018-09-17 22:56:37 -04001200 }
khenaidoo92e62c52018-10-03 14:02:54 -04001201 cp := proto.Clone(port).(*voltha.Port)
1202 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1203 // TODO: Set by northbound system?
1204 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1205 cp.AdminState = voltha.AdminState_ENABLED
1206 }
1207 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001208 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001209 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001210 }
1211}
1212
1213func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1214 agent.lockDevice.Lock()
1215 defer agent.lockDevice.Unlock()
1216 log.Debug("addPeerPort")
1217 // Work only on latest data
1218 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1219 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1220 } else {
1221 // clone the device
1222 cloned := proto.Clone(storeDevice).(*voltha.Device)
1223 // Get the peer port on the device based on the port no
1224 for _, peerPort := range cloned.Ports {
1225 if peerPort.PortNo == port.PortNo { // found port
1226 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1227 peerPort.Peers = append(peerPort.Peers, cp)
1228 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1229 break
1230 }
1231 }
1232 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001233 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001234 }
1235}
1236
khenaidoo0a822f92019-05-08 15:15:57 -04001237func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1238 agent.lockDevice.Lock()
1239 defer agent.lockDevice.Unlock()
1240 log.Debug("deletePeerPorts")
1241 // Work only on latest data
1242 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1243 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1244 } else {
1245 // clone the device
1246 cloned := proto.Clone(storeDevice).(*voltha.Device)
1247 var updatedPeers []*voltha.Port_PeerPort
1248 for _, port := range cloned.Ports {
1249 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1250 for _, peerPort := range port.Peers {
1251 if peerPort.DeviceId != deviceId {
1252 updatedPeers = append(updatedPeers, peerPort)
1253 }
1254 }
1255 port.Peers = updatedPeers
1256 }
1257
1258 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001259 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001260 }
1261}
1262
khenaidoob9203542018-09-17 22:56:37 -04001263// TODO: A generic device update by attribute
1264func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001265 agent.lockDevice.Lock()
1266 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001267 if value == nil {
1268 return
1269 }
1270 var storeDevice *voltha.Device
1271 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001272 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001273 return
1274 }
1275 updated := false
1276 s := reflect.ValueOf(storeDevice).Elem()
1277 if s.Kind() == reflect.Struct {
1278 // exported field
1279 f := s.FieldByName(name)
1280 if f.IsValid() && f.CanSet() {
1281 switch f.Kind() {
1282 case reflect.String:
1283 f.SetString(value.(string))
1284 updated = true
1285 case reflect.Uint32:
1286 f.SetUint(uint64(value.(uint32)))
1287 updated = true
1288 case reflect.Bool:
1289 f.SetBool(value.(bool))
1290 updated = true
1291 }
1292 }
1293 }
khenaidoo92e62c52018-10-03 14:02:54 -04001294 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001295 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001296 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001297 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001298 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1299 }
1300 return
1301}
serkant.uluderya334479d2019-04-10 08:26:15 -07001302
1303func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1304 agent.lockDevice.Lock()
1305 defer agent.lockDevice.Unlock()
1306 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1307 // Get the most up to date the device info
1308 if device, err := agent.getDeviceWithoutLock(); err != nil {
1309 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1310 } else {
1311 // First send the request to an Adapter and wait for a response
1312 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1313 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1314 return err
1315 }
1316 }
1317 return nil
1318}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001319
1320//This is an update operation to model without Lock.This function must never be invoked by another function unless the latter holds a lock on the device.
1321// It is an internal helper function.
1322func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1323 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1324 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1325 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1326 }
1327 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1328
1329 return nil
1330}