blob: fea66d6fcc0765677debda3da8ce20b7facd85d0 [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"
Scott Bakerb671a862019-10-24 10:53:40 -070022 coreutils "github.com/opencord/voltha-go/rw_core/utils"
Scott Baker807addd2019-10-24 15:16:21 -070023 "github.com/opencord/voltha-lib-go/v2/pkg/db/model"
24 fu "github.com/opencord/voltha-lib-go/v2/pkg/flows"
25 "github.com/opencord/voltha-lib-go/v2/pkg/log"
William Kurkiandaa6bb22019-03-07 12:26:28 -050026 ic "github.com/opencord/voltha-protos/go/inter_container"
27 ofp "github.com/opencord/voltha-protos/go/openflow_13"
28 "github.com/opencord/voltha-protos/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040029 "google.golang.org/grpc/codes"
30 "google.golang.org/grpc/status"
khenaidoo19d7b632018-10-30 10:49:50 -040031 "reflect"
32 "sync"
Stephane Barbarieef6650d2019-07-18 12:15:09 -040033 "time"
khenaidoob9203542018-09-17 22:56:37 -040034)
35
36type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040037 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040038 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050039 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040040 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040041 lastData *voltha.Device
42 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070043 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040044 deviceMgr *DeviceManager
45 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040046 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040047 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040048 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040049 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040050}
51
khenaidoo4d4802d2018-10-04 21:59:49 -040052//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
53//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040054func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040055 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040056 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040057 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050058 if cloned.Id == "" {
59 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050060 cloned.AdminState = voltha.AdminState_PREPROVISIONED
61 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
62 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050063 }
khenaidoo19d7b632018-10-30 10:49:50 -040064 if !device.GetRoot() && device.ProxyAddress != nil {
65 // Set the default vlan ID to the one specified by the parent adapter. It can be
66 // overwritten by the child adapter during a device update request
67 cloned.Vlan = device.ProxyAddress.ChannelId
68 }
khenaidoo2c6a0992019-04-29 13:46:56 -040069 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040070 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040071 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050072 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040073 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040074 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050075 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040076 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040077 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040078 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040079 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040080 return &agent
81}
82
khenaidoo297cd252019-02-07 22:10:23 -050083// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
84// it will load the data from the dB and setup teh necessary callbacks and proxies.
85func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040086 agent.lockDevice.Lock()
87 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050088 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
89 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040090 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050091 if d, ok := device.(*voltha.Device); ok {
92 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050093 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050094 }
95 } else {
96 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
97 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
98 }
khenaidoo4c9e5592019-09-09 16:20:41 -040099 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500100 } else {
101 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400102 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500103 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
khenaidoo4c9e5592019-09-09 16:20:41 -0400104 return status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -0500105 }
khenaidoob9203542018-09-17 22:56:37 -0400106 }
khenaidoo297cd252019-02-07 22:10:23 -0500107
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400108 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500109 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400110
khenaidoo4c9e5592019-09-09 16:20:41 -0400111 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500112 return nil
khenaidoob9203542018-09-17 22:56:37 -0400113}
114
khenaidoo4d4802d2018-10-04 21:59:49 -0400115// stop stops the device agent. Not much to do for now
116func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400117 agent.lockDevice.Lock()
118 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400119 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400120 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400121 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400122 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400123 }
khenaidoob9203542018-09-17 22:56:37 -0400124 agent.exitChannel <- 1
125 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400126
khenaidoob9203542018-09-17 22:56:37 -0400127}
128
khenaidoo19d7b632018-10-30 10:49:50 -0400129// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400130func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400131 agent.lockDevice.RLock()
132 defer agent.lockDevice.RUnlock()
Stephane Barbarieb6b68c42019-10-10 16:05:13 -0400133 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400134 if d, ok := device.(*voltha.Device); ok {
135 cloned := proto.Clone(d).(*voltha.Device)
136 return cloned, nil
137 }
138 }
139 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
140}
141
khenaidoo4d4802d2018-10-04 21:59:49 -0400142// 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 -0400143// This function is meant so that we do not have duplicate code all over the device agent functions
144func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400145 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400146 if d, ok := device.(*voltha.Device); ok {
147 cloned := proto.Clone(d).(*voltha.Device)
148 return cloned, nil
149 }
150 }
151 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
152}
153
khenaidoo3ab34882019-05-02 21:33:30 -0400154// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400155func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400156 agent.lockDevice.Lock()
157 defer agent.lockDevice.Unlock()
158 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500159
khenaidoo92e62c52018-10-03 14:02:54 -0400160 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400161 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
162 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500163 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
164 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
165 // with the adapter then we need to know the adapter that will handle this request
166 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
167 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
168 return err
169 } else {
170 device.Adapter = adapterName
171 }
172
khenaidoo92e62c52018-10-03 14:02:54 -0400173 if device.AdminState == voltha.AdminState_ENABLED {
174 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400175 return nil
176 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400177
178 if device.AdminState == voltha.AdminState_DELETED {
179 // This is a temporary state when a device is deleted before it gets removed from the model.
180 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
181 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
182 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400183 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400184
185 previousAdminState := device.AdminState
186
187 // Update the Admin State and set the operational state to activating before sending the request to the
188 // Adapters
189 cloned := proto.Clone(device).(*voltha.Device)
190 cloned.AdminState = voltha.AdminState_ENABLED
191 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400192
Mahir Gunyelb5851672019-07-24 10:46:26 +0300193 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
194 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400195 }
196
197 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
198 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400199 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
200 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400201 return err
202 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400203 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400204 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
205 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
206 return err
207 }
khenaidoob9203542018-09-17 22:56:37 -0400208 }
209 }
210 return nil
211}
212
khenaidoo2c6a0992019-04-29 13:46:56 -0400213func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
214 if err := agent.updateDeviceWithoutLock(device); err != nil {
215 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400216 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400217 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400218}
219
Manikkaraj kb1a10922019-07-29 12:10:34 -0400220func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
221 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400222 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
223 ch <- err
224 }
225 ch <- nil
226}
227
Manikkaraj kb1a10922019-07-29 12:10:34 -0400228func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
229 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400230 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
231 ch <- err
232 }
233 ch <- nil
234}
235
khenaidoo0458db62019-06-20 08:50:36 -0400236//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
237//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400238func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
239 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400240
khenaidoo2c6a0992019-04-29 13:46:56 -0400241 if (len(newFlows) | len(newGroups)) == 0 {
242 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
243 return nil
244 }
245
khenaidoo19d7b632018-10-30 10:49:50 -0400246 agent.lockDevice.Lock()
247 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400248
khenaidoo0458db62019-06-20 08:50:36 -0400249 var device *voltha.Device
250 var err error
251 if device, err = agent.getDeviceWithoutLock(); err != nil {
252 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
253 }
254
255 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
256 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
257
258 var updatedFlows []*ofp.OfpFlowStats
259 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400260 var updatedGroups []*ofp.OfpGroupEntry
Manikkaraj k33f779a2019-08-23 01:38:00 -0400261 var flowsToAdd []*ofp.OfpFlowStats
262 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400263
264 // Process flows
265 for _, flow := range newFlows {
266 updatedFlows = append(updatedFlows, flow)
Manikkaraj k33f779a2019-08-23 01:38:00 -0400267 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 { // does not exist now , add new flow
268 flowsToAdd = append(flowsToAdd, flow)
269 }
khenaidoo0458db62019-06-20 08:50:36 -0400270 }
271 for _, flow := range existingFlows.Items {
272 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Manikkaraj k33f779a2019-08-23 01:38:00 -0400273 updatedFlows = append(updatedFlows, flow) // append existing flows
khenaidoo0458db62019-06-20 08:50:36 -0400274 } else {
Manikkaraj k33f779a2019-08-23 01:38:00 -0400275 // OF-1.3.1: If a flow entry with identical match fields and priority already resides , clear old flow and add new flow
khenaidoo0458db62019-06-20 08:50:36 -0400276 flowsToDelete = append(flowsToDelete, flow)
Manikkaraj k33f779a2019-08-23 01:38:00 -0400277 flowsToAdd = append(flowsToAdd, newFlows[idx])
khenaidoo0458db62019-06-20 08:50:36 -0400278 }
279 }
280
281 // Process groups
282 for _, g := range newGroups {
283 updatedGroups = append(updatedGroups, g)
Manikkaraj k33f779a2019-08-23 01:38:00 -0400284 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
285 groupsToAdd = append(groupsToAdd, g)
286 }
khenaidoo0458db62019-06-20 08:50:36 -0400287 }
288 for _, group := range existingGroups.Items {
Manikkaraj k33f779a2019-08-23 01:38:00 -0400289 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 {
290 updatedGroups = append(updatedGroups, group) // Add existing groups
khenaidoo0458db62019-06-20 08:50:36 -0400291 }
292 }
293
294 // Sanity check
Manikkaraj k33f779a2019-08-23 01:38:00 -0400295 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups)) == 0 {
khenaidoo0458db62019-06-20 08:50:36 -0400296 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
297 return nil
298 }
299
300 // Send update to adapters
301 // Create two channels to receive responses from the dB and from the adapters.
302 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
303 // to send their responses. These channels will be garbage collected once all the responses are
304 // received
305 chAdapters := make(chan interface{})
306 chdB := make(chan interface{})
307 dType := agent.adapterMgr.getDeviceType(device.Type)
308 if !dType.AcceptsAddRemoveFlowUpdates {
309
310 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
311 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
312 return nil
313 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400314 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400315
316 } else {
317 flowChanges := &ofp.FlowChanges{
Manikkaraj k33f779a2019-08-23 01:38:00 -0400318 ToAdd: &voltha.Flows{Items: flowsToAdd},
khenaidoo0458db62019-06-20 08:50:36 -0400319 ToRemove: &voltha.Flows{Items: flowsToDelete},
320 }
321 groupChanges := &ofp.FlowGroupChanges{
Manikkaraj k33f779a2019-08-23 01:38:00 -0400322 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
323 ToRemove: &voltha.FlowGroups{Items: nil},
khenaidoo0458db62019-06-20 08:50:36 -0400324 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
325 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400326 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400327 }
328
329 // store the changed data
330 device.Flows = &voltha.Flows{Items: updatedFlows}
331 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
332 go agent.updateDeviceWithoutLockAsync(device, chdB)
333
Scott Bakerb671a862019-10-24 10:53:40 -0700334 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400335 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400336 return status.Errorf(codes.Aborted, "errors-%s", res)
337 }
338
339 return nil
340}
341
342//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
343//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400344func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400345 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
346
347 if (len(flowsToDel) | len(groupsToDel)) == 0 {
348 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
349 return nil
350 }
351
352 agent.lockDevice.Lock()
353 defer agent.lockDevice.Unlock()
354
355 var device *voltha.Device
356 var err error
357
358 if device, err = agent.getDeviceWithoutLock(); err != nil {
359 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
360 }
361
362 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
363 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
364
365 var flowsToKeep []*ofp.OfpFlowStats
366 var groupsToKeep []*ofp.OfpGroupEntry
367
368 // Process flows
369 for _, flow := range existingFlows.Items {
370 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
371 flowsToKeep = append(flowsToKeep, flow)
372 }
373 }
374
375 // Process groups
376 for _, group := range existingGroups.Items {
377 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
378 groupsToKeep = append(groupsToKeep, group)
379 }
380 }
381
382 log.Debugw("deleteFlowsAndGroups",
383 log.Fields{
384 "deviceId": agent.deviceId,
385 "flowsToDel": len(flowsToDel),
386 "flowsToKeep": len(flowsToKeep),
387 "groupsToDel": len(groupsToDel),
388 "groupsToKeep": len(groupsToKeep),
389 })
390
391 // Sanity check
392 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
393 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
394 return nil
395 }
396
397 // Send update to adapters
398 chAdapters := make(chan interface{})
399 chdB := make(chan interface{})
400 dType := agent.adapterMgr.getDeviceType(device.Type)
401 if !dType.AcceptsAddRemoveFlowUpdates {
402 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
403 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
404 return nil
405 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400406 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400407 } else {
408 flowChanges := &ofp.FlowChanges{
409 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
410 ToRemove: &voltha.Flows{Items: flowsToDel},
411 }
412 groupChanges := &ofp.FlowGroupChanges{
413 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
414 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
415 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
416 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400417 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400418 }
419
420 // store the changed data
421 device.Flows = &voltha.Flows{Items: flowsToKeep}
422 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
423 go agent.updateDeviceWithoutLockAsync(device, chdB)
424
Scott Bakerb671a862019-10-24 10:53:40 -0700425 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400426 return status.Errorf(codes.Aborted, "errors-%s", res)
427 }
428 return nil
429
430}
431
432//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
433//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400434func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400435 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
436
437 if (len(updatedFlows) | len(updatedGroups)) == 0 {
438 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
439 return nil
440 }
441
442 agent.lockDevice.Lock()
443 defer agent.lockDevice.Unlock()
444 var device *voltha.Device
445 var err error
446 if device, err = agent.getDeviceWithoutLock(); err != nil {
447 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
448 }
449 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
450 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
451
452 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
453 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
454 return nil
455 }
456
457 log.Debugw("updating-flows-and-groups",
458 log.Fields{
459 "deviceId": agent.deviceId,
460 "updatedFlows": updatedFlows,
461 "updatedGroups": updatedGroups,
462 })
463
464 chAdapters := make(chan interface{})
465 chdB := make(chan interface{})
466 dType := agent.adapterMgr.getDeviceType(device.Type)
467
468 // Process bulk flow update differently than incremental update
469 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400470 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400471 } else {
472 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400473 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400474 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400475 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400476
477 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400478 for _, flow := range updatedFlows {
479 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
480 flowsToAdd = append(flowsToAdd, flow)
481 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400482 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400483 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400484 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400485 flowsToDelete = append(flowsToDelete, flow)
486 }
487 }
488
489 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400490 for _, g := range updatedGroups {
491 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
492 groupsToAdd = append(groupsToAdd, g)
493 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400494 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400495 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400496 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400497 groupsToDelete = append(groupsToDelete, group)
498 }
499 }
500
khenaidoo0458db62019-06-20 08:50:36 -0400501 log.Debugw("updating-flows-and-groups",
502 log.Fields{
503 "deviceId": agent.deviceId,
504 "flowsToAdd": flowsToAdd,
505 "flowsToDelete": flowsToDelete,
506 "groupsToAdd": groupsToAdd,
507 "groupsToDelete": groupsToDelete,
508 })
509
khenaidoo2c6a0992019-04-29 13:46:56 -0400510 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400511 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
512 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400513 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400514 }
515
khenaidoo0458db62019-06-20 08:50:36 -0400516 flowChanges := &ofp.FlowChanges{
517 ToAdd: &voltha.Flows{Items: flowsToAdd},
518 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400519 }
khenaidoo0458db62019-06-20 08:50:36 -0400520 groupChanges := &ofp.FlowGroupChanges{
521 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
522 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
523 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
524 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400525 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400526 }
khenaidoo0458db62019-06-20 08:50:36 -0400527
528 // store the updated data
529 device.Flows = &voltha.Flows{Items: updatedFlows}
530 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
531 go agent.updateDeviceWithoutLockAsync(device, chdB)
532
Scott Bakerb671a862019-10-24 10:53:40 -0700533 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400534 return status.Errorf(codes.Aborted, "errors-%s", res)
535 }
536 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400537}
538
khenaidoo4d4802d2018-10-04 21:59:49 -0400539//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400540func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400541 agent.lockDevice.Lock()
542 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400543 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
544 // Get the most up to date the device info
545 if device, err := agent.getDeviceWithoutLock(); err != nil {
546 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
547 } else {
548 if device.AdminState == voltha.AdminState_DISABLED {
549 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400550 return nil
551 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400552 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
553 device.AdminState == voltha.AdminState_DELETED {
554 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
555 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
556 }
557
khenaidoo59ef7be2019-06-21 12:40:28 -0400558 // Update the Admin State and operational state before sending the request out
559 cloned := proto.Clone(device).(*voltha.Device)
560 cloned.AdminState = voltha.AdminState_DISABLED
561 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300562 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
563 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400564 }
565
khenaidoo92e62c52018-10-03 14:02:54 -0400566 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
567 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400568 return err
569 }
khenaidoo0a822f92019-05-08 15:15:57 -0400570 }
571 return nil
572}
573
574func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
575 agent.lockDevice.Lock()
576 defer agent.lockDevice.Unlock()
577 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
578 // Get the most up to date the device info
579 if device, err := agent.getDeviceWithoutLock(); err != nil {
580 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
581 } else {
582 if device.AdminState == adminState {
583 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
584 return nil
585 }
khenaidoo92e62c52018-10-03 14:02:54 -0400586 // Received an Ack (no error found above). Now update the device in the model to the expected state
587 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400588 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300589 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
590 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400591 }
khenaidoo92e62c52018-10-03 14:02:54 -0400592 }
593 return nil
594}
595
khenaidoo4d4802d2018-10-04 21:59:49 -0400596func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
597 agent.lockDevice.Lock()
598 defer agent.lockDevice.Unlock()
599 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
600 // Get the most up to date the device info
601 if device, err := agent.getDeviceWithoutLock(); err != nil {
602 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
603 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400604 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
605 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
606 return err
607 }
608 }
609 return nil
610}
611
612func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
613 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400614 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400615 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
616 // Get the most up to date the device info
617 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400618 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
619 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400620 if device.AdminState == voltha.AdminState_DELETED {
621 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
622 return nil
623 }
khenaidoo43c82122018-11-22 18:38:28 -0500624 if (device.AdminState != voltha.AdminState_DISABLED) &&
625 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400626 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
627 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400628 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
629 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400630 if device.AdminState != voltha.AdminState_PREPROVISIONED {
631 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
632 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
633 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
634 return err
635 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400636 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400637 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
638 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400639 cloned := proto.Clone(device).(*voltha.Device)
640 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300641 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
642 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400643 }
khenaidoo0a822f92019-05-08 15:15:57 -0400644 // If this is a child device then remove the associated peer ports on the parent device
645 if !device.Root {
646 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
647 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400648 }
649 return nil
650}
651
khenaidoob3127472019-07-24 21:04:55 -0400652func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
653 agent.lockDevice.Lock()
654 defer agent.lockDevice.Unlock()
655 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
656 // Work only on latest data
657 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
658 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
659 } else {
660 // clone the device
661 cloned := proto.Clone(storeDevice).(*voltha.Device)
662 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
663 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300664 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
665 return err
khenaidoob3127472019-07-24 21:04:55 -0400666 }
667 // Send the request to the adapter
668 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
669 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
670 return err
671 }
672 return nil
673 }
674}
675
676func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
677 agent.lockDevice.Lock()
678 defer agent.lockDevice.Unlock()
679 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
680 // Work only on latest data
681 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
682 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
683 } else {
684 // clone the device
685 cloned := proto.Clone(storeDevice).(*voltha.Device)
686 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
687 // Store the device
688 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
689 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
690 if afterUpdate == nil {
691 return status.Errorf(codes.Internal, "%s", agent.deviceId)
692 }
693 return nil
694 }
695}
696
697func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
698 agent.lockDevice.RLock()
699 defer agent.lockDevice.RUnlock()
700 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
701 // Get the most up to date the device info
702 if device, err := agent.getDeviceWithoutLock(); err != nil {
703 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
704 } else {
705 cloned := proto.Clone(device).(*voltha.Device)
706 return cloned.PmConfigs, nil
707 }
708}
709
khenaidoof5a5bfa2019-01-23 22:20:29 -0500710func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
711 agent.lockDevice.Lock()
712 defer agent.lockDevice.Unlock()
713 log.Debugw("downloadImage", 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 if device.AdminState != voltha.AdminState_ENABLED {
719 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
720 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
721 }
722 // Save the image
723 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500724 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500725 cloned := proto.Clone(device).(*voltha.Device)
726 if cloned.ImageDownloads == nil {
727 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
728 } else {
729 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
730 }
731 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300732 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
733 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500734 }
735 // Send the request to the adapter
736 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
737 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
738 return nil, err
739 }
740 }
741 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
742}
743
744// isImageRegistered is a helper method to figure out if an image is already registered
745func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
746 for _, image := range device.ImageDownloads {
747 if image.Id == img.Id && image.Name == img.Name {
748 return true
749 }
750 }
751 return false
752}
753
754func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
755 agent.lockDevice.Lock()
756 defer agent.lockDevice.Unlock()
757 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
758 // Get the most up to date the device info
759 if device, err := agent.getDeviceWithoutLock(); err != nil {
760 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
761 } else {
762 // Verify whether the Image is in the list of image being downloaded
763 if !isImageRegistered(img, device) {
764 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
765 }
766
767 // Update image download state
768 cloned := proto.Clone(device).(*voltha.Device)
769 for _, image := range cloned.ImageDownloads {
770 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500771 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500772 }
773 }
774
khenaidoof5a5bfa2019-01-23 22:20:29 -0500775 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500776 // Set the device to Enabled
777 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300778 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
779 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500780 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400781 // Send the request to teh adapter
782 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
783 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
784 return nil, err
785 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500786 }
787 }
788 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700789}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500790
791func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
792 agent.lockDevice.Lock()
793 defer agent.lockDevice.Unlock()
794 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
795 // Get the most up to date the device info
796 if device, err := agent.getDeviceWithoutLock(); err != nil {
797 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
798 } else {
799 // Verify whether the Image is in the list of image being downloaded
800 if !isImageRegistered(img, device) {
801 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
802 }
803
804 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
805 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
806 }
807 // Update image download state
808 cloned := proto.Clone(device).(*voltha.Device)
809 for _, image := range cloned.ImageDownloads {
810 if image.Id == img.Id && image.Name == img.Name {
811 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
812 }
813 }
814 // Set the device to downloading_image
815 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300816 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
817 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500818 }
819
820 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
821 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
822 return nil, err
823 }
824 // The status of the AdminState will be changed following the update_download_status response from the adapter
825 // The image name will also be removed from the device list
826 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700827 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
828}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500829
830func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
831 agent.lockDevice.Lock()
832 defer agent.lockDevice.Unlock()
833 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
834 // Get the most up to date the device info
835 if device, err := agent.getDeviceWithoutLock(); err != nil {
836 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
837 } else {
838 // Verify whether the Image is in the list of image being downloaded
839 if !isImageRegistered(img, device) {
840 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
841 }
842
843 if device.AdminState != voltha.AdminState_ENABLED {
844 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
845 }
846 // Update image download state
847 cloned := proto.Clone(device).(*voltha.Device)
848 for _, image := range cloned.ImageDownloads {
849 if image.Id == img.Id && image.Name == img.Name {
850 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
851 }
852 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300853
854 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
855 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500856 }
857
858 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
859 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
860 return nil, err
861 }
862 }
863 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700864}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500865
866func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
867 agent.lockDevice.Lock()
868 defer agent.lockDevice.Unlock()
869 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
870 // Get the most up to date the device info
871 if device, err := agent.getDeviceWithoutLock(); err != nil {
872 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
873 } else {
874 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
875 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
876 return nil, err
877 } else {
878 return resp, nil
879 }
880 }
881}
882
serkant.uluderya334479d2019-04-10 08:26:15 -0700883func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500884 agent.lockDevice.Lock()
885 defer agent.lockDevice.Unlock()
886 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
887 // Get the most up to date the device info
888 if device, err := agent.getDeviceWithoutLock(); err != nil {
889 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
890 } else {
891 // Update the image as well as remove it if the download was cancelled
892 cloned := proto.Clone(device).(*voltha.Device)
893 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
894 for _, image := range cloned.ImageDownloads {
895 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500896 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500897 clonedImages = append(clonedImages, img)
898 }
899 }
900 }
901 cloned.ImageDownloads = clonedImages
902 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500903 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
904 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700905 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500906 cloned.AdminState = voltha.AdminState_ENABLED
907 }
908
Mahir Gunyelb5851672019-07-24 10:46:26 +0300909 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
910 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500911 }
912 }
913 return nil
914}
915
916func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400917 agent.lockDevice.RLock()
918 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500919 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
920 // Get the most up to date the device info
921 if device, err := agent.getDeviceWithoutLock(); err != nil {
922 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
923 } else {
924 for _, image := range device.ImageDownloads {
925 if image.Id == img.Id && image.Name == img.Name {
926 return image, nil
927 }
928 }
929 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
930 }
931}
932
933func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400934 agent.lockDevice.RLock()
935 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500936 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
937 // Get the most up to date the device info
938 if device, err := agent.getDeviceWithoutLock(); err != nil {
939 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
940 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700941 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500942 }
943}
944
khenaidoo4d4802d2018-10-04 21:59:49 -0400945// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400946func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
947 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400948 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400949 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400950 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400951 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400952 ports.Items = append(ports.Items, port)
953 }
954 }
955 }
956 return ports
957}
958
khenaidoo4d4802d2018-10-04 21:59:49 -0400959// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
960// parent device
khenaidoo79232702018-12-04 11:00:41 -0500961func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400962 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400963 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400964 return nil, err
965 } else {
khenaidoo79232702018-12-04 11:00:41 -0500966 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400967 var err error
968 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
969 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
970 return nil, err
971 }
972 return switchCap, nil
973 }
974}
975
khenaidoo4d4802d2018-10-04 21:59:49 -0400976// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
977// device
khenaidoo79232702018-12-04 11:00:41 -0500978func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400979 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400980 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400981 return nil, err
982 } else {
khenaidoo79232702018-12-04 11:00:41 -0500983 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400984 var err error
985 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
986 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
987 return nil, err
988 }
989 return portCap, nil
990 }
991}
992
khenaidoofdbad6e2018-11-06 22:26:38 -0500993func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
994 // Send packet to adapter
995 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
996 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
997 return err
998 }
999 return nil
1000}
1001
khenaidoo4d4802d2018-10-04 21:59:49 -04001002// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001003func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001004 //// Run this callback in its own go routine
1005 go func(args ...interface{}) interface{} {
1006 var previous *voltha.Device
1007 var current *voltha.Device
1008 var ok bool
1009 if len(args) == 2 {
1010 if previous, ok = args[0].(*voltha.Device); !ok {
1011 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1012 return nil
1013 }
1014 if current, ok = args[1].(*voltha.Device); !ok {
1015 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1016 return nil
1017 }
1018 } else {
1019 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1020 return nil
1021 }
1022 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001023 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1024 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1025 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1026 }
khenaidoo43c82122018-11-22 18:38:28 -05001027 return nil
1028 }(args...)
1029
khenaidoo92e62c52018-10-03 14:02:54 -04001030 return nil
1031}
1032
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001033// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1034// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1035func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1036 // First retrieve the most up to date device info
1037 var currentDevice *voltha.Device
1038 var err error
1039 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1040 return nil, err
1041 }
1042 cloned := proto.Clone(currentDevice).(*voltha.Device)
1043 cloned.Root = device.Root
1044 cloned.Vendor = device.Vendor
1045 cloned.Model = device.Model
1046 cloned.SerialNumber = device.SerialNumber
1047 cloned.MacAddress = device.MacAddress
1048 cloned.Vlan = device.Vlan
1049 cloned.Reason = device.Reason
1050 return cloned, nil
1051}
1052func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001053 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001054 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001055 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1056 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1057 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1058 return status.Errorf(codes.Internal, "%s", err.Error())
1059 } else {
1060 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1061 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1062 }
khenaidoo43c82122018-11-22 18:38:28 -05001063}
1064
1065func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1066 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1067 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001068 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001069}
1070
khenaidoo92e62c52018-10-03 14:02:54 -04001071func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1072 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001073 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001074 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001075 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001076 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1077 } else {
1078 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001079 cloned := proto.Clone(storeDevice).(*voltha.Device)
1080 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1081 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1082 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1083 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001084 }
khenaidoo92e62c52018-10-03 14:02:54 -04001085 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1086 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1087 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001088 }
khenaidoo92e62c52018-10-03 14:02:54 -04001089 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001090 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001091 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001092 }
1093}
1094
khenaidoo3ab34882019-05-02 21:33:30 -04001095func (agent *DeviceAgent) enablePorts() error {
1096 agent.lockDevice.Lock()
1097 defer agent.lockDevice.Unlock()
1098 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1099 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1100 } else {
1101 // clone the device
1102 cloned := proto.Clone(storeDevice).(*voltha.Device)
1103 for _, port := range cloned.Ports {
1104 port.AdminState = voltha.AdminState_ENABLED
1105 port.OperStatus = voltha.OperStatus_ACTIVE
1106 }
1107 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001108 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001109 }
1110}
1111
1112func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001113 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001114 agent.lockDevice.Lock()
1115 defer agent.lockDevice.Unlock()
1116 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1117 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1118 } else {
1119 // clone the device
1120 cloned := proto.Clone(storeDevice).(*voltha.Device)
1121 for _, port := range cloned.Ports {
1122 port.AdminState = voltha.AdminState_DISABLED
1123 port.OperStatus = voltha.OperStatus_UNKNOWN
1124 }
1125 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001126 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001127 }
1128}
1129
khenaidoo92e62c52018-10-03 14:02:54 -04001130func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1131 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001132 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001133 // Work only on latest data
1134 // TODO: Get list of ports from device directly instead of the entire device
1135 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001136 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1137 } else {
1138 // clone the device
1139 cloned := proto.Clone(storeDevice).(*voltha.Device)
1140 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1141 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001142 return status.Errorf(codes.InvalidArgument, "%s", portType)
1143 }
1144 for _, port := range cloned.Ports {
1145 if port.Type == portType && port.PortNo == portNo {
1146 port.OperStatus = operStatus
1147 // Set the admin status to ENABLED if the operational status is ACTIVE
1148 // TODO: Set by northbound system?
1149 if operStatus == voltha.OperStatus_ACTIVE {
1150 port.AdminState = voltha.AdminState_ENABLED
1151 }
1152 break
1153 }
1154 }
1155 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1156 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001157 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001158 }
1159}
1160
khenaidoo0a822f92019-05-08 15:15:57 -04001161func (agent *DeviceAgent) deleteAllPorts() error {
1162 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1163 agent.lockDevice.Lock()
1164 defer agent.lockDevice.Unlock()
1165 // Work only on latest data
1166 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1167 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1168 } else {
1169 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1170 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1171 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1172 return err
1173 }
1174 if len(storeDevice.Ports) == 0 {
1175 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1176 return nil
1177 }
1178 // clone the device & set the fields to empty
1179 cloned := proto.Clone(storeDevice).(*voltha.Device)
1180 cloned.Ports = []*voltha.Port{}
1181 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1182 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001183 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001184 }
1185}
1186
khenaidoob9203542018-09-17 22:56:37 -04001187func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001188 agent.lockDevice.Lock()
1189 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001190 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001191 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001192 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001193 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1194 } else {
1195 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001196 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001197 if cloned.Ports == nil {
1198 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001199 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001200 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001201 } else {
1202 for _, p := range cloned.Ports {
1203 if p.Type == port.Type && p.PortNo == port.PortNo {
1204 log.Debugw("port already exists", log.Fields{"port": *port})
1205 return nil
1206 }
1207 }
khenaidoob9203542018-09-17 22:56:37 -04001208 }
khenaidoo92e62c52018-10-03 14:02:54 -04001209 cp := proto.Clone(port).(*voltha.Port)
1210 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1211 // TODO: Set by northbound system?
1212 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1213 cp.AdminState = voltha.AdminState_ENABLED
1214 }
1215 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001216 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001217 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001218 }
1219}
1220
1221func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1222 agent.lockDevice.Lock()
1223 defer agent.lockDevice.Unlock()
1224 log.Debug("addPeerPort")
1225 // Work only on latest data
1226 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1227 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1228 } else {
1229 // clone the device
1230 cloned := proto.Clone(storeDevice).(*voltha.Device)
1231 // Get the peer port on the device based on the port no
1232 for _, peerPort := range cloned.Ports {
1233 if peerPort.PortNo == port.PortNo { // found port
1234 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1235 peerPort.Peers = append(peerPort.Peers, cp)
1236 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1237 break
1238 }
1239 }
1240 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001241 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001242 }
1243}
1244
khenaidoo0a822f92019-05-08 15:15:57 -04001245func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1246 agent.lockDevice.Lock()
1247 defer agent.lockDevice.Unlock()
1248 log.Debug("deletePeerPorts")
1249 // Work only on latest data
1250 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1251 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1252 } else {
1253 // clone the device
1254 cloned := proto.Clone(storeDevice).(*voltha.Device)
1255 var updatedPeers []*voltha.Port_PeerPort
1256 for _, port := range cloned.Ports {
1257 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1258 for _, peerPort := range port.Peers {
1259 if peerPort.DeviceId != deviceId {
1260 updatedPeers = append(updatedPeers, peerPort)
1261 }
1262 }
1263 port.Peers = updatedPeers
1264 }
1265
1266 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001267 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001268 }
1269}
1270
khenaidoob9203542018-09-17 22:56:37 -04001271// TODO: A generic device update by attribute
1272func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001273 agent.lockDevice.Lock()
1274 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001275 if value == nil {
1276 return
1277 }
1278 var storeDevice *voltha.Device
1279 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001280 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001281 return
1282 }
1283 updated := false
1284 s := reflect.ValueOf(storeDevice).Elem()
1285 if s.Kind() == reflect.Struct {
1286 // exported field
1287 f := s.FieldByName(name)
1288 if f.IsValid() && f.CanSet() {
1289 switch f.Kind() {
1290 case reflect.String:
1291 f.SetString(value.(string))
1292 updated = true
1293 case reflect.Uint32:
1294 f.SetUint(uint64(value.(uint32)))
1295 updated = true
1296 case reflect.Bool:
1297 f.SetBool(value.(bool))
1298 updated = true
1299 }
1300 }
1301 }
khenaidoo92e62c52018-10-03 14:02:54 -04001302 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001303 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001304 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001305 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001306 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1307 }
1308 return
1309}
serkant.uluderya334479d2019-04-10 08:26:15 -07001310
1311func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1312 agent.lockDevice.Lock()
1313 defer agent.lockDevice.Unlock()
1314 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1315 // Get the most up to date the device info
1316 if device, err := agent.getDeviceWithoutLock(); err != nil {
1317 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1318 } else {
1319 // First send the request to an Adapter and wait for a response
1320 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1321 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1322 return err
1323 }
1324 }
1325 return nil
1326}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001327
1328//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.
1329// It is an internal helper function.
1330func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1331 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1332 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1333 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1334 }
1335 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1336
1337 return nil
1338}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001339
1340func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1341 agent.lockDevice.Lock()
1342 defer agent.lockDevice.Unlock()
1343 // Work only on latest data
1344 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1345 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1346 } else {
1347 // clone the device
1348 cloned := proto.Clone(storeDevice).(*voltha.Device)
1349 cloned.Reason = reason
1350 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1351 // Store the device
1352 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1353 }
1354}