blob: 37a79c8f7bcb065db556f6eaf2f9ba14632f0916 [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 */
npujar1d86a522019-11-14 17:11:16 +053016
khenaidoob9203542018-09-17 22:56:37 -040017package core
18
19import (
20 "context"
Matteo Scandolo360605d2019-11-05 18:29:17 -080021 "encoding/hex"
khenaidoo3ab34882019-05-02 21:33:30 -040022 "fmt"
khenaidoo442e7c72020-03-10 16:13:48 -040023 "github.com/golang/protobuf/ptypes"
24 "github.com/opencord/voltha-lib-go/v3/pkg/kafka"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040025 "reflect"
26 "sync"
27 "time"
28
khenaidoob9203542018-09-17 22:56:37 -040029 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050030 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070031 coreutils "github.com/opencord/voltha-go/rw_core/utils"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080032 fu "github.com/opencord/voltha-lib-go/v3/pkg/flows"
33 "github.com/opencord/voltha-lib-go/v3/pkg/log"
34 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
35 ofp "github.com/opencord/voltha-protos/v3/go/openflow_13"
36 "github.com/opencord/voltha-protos/v3/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040037 "google.golang.org/grpc/codes"
38 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040039)
40
npujar1d86a522019-11-14 17:11:16 +053041// DeviceAgent represents device agent attributes
khenaidoob9203542018-09-17 22:56:37 -040042type DeviceAgent struct {
npujar1d86a522019-11-14 17:11:16 +053043 deviceID string
44 parentID string
khenaidoo43c82122018-11-22 18:38:28 -050045 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040046 isRootdevice bool
khenaidoo9a468962018-09-19 15:33:13 -040047 adapterProxy *AdapterProxy
serkant.uluderya334479d2019-04-10 08:26:15 -070048 adapterMgr *AdapterManager
khenaidoo9a468962018-09-19 15:33:13 -040049 deviceMgr *DeviceManager
50 clusterDataProxy *model.Proxy
khenaidoo92e62c52018-10-03 14:02:54 -040051 deviceProxy *model.Proxy
khenaidoo9a468962018-09-19 15:33:13 -040052 exitChannel chan int
khenaidoo6e55d9e2019-12-12 18:26:26 -050053 device *voltha.Device
khenaidoo442e7c72020-03-10 16:13:48 -040054 requestQueue *coreutils.RequestQueue
55 defaultTimeout time.Duration
56 startOnce sync.Once
57 stopOnce sync.Once
58 stopped bool
khenaidoob9203542018-09-17 22:56:37 -040059}
60
Scott Baker80678602019-11-14 16:57:36 -080061//newDeviceAgent creates a new device agent. The device will be initialized when start() is called.
khenaidoo442e7c72020-03-10 16:13:48 -040062func newDeviceAgent(ap *AdapterProxy, device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy, timeout time.Duration) *DeviceAgent {
khenaidoob9203542018-09-17 22:56:37 -040063 var agent DeviceAgent
khenaidoob9203542018-09-17 22:56:37 -040064 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080065 if device.Id == "" {
npujar1d86a522019-11-14 17:11:16 +053066 agent.deviceID = CreateDeviceID()
Scott Baker80678602019-11-14 16:57:36 -080067 } else {
npujar1d86a522019-11-14 17:11:16 +053068 agent.deviceID = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050069 }
Scott Baker80678602019-11-14 16:57:36 -080070
khenaidoo2c6a0992019-04-29 13:46:56 -040071 agent.isRootdevice = device.Root
npujar1d86a522019-11-14 17:11:16 +053072 agent.parentID = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080073 agent.deviceType = device.Type
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
khenaidoo2c6a0992019-04-29 13:46:56 -040078 agent.defaultTimeout = timeout
khenaidoo6e55d9e2019-12-12 18:26:26 -050079 agent.device = proto.Clone(device).(*voltha.Device)
Kent Hagerman730cbdf2020-03-31 12:22:08 -040080 agent.requestQueue = coreutils.NewRequestQueue()
khenaidoob9203542018-09-17 22:56:37 -040081 return &agent
82}
83
khenaidoo442e7c72020-03-10 16:13:48 -040084// start() saves the device to the data model and registers for callbacks on that device if deviceToCreate!=nil.
85// Otherwise, it will load the data from the dB and setup the necessary callbacks and proxies. Returns the device that
Scott Baker80678602019-11-14 16:57:36 -080086// was started.
87func (agent *DeviceAgent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
khenaidoo442e7c72020-03-10 16:13:48 -040088 needToStart := false
89 if agent.startOnce.Do(func() { needToStart = true }); !needToStart {
90 return agent.getDevice(ctx)
91 }
92 var startSucceeded bool
93 defer func() {
94 if !startSucceeded {
95 if err := agent.stop(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +000096 logger.Errorw("failed-to-cleanup-after-unsuccessful-start", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -040097 }
98 }
99 }()
Scott Baker80678602019-11-14 16:57:36 -0800100
khenaidoo442e7c72020-03-10 16:13:48 -0400101 var device *voltha.Device
Scott Baker80678602019-11-14 16:57:36 -0800102 if deviceToCreate == nil {
103 // Load the existing device
Thomas Lee Se5a44012019-11-07 20:32:24 +0530104 loadedDevice, err := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, "")
105 if err != nil {
Thomas Lee Se5a44012019-11-07 20:32:24 +0530106 return nil, err
107 }
108 if loadedDevice != nil {
Scott Baker80678602019-11-14 16:57:36 -0800109 var ok bool
110 if device, ok = loadedDevice.(*voltha.Device); ok {
111 agent.deviceType = device.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -0500112 agent.device = proto.Clone(device).(*voltha.Device)
Scott Baker80678602019-11-14 16:57:36 -0800113 } else {
npujar1d86a522019-11-14 17:11:16 +0530114 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500115 }
116 } else {
khenaidoo442e7c72020-03-10 16:13:48 -0400117 return nil, status.Errorf(codes.NotFound, "device-%s-loading-failed", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500118 }
Girish Kumarf56a4682020-03-20 20:07:46 +0000119 logger.Infow("device-loaded-from-dB", log.Fields{"device-id": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500120 } else {
Scott Baker80678602019-11-14 16:57:36 -0800121 // Create a new device
122 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
123 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
124 // agent.deviceId will also have been set during newDeviceAgent().
125 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530126 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800127 device.AdminState = voltha.AdminState_PREPROVISIONED
128 device.FlowGroups = &ofp.FlowGroups{Items: nil}
129 device.Flows = &ofp.Flows{Items: nil}
130 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
131 // Set the default vlan ID to the one specified by the parent adapter. It can be
132 // overwritten by the child adapter during a device update request
133 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
134 }
135
khenaidoo297cd252019-02-07 22:10:23 -0500136 // Add the initial device to the local model
Thomas Lee Se5a44012019-11-07 20:32:24 +0530137 added, err := agent.clusterDataProxy.AddWithID(ctx, "/devices", agent.deviceID, device, "")
138 if err != nil {
Thomas Lee Se5a44012019-11-07 20:32:24 +0530139 return nil, err
140 }
141 if added == nil {
npujar1d86a522019-11-14 17:11:16 +0530142 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s", agent.deviceID)
khenaidoo297cd252019-02-07 22:10:23 -0500143 }
khenaidoo442e7c72020-03-10 16:13:48 -0400144 agent.device = device
khenaidoob9203542018-09-17 22:56:37 -0400145 }
Thomas Lee Se5a44012019-11-07 20:32:24 +0530146 var err error
147 if agent.deviceProxy, err = agent.clusterDataProxy.CreateProxy(ctx, "/devices/"+agent.deviceID, false); err != nil {
Thomas Lee Se5a44012019-11-07 20:32:24 +0530148 return nil, err
149 }
npujar9a30c702019-11-14 17:06:39 +0530150 agent.deviceProxy.RegisterCallback(model.PostUpdate, agent.processUpdate)
khenaidoo19d7b632018-10-30 10:49:50 -0400151
khenaidoo442e7c72020-03-10 16:13:48 -0400152 startSucceeded = true
Girish Kumarf56a4682020-03-20 20:07:46 +0000153 logger.Debugw("device-agent-started", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400154
155 return agent.getDevice(ctx)
khenaidoob9203542018-09-17 22:56:37 -0400156}
157
khenaidoo4d4802d2018-10-04 21:59:49 -0400158// stop stops the device agent. Not much to do for now
khenaidoo442e7c72020-03-10 16:13:48 -0400159func (agent *DeviceAgent) stop(ctx context.Context) error {
160 needToStop := false
161 if agent.stopOnce.Do(func() { needToStop = true }); !needToStop {
162 return nil
163 }
164 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
165 return err
166 }
167 defer agent.requestQueue.RequestComplete()
khenaidoo49085352020-01-13 19:15:43 -0500168
Girish Kumarf56a4682020-03-20 20:07:46 +0000169 logger.Infow("stopping-device-agent", log.Fields{"deviceId": agent.deviceID, "parentId": agent.parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500170
171 // First unregister any callbacks
khenaidoo442e7c72020-03-10 16:13:48 -0400172 if agent.deviceProxy != nil {
173 agent.deviceProxy.UnregisterCallback(model.PostUpdate, agent.processUpdate)
174 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500175
khenaidoo0a822f92019-05-08 15:15:57 -0400176 // Remove the device from the KV store
Thomas Lee Se5a44012019-11-07 20:32:24 +0530177 removed, err := agent.clusterDataProxy.Remove(ctx, "/devices/"+agent.deviceID, "")
178 if err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400179 return err
Thomas Lee Se5a44012019-11-07 20:32:24 +0530180 }
181 if removed == nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000182 logger.Debugw("device-already-removed", log.Fields{"device-id": agent.deviceID})
khenaidoo0a822f92019-05-08 15:15:57 -0400183 }
khenaidoo442e7c72020-03-10 16:13:48 -0400184
khenaidoo442e7c72020-03-10 16:13:48 -0400185 close(agent.exitChannel)
186
187 agent.stopped = true
188
Girish Kumarf56a4682020-03-20 20:07:46 +0000189 logger.Infow("device-agent-stopped", log.Fields{"device-id": agent.deviceID, "parent-id": agent.parentID})
khenaidoo442e7c72020-03-10 16:13:48 -0400190
191 return nil
khenaidoob9203542018-09-17 22:56:37 -0400192}
193
Scott Baker80678602019-11-14 16:57:36 -0800194// Load the most recent state from the KVStore for the device.
npujar467fe752020-01-16 20:17:45 +0530195func (agent *DeviceAgent) reconcileWithKVStore(ctx context.Context) {
khenaidoo442e7c72020-03-10 16:13:48 -0400196 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000197 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -0400198 return
199 }
200 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000201 logger.Debug("reconciling-device-agent-devicetype")
Scott Baker80678602019-11-14 16:57:36 -0800202 // TODO: context timeout
npujar467fe752020-01-16 20:17:45 +0530203 device, err := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 1, true, "")
Thomas Lee Se5a44012019-11-07 20:32:24 +0530204 if err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000205 logger.Errorw("kv-get-failed", log.Fields{"device-id": agent.deviceID, "error": err})
Thomas Lee Se5a44012019-11-07 20:32:24 +0530206 return
207 }
208 if device != nil {
Scott Baker80678602019-11-14 16:57:36 -0800209 if d, ok := device.(*voltha.Device); ok {
210 agent.deviceType = d.Adapter
khenaidoo6e55d9e2019-12-12 18:26:26 -0500211 agent.device = proto.Clone(d).(*voltha.Device)
Girish Kumarf56a4682020-03-20 20:07:46 +0000212 logger.Debugw("reconciled-device-agent-devicetype", log.Fields{"device-id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800213 }
214 }
215}
216
khenaidoo442e7c72020-03-10 16:13:48 -0400217// onSuccess is a common callback for scenarios where we receive a nil response following a request to an adapter
218// and the only action required is to publish a successful result on kafka
219func (agent *DeviceAgent) onSuccess(rpc string, response interface{}, reqArgs ...interface{}) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000220 logger.Debugw("response successful", log.Fields{"rpc": rpc, "device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400221 // TODO: Post success message onto kafka
222}
223
224// onFailure is a common callback for scenarios where we receive an error response following a request to an adapter
225// and the only action required is to publish the failed result on kafka
226func (agent *DeviceAgent) onFailure(rpc string, response interface{}, reqArgs ...interface{}) {
227 if res, ok := response.(error); ok {
Girish Kumarf56a4682020-03-20 20:07:46 +0000228 logger.Errorw("rpc-failed", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "error": res, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400229 } else {
Girish Kumarf56a4682020-03-20 20:07:46 +0000230 logger.Errorw("rpc-failed-invalid-error", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400231 }
232 // TODO: Post failure message onto kafka
233}
234
235func (agent *DeviceAgent) waitForAdapterResponse(ctx context.Context, cancel context.CancelFunc, rpc string, ch chan *kafka.RpcResponse,
236 onSuccess coreutils.ResponseCallback, onFailure coreutils.ResponseCallback, reqArgs ...interface{}) {
237 defer cancel()
238 select {
239 case rpcResponse, ok := <-ch:
240 if !ok {
241 onFailure(rpc, status.Errorf(codes.Aborted, "channel-closed"), reqArgs)
242 } else if rpcResponse.Err != nil {
243 onFailure(rpc, rpcResponse.Err, reqArgs)
244 } else {
245 onSuccess(rpc, rpcResponse.Reply, reqArgs)
246 }
247 case <-ctx.Done():
248 onFailure(rpc, ctx.Err(), reqArgs)
249 }
250}
251
khenaidoo6e55d9e2019-12-12 18:26:26 -0500252// getDevice returns the device data from cache
khenaidoo442e7c72020-03-10 16:13:48 -0400253func (agent *DeviceAgent) getDevice(ctx context.Context) (*voltha.Device, error) {
254 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
255 return nil, err
256 }
257 defer agent.requestQueue.RequestComplete()
258 return proto.Clone(agent.device).(*voltha.Device), nil
khenaidoo92e62c52018-10-03 14:02:54 -0400259}
260
khenaidoo4d4802d2018-10-04 21:59:49 -0400261// getDeviceWithoutLock is a helper function to be used ONLY by any device agent function AFTER it has acquired the device lock.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500262func (agent *DeviceAgent) getDeviceWithoutLock() *voltha.Device {
263 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400264}
265
khenaidoo3ab34882019-05-02 21:33:30 -0400266// enableDevice activates a preprovisioned or a disable device
khenaidoob9203542018-09-17 22:56:37 -0400267func (agent *DeviceAgent) enableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400268 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
269 return err
270 }
271 defer agent.requestQueue.RequestComplete()
272
Girish Kumarf56a4682020-03-20 20:07:46 +0000273 logger.Debugw("enableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500274
khenaidoo6e55d9e2019-12-12 18:26:26 -0500275 cloned := agent.getDeviceWithoutLock()
276
npujar1d86a522019-11-14 17:11:16 +0530277 // First figure out which adapter will handle this device type. We do it at this stage as allow devices to be
khenaidoo442e7c72020-03-10 16:13:48 -0400278 // pre-provisioned with the required adapter not registered. At this stage, since we need to communicate
npujar1d86a522019-11-14 17:11:16 +0530279 // with the adapter then we need to know the adapter that will handle this request
khenaidoo6e55d9e2019-12-12 18:26:26 -0500280 adapterName, err := agent.adapterMgr.getAdapterName(cloned.Type)
npujar1d86a522019-11-14 17:11:16 +0530281 if err != nil {
npujar1d86a522019-11-14 17:11:16 +0530282 return err
283 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500284 cloned.Adapter = adapterName
npujar1d86a522019-11-14 17:11:16 +0530285
khenaidoo6e55d9e2019-12-12 18:26:26 -0500286 if cloned.AdminState == voltha.AdminState_ENABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000287 logger.Debugw("device-already-enabled", log.Fields{"device-id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530288 return nil
289 }
290
khenaidoo6e55d9e2019-12-12 18:26:26 -0500291 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530292 // This is a temporary state when a device is deleted before it gets removed from the model.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500293 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", cloned.Id))
npujar1d86a522019-11-14 17:11:16 +0530294 return err
295 }
296
khenaidoo6e55d9e2019-12-12 18:26:26 -0500297 previousAdminState := cloned.AdminState
npujar1d86a522019-11-14 17:11:16 +0530298
299 // Update the Admin State and set the operational state to activating before sending the request to the
300 // Adapters
npujar1d86a522019-11-14 17:11:16 +0530301 cloned.AdminState = voltha.AdminState_ENABLED
302 cloned.OperStatus = voltha.OperStatus_ACTIVATING
303
npujar467fe752020-01-16 20:17:45 +0530304 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530305 return err
306 }
307
khenaidoo442e7c72020-03-10 16:13:48 -0400308 // Adopt the device if it was in pre-provision state. In all other cases, try to re-enable it.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500309 device := proto.Clone(cloned).(*voltha.Device)
khenaidoo442e7c72020-03-10 16:13:48 -0400310 var ch chan *kafka.RpcResponse
311 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
npujar1d86a522019-11-14 17:11:16 +0530312 if previousAdminState == voltha.AdminState_PREPROVISIONED {
khenaidoo442e7c72020-03-10 16:13:48 -0400313 ch, err = agent.adapterProxy.adoptDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400314 } else {
khenaidoo442e7c72020-03-10 16:13:48 -0400315 ch, err = agent.adapterProxy.reEnableDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400316 }
khenaidoo442e7c72020-03-10 16:13:48 -0400317 if err != nil {
318 cancel()
319 return err
320 }
321 // Wait for response
322 go agent.waitForAdapterResponse(subCtx, cancel, "enableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoob9203542018-09-17 22:56:37 -0400323 return nil
324}
325
khenaidoo442e7c72020-03-10 16:13:48 -0400326func (agent *DeviceAgent) waitForAdapterFlowResponse(ctx context.Context, cancel context.CancelFunc, ch chan *kafka.RpcResponse, response coreutils.Response) {
327 defer cancel()
328 select {
329 case rpcResponse, ok := <-ch:
330 if !ok {
331 response.Error(status.Errorf(codes.Aborted, "channel-closed"))
332 } else if rpcResponse.Err != nil {
333 response.Error(rpcResponse.Err)
334 } else {
335 response.Done()
336 }
337 case <-ctx.Done():
338 response.Error(ctx.Err())
khenaidoo2c6a0992019-04-29 13:46:56 -0400339 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400340}
341
khenaidoob2121e52019-12-16 17:17:22 -0500342//deleteFlowWithoutPreservingOrder removes a flow specified by index from the flows slice. This function will
343//panic if the index is out of range.
344func deleteFlowWithoutPreservingOrder(flows []*ofp.OfpFlowStats, index int) []*ofp.OfpFlowStats {
345 flows[index] = flows[len(flows)-1]
346 flows[len(flows)-1] = nil
347 return flows[:len(flows)-1]
348}
349
350//deleteGroupWithoutPreservingOrder removes a group specified by index from the groups slice. This function will
351//panic if the index is out of range.
352func deleteGroupWithoutPreservingOrder(groups []*ofp.OfpGroupEntry, index int) []*ofp.OfpGroupEntry {
353 groups[index] = groups[len(groups)-1]
354 groups[len(groups)-1] = nil
355 return groups[:len(groups)-1]
356}
357
358func flowsToUpdateToDelete(newFlows, existingFlows []*ofp.OfpFlowStats) (updatedNewFlows, flowsToDelete, updatedAllFlows []*ofp.OfpFlowStats) {
359 // Process flows
360 for _, flow := range existingFlows {
361 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
362 updatedAllFlows = append(updatedAllFlows, flow)
363 } else {
364 // We have a matching flow (i.e. the following field matches: "TableId", "Priority", "Flags", "Cookie",
365 // "Match". If this is an exact match (i.e. all other fields matches as well) then this flow will be
366 // ignored. Otherwise, the previous flow will be deleted and the new one added
367 if proto.Equal(newFlows[idx], flow) {
368 // Flow already exist, remove it from the new flows but keep it in the updated flows slice
369 newFlows = deleteFlowWithoutPreservingOrder(newFlows, idx)
370 updatedAllFlows = append(updatedAllFlows, flow)
371 } else {
372 // Minor change to flow, delete old and add new one
373 flowsToDelete = append(flowsToDelete, flow)
374 }
375 }
376 }
377 updatedAllFlows = append(updatedAllFlows, newFlows...)
378 return newFlows, flowsToDelete, updatedAllFlows
379}
380
381func groupsToUpdateToDelete(newGroups, existingGroups []*ofp.OfpGroupEntry) (updatedNewGroups, groupsToDelete, updatedAllGroups []*ofp.OfpGroupEntry) {
382 for _, group := range existingGroups {
383 if idx := fu.FindGroup(newGroups, group.Desc.GroupId); idx == -1 { // does not exist now
384 updatedAllGroups = append(updatedAllGroups, group)
385 } else {
386 // Follow same logic as flows
387 if proto.Equal(newGroups[idx], group) {
388 // Group already exist, remove it from the new groups
389 newGroups = deleteGroupWithoutPreservingOrder(newGroups, idx)
390 updatedAllGroups = append(updatedAllGroups, group)
391 } else {
392 // Minor change to group, delete old and add new one
393 groupsToDelete = append(groupsToDelete, group)
394 }
395 }
396 }
397 updatedAllGroups = append(updatedAllGroups, newGroups...)
398 return newGroups, groupsToDelete, updatedAllGroups
399}
400
npujar467fe752020-01-16 20:17:45 +0530401func (agent *DeviceAgent) addFlowsAndGroupsToAdapter(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000402 logger.Debugw("add-flows-groups-to-adapters", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups, "flow-metadata": flowMetadata})
khenaidoo0458db62019-06-20 08:50:36 -0400403
khenaidoo2c6a0992019-04-29 13:46:56 -0400404 if (len(newFlows) | len(newGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000405 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800406 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400407 }
408
khenaidoo442e7c72020-03-10 16:13:48 -0400409 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
410 return coreutils.DoneResponse(), err
411 }
412 defer agent.requestQueue.RequestComplete()
khenaidoo2c6a0992019-04-29 13:46:56 -0400413
khenaidoo6e55d9e2019-12-12 18:26:26 -0500414 device := agent.getDeviceWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400415 dType := agent.adapterMgr.getDeviceType(device.Type)
416 if dType == nil {
417 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
418 }
419
khenaidoo0458db62019-06-20 08:50:36 -0400420 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
421 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
422
khenaidoo0458db62019-06-20 08:50:36 -0400423 // Process flows
khenaidoob2121e52019-12-16 17:17:22 -0500424 newFlows, flowsToDelete, updatedAllFlows := flowsToUpdateToDelete(newFlows, existingFlows.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400425
426 // Process groups
khenaidoob2121e52019-12-16 17:17:22 -0500427 newGroups, groupsToDelete, updatedAllGroups := groupsToUpdateToDelete(newGroups, existingGroups.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400428
429 // Sanity check
khenaidoob2121e52019-12-16 17:17:22 -0500430 if (len(updatedAllFlows) | len(flowsToDelete) | len(updatedAllGroups) | len(groupsToDelete)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000431 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800432 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400433 }
434
khenaidoo442e7c72020-03-10 16:13:48 -0400435 // store the changed data
436 device.Flows = &voltha.Flows{Items: updatedAllFlows}
437 device.FlowGroups = &voltha.FlowGroups{Items: updatedAllGroups}
438 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
439 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-device-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500440 }
khenaidoo0458db62019-06-20 08:50:36 -0400441
khenaidoo442e7c72020-03-10 16:13:48 -0400442 // Send update to adapters
443 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
444 response := coreutils.NewResponse()
445 if !dType.AcceptsAddRemoveFlowUpdates {
khenaidoob2121e52019-12-16 17:17:22 -0500446 if len(updatedAllGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedAllGroups) && len(updatedAllFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedAllFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000447 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400448 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800449 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400450 }
khenaidoo442e7c72020-03-10 16:13:48 -0400451 rpcResponse, err := agent.adapterProxy.updateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedAllFlows}, &voltha.FlowGroups{Items: updatedAllGroups}, flowMetadata)
452 if err != nil {
453 cancel()
454 return coreutils.DoneResponse(), err
455 }
456 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400457 } else {
458 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400459 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400460 ToRemove: &voltha.Flows{Items: flowsToDelete},
461 }
462 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400463 ToAdd: &voltha.FlowGroups{Items: newGroups},
464 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400465 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
466 }
khenaidoo442e7c72020-03-10 16:13:48 -0400467 rpcResponse, err := agent.adapterProxy.updateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
468 if err != nil {
469 cancel()
470 return coreutils.DoneResponse(), err
471 }
472 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400473 }
A R Karthick5c28f552019-12-11 22:47:44 -0800474 return response, nil
475}
476
477//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
478//adapters
npujar467fe752020-01-16 20:17:45 +0530479func (agent *DeviceAgent) addFlowsAndGroups(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
480 response, err := agent.addFlowsAndGroupsToAdapter(ctx, newFlows, newGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800481 if err != nil {
482 return err
483 }
khenaidoo442e7c72020-03-10 16:13:48 -0400484 if errs := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); errs != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000485 logger.Warnw("no-adapter-response", log.Fields{"device-id": agent.deviceID, "result": errs})
khenaidoo442e7c72020-03-10 16:13:48 -0400486 return status.Errorf(codes.Aborted, "flow-failure-device-%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400487 }
khenaidoo0458db62019-06-20 08:50:36 -0400488 return nil
489}
490
npujar467fe752020-01-16 20:17:45 +0530491func (agent *DeviceAgent) deleteFlowsAndGroupsFromAdapter(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000492 logger.Debugw("delete-flows-groups-from-adapter", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400493
494 if (len(flowsToDel) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000495 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800496 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400497 }
498
khenaidoo442e7c72020-03-10 16:13:48 -0400499 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
500 return coreutils.DoneResponse(), err
501 }
502 defer agent.requestQueue.RequestComplete()
khenaidoo0458db62019-06-20 08:50:36 -0400503
khenaidoo6e55d9e2019-12-12 18:26:26 -0500504 device := agent.getDeviceWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400505 dType := agent.adapterMgr.getDeviceType(device.Type)
506 if dType == nil {
507 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
508 }
khenaidoo0458db62019-06-20 08:50:36 -0400509
510 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
511 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
512
513 var flowsToKeep []*ofp.OfpFlowStats
514 var groupsToKeep []*ofp.OfpGroupEntry
515
516 // Process flows
517 for _, flow := range existingFlows.Items {
518 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
519 flowsToKeep = append(flowsToKeep, flow)
520 }
521 }
522
523 // Process groups
524 for _, group := range existingGroups.Items {
525 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
526 groupsToKeep = append(groupsToKeep, group)
527 }
528 }
529
Girish Kumarf56a4682020-03-20 20:07:46 +0000530 logger.Debugw("deleteFlowsAndGroups",
khenaidoo0458db62019-06-20 08:50:36 -0400531 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400532 "device-id": agent.deviceID,
533 "flows-to-del": len(flowsToDel),
534 "flows-to-keep": len(flowsToKeep),
535 "groups-to-del": len(groupsToDel),
536 "groups-to-keep": len(groupsToKeep),
khenaidoo0458db62019-06-20 08:50:36 -0400537 })
538
539 // Sanity check
540 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000541 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows-to-del": flowsToDel, "groups-to-del": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800542 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400543 }
544
khenaidoo442e7c72020-03-10 16:13:48 -0400545 // store the changed data
546 device.Flows = &voltha.Flows{Items: flowsToKeep}
547 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
548 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
549 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500550 }
khenaidoo442e7c72020-03-10 16:13:48 -0400551
552 // Send update to adapters
553 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
554 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400555 if !dType.AcceptsAddRemoveFlowUpdates {
556 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000557 logger.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
khenaidoo442e7c72020-03-10 16:13:48 -0400558 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800559 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400560 }
khenaidoo442e7c72020-03-10 16:13:48 -0400561 rpcResponse, err := agent.adapterProxy.updateFlowsBulk(subCtx, device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata)
562 if err != nil {
563 cancel()
564 return coreutils.DoneResponse(), err
565 }
566 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400567 } else {
568 flowChanges := &ofp.FlowChanges{
569 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
570 ToRemove: &voltha.Flows{Items: flowsToDel},
571 }
572 groupChanges := &ofp.FlowGroupChanges{
573 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
574 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
575 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
576 }
khenaidoo442e7c72020-03-10 16:13:48 -0400577 rpcResponse, err := agent.adapterProxy.updateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
578 if err != nil {
579 cancel()
580 return coreutils.DoneResponse(), err
581 }
582 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400583 }
A R Karthick5c28f552019-12-11 22:47:44 -0800584 return response, nil
A R Karthick5c28f552019-12-11 22:47:44 -0800585}
586
587//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
588//adapters
npujar467fe752020-01-16 20:17:45 +0530589func (agent *DeviceAgent) deleteFlowsAndGroups(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
590 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDel, groupsToDel, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800591 if err != nil {
592 return err
593 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500594 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400595 return status.Errorf(codes.Aborted, "errors-%s", res)
596 }
597 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400598}
599
npujar467fe752020-01-16 20:17:45 +0530600func (agent *DeviceAgent) updateFlowsAndGroupsToAdapter(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000601 logger.Debugw("updateFlowsAndGroups", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400602
603 if (len(updatedFlows) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000604 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800605 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400606 }
607
khenaidoo442e7c72020-03-10 16:13:48 -0400608 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
609 return coreutils.DoneResponse(), err
610 }
611 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500612
613 device := agent.getDeviceWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400614 if device.OperStatus != voltha.OperStatus_ACTIVE || device.ConnectStatus != voltha.ConnectStatus_REACHABLE || device.AdminState != voltha.AdminState_ENABLED {
615 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "invalid device states")
616 }
617 dType := agent.adapterMgr.getDeviceType(device.Type)
618 if dType == nil {
619 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
620 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500621
khenaidoo0458db62019-06-20 08:50:36 -0400622 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
623 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
624
625 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000626 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800627 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400628 }
629
Girish Kumarf56a4682020-03-20 20:07:46 +0000630 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400631 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400632 "device-id": agent.deviceID,
633 "updated-flows": updatedFlows,
634 "updated-groups": updatedGroups,
khenaidoo0458db62019-06-20 08:50:36 -0400635 })
636
khenaidoo442e7c72020-03-10 16:13:48 -0400637 // store the updated data
638 device.Flows = &voltha.Flows{Items: updatedFlows}
639 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
640 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
641 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500642 }
khenaidoo0458db62019-06-20 08:50:36 -0400643
khenaidoo442e7c72020-03-10 16:13:48 -0400644 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
645 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400646 // Process bulk flow update differently than incremental update
647 if !dType.AcceptsAddRemoveFlowUpdates {
khenaidoo442e7c72020-03-10 16:13:48 -0400648 rpcResponse, err := agent.adapterProxy.updateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil)
649 if err != nil {
650 cancel()
651 return coreutils.DoneResponse(), err
652 }
653 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400654 } else {
655 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400656 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400657 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400658 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400659
660 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400661 for _, flow := range updatedFlows {
662 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
663 flowsToAdd = append(flowsToAdd, flow)
664 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400665 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400666 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400667 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400668 flowsToDelete = append(flowsToDelete, flow)
669 }
670 }
671
672 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400673 for _, g := range updatedGroups {
674 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
675 groupsToAdd = append(groupsToAdd, g)
676 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400677 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400678 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400679 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400680 groupsToDelete = append(groupsToDelete, group)
681 }
682 }
683
Girish Kumarf56a4682020-03-20 20:07:46 +0000684 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400685 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400686 "device-id": agent.deviceID,
687 "flows-to-add": flowsToAdd,
688 "flows-to-delete": flowsToDelete,
689 "groups-to-add": groupsToAdd,
690 "groups-to-delete": groupsToDelete,
khenaidoo0458db62019-06-20 08:50:36 -0400691 })
692
khenaidoo2c6a0992019-04-29 13:46:56 -0400693 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400694 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000695 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400696 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800697 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400698 }
699
khenaidoo0458db62019-06-20 08:50:36 -0400700 flowChanges := &ofp.FlowChanges{
701 ToAdd: &voltha.Flows{Items: flowsToAdd},
702 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400703 }
khenaidoo0458db62019-06-20 08:50:36 -0400704 groupChanges := &ofp.FlowGroupChanges{
705 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
706 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
707 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
708 }
khenaidoo442e7c72020-03-10 16:13:48 -0400709 rpcResponse, err := agent.adapterProxy.updateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
710 if err != nil {
711 cancel()
712 return coreutils.DoneResponse(), err
713 }
714 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
Kent Hagerman3c513972019-11-25 13:49:41 -0500715 }
khenaidoo0458db62019-06-20 08:50:36 -0400716
A R Karthick5c28f552019-12-11 22:47:44 -0800717 return response, nil
718}
719
720//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
721//also sends the updates to the adapters
npujar467fe752020-01-16 20:17:45 +0530722func (agent *DeviceAgent) updateFlowsAndGroups(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
723 response, err := agent.updateFlowsAndGroupsToAdapter(ctx, updatedFlows, updatedGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800724 if err != nil {
725 return err
726 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500727 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400728 return status.Errorf(codes.Aborted, "errors-%s", res)
729 }
730 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400731}
732
Girish Gowdra408cd962020-03-11 14:31:31 -0700733//deleteAllFlows deletes all flows in the device table
734func (agent *DeviceAgent) deleteAllFlows(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000735 logger.Debugw("deleteAllFlows", log.Fields{"deviceId": agent.deviceID})
Girish Gowdra408cd962020-03-11 14:31:31 -0700736 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
737 return err
738 }
739 defer agent.requestQueue.RequestComplete()
740
741 device := agent.getDeviceWithoutLock()
742 // purge all flows on the device by setting it to nil
743 device.Flows = &ofp.Flows{Items: nil}
744 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
745 // The caller logs the error
746 return err
747 }
748 return nil
749}
750
khenaidoo4d4802d2018-10-04 21:59:49 -0400751//disableDevice disable a device
khenaidoo92e62c52018-10-03 14:02:54 -0400752func (agent *DeviceAgent) disableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400753 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
754 return err
755 }
756 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000757 logger.Debugw("disableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500758
759 cloned := agent.getDeviceWithoutLock()
760
761 if cloned.AdminState == voltha.AdminState_DISABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000762 logger.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530763 return nil
764 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500765 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
766 cloned.AdminState == voltha.AdminState_DELETED {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500767 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530768 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400769
npujar1d86a522019-11-14 17:11:16 +0530770 // Update the Admin State and operational state before sending the request out
npujar1d86a522019-11-14 17:11:16 +0530771 cloned.AdminState = voltha.AdminState_DISABLED
772 cloned.OperStatus = voltha.OperStatus_UNKNOWN
npujar467fe752020-01-16 20:17:45 +0530773 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530774 return err
775 }
khenaidoo442e7c72020-03-10 16:13:48 -0400776
777 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
778 ch, err := agent.adapterProxy.disableDevice(subCtx, proto.Clone(cloned).(*voltha.Device))
779 if err != nil {
780 cancel()
npujar1d86a522019-11-14 17:11:16 +0530781 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400782 }
khenaidoo442e7c72020-03-10 16:13:48 -0400783 go agent.waitForAdapterResponse(subCtx, cancel, "disableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo0a822f92019-05-08 15:15:57 -0400784
khenaidoo92e62c52018-10-03 14:02:54 -0400785 return nil
786}
787
khenaidoo4d4802d2018-10-04 21:59:49 -0400788func (agent *DeviceAgent) rebootDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400789 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530790 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400791 }
khenaidoo442e7c72020-03-10 16:13:48 -0400792 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000793 logger.Debugw("rebootDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400794
795 device := agent.getDeviceWithoutLock()
796 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
797 ch, err := agent.adapterProxy.rebootDevice(subCtx, device)
798 if err != nil {
799 cancel()
800 return err
801 }
802 go agent.waitForAdapterResponse(subCtx, cancel, "rebootDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo4d4802d2018-10-04 21:59:49 -0400803 return nil
804}
805
806func (agent *DeviceAgent) deleteDevice(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000807 logger.Debugw("deleteDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400808 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
809 return err
810 }
811 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500812
813 cloned := agent.getDeviceWithoutLock()
Chaitrashree G S543df3e2020-02-24 22:36:54 -0500814
khenaidoo442e7c72020-03-10 16:13:48 -0400815 previousState := cloned.AdminState
816
817 // No check is required when deleting a device. Changing the state to DELETE will trigger the removal of this
818 // device by the state machine
819 cloned.AdminState = voltha.AdminState_DELETED
npujar467fe752020-01-16 20:17:45 +0530820 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530821 return err
822 }
khenaidoo442e7c72020-03-10 16:13:48 -0400823
824 // If the device was in pre-prov state (only parent device are in that state) then do not send the request to the
825 // adapter
826 if previousState != ic.AdminState_PREPROVISIONED {
827 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
828 ch, err := agent.adapterProxy.deleteDevice(subCtx, cloned)
829 if err != nil {
830 cancel()
831 return err
832 }
833 go agent.waitForAdapterResponse(subCtx, cancel, "deleteDevice", ch, agent.onSuccess, agent.onFailure)
834 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400835 return nil
836}
837
npujar467fe752020-01-16 20:17:45 +0530838func (agent *DeviceAgent) setParentID(ctx context.Context, device *voltha.Device, parentID string) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400839 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
840 return err
841 }
842 defer agent.requestQueue.RequestComplete()
843
Girish Kumarf56a4682020-03-20 20:07:46 +0000844 logger.Debugw("setParentId", log.Fields{"device-id": device.Id, "parent-id": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500845
846 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530847 cloned.ParentId = parentID
848 // Store the device
npujar467fe752020-01-16 20:17:45 +0530849 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530850 return err
851 }
khenaidoo442e7c72020-03-10 16:13:48 -0400852
npujar1d86a522019-11-14 17:11:16 +0530853 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400854}
855
khenaidoob3127472019-07-24 21:04:55 -0400856func (agent *DeviceAgent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400857 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
858 return err
859 }
860 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000861 logger.Debugw("updatePmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500862
863 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530864 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
865 // Store the device
npujar467fe752020-01-16 20:17:45 +0530866 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530867 return err
868 }
869 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400870 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
871 ch, err := agent.adapterProxy.updatePmConfigs(subCtx, cloned, pmConfigs)
872 if err != nil {
873 cancel()
npujar1d86a522019-11-14 17:11:16 +0530874 return err
875 }
khenaidoo442e7c72020-03-10 16:13:48 -0400876 go agent.waitForAdapterResponse(subCtx, cancel, "updatePmConfigs", ch, agent.onSuccess, agent.onFailure)
npujar1d86a522019-11-14 17:11:16 +0530877 return nil
khenaidoob3127472019-07-24 21:04:55 -0400878}
879
npujar467fe752020-01-16 20:17:45 +0530880func (agent *DeviceAgent) initPmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400881 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
882 return err
883 }
884 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000885 logger.Debugw("initPmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500886
887 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530888 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
npujar467fe752020-01-16 20:17:45 +0530889 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Thomas Lee Se5a44012019-11-07 20:32:24 +0530890 afterUpdate, err := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, cloned, false, "")
891 if err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400892 return err
Thomas Lee Se5a44012019-11-07 20:32:24 +0530893 }
npujar1d86a522019-11-14 17:11:16 +0530894 if afterUpdate == nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400895 return status.Errorf(codes.Internal, "pm-kv-update-failed-for-device-id-%s", agent.deviceID)
npujar1d86a522019-11-14 17:11:16 +0530896 }
897 return nil
khenaidoob3127472019-07-24 21:04:55 -0400898}
899
900func (agent *DeviceAgent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400901 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
902 return nil, err
903 }
904 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000905 logger.Debugw("listPmConfigs", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500906
907 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400908}
909
khenaidoof5a5bfa2019-01-23 22:20:29 -0500910func (agent *DeviceAgent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400911 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
912 return nil, err
913 }
914 defer agent.requestQueue.RequestComplete()
915
Girish Kumarf56a4682020-03-20 20:07:46 +0000916 logger.Debugw("downloadImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500917
918 device := agent.getDeviceWithoutLock()
919
npujar1d86a522019-11-14 17:11:16 +0530920 if device.AdminState != voltha.AdminState_ENABLED {
khenaidoo442e7c72020-03-10 16:13:48 -0400921 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
npujar1d86a522019-11-14 17:11:16 +0530922 }
923 // Save the image
924 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
925 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
926 cloned := proto.Clone(device).(*voltha.Device)
927 if cloned.ImageDownloads == nil {
928 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500929 } else {
930 if device.AdminState != voltha.AdminState_ENABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000931 logger.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530932 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500933 }
934 // Save the image
935 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500936 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500937 cloned := proto.Clone(device).(*voltha.Device)
938 if cloned.ImageDownloads == nil {
939 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
940 } else {
941 cloned.ImageDownloads = append(cloned.ImageDownloads, clonedImg)
942 }
943 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
npujar467fe752020-01-16 20:17:45 +0530944 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
Mahir Gunyelb5851672019-07-24 10:46:26 +0300945 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500946 }
947 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400948 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
949 ch, err := agent.adapterProxy.downloadImage(ctx, cloned, clonedImg)
950 if err != nil {
951 cancel()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500952 return nil, err
953 }
khenaidoo442e7c72020-03-10 16:13:48 -0400954 go agent.waitForAdapterResponse(subCtx, cancel, "downloadImage", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500955 }
956 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
957}
958
959// isImageRegistered is a helper method to figure out if an image is already registered
960func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
961 for _, image := range device.ImageDownloads {
962 if image.Id == img.Id && image.Name == img.Name {
963 return true
964 }
965 }
966 return false
967}
968
969func (agent *DeviceAgent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400970 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
971 return nil, err
972 }
973 defer agent.requestQueue.RequestComplete()
974
Girish Kumarf56a4682020-03-20 20:07:46 +0000975 logger.Debugw("cancelImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500976
977 device := agent.getDeviceWithoutLock()
978
npujar1d86a522019-11-14 17:11:16 +0530979 // Verify whether the Image is in the list of image being downloaded
980 if !isImageRegistered(img, device) {
khenaidoo442e7c72020-03-10 16:13:48 -0400981 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +0530982 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500983
npujar1d86a522019-11-14 17:11:16 +0530984 // Update image download state
985 cloned := proto.Clone(device).(*voltha.Device)
986 for _, image := range cloned.ImageDownloads {
987 if image.Id == img.Id && image.Name == img.Name {
988 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500989 }
npujar1d86a522019-11-14 17:11:16 +0530990 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500991
npujar1d86a522019-11-14 17:11:16 +0530992 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
993 // Set the device to Enabled
994 cloned.AdminState = voltha.AdminState_ENABLED
npujar467fe752020-01-16 20:17:45 +0530995 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530996 return nil, err
997 }
khenaidoo442e7c72020-03-10 16:13:48 -0400998 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
999 ch, err := agent.adapterProxy.cancelImageDownload(subCtx, device, img)
1000 if err != nil {
1001 cancel()
npujar1d86a522019-11-14 17:11:16 +05301002 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -05001003 }
khenaidoo442e7c72020-03-10 16:13:48 -04001004 go agent.waitForAdapterResponse(subCtx, cancel, "cancelImageDownload", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001005 }
1006 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001007}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001008
1009func (agent *DeviceAgent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001010 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1011 return nil, err
1012 }
1013 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001014 logger.Debugw("activateImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001015 cloned := agent.getDeviceWithoutLock()
1016
npujar1d86a522019-11-14 17:11:16 +05301017 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001018 if !isImageRegistered(img, cloned) {
khenaidoo442e7c72020-03-10 16:13:48 -04001019 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301020 }
1021
khenaidoo6e55d9e2019-12-12 18:26:26 -05001022 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoo442e7c72020-03-10 16:13:48 -04001023 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301024 }
1025 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301026 for _, image := range cloned.ImageDownloads {
1027 if image.Id == img.Id && image.Name == img.Name {
1028 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
1029 }
1030 }
1031 // Set the device to downloading_image
1032 cloned.AdminState = voltha.AdminState_DOWNLOADING_IMAGE
npujar467fe752020-01-16 20:17:45 +05301033 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301034 return nil, err
1035 }
1036
khenaidoo442e7c72020-03-10 16:13:48 -04001037 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1038 ch, err := agent.adapterProxy.activateImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
1039 if err != nil {
1040 cancel()
npujar1d86a522019-11-14 17:11:16 +05301041 return nil, err
1042 }
khenaidoo442e7c72020-03-10 16:13:48 -04001043 go agent.waitForAdapterResponse(subCtx, cancel, "activateImageUpdate", ch, agent.onSuccess, agent.onFailure)
1044
npujar1d86a522019-11-14 17:11:16 +05301045 // The status of the AdminState will be changed following the update_download_status response from the adapter
1046 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -07001047 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
1048}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001049
1050func (agent *DeviceAgent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001051 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1052 return nil, err
1053 }
1054 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001055 logger.Debugw("revertImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001056
1057 cloned := agent.getDeviceWithoutLock()
1058
npujar1d86a522019-11-14 17:11:16 +05301059 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001060 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +05301061 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
1062 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001063
khenaidoo6e55d9e2019-12-12 18:26:26 -05001064 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +05301065 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
1066 }
1067 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301068 for _, image := range cloned.ImageDownloads {
1069 if image.Id == img.Id && image.Name == img.Name {
1070 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -05001071 }
npujar1d86a522019-11-14 17:11:16 +05301072 }
Mahir Gunyelb5851672019-07-24 10:46:26 +03001073
npujar467fe752020-01-16 20:17:45 +05301074 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301075 return nil, err
1076 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001077
khenaidoo442e7c72020-03-10 16:13:48 -04001078 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1079 ch, err := agent.adapterProxy.revertImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
1080 if err != nil {
1081 cancel()
npujar1d86a522019-11-14 17:11:16 +05301082 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -05001083 }
khenaidoo442e7c72020-03-10 16:13:48 -04001084 go agent.waitForAdapterResponse(subCtx, cancel, "revertImageUpdate", ch, agent.onSuccess, agent.onFailure)
1085
khenaidoof5a5bfa2019-01-23 22:20:29 -05001086 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001087}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001088
1089func (agent *DeviceAgent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001090 logger.Debugw("getImageDownloadStatus", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001091
khenaidoo442e7c72020-03-10 16:13:48 -04001092 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301093 return nil, err
1094 }
khenaidoo442e7c72020-03-10 16:13:48 -04001095 device := agent.getDeviceWithoutLock()
1096 ch, err := agent.adapterProxy.getImageDownloadStatus(ctx, device, img)
1097 agent.requestQueue.RequestComplete()
1098 if err != nil {
1099 return nil, err
1100 }
1101 // Wait for the adapter response
1102 rpcResponse, ok := <-ch
1103 if !ok {
1104 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1105 }
1106 if rpcResponse.Err != nil {
1107 return nil, rpcResponse.Err
1108 }
1109 // Successful response
1110 imgDownload := &voltha.ImageDownload{}
1111 if err := ptypes.UnmarshalAny(rpcResponse.Reply, imgDownload); err != nil {
1112 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1113 }
1114 return imgDownload, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001115}
1116
npujar467fe752020-01-16 20:17:45 +05301117func (agent *DeviceAgent) updateImageDownload(ctx context.Context, img *voltha.ImageDownload) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001118 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1119 return err
1120 }
1121 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001122 logger.Debugw("updating-image-download", log.Fields{"device-id": agent.deviceID, "img": img})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001123
1124 cloned := agent.getDeviceWithoutLock()
1125
npujar1d86a522019-11-14 17:11:16 +05301126 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +05301127 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
1128 for _, image := range cloned.ImageDownloads {
1129 if image.Id == img.Id && image.Name == img.Name {
1130 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
1131 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001132 }
1133 }
npujar1d86a522019-11-14 17:11:16 +05301134 }
1135 cloned.ImageDownloads = clonedImages
1136 // Set the Admin state to enabled if required
1137 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
1138 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
1139 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
1140 cloned.AdminState = voltha.AdminState_ENABLED
1141 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001142
npujar467fe752020-01-16 20:17:45 +05301143 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301144 return err
khenaidoof5a5bfa2019-01-23 22:20:29 -05001145 }
1146 return nil
1147}
1148
1149func (agent *DeviceAgent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001150 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1151 return nil, err
1152 }
1153 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001154 logger.Debugw("getImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001155
1156 cloned := agent.getDeviceWithoutLock()
1157 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +05301158 if image.Id == img.Id && image.Name == img.Name {
1159 return image, nil
1160 }
1161 }
1162 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001163}
1164
npujar1d86a522019-11-14 17:11:16 +05301165func (agent *DeviceAgent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001166 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1167 return nil, err
1168 }
1169 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001170 logger.Debugw("listImageDownloads", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001171
1172 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001173}
1174
khenaidoo4d4802d2018-10-04 21:59:49 -04001175// getPorts retrieves the ports information of the device based on the port type.
khenaidoo92e62c52018-10-03 14:02:54 -04001176func (agent *DeviceAgent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
Girish Kumarf56a4682020-03-20 20:07:46 +00001177 logger.Debugw("getPorts", log.Fields{"device-id": agent.deviceID, "port-type": portType})
khenaidoob9203542018-09-17 22:56:37 -04001178 ports := &voltha.Ports{}
npujar467fe752020-01-16 20:17:45 +05301179 if device, _ := agent.deviceMgr.GetDevice(ctx, agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -04001180 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -04001181 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -04001182 ports.Items = append(ports.Items, port)
1183 }
1184 }
1185 }
1186 return ports
1187}
1188
khenaidoo442e7c72020-03-10 16:13:48 -04001189// getSwitchCapability retrieves the switch capability of a parent device
khenaidoo79232702018-12-04 11:00:41 -05001190func (agent *DeviceAgent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001191 logger.Debugw("getSwitchCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001192
1193 cloned, err := agent.getDevice(ctx)
1194 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001195 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001196 }
khenaidoo442e7c72020-03-10 16:13:48 -04001197 ch, err := agent.adapterProxy.getOfpDeviceInfo(ctx, cloned)
1198 if err != nil {
1199 return nil, err
1200 }
1201
1202 // Wait for adapter response
1203 rpcResponse, ok := <-ch
1204 if !ok {
1205 return nil, status.Errorf(codes.Aborted, "channel-closed")
1206 }
1207 if rpcResponse.Err != nil {
1208 return nil, rpcResponse.Err
1209 }
1210 // Successful response
1211 switchCap := &ic.SwitchCapability{}
1212 if err := ptypes.UnmarshalAny(rpcResponse.Reply, switchCap); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301213 return nil, err
1214 }
1215 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001216}
1217
khenaidoo442e7c72020-03-10 16:13:48 -04001218// getPortCapability retrieves the port capability of a device
khenaidoo79232702018-12-04 11:00:41 -05001219func (agent *DeviceAgent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001220 logger.Debugw("getPortCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001221 device, err := agent.getDevice(ctx)
1222 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001223 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001224 }
khenaidoo442e7c72020-03-10 16:13:48 -04001225 ch, err := agent.adapterProxy.getOfpPortInfo(ctx, device, portNo)
1226 if err != nil {
npujar1d86a522019-11-14 17:11:16 +05301227 return nil, err
1228 }
khenaidoo442e7c72020-03-10 16:13:48 -04001229 // Wait for adapter response
1230 rpcResponse, ok := <-ch
1231 if !ok {
1232 return nil, status.Errorf(codes.Aborted, "channel-closed")
1233 }
1234 if rpcResponse.Err != nil {
1235 return nil, rpcResponse.Err
1236 }
1237 // Successful response
1238 portCap := &ic.PortCapability{}
1239 if err := ptypes.UnmarshalAny(rpcResponse.Reply, portCap); err != nil {
1240 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1241 }
npujar1d86a522019-11-14 17:11:16 +05301242 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001243}
1244
khenaidoo442e7c72020-03-10 16:13:48 -04001245func (agent *DeviceAgent) onPacketFailure(rpc string, response interface{}, args ...interface{}) {
1246 // packet data is encoded in the args param as the first parameter
1247 var packet []byte
1248 if len(args) >= 1 {
1249 if pkt, ok := args[0].([]byte); ok {
1250 packet = pkt
1251 }
1252 }
1253 var errResp error
1254 if err, ok := response.(error); ok {
1255 errResp = err
1256 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001257 logger.Warnw("packet-out-error", log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -04001258 "device-id": agent.deviceID,
1259 "error": errResp,
1260 "packet": hex.EncodeToString(packet),
1261 })
1262}
1263
npujar467fe752020-01-16 20:17:45 +05301264func (agent *DeviceAgent) packetOut(ctx context.Context, outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001265 // If deviceType=="" then we must have taken ownership of this device.
1266 // Fixes VOL-2226 where a core would take ownership and have stale data
1267 if agent.deviceType == "" {
npujar467fe752020-01-16 20:17:45 +05301268 agent.reconcileWithKVStore(ctx)
Scott Baker80678602019-11-14 16:57:36 -08001269 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001270 // Send packet to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001271 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1272 ch, err := agent.adapterProxy.packetOut(subCtx, agent.deviceType, agent.deviceID, outPort, packet)
1273 if err != nil {
1274 cancel()
1275 return nil
khenaidoofdbad6e2018-11-06 22:26:38 -05001276 }
khenaidoo442e7c72020-03-10 16:13:48 -04001277 go agent.waitForAdapterResponse(subCtx, cancel, "packetOut", ch, agent.onSuccess, agent.onPacketFailure, packet.Data)
khenaidoofdbad6e2018-11-06 22:26:38 -05001278 return nil
1279}
1280
khenaidoo442e7c72020-03-10 16:13:48 -04001281// processUpdate is a respCallback invoked whenever there is a change on the device manages by this device agent
npujar467fe752020-01-16 20:17:45 +05301282func (agent *DeviceAgent) processUpdate(ctx context.Context, args ...interface{}) interface{} {
khenaidoo442e7c72020-03-10 16:13:48 -04001283 //// Run this respCallback in its own go routine
khenaidoo43c82122018-11-22 18:38:28 -05001284 go func(args ...interface{}) interface{} {
1285 var previous *voltha.Device
1286 var current *voltha.Device
1287 var ok bool
1288 if len(args) == 2 {
1289 if previous, ok = args[0].(*voltha.Device); !ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001290 logger.Errorw("invalid-callback-type", log.Fields{"data": args[0]})
khenaidoo43c82122018-11-22 18:38:28 -05001291 return nil
1292 }
1293 if current, ok = args[1].(*voltha.Device); !ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001294 logger.Errorw("invalid-callback-type", log.Fields{"data": args[1]})
khenaidoo43c82122018-11-22 18:38:28 -05001295 return nil
1296 }
1297 } else {
Girish Kumarf56a4682020-03-20 20:07:46 +00001298 logger.Errorw("too-many-args-in-callback", log.Fields{"len": len(args)})
khenaidoo43c82122018-11-22 18:38:28 -05001299 return nil
1300 }
khenaidoo442e7c72020-03-10 16:13:48 -04001301 // Perform the state transition in it's own go routine
npujar467fe752020-01-16 20:17:45 +05301302 if err := agent.deviceMgr.processTransition(context.Background(), previous, current); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001303 logger.Errorw("failed-process-transition", log.Fields{"device-id": previous.Id,
khenaidoo442e7c72020-03-10 16:13:48 -04001304 "previous-admin-state": previous.AdminState, "current-admin-state": current.AdminState})
khenaidoof5a5bfa2019-01-23 22:20:29 -05001305 }
khenaidoo43c82122018-11-22 18:38:28 -05001306 return nil
1307 }(args...)
1308
khenaidoo92e62c52018-10-03 14:02:54 -04001309 return nil
1310}
1311
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001312// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1313// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
1314func (agent *DeviceAgent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001315 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001316 cloned.Root = device.Root
1317 cloned.Vendor = device.Vendor
1318 cloned.Model = device.Model
1319 cloned.SerialNumber = device.SerialNumber
1320 cloned.MacAddress = device.MacAddress
1321 cloned.Vlan = device.Vlan
1322 cloned.Reason = device.Reason
1323 return cloned, nil
1324}
khenaidoo442e7c72020-03-10 16:13:48 -04001325
npujar467fe752020-01-16 20:17:45 +05301326func (agent *DeviceAgent) updateDeviceUsingAdapterData(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001327 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1328 return err
1329 }
1330 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001331 logger.Debugw("updateDeviceUsingAdapterData", log.Fields{"device-id": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001332
npujar1d86a522019-11-14 17:11:16 +05301333 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1334 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001335 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001336 }
npujar1d86a522019-11-14 17:11:16 +05301337 cloned := proto.Clone(updatedDevice).(*voltha.Device)
npujar467fe752020-01-16 20:17:45 +05301338 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001339}
1340
npujar467fe752020-01-16 20:17:45 +05301341func (agent *DeviceAgent) updateDeviceWithoutLock(ctx context.Context, device *voltha.Device) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001342 logger.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001343 //cloned := proto.Clone(device).(*voltha.Device)
1344 cloned := device
npujar467fe752020-01-16 20:17:45 +05301345 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001346}
1347
npujar467fe752020-01-16 20:17:45 +05301348func (agent *DeviceAgent) updateDeviceStatus(ctx context.Context, operStatus voltha.OperStatus_Types, connStatus voltha.ConnectStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001349 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1350 return err
1351 }
1352 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001353
1354 cloned := agent.getDeviceWithoutLock()
1355
npujar1d86a522019-11-14 17:11:16 +05301356 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001357 if s, ok := voltha.ConnectStatus_Types_value[connStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001358 logger.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
npujar1d86a522019-11-14 17:11:16 +05301359 cloned.ConnectStatus = connStatus
1360 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001361 if s, ok := voltha.OperStatus_Types_value[operStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001362 logger.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
npujar1d86a522019-11-14 17:11:16 +05301363 cloned.OperStatus = operStatus
1364 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001365 logger.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
npujar1d86a522019-11-14 17:11:16 +05301366 // Store the device
npujar467fe752020-01-16 20:17:45 +05301367 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001368}
1369
kesavandbc2d1622020-01-21 00:42:01 -05001370func (agent *DeviceAgent) updatePortsOperState(ctx context.Context, operStatus voltha.OperStatus_Types) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001371 logger.Debugw("updatePortsOperState", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001372 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1373 return err
1374 }
1375 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001376 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301377 for _, port := range cloned.Ports {
kesavandbc2d1622020-01-21 00:42:01 -05001378 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301379 }
1380 // Store the device
npujar467fe752020-01-16 20:17:45 +05301381 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001382}
1383
npujar467fe752020-01-16 20:17:45 +05301384func (agent *DeviceAgent) updatePortState(ctx context.Context, portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001385 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1386 return err
1387 }
1388 defer agent.requestQueue.RequestComplete()
khenaidoo92e62c52018-10-03 14:02:54 -04001389 // Work only on latest data
1390 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001391 cloned := agent.getDeviceWithoutLock()
1392
npujar1d86a522019-11-14 17:11:16 +05301393 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1394 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1395 return status.Errorf(codes.InvalidArgument, "%s", portType)
1396 }
1397 for _, port := range cloned.Ports {
1398 if port.Type == portType && port.PortNo == portNo {
1399 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301400 }
1401 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001402 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301403 // Store the device
npujar467fe752020-01-16 20:17:45 +05301404 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001405}
1406
npujar467fe752020-01-16 20:17:45 +05301407func (agent *DeviceAgent) deleteAllPorts(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001408 logger.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001409 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1410 return err
1411 }
1412 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001413
1414 cloned := agent.getDeviceWithoutLock()
1415
1416 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1417 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
Girish Kumarf56a4682020-03-20 20:07:46 +00001418 logger.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301419 return err
1420 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001421 if len(cloned.Ports) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +00001422 logger.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301423 return nil
1424 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001425
npujar1d86a522019-11-14 17:11:16 +05301426 cloned.Ports = []*voltha.Port{}
Girish Kumarf56a4682020-03-20 20:07:46 +00001427 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301428 // Store the device
npujar467fe752020-01-16 20:17:45 +05301429 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001430}
1431
npujar467fe752020-01-16 20:17:45 +05301432func (agent *DeviceAgent) addPort(ctx context.Context, port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001433 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1434 return err
1435 }
1436 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001437 logger.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001438
1439 cloned := agent.getDeviceWithoutLock()
khenaidoo80b987d2020-02-20 10:52:52 -05001440 updatePort := false
npujar1d86a522019-11-14 17:11:16 +05301441 if cloned.Ports == nil {
1442 // First port
Girish Kumarf56a4682020-03-20 20:07:46 +00001443 logger.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301444 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001445 } else {
npujar1d86a522019-11-14 17:11:16 +05301446 for _, p := range cloned.Ports {
1447 if p.Type == port.Type && p.PortNo == port.PortNo {
khenaidoo80b987d2020-02-20 10:52:52 -05001448 if p.Label == "" && p.Type == voltha.Port_PON_OLT {
1449 //Creation of OLT PON port is being processed after a default PON port was created. Just update it.
Girish Kumarf56a4682020-03-20 20:07:46 +00001450 logger.Infow("update-pon-port-created-by-default", log.Fields{"default-port": p, "port-to-add": port})
khenaidoo80b987d2020-02-20 10:52:52 -05001451 p.Label = port.Label
1452 p.OperStatus = port.OperStatus
1453 updatePort = true
1454 break
1455 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001456 logger.Debugw("port already exists", log.Fields{"port": port})
npujar1d86a522019-11-14 17:11:16 +05301457 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001458 }
khenaidoob9203542018-09-17 22:56:37 -04001459 }
khenaidoo92e62c52018-10-03 14:02:54 -04001460 }
khenaidoo80b987d2020-02-20 10:52:52 -05001461 if !updatePort {
1462 cp := proto.Clone(port).(*voltha.Port)
1463 // Set the admin state of the port to ENABLE
1464 cp.AdminState = voltha.AdminState_ENABLED
1465 cloned.Ports = append(cloned.Ports, cp)
1466 }
npujar1d86a522019-11-14 17:11:16 +05301467 // Store the device
npujar467fe752020-01-16 20:17:45 +05301468 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001469}
1470
khenaidoo80b987d2020-02-20 10:52:52 -05001471func (agent *DeviceAgent) addPeerPort(ctx context.Context, peerPort *voltha.Port_PeerPort) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001472 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1473 return err
1474 }
1475 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001476 logger.Debugw("adding-peer-peerPort", log.Fields{"device-id": agent.deviceID, "peer-peerPort": peerPort})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001477
1478 cloned := agent.getDeviceWithoutLock()
1479
khenaidoo80b987d2020-02-20 10:52:52 -05001480 // Get the peer port on the device based on the peerPort no
1481 found := false
1482 for _, port := range cloned.Ports {
1483 if port.PortNo == peerPort.PortNo { // found peerPort
1484 cp := proto.Clone(peerPort).(*voltha.Port_PeerPort)
1485 port.Peers = append(port.Peers, cp)
Girish Kumarf56a4682020-03-20 20:07:46 +00001486 logger.Debugw("found-peer", log.Fields{"device-id": agent.deviceID, "portNo": peerPort.PortNo, "deviceId": agent.deviceID})
khenaidoo80b987d2020-02-20 10:52:52 -05001487 found = true
npujar1d86a522019-11-14 17:11:16 +05301488 break
1489 }
1490 }
khenaidoo80b987d2020-02-20 10:52:52 -05001491 if !found && agent.isRootdevice {
1492 // An ONU PON port has been created before the corresponding creation of the OLT PON port. Create the OLT PON port
1493 // with default values which will be updated once the OLT PON port creation is processed.
1494 ponPort := &voltha.Port{
1495 PortNo: peerPort.PortNo,
1496 Type: voltha.Port_PON_OLT,
1497 AdminState: voltha.AdminState_ENABLED,
1498 DeviceId: agent.deviceID,
1499 Peers: []*voltha.Port_PeerPort{proto.Clone(peerPort).(*voltha.Port_PeerPort)},
1500 }
1501 cloned.Ports = append(cloned.Ports, ponPort)
Girish Kumarf56a4682020-03-20 20:07:46 +00001502 logger.Infow("adding-default-pon-port", log.Fields{"device-id": agent.deviceID, "peer": peerPort, "pon-port": ponPort})
khenaidoo80b987d2020-02-20 10:52:52 -05001503 }
npujar1d86a522019-11-14 17:11:16 +05301504 // Store the device
npujar467fe752020-01-16 20:17:45 +05301505 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001506}
1507
1508// TODO: A generic device update by attribute
npujar467fe752020-01-16 20:17:45 +05301509func (agent *DeviceAgent) updateDeviceAttribute(ctx context.Context, name string, value interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -04001510 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001511 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "name": name, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -04001512 return
1513 }
1514 defer agent.requestQueue.RequestComplete()
khenaidoob9203542018-09-17 22:56:37 -04001515 if value == nil {
1516 return
1517 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001518
1519 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001520 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001521 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001522 if s.Kind() == reflect.Struct {
1523 // exported field
1524 f := s.FieldByName(name)
1525 if f.IsValid() && f.CanSet() {
1526 switch f.Kind() {
1527 case reflect.String:
1528 f.SetString(value.(string))
1529 updated = true
1530 case reflect.Uint32:
1531 f.SetUint(uint64(value.(uint32)))
1532 updated = true
1533 case reflect.Bool:
1534 f.SetBool(value.(bool))
1535 updated = true
1536 }
1537 }
1538 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001539 logger.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001540 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001541
npujar467fe752020-01-16 20:17:45 +05301542 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001543 logger.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
khenaidoob9203542018-09-17 22:56:37 -04001544 }
khenaidoob9203542018-09-17 22:56:37 -04001545}
serkant.uluderya334479d2019-04-10 08:26:15 -07001546
1547func (agent *DeviceAgent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001548 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1549 return err
1550 }
1551 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001552 logger.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001553
1554 cloned := agent.getDeviceWithoutLock()
1555
khenaidoo442e7c72020-03-10 16:13:48 -04001556 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1557 ch, err := agent.adapterProxy.simulateAlarm(subCtx, cloned, simulatereq)
1558 if err != nil {
1559 cancel()
npujar1d86a522019-11-14 17:11:16 +05301560 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001561 }
khenaidoo442e7c72020-03-10 16:13:48 -04001562 go agent.waitForAdapterResponse(subCtx, cancel, "simulateAlarm", ch, agent.onSuccess, agent.onFailure)
serkant.uluderya334479d2019-04-10 08:26:15 -07001563 return nil
1564}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001565
1566//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.
1567// It is an internal helper function.
npujar467fe752020-01-16 20:17:45 +05301568func (agent *DeviceAgent) updateDeviceInStoreWithoutLock(ctx context.Context, device *voltha.Device, strict bool, txid string) error {
1569 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Thomas Lee Se5a44012019-11-07 20:32:24 +05301570 afterUpdate, err := agent.clusterDataProxy.Update(updateCtx, "/devices/"+agent.deviceID, device, strict, txid)
1571 if err != nil {
1572 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
1573 }
1574 if afterUpdate == nil {
npujar1d86a522019-11-14 17:11:16 +05301575 return status.Errorf(codes.Internal, "failed-update-device:%s", agent.deviceID)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001576 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001577 logger.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001578
khenaidoo6e55d9e2019-12-12 18:26:26 -05001579 agent.device = proto.Clone(device).(*voltha.Device)
1580
Mahir Gunyelb5851672019-07-24 10:46:26 +03001581 return nil
1582}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001583
npujar467fe752020-01-16 20:17:45 +05301584func (agent *DeviceAgent) updateDeviceReason(ctx context.Context, reason string) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001585 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1586 return err
1587 }
1588 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001589
1590 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301591 cloned.Reason = reason
Girish Kumarf56a4682020-03-20 20:07:46 +00001592 logger.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
npujar1d86a522019-11-14 17:11:16 +05301593 // Store the device
npujar467fe752020-01-16 20:17:45 +05301594 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001595}
kesavandbc2d1622020-01-21 00:42:01 -05001596
1597func (agent *DeviceAgent) disablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001598 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1599 return err
1600 }
1601 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001602 logger.Debugw("disablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001603 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001604 // Get the most up to date the device info
1605 device := agent.getDeviceWithoutLock()
1606 for _, port := range device.Ports {
1607 if port.PortNo == Port.PortNo {
1608 port.AdminState = voltha.AdminState_DISABLED
1609 cp = proto.Clone(port).(*voltha.Port)
1610 break
1611
1612 }
1613 }
1614 if cp == nil {
1615 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1616 }
1617
1618 if cp.Type != voltha.Port_PON_OLT {
1619 return status.Errorf(codes.InvalidArgument, "Disabling of Port Type %v unimplemented", cp.Type)
1620 }
1621 // Store the device
1622 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001623 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001624 return err
1625 }
khenaidoo442e7c72020-03-10 16:13:48 -04001626
kesavandbc2d1622020-01-21 00:42:01 -05001627 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001628 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1629 ch, err := agent.adapterProxy.disablePort(ctx, device, cp)
1630 if err != nil {
1631 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001632 return err
1633 }
khenaidoo442e7c72020-03-10 16:13:48 -04001634 go agent.waitForAdapterResponse(subCtx, cancel, "disablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001635 return nil
1636}
1637
1638func (agent *DeviceAgent) enablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001639 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1640 return err
1641 }
1642 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001643 logger.Debugw("enablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001644
1645 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001646 // Get the most up to date the device info
1647 device := agent.getDeviceWithoutLock()
1648 for _, port := range device.Ports {
1649 if port.PortNo == Port.PortNo {
1650 port.AdminState = voltha.AdminState_ENABLED
1651 cp = proto.Clone(port).(*voltha.Port)
1652 break
1653 }
1654 }
1655
1656 if cp == nil {
1657 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1658 }
1659
1660 if cp.Type != voltha.Port_PON_OLT {
1661 return status.Errorf(codes.InvalidArgument, "Enabling of Port Type %v unimplemented", cp.Type)
1662 }
1663 // Store the device
1664 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001665 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001666 return err
1667 }
1668 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001669 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1670 ch, err := agent.adapterProxy.enablePort(ctx, device, cp)
1671 if err != nil {
1672 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001673 return err
1674 }
khenaidoo442e7c72020-03-10 16:13:48 -04001675 go agent.waitForAdapterResponse(subCtx, cancel, "enablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001676 return nil
1677}
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001678
1679func (agent *DeviceAgent) ChildDeviceLost(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001680 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1681 return err
1682 }
1683 defer agent.requestQueue.RequestComplete()
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001684
Girish Kumarf56a4682020-03-20 20:07:46 +00001685 logger.Debugw("childDeviceLost", log.Fields{"child-device-id": device.Id, "parent-device-ud": agent.deviceID})
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001686
1687 //Remove the associated peer ports on the parent device
khenaidoo442e7c72020-03-10 16:13:48 -04001688 parentDevice := agent.getDeviceWithoutLock()
1689 var updatedPeers []*voltha.Port_PeerPort
1690 for _, port := range parentDevice.Ports {
1691 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1692 for _, peerPort := range port.Peers {
1693 if peerPort.DeviceId != device.Id {
1694 updatedPeers = append(updatedPeers, peerPort)
1695 }
1696 }
1697 port.Peers = updatedPeers
1698 }
1699 if err := agent.updateDeviceInStoreWithoutLock(ctx, parentDevice, false, ""); err != nil {
1700 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001701 }
1702
khenaidoo442e7c72020-03-10 16:13:48 -04001703 //send request to adapter
1704 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
1705 ch, err := agent.adapterProxy.childDeviceLost(ctx, agent.deviceType, agent.deviceID, device.ParentPortNo, device.ProxyAddress.OnuId)
1706 if err != nil {
1707 cancel()
1708 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001709 }
khenaidoo442e7c72020-03-10 16:13:48 -04001710 go agent.waitForAdapterResponse(subCtx, cancel, "childDeviceLost", ch, agent.onSuccess, agent.onFailure)
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001711 return nil
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001712}
onkarkundargi87285252020-01-27 11:34:52 +05301713
1714func (agent *DeviceAgent) startOmciTest(ctx context.Context, omcitestrequest *voltha.OmciTestRequest) (*voltha.TestResponse, error) {
1715 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1716 return nil, err
1717 }
1718
1719 device := agent.getDeviceWithoutLock()
1720 adapterName, err := agent.adapterMgr.getAdapterName(device.Type)
1721 if err != nil {
1722 agent.requestQueue.RequestComplete()
1723 return nil, err
1724 }
1725
1726 // Send request to the adapter
1727 device.Adapter = adapterName
1728 ch, err := agent.adapterProxy.startOmciTest(ctx, device, omcitestrequest)
1729 agent.requestQueue.RequestComplete()
1730 if err != nil {
1731 return nil, err
1732 }
1733
1734 // Wait for the adapter response
1735 rpcResponse, ok := <-ch
1736 if !ok {
1737 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1738 }
1739 if rpcResponse.Err != nil {
1740 return nil, rpcResponse.Err
1741 }
1742
1743 // Unmarshal and return the response
1744 testResp := &voltha.TestResponse{}
1745 if err := ptypes.UnmarshalAny(rpcResponse.Reply, testResp); err != nil {
1746 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1747 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001748 logger.Debugw("Omci_test_Request-Success-device-agent", log.Fields{"testResp": testResp})
onkarkundargi87285252020-01-27 11:34:52 +05301749 return testResp, nil
1750}