blob: 3d356ec03680f8a002ee9fd9d7d2e58d784c73f6 [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"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040021 "reflect"
22 "sync"
23 "time"
24
khenaidoob9203542018-09-17 22:56:37 -040025 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050026 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070027 coreutils "github.com/opencord/voltha-go/rw_core/utils"
Scott Baker807addd2019-10-24 15:16:21 -070028 fu "github.com/opencord/voltha-lib-go/v2/pkg/flows"
29 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Baker555307d2019-11-04 08:58:01 -080030 ic "github.com/opencord/voltha-protos/v2/go/inter_container"
31 ofp "github.com/opencord/voltha-protos/v2/go/openflow_13"
32 "github.com/opencord/voltha-protos/v2/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040033 "google.golang.org/grpc/codes"
34 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040035)
36
37type DeviceAgent struct {
khenaidoo9a468962018-09-19 15:33:13 -040038 deviceId string
khenaidoo6d62c002019-05-15 21:57:03 -040039 parentId string
khenaidoo43c82122018-11-22 18:38:28 -050040 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040041 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040042 lastData *voltha.Device
43 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070044 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040045 deviceMgr *DeviceManager
46 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040047 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040048 exitChannel chan int
khenaidoo92e62c52018-10-03 14:02:54 -040049 lockDevice sync.RWMutex
khenaidoo2c6a0992019-04-29 13:46:56 -040050 defaultTimeout int64
khenaidoob9203542018-09-17 22:56:37 -040051}
52
khenaidoo4d4802d2018-10-04 21:59:49 -040053//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
54//preprovisioning
khenaidoo2c6a0992019-04-29 13:46:56 -040055func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout int64) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040056 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040057 agent.adapterProxy = ap
khenaidoo92e62c52018-10-03 14:02:54 -040058 cloned := (proto.Clone(device)).(*voltha.Device)
Stephane Barbarie1ab43272018-12-08 21:42:13 -050059 if cloned.Id == "" {
60 cloned.Id = CreateDeviceId()
khenaidoo297cd252019-02-07 22:10:23 -050061 cloned.AdminState = voltha.AdminState_PREPROVISIONED
62 cloned.FlowGroups = &ofp.FlowGroups{Items: nil}
63 cloned.Flows = &ofp.Flows{Items: nil}
Stephane Barbarie1ab43272018-12-08 21:42:13 -050064 }
khenaidoo19d7b632018-10-30 10:49:50 -040065 if !device.GetRoot() && device.ProxyAddress != nil {
66 // Set the default vlan ID to the one specified by the parent adapter. It can be
67 // overwritten by the child adapter during a device update request
68 cloned.Vlan = device.ProxyAddress.ChannelId
69 }
khenaidoo2c6a0992019-04-29 13:46:56 -040070 agent.isRootdevice = device.Root
khenaidoo92e62c52018-10-03 14:02:54 -040071 agent.deviceId = cloned.Id
khenaidoo6d62c002019-05-15 21:57:03 -040072 agent.parentId = device.ParentId
khenaidoofdbad6e2018-11-06 22:26:38 -050073 agent.deviceType = cloned.Type
khenaidoo92e62c52018-10-03 14:02:54 -040074 agent.lastData = cloned
khenaidoob9203542018-09-17 22:56:37 -040075 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050076 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040077 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040078 agent.clusterDataProxy = cdProxy
khenaidoo92e62c52018-10-03 14:02:54 -040079 agent.lockDevice = sync.RWMutex{}
khenaidoo2c6a0992019-04-29 13:46:56 -040080 agent.defaultTimeout = timeout
khenaidoob9203542018-09-17 22:56:37 -040081 return &agent
82}
83
khenaidoo297cd252019-02-07 22:10:23 -050084// start save the device to the data model and registers for callbacks on that device if loadFromdB is false. Otherwise,
85// it will load the data from the dB and setup teh necessary callbacks and proxies.
86func (agent *DeviceAgent) start(ctx context.Context, loadFromdB bool) error {
khenaidoo92e62c52018-10-03 14:02:54 -040087 agent.lockDevice.Lock()
88 defer agent.lockDevice.Unlock()
khenaidoo297cd252019-02-07 22:10:23 -050089 log.Debugw("starting-device-agent", log.Fields{"deviceId": agent.deviceId})
90 if loadFromdB {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040091 if device := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceId, 1, false, ""); device != nil {
khenaidoo297cd252019-02-07 22:10:23 -050092 if d, ok := device.(*voltha.Device); ok {
93 agent.lastData = proto.Clone(d).(*voltha.Device)
khenaidoo6d055132019-02-12 16:51:19 -050094 agent.deviceType = agent.lastData.Adapter
khenaidoo297cd252019-02-07 22:10:23 -050095 }
96 } else {
97 log.Errorw("failed-to-load-device", log.Fields{"deviceId": agent.deviceId})
98 return status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
99 }
khenaidoo4c9e5592019-09-09 16:20:41 -0400100 log.Debugw("device-loaded-from-dB", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500101 } else {
102 // Add the initial device to the local model
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400103 if added := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceId, agent.lastData, ""); added == nil {
khenaidoo297cd252019-02-07 22:10:23 -0500104 log.Errorw("failed-to-add-device", log.Fields{"deviceId": agent.deviceId})
khenaidoo4c9e5592019-09-09 16:20:41 -0400105 return status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceId)
khenaidoo297cd252019-02-07 22:10:23 -0500106 }
khenaidoob9203542018-09-17 22:56:37 -0400107 }
khenaidoo297cd252019-02-07 22:10:23 -0500108
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400109 agent.deviceProxy = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceId, false)
khenaidoo43c82122018-11-22 18:38:28 -0500110 agent.deviceProxy.RegisterCallback(model.POST_UPDATE, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400111
khenaidoo4c9e5592019-09-09 16:20:41 -0400112 log.Debugw("device-agent-started", log.Fields{"deviceId": agent.deviceId})
khenaidoo297cd252019-02-07 22:10:23 -0500113 return nil
khenaidoob9203542018-09-17 22:56:37 -0400114}
115
khenaidoo4d4802d2018-10-04 21:59:49 -0400116// stop stops the device agent. Not much to do for now
117func (agent *DeviceAgent) stop(ctx context.Context) {
khenaidoo92e62c52018-10-03 14:02:54 -0400118 agent.lockDevice.Lock()
119 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -0400120 log.Debug("stopping-device-agent")
khenaidoo0a822f92019-05-08 15:15:57 -0400121 // Remove the device from the KV store
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400122 if removed := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceId, ""); removed == nil {
khenaidoo4554f7c2019-05-29 22:13:15 -0400123 log.Debugw("device-already-removed", log.Fields{"id": agent.deviceId})
khenaidoo0a822f92019-05-08 15:15:57 -0400124 }
khenaidoob9203542018-09-17 22:56:37 -0400125 agent.exitChannel <- 1
126 log.Debug("device-agent-stopped")
khenaidoo0a822f92019-05-08 15:15:57 -0400127
khenaidoob9203542018-09-17 22:56:37 -0400128}
129
khenaidoo19d7b632018-10-30 10:49:50 -0400130// GetDevice retrieves the latest device information from the data model
khenaidoo92e62c52018-10-03 14:02:54 -0400131func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400132 agent.lockDevice.RLock()
133 defer agent.lockDevice.RUnlock()
Stephane Barbarieb6b68c42019-10-10 16:05:13 -0400134 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400135 if d, ok := device.(*voltha.Device); ok {
136 cloned := proto.Clone(d).(*voltha.Device)
137 return cloned, nil
138 }
139 }
140 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
141}
142
khenaidoo4d4802d2018-10-04 21:59:49 -0400143// 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 -0400144// This function is meant so that we do not have duplicate code all over the device agent functions
145func (agent *DeviceAgent) getDeviceWithoutLock() (*voltha.Device, error) {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400146 if device := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceId, 0, false, ""); device != nil {
khenaidoo92e62c52018-10-03 14:02:54 -0400147 if d, ok := device.(*voltha.Device); ok {
148 cloned := proto.Clone(d).(*voltha.Device)
149 return cloned, nil
150 }
151 }
152 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceId)
153}
154
khenaidoo3ab34882019-05-02 21:33:30 -0400155// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400156func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo92e62c52018-10-03 14:02:54 -0400157 agent.lockDevice.Lock()
158 defer agent.lockDevice.Unlock()
159 log.Debugw("enableDevice", log.Fields{"id": agent.deviceId})
khenaidoo21d51152019-02-01 13:48:37 -0500160
khenaidoo92e62c52018-10-03 14:02:54 -0400161 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -0400162 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
163 } else {
khenaidoo21d51152019-02-01 13:48:37 -0500164 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
165 // pre-provisionned with the required adapter not registered. At this stage, since we need to communicate
166 // with the adapter then we need to know the adapter that will handle this request
167 if adapterName, err := agent.adapterMgr.getAdapterName(device.Type); err != nil {
168 log.Warnw("no-adapter-registered-for-device-type", log.Fields{"deviceType": device.Type, "deviceAdapter": device.Adapter})
169 return err
170 } else {
171 device.Adapter = adapterName
172 }
173
khenaidoo92e62c52018-10-03 14:02:54 -0400174 if device.AdminState == voltha.AdminState_ENABLED {
175 log.Debugw("device-already-enabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400176 return nil
177 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400178
179 if device.AdminState == voltha.AdminState_DELETED {
180 // This is a temporary state when a device is deleted before it gets removed from the model.
181 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", device.Id))
182 log.Warnw("invalid-state", log.Fields{"id": agent.deviceId, "state": device.AdminState, "error": err})
183 return err
khenaidoo3ab34882019-05-02 21:33:30 -0400184 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400185
186 previousAdminState := device.AdminState
187
188 // Update the Admin State and set the operational state to activating before sending the request to the
189 // Adapters
190 cloned := proto.Clone(device).(*voltha.Device)
191 cloned.AdminState = voltha.AdminState_ENABLED
192 cloned.OperStatus = voltha.OperStatus_ACTIVATING
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400193
Mahir Gunyelb5851672019-07-24 10:46:26 +0300194 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
195 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400196 }
197
198 // Adopt the device if it was in preprovision state. In all other cases, try to reenable it.
199 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo92e62c52018-10-03 14:02:54 -0400200 if err := agent.adapterProxy.AdoptDevice(ctx, device); err != nil {
201 log.Debugw("adoptDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoob9203542018-09-17 22:56:37 -0400202 return err
203 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400204 } else {
khenaidoo92e62c52018-10-03 14:02:54 -0400205 if err := agent.adapterProxy.ReEnableDevice(ctx, device); err != nil {
206 log.Debugw("renableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
207 return err
208 }
khenaidoob9203542018-09-17 22:56:37 -0400209 }
210 }
211 return nil
212}
213
khenaidoo2c6a0992019-04-29 13:46:56 -0400214func (agent *DeviceAgent) updateDeviceWithoutLockAsync(device *voltha.Device, ch chan interface{}) {
215 if err := agent.updateDeviceWithoutLock(device); err != nil {
216 ch <- status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceId)
khenaidoo19d7b632018-10-30 10:49:50 -0400217 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400218 ch <- nil
khenaidoo19d7b632018-10-30 10:49:50 -0400219}
220
Manikkaraj kb1a10922019-07-29 12:10:34 -0400221func (agent *DeviceAgent) sendBulkFlowsToAdapters(device *voltha.Device, flows *voltha.Flows, groups *voltha.FlowGroups, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
222 if err := agent.adapterProxy.UpdateFlowsBulk(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400223 log.Debugw("update-flow-bulk-error", log.Fields{"id": agent.lastData.Id, "error": err})
224 ch <- err
225 }
226 ch <- nil
227}
228
Manikkaraj kb1a10922019-07-29 12:10:34 -0400229func (agent *DeviceAgent) sendIncrementalFlowsToAdapters(device *voltha.Device, flows *ofp.FlowChanges, groups *ofp.FlowGroupChanges, flowMetadata *voltha.FlowMetadata, ch chan interface{}) {
230 if err := agent.adapterProxy.UpdateFlowsIncremental(device, flows, groups, flowMetadata); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400231 log.Debugw("update-flow-incremental-error", log.Fields{"id": agent.lastData.Id, "error": err})
232 ch <- err
233 }
234 ch <- nil
235}
236
khenaidoo0458db62019-06-20 08:50:36 -0400237//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
238//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400239func (agent *DeviceAgent) addFlowsAndGroups(newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
240 log.Debugw("addFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups, "flowMetadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400241
khenaidoo2c6a0992019-04-29 13:46:56 -0400242 if (len(newFlows) | len(newGroups)) == 0 {
243 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
244 return nil
245 }
246
khenaidoo19d7b632018-10-30 10:49:50 -0400247 agent.lockDevice.Lock()
248 defer agent.lockDevice.Unlock()
khenaidoo2c6a0992019-04-29 13:46:56 -0400249
khenaidoo0458db62019-06-20 08:50:36 -0400250 var device *voltha.Device
251 var err error
252 if device, err = agent.getDeviceWithoutLock(); err != nil {
253 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
254 }
255
256 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
257 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
258
259 var updatedFlows []*ofp.OfpFlowStats
260 var flowsToDelete []*ofp.OfpFlowStats
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400261 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo0458db62019-06-20 08:50:36 -0400262 var updatedGroups []*ofp.OfpGroupEntry
263
264 // Process flows
265 for _, flow := range newFlows {
266 updatedFlows = append(updatedFlows, flow)
267 }
268 for _, flow := range existingFlows.Items {
269 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400270 updatedFlows = append(updatedFlows, flow)
khenaidoo0458db62019-06-20 08:50:36 -0400271 } else {
272 flowsToDelete = append(flowsToDelete, flow)
273 }
274 }
275
276 // Process groups
277 for _, g := range newGroups {
278 updatedGroups = append(updatedGroups, g)
279 }
280 for _, group := range existingGroups.Items {
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400281 if fu.FindGroup(newGroups, group.Desc.GroupId) == -1 { // does not exist now
282 updatedGroups = append(updatedGroups, group)
283 } else {
284 groupsToDelete = append(groupsToDelete, group)
khenaidoo0458db62019-06-20 08:50:36 -0400285 }
286 }
287
288 // Sanity check
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400289 if (len(updatedFlows) | len(flowsToDelete) | len(updatedGroups) | len(groupsToDelete)) == 0 {
khenaidoo0458db62019-06-20 08:50:36 -0400290 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
291 return nil
292 }
293
294 // Send update to adapters
295 // Create two channels to receive responses from the dB and from the adapters.
296 // Do not close these channels as this function may exit on timeout before the dB or adapters get a chance
297 // to send their responses. These channels will be garbage collected once all the responses are
298 // received
299 chAdapters := make(chan interface{})
300 chdB := make(chan interface{})
301 dType := agent.adapterMgr.getDeviceType(device.Type)
302 if !dType.AcceptsAddRemoveFlowUpdates {
303
304 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
305 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": newFlows, "groups": newGroups})
306 return nil
307 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400308 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400309
310 } else {
311 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400312 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400313 ToRemove: &voltha.Flows{Items: flowsToDelete},
314 }
315 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400316 ToAdd: &voltha.FlowGroups{Items: newGroups},
317 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400318 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
319 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400320 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400321 }
322
323 // store the changed data
324 device.Flows = &voltha.Flows{Items: updatedFlows}
325 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
326 go agent.updateDeviceWithoutLockAsync(device, chdB)
327
Scott Bakerb671a862019-10-24 10:53:40 -0700328 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400329 log.Debugw("Failed to get response from adapter[or] DB", log.Fields{"result": res})
khenaidoo0458db62019-06-20 08:50:36 -0400330 return status.Errorf(codes.Aborted, "errors-%s", res)
331 }
332
333 return nil
334}
335
336//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
337//adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400338func (agent *DeviceAgent) deleteFlowsAndGroups(flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400339 log.Debugw("deleteFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
340
341 if (len(flowsToDel) | len(groupsToDel)) == 0 {
342 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": flowsToDel, "groups": groupsToDel})
343 return nil
344 }
345
346 agent.lockDevice.Lock()
347 defer agent.lockDevice.Unlock()
348
349 var device *voltha.Device
350 var err error
351
352 if device, err = agent.getDeviceWithoutLock(); err != nil {
353 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
354 }
355
356 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
357 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
358
359 var flowsToKeep []*ofp.OfpFlowStats
360 var groupsToKeep []*ofp.OfpGroupEntry
361
362 // Process flows
363 for _, flow := range existingFlows.Items {
364 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
365 flowsToKeep = append(flowsToKeep, flow)
366 }
367 }
368
369 // Process groups
370 for _, group := range existingGroups.Items {
371 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
372 groupsToKeep = append(groupsToKeep, group)
373 }
374 }
375
376 log.Debugw("deleteFlowsAndGroups",
377 log.Fields{
378 "deviceId": agent.deviceId,
379 "flowsToDel": len(flowsToDel),
380 "flowsToKeep": len(flowsToKeep),
381 "groupsToDel": len(groupsToDel),
382 "groupsToKeep": len(groupsToKeep),
383 })
384
385 // Sanity check
386 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
387 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
388 return nil
389 }
390
391 // Send update to adapters
392 chAdapters := make(chan interface{})
393 chdB := make(chan interface{})
394 dType := agent.adapterMgr.getDeviceType(device.Type)
395 if !dType.AcceptsAddRemoveFlowUpdates {
396 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
397 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
398 return nil
399 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400400 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400401 } else {
402 flowChanges := &ofp.FlowChanges{
403 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
404 ToRemove: &voltha.Flows{Items: flowsToDel},
405 }
406 groupChanges := &ofp.FlowGroupChanges{
407 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
408 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
409 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
410 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400411 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400412 }
413
414 // store the changed data
415 device.Flows = &voltha.Flows{Items: flowsToKeep}
416 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
417 go agent.updateDeviceWithoutLockAsync(device, chdB)
418
Scott Bakerb671a862019-10-24 10:53:40 -0700419 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400420 return status.Errorf(codes.Aborted, "errors-%s", res)
421 }
422 return nil
423
424}
425
426//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
427//also sends the updates to the adapters
Manikkaraj kb1a10922019-07-29 12:10:34 -0400428func (agent *DeviceAgent) updateFlowsAndGroups(updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
khenaidoo0458db62019-06-20 08:50:36 -0400429 log.Debugw("updateFlowsAndGroups", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
430
431 if (len(updatedFlows) | len(updatedGroups)) == 0 {
432 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
433 return nil
434 }
435
436 agent.lockDevice.Lock()
437 defer agent.lockDevice.Unlock()
438 var device *voltha.Device
439 var err error
440 if device, err = agent.getDeviceWithoutLock(); err != nil {
441 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
442 }
443 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
444 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
445
446 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
447 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
448 return nil
449 }
450
451 log.Debugw("updating-flows-and-groups",
452 log.Fields{
453 "deviceId": agent.deviceId,
454 "updatedFlows": updatedFlows,
455 "updatedGroups": updatedGroups,
456 })
457
458 chAdapters := make(chan interface{})
459 chdB := make(chan interface{})
460 dType := agent.adapterMgr.getDeviceType(device.Type)
461
462 // Process bulk flow update differently than incremental update
463 if !dType.AcceptsAddRemoveFlowUpdates {
Manikkaraj kb1a10922019-07-29 12:10:34 -0400464 go agent.sendBulkFlowsToAdapters(device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil, chAdapters)
khenaidoo0458db62019-06-20 08:50:36 -0400465 } else {
466 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400467 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400468 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400469 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400470
471 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400472 for _, flow := range updatedFlows {
473 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
474 flowsToAdd = append(flowsToAdd, flow)
475 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400476 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400477 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400478 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400479 flowsToDelete = append(flowsToDelete, flow)
480 }
481 }
482
483 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400484 for _, g := range updatedGroups {
485 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
486 groupsToAdd = append(groupsToAdd, g)
487 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400488 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400489 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400490 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400491 groupsToDelete = append(groupsToDelete, group)
492 }
493 }
494
khenaidoo0458db62019-06-20 08:50:36 -0400495 log.Debugw("updating-flows-and-groups",
496 log.Fields{
497 "deviceId": agent.deviceId,
498 "flowsToAdd": flowsToAdd,
499 "flowsToDelete": flowsToDelete,
500 "groupsToAdd": groupsToAdd,
501 "groupsToDelete": groupsToDelete,
502 })
503
khenaidoo2c6a0992019-04-29 13:46:56 -0400504 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400505 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
506 log.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceId, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo2c6a0992019-04-29 13:46:56 -0400507 return nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400508 }
509
khenaidoo0458db62019-06-20 08:50:36 -0400510 flowChanges := &ofp.FlowChanges{
511 ToAdd: &voltha.Flows{Items: flowsToAdd},
512 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400513 }
khenaidoo0458db62019-06-20 08:50:36 -0400514 groupChanges := &ofp.FlowGroupChanges{
515 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
516 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
517 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
518 }
Manikkaraj kb1a10922019-07-29 12:10:34 -0400519 go agent.sendIncrementalFlowsToAdapters(device, flowChanges, groupChanges, flowMetadata, chAdapters)
khenaidoo19d7b632018-10-30 10:49:50 -0400520 }
khenaidoo0458db62019-06-20 08:50:36 -0400521
522 // store the updated data
523 device.Flows = &voltha.Flows{Items: updatedFlows}
524 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
525 go agent.updateDeviceWithoutLockAsync(device, chdB)
526
Scott Bakerb671a862019-10-24 10:53:40 -0700527 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, chAdapters, chdB); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400528 return status.Errorf(codes.Aborted, "errors-%s", res)
529 }
530 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400531}
532
khenaidoo4d4802d2018-10-04 21:59:49 -0400533//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400534func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo59ef7be2019-06-21 12:40:28 -0400535 agent.lockDevice.Lock()
536 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -0400537 log.Debugw("disableDevice", log.Fields{"id": agent.deviceId})
538 // Get the most up to date the device info
539 if device, err := agent.getDeviceWithoutLock(); err != nil {
540 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
541 } else {
542 if device.AdminState == voltha.AdminState_DISABLED {
543 log.Debugw("device-already-disabled", log.Fields{"id": agent.deviceId})
khenaidoo92e62c52018-10-03 14:02:54 -0400544 return nil
545 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400546 if device.AdminState == voltha.AdminState_PREPROVISIONED ||
547 device.AdminState == voltha.AdminState_DELETED {
548 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
549 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceId, device.AdminState)
550 }
551
khenaidoo59ef7be2019-06-21 12:40:28 -0400552 // Update the Admin State and operational state before sending the request out
553 cloned := proto.Clone(device).(*voltha.Device)
554 cloned.AdminState = voltha.AdminState_DISABLED
555 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Mahir Gunyelb5851672019-07-24 10:46:26 +0300556 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
557 return err
khenaidoo59ef7be2019-06-21 12:40:28 -0400558 }
559
khenaidoo92e62c52018-10-03 14:02:54 -0400560 if err := agent.adapterProxy.DisableDevice(ctx, device); err != nil {
561 log.Debugw("disableDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
khenaidoo92e62c52018-10-03 14:02:54 -0400562 return err
563 }
khenaidoo0a822f92019-05-08 15:15:57 -0400564 }
565 return nil
566}
567
568func (agent *DeviceAgent) updateAdminState(adminState voltha.AdminState_AdminState) error {
569 agent.lockDevice.Lock()
570 defer agent.lockDevice.Unlock()
571 log.Debugw("updateAdminState", log.Fields{"id": agent.deviceId})
572 // Get the most up to date the device info
573 if device, err := agent.getDeviceWithoutLock(); err != nil {
574 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
575 } else {
576 if device.AdminState == adminState {
577 log.Debugw("no-change-needed", log.Fields{"id": agent.deviceId, "state": adminState})
578 return nil
579 }
khenaidoo92e62c52018-10-03 14:02:54 -0400580 // Received an Ack (no error found above). Now update the device in the model to the expected state
581 cloned := proto.Clone(device).(*voltha.Device)
khenaidoo0a822f92019-05-08 15:15:57 -0400582 cloned.AdminState = adminState
Mahir Gunyelb5851672019-07-24 10:46:26 +0300583 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
584 return err
khenaidoo92e62c52018-10-03 14:02:54 -0400585 }
khenaidoo92e62c52018-10-03 14:02:54 -0400586 }
587 return nil
588}
589
khenaidoo4d4802d2018-10-04 21:59:49 -0400590func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
591 agent.lockDevice.Lock()
592 defer agent.lockDevice.Unlock()
593 log.Debugw("rebootDevice", log.Fields{"id": agent.deviceId})
594 // Get the most up to date the device info
595 if device, err := agent.getDeviceWithoutLock(); err != nil {
596 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
597 } else {
khenaidoo4d4802d2018-10-04 21:59:49 -0400598 if err := agent.adapterProxy.RebootDevice(ctx, device); err != nil {
599 log.Debugw("rebootDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
600 return err
601 }
602 }
603 return nil
604}
605
606func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
607 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -0400608 defer agent.lockDevice.Unlock()
khenaidoo4d4802d2018-10-04 21:59:49 -0400609 log.Debugw("deleteDevice", log.Fields{"id": agent.deviceId})
610 // Get the most up to date the device info
611 if device, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo4d4802d2018-10-04 21:59:49 -0400612 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
613 } else {
khenaidoo0a822f92019-05-08 15:15:57 -0400614 if device.AdminState == voltha.AdminState_DELETED {
615 log.Debugw("device-already-in-deleted-state", log.Fields{"id": agent.deviceId})
616 return nil
617 }
khenaidoo43c82122018-11-22 18:38:28 -0500618 if (device.AdminState != voltha.AdminState_DISABLED) &&
619 (device.AdminState != voltha.AdminState_PREPROVISIONED) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400620 log.Debugw("device-not-disabled", log.Fields{"id": agent.deviceId})
621 //TODO: Needs customized error message
khenaidoo4d4802d2018-10-04 21:59:49 -0400622 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_DISABLED)
623 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400624 if device.AdminState != voltha.AdminState_PREPROVISIONED {
625 // Send the request to an Adapter only if the device is not in poreporovision state and wait for a response
626 if err := agent.adapterProxy.DeleteDevice(ctx, device); err != nil {
627 log.Debugw("deleteDevice-error", log.Fields{"id": agent.lastData.Id, "error": err})
628 return err
629 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400630 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400631 // Set the state to deleted after we recieve an Ack - this will trigger some background process to clean up
632 // the device as well as its association with the logical device
khenaidoo0a822f92019-05-08 15:15:57 -0400633 cloned := proto.Clone(device).(*voltha.Device)
634 cloned.AdminState = voltha.AdminState_DELETED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300635 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
636 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400637 }
khenaidoo0a822f92019-05-08 15:15:57 -0400638 // If this is a child device then remove the associated peer ports on the parent device
639 if !device.Root {
640 go agent.deviceMgr.deletePeerPorts(device.ParentId, device.Id)
641 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400642 }
643 return nil
644}
645
khenaidooad06fd72019-10-28 12:26:05 -0400646func (agent *DeviceAgent) setParentId(device *voltha.Device, parentId string) error {
647 agent.lockDevice.Lock()
648 defer agent.lockDevice.Unlock()
649 log.Debugw("setParentId", log.Fields{"deviceId": device.Id, "parentId": parentId})
650 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
651 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
652 } else {
653 // clone the device
654 cloned := proto.Clone(storeDevice).(*voltha.Device)
655 cloned.ParentId = parentId
656 // Store the device
657 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
658 return err
659 }
660 return nil
661 }
662}
663
khenaidoob3127472019-07-24 21:04:55 -0400664func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
665 agent.lockDevice.Lock()
666 defer agent.lockDevice.Unlock()
667 log.Debugw("updatePmConfigs", log.Fields{"id": pmConfigs.Id})
668 // Work only on latest data
669 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
670 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
671 } else {
672 // clone the device
673 cloned := proto.Clone(storeDevice).(*voltha.Device)
674 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
675 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +0300676 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
677 return err
khenaidoob3127472019-07-24 21:04:55 -0400678 }
679 // Send the request to the adapter
680 if err := agent.adapterProxy.UpdatePmConfigs(ctx, cloned, pmConfigs); err != nil {
681 log.Errorw("update-pm-configs-error", log.Fields{"id": agent.lastData.Id, "error": err})
682 return err
683 }
684 return nil
685 }
686}
687
688func (agent *DeviceAgent) initPmConfigs(pmConfigs *voltha.PmConfigs) error {
689 agent.lockDevice.Lock()
690 defer agent.lockDevice.Unlock()
691 log.Debugw("initPmConfigs", log.Fields{"id": pmConfigs.Id})
692 // Work only on latest data
693 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
694 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
695 } else {
696 // clone the device
697 cloned := proto.Clone(storeDevice).(*voltha.Device)
698 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
699 // Store the device
700 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
701 afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, cloned, false, "")
702 if afterUpdate == nil {
703 return status.Errorf(codes.Internal, "%s", agent.deviceId)
704 }
705 return nil
706 }
707}
708
709func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
710 agent.lockDevice.RLock()
711 defer agent.lockDevice.RUnlock()
712 log.Debugw("listPmConfigs", log.Fields{"id": agent.deviceId})
713 // Get the most up to date the device info
714 if device, err := agent.getDeviceWithoutLock(); err != nil {
715 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
716 } else {
717 cloned := proto.Clone(device).(*voltha.Device)
718 return cloned.PmConfigs, nil
719 }
720}
721
khenaidoof5a5bfa2019-01-23 22:20:29 -0500722func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
723 agent.lockDevice.Lock()
724 defer agent.lockDevice.Unlock()
725 log.Debugw("downloadImage", log.Fields{"id": agent.deviceId})
726 // Get the most up to date the device info
727 if device, err := agent.getDeviceWithoutLock(); err != nil {
728 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
729 } else {
730 if device.AdminState != voltha.AdminState_ENABLED {
731 log.Debugw("device-not-enabled", log.Fields{"id": agent.deviceId})
732 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceId, voltha.AdminState_ENABLED)
733 }
734 // Save the image
735 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500736 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500737 cloned := proto.Clone(device).(*voltha.Device)
738 if cloned.ImageDownloads == nil {
739 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
740 } else {
741 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
742 }
743 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300744 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
745 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500746 }
747 // Send the request to the adapter
748 if err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg); err != nil {
749 log.Debugw("downloadImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
750 return nil, err
751 }
752 }
753 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
754}
755
756// isImageRegistered is a helper method to figure out if an image is already registered
757func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
758 for _, image := range device.ImageDownloads {
759 if image.Id == img.Id && image.Name == img.Name {
760 return true
761 }
762 }
763 return false
764}
765
766func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
767 agent.lockDevice.Lock()
768 defer agent.lockDevice.Unlock()
769 log.Debugw("cancelImageDownload", log.Fields{"id": agent.deviceId})
770 // Get the most up to date the device info
771 if device, err := agent.getDeviceWithoutLock(); err != nil {
772 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
773 } else {
774 // Verify whether the Image is in the list of image being downloaded
775 if !isImageRegistered(img, device) {
776 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
777 }
778
779 // Update image download state
780 cloned := proto.Clone(device).(*voltha.Device)
781 for _, image := range cloned.ImageDownloads {
782 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500783 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500784 }
785 }
786
khenaidoof5a5bfa2019-01-23 22:20:29 -0500787 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500788 // Set the device to Enabled
789 cloned.AdminState = voltha.AdminState_ENABLED
Mahir Gunyelb5851672019-07-24 10:46:26 +0300790 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
791 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500792 }
khenaidoo59ef7be2019-06-21 12:40:28 -0400793 // Send the request to teh adapter
794 if err := agent.adapterProxy.CancelImageDownload(ctx, device, img); err != nil {
795 log.Debugw("cancelImageDownload-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
796 return nil, err
797 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500798 }
799 }
800 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700801}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500802
803func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
804 agent.lockDevice.Lock()
805 defer agent.lockDevice.Unlock()
806 log.Debugw("activateImage", log.Fields{"id": agent.deviceId})
807 // Get the most up to date the device info
808 if device, err := agent.getDeviceWithoutLock(); err != nil {
809 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
810 } else {
811 // Verify whether the Image is in the list of image being downloaded
812 if !isImageRegistered(img, device) {
813 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
814 }
815
816 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
817 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-in-downloading-state:%s", agent.deviceId, img.Name)
818 }
819 // Update image download state
820 cloned := proto.Clone(device).(*voltha.Device)
821 for _, image := range cloned.ImageDownloads {
822 if image.Id == img.Id && image.Name == img.Name {
823 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
824 }
825 }
826 // Set the device to downloading_image
827 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
Mahir Gunyelb5851672019-07-24 10:46:26 +0300828 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
829 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500830 }
831
832 if err := agent.adapterProxy.ActivateImageUpdate(ctx, device, img); err != nil {
833 log.Debugw("activateImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
834 return nil, err
835 }
836 // The status of the AdminState will be changed following the update_download_status response from the adapter
837 // The image name will also be removed from the device list
838 }
serkant.uluderya334479d2019-04-10 08:26:15 -0700839 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
840}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500841
842func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
843 agent.lockDevice.Lock()
844 defer agent.lockDevice.Unlock()
845 log.Debugw("revertImage", log.Fields{"id": agent.deviceId})
846 // Get the most up to date the device info
847 if device, err := agent.getDeviceWithoutLock(); err != nil {
848 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
849 } else {
850 // Verify whether the Image is in the list of image being downloaded
851 if !isImageRegistered(img, device) {
852 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceId, img.Name)
853 }
854
855 if device.AdminState != voltha.AdminState_ENABLED {
856 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceId, img.Name)
857 }
858 // Update image download state
859 cloned := proto.Clone(device).(*voltha.Device)
860 for _, image := range cloned.ImageDownloads {
861 if image.Id == img.Id && image.Name == img.Name {
862 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
863 }
864 }
Mahir Gunyelb5851672019-07-24 10:46:26 +0300865
866 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
867 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500868 }
869
870 if err := agent.adapterProxy.RevertImageUpdate(ctx, device, img); err != nil {
871 log.Debugw("revertImage-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
872 return nil, err
873 }
874 }
875 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -0700876}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500877
878func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
879 agent.lockDevice.Lock()
880 defer agent.lockDevice.Unlock()
881 log.Debugw("getImageDownloadStatus", log.Fields{"id": agent.deviceId})
882 // Get the most up to date the device info
883 if device, err := agent.getDeviceWithoutLock(); err != nil {
884 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
885 } else {
886 if resp, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img); err != nil {
887 log.Debugw("getImageDownloadStatus-error", log.Fields{"id": agent.lastData.Id, "error": err, "image": img.Name})
888 return nil, err
889 } else {
890 return resp, nil
891 }
892 }
893}
894
serkant.uluderya334479d2019-04-10 08:26:15 -0700895func (agent *DeviceAgent) updateImageDownload(img *voltha.ImageDownload) error {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500896 agent.lockDevice.Lock()
897 defer agent.lockDevice.Unlock()
898 log.Debugw("updateImageDownload", log.Fields{"id": agent.deviceId})
899 // Get the most up to date the device info
900 if device, err := agent.getDeviceWithoutLock(); err != nil {
901 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
902 } else {
903 // Update the image as well as remove it if the download was cancelled
904 cloned := proto.Clone(device).(*voltha.Device)
905 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
906 for _, image := range cloned.ImageDownloads {
907 if image.Id == img.Id && image.Name == img.Name {
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500908 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500909 clonedImages = append(clonedImages, img)
910 }
911 }
912 }
913 cloned.ImageDownloads = clonedImages
914 // Set the Admin state to enabled if required
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500915 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
916 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
serkant.uluderya334479d2019-04-10 08:26:15 -0700917 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500918 cloned.AdminState = voltha.AdminState_ENABLED
919 }
920
Mahir Gunyelb5851672019-07-24 10:46:26 +0300921 if err := agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
922 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500923 }
924 }
925 return nil
926}
927
928func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400929 agent.lockDevice.RLock()
930 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500931 log.Debugw("getImageDownload", log.Fields{"id": agent.deviceId})
932 // Get the most up to date the device info
933 if device, err := agent.getDeviceWithoutLock(); err != nil {
934 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
935 } else {
936 for _, image := range device.ImageDownloads {
937 if image.Id == img.Id && image.Name == img.Name {
938 return image, nil
939 }
940 }
941 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
942 }
943}
944
945func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceId string) (*voltha.ImageDownloads, error) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400946 agent.lockDevice.RLock()
947 defer agent.lockDevice.RUnlock()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500948 log.Debugw("listImageDownloads", log.Fields{"id": agent.deviceId})
949 // Get the most up to date the device info
950 if device, err := agent.getDeviceWithoutLock(); err != nil {
951 return nil, status.Errorf(codes.NotFound, "%s", agent.deviceId)
952 } else {
serkant.uluderya334479d2019-04-10 08:26:15 -0700953 return &voltha.ImageDownloads{Items: device.ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -0500954 }
955}
956
khenaidoo4d4802d2018-10-04 21:59:49 -0400957// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -0400958func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
959 log.Debugw("getPorts", log.Fields{"id": agent.deviceId, "portType": portType})
khenaidoob9203542018-09-17 22:56:37 -0400960 ports := &voltha.Ports{}
khenaidoo19d7b632018-10-30 10:49:50 -0400961 if device, _ := agent.deviceMgr.GetDevice(agent.deviceId); device != nil {
khenaidoob9203542018-09-17 22:56:37 -0400962 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -0400963 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -0400964 ports.Items = append(ports.Items, port)
965 }
966 }
967 }
968 return ports
969}
970
khenaidoo4d4802d2018-10-04 21:59:49 -0400971// getSwitchCapability is a helper method that a logical device agent uses to retrieve the switch capability of a
972// parent device
khenaidoo79232702018-12-04 11:00:41 -0500973func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400974 log.Debugw("getSwitchCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400975 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400976 return nil, err
977 } else {
khenaidoo79232702018-12-04 11:00:41 -0500978 var switchCap *ic.SwitchCapability
khenaidoob9203542018-09-17 22:56:37 -0400979 var err error
980 if switchCap, err = agent.adapterProxy.GetOfpDeviceInfo(ctx, device); err != nil {
981 log.Debugw("getSwitchCapability-error", log.Fields{"id": device.Id, "error": err})
982 return nil, err
983 }
984 return switchCap, nil
985 }
986}
987
khenaidoo4d4802d2018-10-04 21:59:49 -0400988// getPortCapability is a helper method that a logical device agent uses to retrieve the port capability of a
989// device
khenaidoo79232702018-12-04 11:00:41 -0500990func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
khenaidoob9203542018-09-17 22:56:37 -0400991 log.Debugw("getPortCapability", log.Fields{"deviceId": agent.deviceId})
khenaidoo19d7b632018-10-30 10:49:50 -0400992 if device, err := agent.deviceMgr.GetDevice(agent.deviceId); device == nil {
khenaidoob9203542018-09-17 22:56:37 -0400993 return nil, err
994 } else {
khenaidoo79232702018-12-04 11:00:41 -0500995 var portCap *ic.PortCapability
khenaidoob9203542018-09-17 22:56:37 -0400996 var err error
997 if portCap, err = agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo); err != nil {
998 log.Debugw("getPortCapability-error", log.Fields{"id": device.Id, "error": err})
999 return nil, err
1000 }
1001 return portCap, nil
1002 }
1003}
1004
khenaidoofdbad6e2018-11-06 22:26:38 -05001005func (agent *DeviceAgent) packetOut(outPort uint32, packet *ofp.OfpPacketOut) error {
1006 // Send packet to adapter
1007 if err := agent.adapterProxy.packetOut(agent.deviceType, agent.deviceId, outPort, packet); err != nil {
1008 log.Debugw("packet-out-error", log.Fields{"id": agent.lastData.Id, "error": err})
1009 return err
1010 }
1011 return nil
1012}
1013
khenaidoo4d4802d2018-10-04 21:59:49 -04001014// processUpdate is a callback invoked whenever there is a change on the device manages by this device agent
khenaidoo92e62c52018-10-03 14:02:54 -04001015func (agent *DeviceAgent) processUpdate(args ...interface{}) interface{} {
khenaidoo43c82122018-11-22 18:38:28 -05001016 //// Run this callback in its own go routine
1017 go func(args ...interface{}) interface{} {
1018 var previous *voltha.Device
1019 var current *voltha.Device
1020 var ok bool
1021 if len(args) == 2 {
1022 if previous, ok = args[0].(*voltha.Device); !ok {
1023 log.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
1024 return nil
1025 }
1026 if current, ok = args[1].(*voltha.Device); !ok {
1027 log.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
1028 return nil
1029 }
1030 } else {
1031 log.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
1032 return nil
1033 }
1034 // Perform the state transition in it's own go routine
khenaidoof5a5bfa2019-01-23 22:20:29 -05001035 if err := agent.deviceMgr.processTransition(previous, current); err != nil {
1036 log.Errorw("failed-process-transition", log.Fields{"deviceId": previous.Id,
1037 "previousAdminState": previous.AdminState, "currentAdminState": current.AdminState})
1038 }
khenaidoo43c82122018-11-22 18:38:28 -05001039 return nil
1040 }(args...)
1041
khenaidoo92e62c52018-10-03 14:02:54 -04001042 return nil
1043}
1044
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001045// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1046// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1047func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
1048 // First retrieve the most up to date device info
1049 var currentDevice *voltha.Device
1050 var err error
1051 if currentDevice, err = agent.getDeviceWithoutLock(); err != nil {
1052 return nil, err
1053 }
1054 cloned := proto.Clone(currentDevice).(*voltha.Device)
1055 cloned.Root = device.Root
1056 cloned.Vendor = device.Vendor
1057 cloned.Model = device.Model
1058 cloned.SerialNumber = device.SerialNumber
1059 cloned.MacAddress = device.MacAddress
1060 cloned.Vlan = device.Vlan
1061 cloned.Reason = device.Reason
1062 return cloned, nil
1063}
1064func (agent *DeviceAgent) updateDeviceUsingAdapterData(device *voltha.Device) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001065 agent.lockDevice.Lock()
khenaidoo43c82122018-11-22 18:38:28 -05001066 defer agent.lockDevice.Unlock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001067 log.Debugw("updateDeviceUsingAdapterData", log.Fields{"deviceId": device.Id})
1068 if updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device); err != nil {
1069 log.Errorw("failed to update device ", log.Fields{"deviceId": device.Id})
1070 return status.Errorf(codes.Internal, "%s", err.Error())
1071 } else {
1072 cloned := proto.Clone(updatedDevice).(*voltha.Device)
1073 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1074 }
khenaidoo43c82122018-11-22 18:38:28 -05001075}
1076
1077func (agent *DeviceAgent) updateDeviceWithoutLock(device *voltha.Device) error {
1078 log.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
1079 cloned := proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001080 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001081}
1082
khenaidoo92e62c52018-10-03 14:02:54 -04001083func (agent *DeviceAgent) updateDeviceStatus(operStatus voltha.OperStatus_OperStatus, connStatus voltha.ConnectStatus_ConnectStatus) error {
1084 agent.lockDevice.Lock()
khenaidoo0a822f92019-05-08 15:15:57 -04001085 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001086 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001087 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001088 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1089 } else {
1090 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001091 cloned := proto.Clone(storeDevice).(*voltha.Device)
1092 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1093 if s, ok := voltha.ConnectStatus_ConnectStatus_value[connStatus.String()]; ok {
1094 log.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
1095 cloned.ConnectStatus = connStatus
khenaidoob9203542018-09-17 22:56:37 -04001096 }
khenaidoo92e62c52018-10-03 14:02:54 -04001097 if s, ok := voltha.OperStatus_OperStatus_value[operStatus.String()]; ok {
1098 log.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
1099 cloned.OperStatus = operStatus
khenaidoob9203542018-09-17 22:56:37 -04001100 }
khenaidoo92e62c52018-10-03 14:02:54 -04001101 log.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
khenaidoob9203542018-09-17 22:56:37 -04001102 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001103 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001104 }
1105}
1106
khenaidoo3ab34882019-05-02 21:33:30 -04001107func (agent *DeviceAgent) enablePorts() error {
1108 agent.lockDevice.Lock()
1109 defer agent.lockDevice.Unlock()
1110 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1111 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1112 } else {
1113 // clone the device
1114 cloned := proto.Clone(storeDevice).(*voltha.Device)
1115 for _, port := range cloned.Ports {
1116 port.AdminState = voltha.AdminState_ENABLED
1117 port.OperStatus = voltha.OperStatus_ACTIVE
1118 }
1119 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001120 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001121 }
1122}
1123
1124func (agent *DeviceAgent) disablePorts() error {
khenaidoo0a822f92019-05-08 15:15:57 -04001125 log.Debugw("disablePorts", log.Fields{"deviceid": agent.deviceId})
khenaidoo3ab34882019-05-02 21:33:30 -04001126 agent.lockDevice.Lock()
1127 defer agent.lockDevice.Unlock()
1128 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1129 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1130 } else {
1131 // clone the device
1132 cloned := proto.Clone(storeDevice).(*voltha.Device)
1133 for _, port := range cloned.Ports {
1134 port.AdminState = voltha.AdminState_DISABLED
1135 port.OperStatus = voltha.OperStatus_UNKNOWN
1136 }
1137 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001138 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001139 }
1140}
1141
khenaidoo92e62c52018-10-03 14:02:54 -04001142func (agent *DeviceAgent) updatePortState(portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_OperStatus) error {
1143 agent.lockDevice.Lock()
khenaidoo59ef7be2019-06-21 12:40:28 -04001144 defer agent.lockDevice.Unlock()
khenaidoo92e62c52018-10-03 14:02:54 -04001145 // Work only on latest data
1146 // TODO: Get list of ports from device directly instead of the entire device
1147 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoo92e62c52018-10-03 14:02:54 -04001148 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1149 } else {
1150 // clone the device
1151 cloned := proto.Clone(storeDevice).(*voltha.Device)
1152 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1153 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
khenaidoo92e62c52018-10-03 14:02:54 -04001154 return status.Errorf(codes.InvalidArgument, "%s", portType)
1155 }
1156 for _, port := range cloned.Ports {
1157 if port.Type == portType && port.PortNo == portNo {
1158 port.OperStatus = operStatus
1159 // Set the admin status to ENABLED if the operational status is ACTIVE
1160 // TODO: Set by northbound system?
1161 if operStatus == voltha.OperStatus_ACTIVE {
1162 port.AdminState = voltha.AdminState_ENABLED
1163 }
1164 break
1165 }
1166 }
1167 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1168 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001169 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001170 }
1171}
1172
khenaidoo0a822f92019-05-08 15:15:57 -04001173func (agent *DeviceAgent) deleteAllPorts() error {
1174 log.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceId})
1175 agent.lockDevice.Lock()
1176 defer agent.lockDevice.Unlock()
1177 // Work only on latest data
1178 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1179 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1180 } else {
1181 if storeDevice.AdminState != voltha.AdminState_DISABLED && storeDevice.AdminState != voltha.AdminState_DELETED {
1182 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", storeDevice.AdminState))
1183 log.Warnw("invalid-state-removing-ports", log.Fields{"state": storeDevice.AdminState, "error": err})
1184 return err
1185 }
1186 if len(storeDevice.Ports) == 0 {
1187 log.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceId})
1188 return nil
1189 }
1190 // clone the device & set the fields to empty
1191 cloned := proto.Clone(storeDevice).(*voltha.Device)
1192 cloned.Ports = []*voltha.Port{}
1193 log.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
1194 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001195 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001196 }
1197}
1198
khenaidoob9203542018-09-17 22:56:37 -04001199func (agent *DeviceAgent) addPort(port *voltha.Port) error {
khenaidoo92e62c52018-10-03 14:02:54 -04001200 agent.lockDevice.Lock()
1201 defer agent.lockDevice.Unlock()
khenaidoo0a822f92019-05-08 15:15:57 -04001202 log.Debugw("addPort", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001203 // Work only on latest data
khenaidoo92e62c52018-10-03 14:02:54 -04001204 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001205 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1206 } else {
1207 // clone the device
khenaidoo92e62c52018-10-03 14:02:54 -04001208 cloned := proto.Clone(storeDevice).(*voltha.Device)
khenaidoob9203542018-09-17 22:56:37 -04001209 if cloned.Ports == nil {
1210 // First port
khenaidoo0a822f92019-05-08 15:15:57 -04001211 log.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceId})
khenaidoob9203542018-09-17 22:56:37 -04001212 cloned.Ports = make([]*voltha.Port, 0)
manikkaraj k259a6f72019-05-06 09:55:44 -04001213 } else {
1214 for _, p := range cloned.Ports {
1215 if p.Type == port.Type && p.PortNo == port.PortNo {
1216 log.Debugw("port already exists", log.Fields{"port": *port})
1217 return nil
1218 }
1219 }
khenaidoob9203542018-09-17 22:56:37 -04001220 }
khenaidoo92e62c52018-10-03 14:02:54 -04001221 cp := proto.Clone(port).(*voltha.Port)
1222 // Set the admin state of the port to ENABLE if the operational state is ACTIVE
1223 // TODO: Set by northbound system?
1224 if cp.OperStatus == voltha.OperStatus_ACTIVE {
1225 cp.AdminState = voltha.AdminState_ENABLED
1226 }
1227 cloned.Ports = append(cloned.Ports, cp)
khenaidoob9203542018-09-17 22:56:37 -04001228 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001229 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001230 }
1231}
1232
1233func (agent *DeviceAgent) addPeerPort(port *voltha.Port_PeerPort) error {
1234 agent.lockDevice.Lock()
1235 defer agent.lockDevice.Unlock()
1236 log.Debug("addPeerPort")
1237 // Work only on latest data
1238 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1239 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1240 } else {
1241 // clone the device
1242 cloned := proto.Clone(storeDevice).(*voltha.Device)
1243 // Get the peer port on the device based on the port no
1244 for _, peerPort := range cloned.Ports {
1245 if peerPort.PortNo == port.PortNo { // found port
1246 cp := proto.Clone(port).(*voltha.Port_PeerPort)
1247 peerPort.Peers = append(peerPort.Peers, cp)
1248 log.Debugw("found-peer", log.Fields{"portNo": port.PortNo, "deviceId": agent.deviceId})
1249 break
1250 }
1251 }
1252 // Store the device
Mahir Gunyelb5851672019-07-24 10:46:26 +03001253 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001254 }
1255}
1256
khenaidoo0a822f92019-05-08 15:15:57 -04001257func (agent *DeviceAgent) deletePeerPorts(deviceId string) error {
1258 agent.lockDevice.Lock()
1259 defer agent.lockDevice.Unlock()
1260 log.Debug("deletePeerPorts")
1261 // Work only on latest data
1262 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1263 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1264 } else {
1265 // clone the device
1266 cloned := proto.Clone(storeDevice).(*voltha.Device)
1267 var updatedPeers []*voltha.Port_PeerPort
1268 for _, port := range cloned.Ports {
1269 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1270 for _, peerPort := range port.Peers {
1271 if peerPort.DeviceId != deviceId {
1272 updatedPeers = append(updatedPeers, peerPort)
1273 }
1274 }
1275 port.Peers = updatedPeers
1276 }
1277
1278 // Store the device with updated peer ports
Mahir Gunyelb5851672019-07-24 10:46:26 +03001279 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001280 }
1281}
1282
khenaidoob9203542018-09-17 22:56:37 -04001283// TODO: A generic device update by attribute
1284func (agent *DeviceAgent) updateDeviceAttribute(name string, value interface{}) {
khenaidoo92e62c52018-10-03 14:02:54 -04001285 agent.lockDevice.Lock()
1286 defer agent.lockDevice.Unlock()
khenaidoob9203542018-09-17 22:56:37 -04001287 if value == nil {
1288 return
1289 }
1290 var storeDevice *voltha.Device
1291 var err error
khenaidoo92e62c52018-10-03 14:02:54 -04001292 if storeDevice, err = agent.getDeviceWithoutLock(); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001293 return
1294 }
1295 updated := false
1296 s := reflect.ValueOf(storeDevice).Elem()
1297 if s.Kind() == reflect.Struct {
1298 // exported field
1299 f := s.FieldByName(name)
1300 if f.IsValid() && f.CanSet() {
1301 switch f.Kind() {
1302 case reflect.String:
1303 f.SetString(value.(string))
1304 updated = true
1305 case reflect.Uint32:
1306 f.SetUint(uint64(value.(uint32)))
1307 updated = true
1308 case reflect.Bool:
1309 f.SetBool(value.(bool))
1310 updated = true
1311 }
1312 }
1313 }
khenaidoo92e62c52018-10-03 14:02:54 -04001314 log.Debugw("update-field-status", log.Fields{"deviceId": storeDevice.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001315 // Save the data
khenaidoo92e62c52018-10-03 14:02:54 -04001316 cloned := proto.Clone(storeDevice).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001317 if err = agent.updateDeviceInStoreWithoutLock(cloned, false, ""); err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001318 log.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
1319 }
1320 return
1321}
serkant.uluderya334479d2019-04-10 08:26:15 -07001322
1323func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
1324 agent.lockDevice.Lock()
1325 defer agent.lockDevice.Unlock()
1326 log.Debugw("simulateAlarm", log.Fields{"id": agent.deviceId})
1327 // Get the most up to date the device info
1328 if device, err := agent.getDeviceWithoutLock(); err != nil {
1329 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1330 } else {
1331 // First send the request to an Adapter and wait for a response
1332 if err := agent.adapterProxy.SimulateAlarm(ctx, device, simulatereq); err != nil {
1333 log.Debugw("simulateAlarm-error", log.Fields{"id": agent.lastData.Id, "error": err})
1334 return err
1335 }
1336 }
1337 return nil
1338}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001339
1340//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.
1341// It is an internal helper function.
1342func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(device *voltha.Device, strict bool, txid string) error {
1343 updateCtx := context.WithValue(context.Background(), model.RequestTimestamp, time.Now().UnixNano())
1344 if afterUpdate := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceId, device, strict, txid); afterUpdate == nil {
1345 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceId)
1346 }
1347 log.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceId})
1348
1349 return nil
1350}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001351
1352func (agent *DeviceAgent) updateDeviceReason(reason string) error {
1353 agent.lockDevice.Lock()
1354 defer agent.lockDevice.Unlock()
1355 // Work only on latest data
1356 if storeDevice, err := agent.getDeviceWithoutLock(); err != nil {
1357 return status.Errorf(codes.NotFound, "%s", agent.deviceId)
1358 } else {
1359 // clone the device
1360 cloned := proto.Clone(storeDevice).(*voltha.Device)
1361 cloned.Reason = reason
1362 log.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
1363 // Store the device
1364 return agent.updateDeviceInStoreWithoutLock(cloned, false, "")
1365 }
1366}