blob: 97c0b2d4787d3afa795d45f65594deffa127cbea [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"
Matteo Scandolo360605d2019-11-05 18:29:17 -080020 "encoding/hex"
khenaidoo3ab34882019-05-02 21:33:30 -040021 "fmt"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040022 "reflect"
23 "sync"
24 "time"
25
khenaidoob9203542018-09-17 22:56:37 -040026 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050027 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070028 coreutils "github.com/opencord/voltha-go/rw_core/utils"
Scott Baker807addd2019-10-24 15:16:21 -070029 fu "github.com/opencord/voltha-lib-go/v2/pkg/flows"
30 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Baker555307d2019-11-04 08:58:01 -080031 ic "github.com/opencord/voltha-protos/v2/go/inter_container"
32 ofp "github.com/opencord/voltha-protos/v2/go/openflow_13"
33 "github.com/opencord/voltha-protos/v2/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040034 "google.golang.org/grpc/codes"
35 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040036)
37
38type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040039 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040040 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050041 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040042 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040043 lastData *voltha.Device
44 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070045 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040046 deviceMgr *DeviceManager
47 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040048 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040049 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040050 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040051 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040052}
53
khenaidoo4d4802d2018-10-04 21:59:49 -040054//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
55//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040056func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040057 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040058 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040059 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050060 if cloned.Id == "" {
61 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050062 cloned.AdminState = voltha.AdminState_PREPROVISIONED
63 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
64 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050065 }
khenaidoo19d7b632018-10-30 10:49:50 -040066 if !device.GetRoot() && device.ProxyAddress != nil {
67 // Set the default vlan ID to the one specified by the parent adapter. It can be
68 // overwritten by the child adapter during a device update request
69 cloned.Vlan = device.ProxyAddress.ChannelId
70 }
khenaidoo2c6a0992019-04-29 13:46:56 -040071 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040072 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040073 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050074 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040075 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040076 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050077 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040078 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040079 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040080 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040081 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040082 return &agent
83}
84
khenaidoo297cd252019-02-07 22:10:23 -050085// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
86// it will load the data from the dB and setup teh necessary callbacks and proxies.
87func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040088 agent.lockDevice.Lock()
89 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050090 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
91 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040092 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050093 if d, ok := device.(*voltha.Device); ok {
94 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050095 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050096 }
97 } else {
98 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
99 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
100 }
khenaidoo4c9e5592019-09-09 16:20:41 -0400101 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500102 } else {
103 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400104 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500105 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
khenaidoo4c9e5592019-09-09 16:20:41 -0400106 return status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -0500107 }
khenaidoob9203542018-09-17 22:56:37 -0400108 }
khenaidoo297cd252019-02-07 22:10:23 -0500109
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400110 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500111 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400112
khenaidoo4c9e5592019-09-09 16:20:41 -0400113 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500114 return nil
khenaidoob9203542018-09-17 22:56:37 -0400115}
116
khenaidoo4d4802d2018-10-04 21:59:49 -0400117// stop stops the device agent. Not much to do for now
118func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400119 agent.lockDevice.Lock()
120 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400121 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400122 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400123 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400124 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400125 }
khenaidoob9203542018-09-17 22:56:37 -0400126 agent.exitChannel <- 1
127 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400128
khenaidoob9203542018-09-17 22:56:37 -0400129}
130
khenaidoo19d7b632018-10-30 10:49:50 -0400131// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400132func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400133 agent.lockDevice.RLock()
134 defer agent.lockDevice.RUnlock()
Stephane Barbarieb6b68c42019-10-10 16:05:13 -0400135 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400136 if d, ok := device.(*voltha.Device); ok {
137 cloned := proto.Clone(d).(*voltha.Device)
138 return cloned, nil
139 }
140 }
141 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
142}
143
khenaidoo4d4802d2018-10-04 21:59:49 -0400144// 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 -0400145// This function is meant so that we do not have duplicate code all over the device agent functions
146func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400147 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400148 if d, ok := device.(*voltha.Device); ok {
149 cloned := proto.Clone(d).(*voltha.Device)
150 return cloned, nil
151 }
152 }
153 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
154}
155
khenaidoo3ab34882019-05-02 21:33:30 -0400156// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400157func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400158 agent.lockDevice.Lock()
159 defer agent.lockDevice.Unlock()
160 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500161
khenaidoo92e62c52018-10-03 14:02:54 -0400162 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400163 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
164 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500165 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
166 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
167 // with the adapter then we need to know the adapter that will handle this request
168 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
169 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
170 return err
171 } else {
172 device.Adapter = adapterName
173 }
174
khenaidoo92e62c52018-10-03 14:02:54 -0400175 if device.AdminState == voltha.AdminState_ENABLED {
176 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400177 return nil
178 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400179
180 if device.AdminState == voltha.AdminState_DELETED {
181 // This is a temporary state when a device is deleted before it gets removed from the model.
182 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
183 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
184 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400185 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400186
187 previousAdminState := device.AdminState
188
189 // Update the Admin State and set the operational state to activating before sending the request to the
190 // Adapters
191 cloned := proto.Clone(device).(*voltha.Device)
192 cloned.AdminState = voltha.AdminState_ENABLED
193 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400194
Mahir Gunyelb5851672019-07-24 10:46:26 +0300195 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
196 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400197 }
198
199 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
200 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400201 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
202 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400203 return err
204 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400205 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400206 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
207 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
208 return err
209 }
khenaidoob9203542018-09-17 22:56:37 -0400210 }
211 }
212 return nil
213}
214
khenaidoo2c6a0992019-04-29 13:46:56 -0400215func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
216 if err := agent.updateDeviceWithoutLock(device); err != nil {
217 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400218 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400219 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400220}
221
Manikkaraj kb1a10922019-07-29 12:10:34 -0400222func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
223 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400224 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
225 ch <- err
226 }
227 ch <- nil
228}
229
Manikkaraj kb1a10922019-07-29 12:10:34 -0400230func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
231 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400232 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
233 ch <- err
234 }
235 ch <- nil
236}
237
khenaidoo0458db62019-06-20 08:50:36 -0400238//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
239//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400240func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
241 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400242
khenaidoo2c6a0992019-04-29 13:46:56 -0400243 if (len(newFlows) | len(newGroups)) == 0 {
244 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
245 return nil
246 }
247
khenaidoo19d7b632018-10-30 10:49:50 -0400248 agent.lockDevice.Lock()
249 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400250
khenaidoo0458db62019-06-20 08:50:36 -0400251 var device *voltha.Device
252 var err error
253 if device, err = agent.getDeviceWithoutLock(); err != nil {
254 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
255 }
256
257 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
258 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
259
260 var updatedFlows []*ofp.OfpFlowStats
261 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400262 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400263 var updatedGroups []*ofp.OfpGroupEntry
264
265 // Process flows
266 for _, flow := range newFlows {
267 updatedFlows = append(updatedFlows, flow)
268 }
269 for _, flow := range existingFlows.Items {
270 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400271 updatedFlows = append(updatedFlows, flow)
khenaidoo0458db62019-06-20 08:50:36 -0400272 } else {
273 flowsToDelete = append(flowsToDelete, flow)
274 }
275 }
276
277 // Process groups
278 for _, g := range newGroups {
279 updatedGroups = append(updatedGroups, g)
280 }
281 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400282 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
283 updatedGroups = append(updatedGroups, group)
284 } else {
285 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400286 }
287 }
288
289 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400290 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
khenaidoo0458db62019-06-20 08:50:36 -0400291 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
292 return nil
293 }
294
295 // Send update to adapters
296 // Create two channels to receive responses from the dB and from the adapters.
297 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
298 // to send their responses. These channels will be garbage collected once all the responses are
299 // received
300 chAdapters := make(chan interface{})
301 chdB := make(chan interface{})
302 dType := agent.adapterMgr.getDeviceType(device.Type)
303 if !dType.AcceptsAddRemoveFlowUpdates {
304
305 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
306 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
307 return nil
308 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400309 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400310
311 } else {
312 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400313 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400314 ToRemove: &voltha.Flows{Items: flowsToDelete},
315 }
316 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400317 ToAdd: &voltha.FlowGroups{Items: newGroups},
318 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400319 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
320 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400321 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400322 }
323
324 // store the changed data
325 device.Flows = &voltha.Flows{Items: updatedFlows}
326 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
327 go agent.updateDeviceWithoutLockAsync(device, chdB)
328
Scott Bakerb671a862019-10-24 10:53:40 -0700329 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400330 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400331 return status.Errorf(codes.Aborted, "errors-%s", res)
332 }
333
334 return nil
335}
336
337//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
338//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400339func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400340 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
341
342 if (len(flowsToDel) | len(groupsToDel)) == 0 {
343 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
344 return nil
345 }
346
347 agent.lockDevice.Lock()
348 defer agent.lockDevice.Unlock()
349
350 var device *voltha.Device
351 var err error
352
353 if device, err = agent.getDeviceWithoutLock(); err != nil {
354 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
355 }
356
357 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
358 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
359
360 var flowsToKeep []*ofp.OfpFlowStats
361 var groupsToKeep []*ofp.OfpGroupEntry
362
363 // Process flows
364 for _, flow := range existingFlows.Items {
365 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
366 flowsToKeep = append(flowsToKeep, flow)
367 }
368 }
369
370 // Process groups
371 for _, group := range existingGroups.Items {
372 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
373 groupsToKeep = append(groupsToKeep, group)
374 }
375 }
376
377 log.Debugw("deleteFlowsAndGroups",
378 log.Fields{
379 "deviceId": agent.deviceId,
380 "flowsToDel": len(flowsToDel),
381 "flowsToKeep": len(flowsToKeep),
382 "groupsToDel": len(groupsToDel),
383 "groupsToKeep": len(groupsToKeep),
384 })
385
386 // Sanity check
387 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
388 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
389 return nil
390 }
391
392 // Send update to adapters
393 chAdapters := make(chan interface{})
394 chdB := make(chan interface{})
395 dType := agent.adapterMgr.getDeviceType(device.Type)
396 if !dType.AcceptsAddRemoveFlowUpdates {
397 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
398 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
399 return nil
400 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400401 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400402 } else {
403 flowChanges := &ofp.FlowChanges{
404 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
405 ToRemove: &voltha.Flows{Items: flowsToDel},
406 }
407 groupChanges := &ofp.FlowGroupChanges{
408 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
409 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
410 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
411 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400412 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400413 }
414
415 // store the changed data
416 device.Flows = &voltha.Flows{Items: flowsToKeep}
417 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
418 go agent.updateDeviceWithoutLockAsync(device, chdB)
419
Scott Bakerb671a862019-10-24 10:53:40 -0700420 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400421 return status.Errorf(codes.Aborted, "errors-%s", res)
422 }
423 return nil
424
425}
426
427//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
428//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400429func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400430 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
431
432 if (len(updatedFlows) | len(updatedGroups)) == 0 {
433 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
434 return nil
435 }
436
437 agent.lockDevice.Lock()
438 defer agent.lockDevice.Unlock()
439 var device *voltha.Device
440 var err error
441 if device, err = agent.getDeviceWithoutLock(); err != nil {
442 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
443 }
444 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
445 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
446
447 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
448 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
449 return nil
450 }
451
452 log.Debugw("updating-flows-and-groups",
453 log.Fields{
454 "deviceId": agent.deviceId,
455 "updatedFlows": updatedFlows,
456 "updatedGroups": updatedGroups,
457 })
458
459 chAdapters := make(chan interface{})
460 chdB := make(chan interface{})
461 dType := agent.adapterMgr.getDeviceType(device.Type)
462
463 // Process bulk flow update differently than incremental update
464 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400465 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400466 } else {
467 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400468 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400469 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400470 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400471
472 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400473 for _, flow := range updatedFlows {
474 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
475 flowsToAdd = append(flowsToAdd, flow)
476 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400477 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400478 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400479 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400480 flowsToDelete = append(flowsToDelete, flow)
481 }
482 }
483
484 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400485 for _, g := range updatedGroups {
486 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
487 groupsToAdd = append(groupsToAdd, g)
488 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400489 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400490 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400491 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400492 groupsToDelete = append(groupsToDelete, group)
493 }
494 }
495
khenaidoo0458db62019-06-20 08:50:36 -0400496 log.Debugw("updating-flows-and-groups",
497 log.Fields{
498 "deviceId": agent.deviceId,
499 "flowsToAdd": flowsToAdd,
500 "flowsToDelete": flowsToDelete,
501 "groupsToAdd": groupsToAdd,
502 "groupsToDelete": groupsToDelete,
503 })
504
khenaidoo2c6a0992019-04-29 13:46:56 -0400505 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400506 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
507 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400508 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400509 }
510
khenaidoo0458db62019-06-20 08:50:36 -0400511 flowChanges := &ofp.FlowChanges{
512 ToAdd: &voltha.Flows{Items: flowsToAdd},
513 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400514 }
khenaidoo0458db62019-06-20 08:50:36 -0400515 groupChanges := &ofp.FlowGroupChanges{
516 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
517 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
518 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
519 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400520 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400521 }
khenaidoo0458db62019-06-20 08:50:36 -0400522
523 // store the updated data
524 device.Flows = &voltha.Flows{Items: updatedFlows}
525 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
526 go agent.updateDeviceWithoutLockAsync(device, chdB)
527
Scott Bakerb671a862019-10-24 10:53:40 -0700528 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400529 return status.Errorf(codes.Aborted, "errors-%s", res)
530 }
531 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400532}
533
khenaidoo4d4802d2018-10-04 21:59:49 -0400534//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400535func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400536 agent.lockDevice.Lock()
537 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400538 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
539 // Get the most up to date the device info
540 if device, err := agent.getDeviceWithoutLock(); err != nil {
541 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
542 } else {
543 if device.AdminState == voltha.AdminState_DISABLED {
544 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400545 return nil
546 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400547 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
548 device.AdminState == voltha.AdminState_DELETED {
549 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
550 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
551 }
552
khenaidoo59ef7be2019-06-21 12:40:28 -0400553 // Update the Admin State and operational state before sending the request out
554 cloned := proto.Clone(device).(*voltha.Device)
555 cloned.AdminState = voltha.AdminState_DISABLED
556 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300557 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
558 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400559 }
560
khenaidoo92e62c52018-10-03 14:02:54 -0400561 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
562 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400563 return err
564 }
khenaidoo0a822f92019-05-08 15:15:57 -0400565 }
566 return nil
567}
568
569func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
570 agent.lockDevice.Lock()
571 defer agent.lockDevice.Unlock()
572 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
573 // Get the most up to date the device info
574 if device, err := agent.getDeviceWithoutLock(); err != nil {
575 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
576 } else {
577 if device.AdminState == adminState {
578 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
579 return nil
580 }
khenaidoo92e62c52018-10-03 14:02:54 -0400581 // Received an Ack (no error found above). Now update the device in the model to the expected state
582 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400583 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300584 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
585 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400586 }
khenaidoo92e62c52018-10-03 14:02:54 -0400587 }
588 return nil
589}
590
khenaidoo4d4802d2018-10-04 21:59:49 -0400591func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
592 agent.lockDevice.Lock()
593 defer agent.lockDevice.Unlock()
594 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
595 // Get the most up to date the device info
596 if device, err := agent.getDeviceWithoutLock(); err != nil {
597 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
598 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400599 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
600 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
601 return err
602 }
603 }
604 return nil
605}
606
607func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
608 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400609 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400610 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
611 // Get the most up to date the device info
612 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400613 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
614 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400615 if device.AdminState == voltha.AdminState_DELETED {
616 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
617 return nil
618 }
khenaidoo43c82122018-11-22 18:38:28 -0500619 if (device.AdminState != voltha.AdminState_DISABLED) &&
620 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400621 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
622 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400623 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
624 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400625 if device.AdminState != voltha.AdminState_PREPROVISIONED {
626 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
627 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
628 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
629 return err
630 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400631 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400632 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
633 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400634 cloned := proto.Clone(device).(*voltha.Device)
635 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300636 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
637 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400638 }
khenaidoo0a822f92019-05-08 15:15:57 -0400639 // 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
khenaidooad06fd72019-10-28 12:26:05 -0400647func (agent *DeviceAgent) setParentId(device *voltha.Device, parentId string) error {
648 agent.lockDevice.Lock()
649 defer agent.lockDevice.Unlock()
650 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentId})
651 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
652 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
653 } else {
654 // clone the device
655 cloned := proto.Clone(storeDevice).(*voltha.Device)
656 cloned.ParentId = parentId
657 // Store the device
658 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
659 return err
660 }
661 return nil
662 }
663}
664
khenaidoob3127472019-07-24 21:04:55 -0400665func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
666 agent.lockDevice.Lock()
667 defer agent.lockDevice.Unlock()
668 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
669 // Work only on latest data
670 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
671 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
672 } else {
673 // clone the device
674 cloned := proto.Clone(storeDevice).(*voltha.Device)
675 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
676 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300677 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
678 return err
khenaidoob3127472019-07-24 21:04:55 -0400679 }
680 // Send the request to the adapter
681 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
682 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
683 return err
684 }
685 return nil
686 }
687}
688
689func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
690 agent.lockDevice.Lock()
691 defer agent.lockDevice.Unlock()
692 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
693 // Work only on latest data
694 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
695 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
696 } else {
697 // clone the device
698 cloned := proto.Clone(storeDevice).(*voltha.Device)
699 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
700 // Store the device
701 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
702 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
703 if afterUpdate == nil {
704 return status.Errorf(codes.Internal, "%s", agent.deviceId)
705 }
706 return nil
707 }
708}
709
710func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
711 agent.lockDevice.RLock()
712 defer agent.lockDevice.RUnlock()
713 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
714 // Get the most up to date the device info
715 if device, err := agent.getDeviceWithoutLock(); err != nil {
716 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
717 } else {
718 cloned := proto.Clone(device).(*voltha.Device)
719 return cloned.PmConfigs, nil
720 }
721}
722
khenaidoof5a5bfa2019-01-23 22:20:29 -0500723func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
724 agent.lockDevice.Lock()
725 defer agent.lockDevice.Unlock()
726 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
727 // Get the most up to date the device info
728 if device, err := agent.getDeviceWithoutLock(); err != nil {
729 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
730 } else {
731 if device.AdminState != voltha.AdminState_ENABLED {
732 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
733 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
734 }
735 // Save the image
736 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500737 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500738 cloned := proto.Clone(device).(*voltha.Device)
739 if cloned.ImageDownloads == nil {
740 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
741 } else {
742 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
743 }
744 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300745 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
746 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500747 }
748 // Send the request to the adapter
749 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
750 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
751 return nil, err
752 }
753 }
754 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
755}
756
757// isImageRegistered is a helper method to figure out if an image is already registered
758func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
759 for _, image := range device.ImageDownloads {
760 if image.Id == img.Id && image.Name == img.Name {
761 return true
762 }
763 }
764 return false
765}
766
767func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
768 agent.lockDevice.Lock()
769 defer agent.lockDevice.Unlock()
770 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
771 // Get the most up to date the device info
772 if device, err := agent.getDeviceWithoutLock(); err != nil {
773 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
774 } else {
775 // Verify whether the Image is in the list of image being downloaded
776 if !isImageRegistered(img, device) {
777 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
778 }
779
780 // Update image download state
781 cloned := proto.Clone(device).(*voltha.Device)
782 for _, image := range cloned.ImageDownloads {
783 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500784 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500785 }
786 }
787
khenaidoof5a5bfa2019-01-23 22:20:29 -0500788 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500789 // Set the device to Enabled
790 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300791 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
792 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500793 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400794 // Send the request to teh adapter
795 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
796 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
797 return nil, err
798 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500799 }
800 }
801 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700802}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500803
804func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
805 agent.lockDevice.Lock()
806 defer agent.lockDevice.Unlock()
807 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
808 // Get the most up to date the device info
809 if device, err := agent.getDeviceWithoutLock(); err != nil {
810 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
811 } else {
812 // Verify whether the Image is in the list of image being downloaded
813 if !isImageRegistered(img, device) {
814 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
815 }
816
817 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
818 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
819 }
820 // Update image download state
821 cloned := proto.Clone(device).(*voltha.Device)
822 for _, image := range cloned.ImageDownloads {
823 if image.Id == img.Id && image.Name == img.Name {
824 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
825 }
826 }
827 // Set the device to downloading_image
828 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300829 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
830 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500831 }
832
833 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
834 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
835 return nil, err
836 }
837 // The status of the AdminState will be changed following the update_download_status response from the adapter
838 // The image name will also be removed from the device list
839 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700840 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
841}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500842
843func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
844 agent.lockDevice.Lock()
845 defer agent.lockDevice.Unlock()
846 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
847 // Get the most up to date the device info
848 if device, err := agent.getDeviceWithoutLock(); err != nil {
849 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
850 } else {
851 // Verify whether the Image is in the list of image being downloaded
852 if !isImageRegistered(img, device) {
853 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
854 }
855
856 if device.AdminState != voltha.AdminState_ENABLED {
857 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
858 }
859 // Update image download state
860 cloned := proto.Clone(device).(*voltha.Device)
861 for _, image := range cloned.ImageDownloads {
862 if image.Id == img.Id && image.Name == img.Name {
863 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
864 }
865 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300866
867 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
868 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500869 }
870
871 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
872 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
873 return nil, err
874 }
875 }
876 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700877}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500878
879func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
880 agent.lockDevice.Lock()
881 defer agent.lockDevice.Unlock()
882 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
883 // Get the most up to date the device info
884 if device, err := agent.getDeviceWithoutLock(); err != nil {
885 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
886 } else {
887 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
888 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
889 return nil, err
890 } else {
891 return resp, nil
892 }
893 }
894}
895
serkant.uluderya334479d2019-04-10 08:26:15 -0700896func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500897 agent.lockDevice.Lock()
898 defer agent.lockDevice.Unlock()
899 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
900 // Get the most up to date the device info
901 if device, err := agent.getDeviceWithoutLock(); err != nil {
902 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
903 } else {
904 // Update the image as well as remove it if the download was cancelled
905 cloned := proto.Clone(device).(*voltha.Device)
906 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
907 for _, image := range cloned.ImageDownloads {
908 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500909 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500910 clonedImages = append(clonedImages, img)
911 }
912 }
913 }
914 cloned.ImageDownloads = clonedImages
915 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500916 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
917 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700918 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500919 cloned.AdminState = voltha.AdminState_ENABLED
920 }
921
Mahir Gunyelb5851672019-07-24 10:46:26 +0300922 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
923 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500924 }
925 }
926 return nil
927}
928
929func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400930 agent.lockDevice.RLock()
931 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500932 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
933 // Get the most up to date the device info
934 if device, err := agent.getDeviceWithoutLock(); err != nil {
935 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
936 } else {
937 for _, image := range device.ImageDownloads {
938 if image.Id == img.Id && image.Name == img.Name {
939 return image, nil
940 }
941 }
942 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
943 }
944}
945
946func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400947 agent.lockDevice.RLock()
948 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500949 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
950 // Get the most up to date the device info
951 if device, err := agent.getDeviceWithoutLock(); err != nil {
952 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
953 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700954 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500955 }
956}
957
khenaidoo4d4802d2018-10-04 21:59:49 -0400958// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400959func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
960 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400961 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400962 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400963 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400964 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400965 ports.Items = append(ports.Items, port)
966 }
967 }
968 }
969 return ports
970}
971
khenaidoo4d4802d2018-10-04 21:59:49 -0400972// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
973// parent device
khenaidoo79232702018-12-04 11:00:41 -0500974func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400975 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400976 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400977 return nil, err
978 } else {
khenaidoo79232702018-12-04 11:00:41 -0500979 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400980 var err error
981 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
982 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
983 return nil, err
984 }
985 return switchCap, nil
986 }
987}
988
khenaidoo4d4802d2018-10-04 21:59:49 -0400989// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
990// device
khenaidoo79232702018-12-04 11:00:41 -0500991func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400992 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400993 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400994 return nil, err
995 } else {
khenaidoo79232702018-12-04 11:00:41 -0500996 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400997 var err error
998 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
999 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
1000 return nil, err
1001 }
1002 return portCap, nil
1003 }
1004}
1005
khenaidoofdbad6e2018-11-06 22:26:38 -05001006func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
1007 // Send packet to adapter
1008 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
Matteo Scandolo360605d2019-11-05 18:29:17 -08001009 log.Debugw("packet-out-error", log.Fields{
1010 "id": agent.lastData.Id,
1011 "error": err,
1012 "packet": hex.EncodeToString(packet.Data),
1013 })
khenaidoofdbad6e2018-11-06 22:26:38 -05001014 return err
1015 }
1016 return nil
1017}
1018
khenaidoo4d4802d2018-10-04 21:59:49 -04001019// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001020func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001021 //// Run this callback in its own go routine
1022 go func(args ...interface{}) interface{} {
1023 var previous *voltha.Device
1024 var current *voltha.Device
1025 var ok bool
1026 if len(args) == 2 {
1027 if previous, ok = args[0].(*voltha.Device); !ok {
1028 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1029 return nil
1030 }
1031 if current, ok = args[1].(*voltha.Device); !ok {
1032 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1033 return nil
1034 }
1035 } else {
1036 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1037 return nil
1038 }
1039 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001040 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1041 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1042 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1043 }
khenaidoo43c82122018-11-22 18:38:28 -05001044 return nil
1045 }(args...)
1046
khenaidoo92e62c52018-10-03 14:02:54 -04001047 return nil
1048}
1049
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001050// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1051// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1052func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1053 // First retrieve the most up to date device info
1054 var currentDevice *voltha.Device
1055 var err error
1056 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1057 return nil, err
1058 }
1059 cloned := proto.Clone(currentDevice).(*voltha.Device)
1060 cloned.Root = device.Root
1061 cloned.Vendor = device.Vendor
1062 cloned.Model = device.Model
1063 cloned.SerialNumber = device.SerialNumber
1064 cloned.MacAddress = device.MacAddress
1065 cloned.Vlan = device.Vlan
1066 cloned.Reason = device.Reason
1067 return cloned, nil
1068}
1069func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001070 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001071 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001072 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1073 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1074 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1075 return status.Errorf(codes.Internal, "%s", err.Error())
1076 } else {
1077 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1078 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1079 }
khenaidoo43c82122018-11-22 18:38:28 -05001080}
1081
1082func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1083 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1084 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001085 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001086}
1087
khenaidoo92e62c52018-10-03 14:02:54 -04001088func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1089 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001090 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001091 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001092 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001093 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1094 } else {
1095 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001096 cloned := proto.Clone(storeDevice).(*voltha.Device)
1097 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1098 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1099 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1100 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001101 }
khenaidoo92e62c52018-10-03 14:02:54 -04001102 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1103 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1104 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001105 }
khenaidoo92e62c52018-10-03 14:02:54 -04001106 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001107 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001108 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001109 }
1110}
1111
khenaidoo3ab34882019-05-02 21:33:30 -04001112func (agent *DeviceAgent) enablePorts() error {
1113 agent.lockDevice.Lock()
1114 defer agent.lockDevice.Unlock()
1115 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1116 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1117 } else {
1118 // clone the device
1119 cloned := proto.Clone(storeDevice).(*voltha.Device)
1120 for _, port := range cloned.Ports {
1121 port.AdminState = voltha.AdminState_ENABLED
1122 port.OperStatus = voltha.OperStatus_ACTIVE
1123 }
1124 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001125 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001126 }
1127}
1128
1129func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001130 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001131 agent.lockDevice.Lock()
1132 defer agent.lockDevice.Unlock()
1133 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1134 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1135 } else {
1136 // clone the device
1137 cloned := proto.Clone(storeDevice).(*voltha.Device)
1138 for _, port := range cloned.Ports {
1139 port.AdminState = voltha.AdminState_DISABLED
1140 port.OperStatus = voltha.OperStatus_UNKNOWN
1141 }
1142 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001143 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001144 }
1145}
1146
khenaidoo92e62c52018-10-03 14:02:54 -04001147func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1148 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001149 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001150 // Work only on latest data
1151 // TODO: Get list of ports from device directly instead of the entire device
1152 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001153 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1154 } else {
1155 // clone the device
1156 cloned := proto.Clone(storeDevice).(*voltha.Device)
1157 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1158 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001159 return status.Errorf(codes.InvalidArgument, "%s", portType)
1160 }
1161 for _, port := range cloned.Ports {
1162 if port.Type == portType && port.PortNo == portNo {
1163 port.OperStatus = operStatus
1164 // Set the admin status to ENABLED if the operational status is ACTIVE
1165 // TODO: Set by northbound system?
1166 if operStatus == voltha.OperStatus_ACTIVE {
1167 port.AdminState = voltha.AdminState_ENABLED
1168 }
1169 break
1170 }
1171 }
1172 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1173 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001174 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001175 }
1176}
1177
khenaidoo0a822f92019-05-08 15:15:57 -04001178func (agent *DeviceAgent) deleteAllPorts() error {
1179 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1180 agent.lockDevice.Lock()
1181 defer agent.lockDevice.Unlock()
1182 // Work only on latest data
1183 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1184 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1185 } else {
1186 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1187 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1188 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1189 return err
1190 }
1191 if len(storeDevice.Ports) == 0 {
1192 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1193 return nil
1194 }
1195 // clone the device & set the fields to empty
1196 cloned := proto.Clone(storeDevice).(*voltha.Device)
1197 cloned.Ports = []*voltha.Port{}
1198 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1199 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001200 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001201 }
1202}
1203
khenaidoob9203542018-09-17 22:56:37 -04001204func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001205 agent.lockDevice.Lock()
1206 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001207 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001208 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001209 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001210 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1211 } else {
1212 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001213 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001214 if cloned.Ports == nil {
1215 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001216 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001217 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001218 } else {
1219 for _, p := range cloned.Ports {
1220 if p.Type == port.Type && p.PortNo == port.PortNo {
1221 log.Debugw("port already exists", log.Fields{"port": *port})
1222 return nil
1223 }
1224 }
khenaidoob9203542018-09-17 22:56:37 -04001225 }
khenaidoo92e62c52018-10-03 14:02:54 -04001226 cp := proto.Clone(port).(*voltha.Port)
1227 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1228 // TODO: Set by northbound system?
1229 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1230 cp.AdminState = voltha.AdminState_ENABLED
1231 }
1232 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001233 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001234 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001235 }
1236}
1237
1238func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1239 agent.lockDevice.Lock()
1240 defer agent.lockDevice.Unlock()
1241 log.Debug("addPeerPort")
1242 // Work only on latest data
1243 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1244 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1245 } else {
1246 // clone the device
1247 cloned := proto.Clone(storeDevice).(*voltha.Device)
1248 // Get the peer port on the device based on the port no
1249 for _, peerPort := range cloned.Ports {
1250 if peerPort.PortNo == port.PortNo { // found port
1251 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1252 peerPort.Peers = append(peerPort.Peers, cp)
1253 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1254 break
1255 }
1256 }
1257 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001258 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001259 }
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
Mahir Gunyelb5851672019-07-24 10:46:26 +03001284 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001285 }
1286}
1287
khenaidoob9203542018-09-17 22:56:37 -04001288// TODO: A generic device update by attribute
1289func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001290 agent.lockDevice.Lock()
1291 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001292 if value == nil {
1293 return
1294 }
1295 var storeDevice *voltha.Device
1296 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001297 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001298 return
1299 }
1300 updated := false
1301 s := reflect.ValueOf(storeDevice).Elem()
1302 if s.Kind() == reflect.Struct {
1303 // exported field
1304 f := s.FieldByName(name)
1305 if f.IsValid() && f.CanSet() {
1306 switch f.Kind() {
1307 case reflect.String:
1308 f.SetString(value.(string))
1309 updated = true
1310 case reflect.Uint32:
1311 f.SetUint(uint64(value.(uint32)))
1312 updated = true
1313 case reflect.Bool:
1314 f.SetBool(value.(bool))
1315 updated = true
1316 }
1317 }
1318 }
khenaidoo92e62c52018-10-03 14:02:54 -04001319 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001320 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001321 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001322 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001323 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1324 }
1325 return
1326}
serkant.uluderya334479d2019-04-10 08:26:15 -07001327
1328func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1329 agent.lockDevice.Lock()
1330 defer agent.lockDevice.Unlock()
1331 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1332 // Get the most up to date the device info
1333 if device, err := agent.getDeviceWithoutLock(); err != nil {
1334 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1335 } else {
1336 // First send the request to an Adapter and wait for a response
1337 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1338 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1339 return err
1340 }
1341 }
1342 return nil
1343}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001344
1345//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.
1346// It is an internal helper function.
1347func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1348 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1349 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1350 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1351 }
1352 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1353
1354 return nil
1355}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001356
1357func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1358 agent.lockDevice.Lock()
1359 defer agent.lockDevice.Unlock()
1360 // Work only on latest data
1361 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1362 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1363 } else {
1364 // clone the device
1365 cloned := proto.Clone(storeDevice).(*voltha.Device)
1366 cloned.Reason = reason
1367 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1368 // Store the device
1369 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1370 }
1371}