blob: 3857a6be144845913d6668f0249055ad916b360d [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
Kent Hagerman2b216042020-04-03 18:28:56 -040017package device
khenaidoob9203542018-09-17 22:56:37 -040018
19import (
20 "context"
Matteo Scandolo360605d2019-11-05 18:29:17 -080021 "encoding/hex"
Kent Hagerman4f355f52020-03-30 16:01:33 -040022 "errors"
khenaidoo3ab34882019-05-02 21:33:30 -040023 "fmt"
khenaidoo442e7c72020-03-10 16:13:48 -040024 "github.com/golang/protobuf/ptypes"
Kent Hagerman2b216042020-04-03 18:28:56 -040025 "github.com/opencord/voltha-go/rw_core/core/adapter"
26 "github.com/opencord/voltha-go/rw_core/core/device/remote"
khenaidoo442e7c72020-03-10 16:13:48 -040027 "github.com/opencord/voltha-lib-go/v3/pkg/kafka"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040028 "reflect"
29 "sync"
30 "time"
31
khenaidoob9203542018-09-17 22:56:37 -040032 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050033 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070034 coreutils "github.com/opencord/voltha-go/rw_core/utils"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080035 fu "github.com/opencord/voltha-lib-go/v3/pkg/flows"
36 "github.com/opencord/voltha-lib-go/v3/pkg/log"
37 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
38 ofp "github.com/opencord/voltha-protos/v3/go/openflow_13"
39 "github.com/opencord/voltha-protos/v3/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040040 "google.golang.org/grpc/codes"
41 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040042)
43
Kent Hagerman2b216042020-04-03 18:28:56 -040044// Agent represents device agent attributes
45type Agent struct {
npujar1d86a522019-11-14 17:11:16 +053046 deviceID string
47 parentID string
khenaidoo43c82122018-11-22 18:38:28 -050048 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040049 isRootdevice bool
Kent Hagerman2b216042020-04-03 18:28:56 -040050 adapterProxy *remote.AdapterProxy
51 adapterMgr *adapter.Manager
52 deviceMgr *Manager
khenaidoo9a468962018-09-19 15:33:13 -040053 clusterDataProxy *model.Proxy
54 exitChannel chan int
khenaidoo6e55d9e2019-12-12 18:26:26 -050055 device *voltha.Device
khenaidoo442e7c72020-03-10 16:13:48 -040056 requestQueue *coreutils.RequestQueue
57 defaultTimeout time.Duration
58 startOnce sync.Once
59 stopOnce sync.Once
60 stopped bool
khenaidoob9203542018-09-17 22:56:37 -040061}
62
Kent Hagerman2b216042020-04-03 18:28:56 -040063//newAgent creates a new device agent. The device will be initialized when start() is called.
64func newAgent(ap *remote.AdapterProxy, device *voltha.Device, deviceMgr *Manager, cdProxy *model.Proxy, timeout time.Duration) *Agent {
65 var agent Agent
khenaidoob9203542018-09-17 22:56:37 -040066 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080067 if device.Id == "" {
Kent Hagerman2b216042020-04-03 18:28:56 -040068 agent.deviceID = coreutils.CreateDeviceID()
Scott Baker80678602019-11-14 16:57:36 -080069 } else {
npujar1d86a522019-11-14 17:11:16 +053070 agent.deviceID = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050071 }
Scott Baker80678602019-11-14 16:57:36 -080072
khenaidoo2c6a0992019-04-29 13:46:56 -040073 agent.isRootdevice = device.Root
npujar1d86a522019-11-14 17:11:16 +053074 agent.parentID = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080075 agent.deviceType = device.Type
khenaidoob9203542018-09-17 22:56:37 -040076 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050077 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040078 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040079 agent.clusterDataProxy = cdProxy
khenaidoo2c6a0992019-04-29 13:46:56 -040080 agent.defaultTimeout = timeout
khenaidoo6e55d9e2019-12-12 18:26:26 -050081 agent.device = proto.Clone(device).(*voltha.Device)
Kent Hagerman730cbdf2020-03-31 12:22:08 -040082 agent.requestQueue = coreutils.NewRequestQueue()
khenaidoob9203542018-09-17 22:56:37 -040083 return &agent
84}
85
khenaidoo442e7c72020-03-10 16:13:48 -040086// start() saves the device to the data model and registers for callbacks on that device if deviceToCreate!=nil.
87// 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 -080088// was started.
Kent Hagerman2b216042020-04-03 18:28:56 -040089func (agent *Agent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
khenaidoo442e7c72020-03-10 16:13:48 -040090 needToStart := false
91 if agent.startOnce.Do(func() { needToStart = true }); !needToStart {
92 return agent.getDevice(ctx)
93 }
94 var startSucceeded bool
95 defer func() {
96 if !startSucceeded {
97 if err := agent.stop(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +000098 logger.Errorw("failed-to-cleanup-after-unsuccessful-start", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -040099 }
100 }
101 }()
Scott Baker80678602019-11-14 16:57:36 -0800102
khenaidoo442e7c72020-03-10 16:13:48 -0400103 var device *voltha.Device
Scott Baker80678602019-11-14 16:57:36 -0800104 if deviceToCreate == nil {
105 // Load the existing device
Kent Hagerman4f355f52020-03-30 16:01:33 -0400106 device := &voltha.Device{}
107 have, err := agent.clusterDataProxy.Get(ctx, "devices/"+agent.deviceID, device)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530108 if err != nil {
Thomas Lee Se5a44012019-11-07 20:32:24 +0530109 return nil, err
Kent Hagerman4f355f52020-03-30 16:01:33 -0400110 } else if !have {
111 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530112 }
Kent Hagerman4f355f52020-03-30 16:01:33 -0400113
114 agent.deviceType = device.Adapter
115 agent.device = proto.Clone(device).(*voltha.Device)
116
Girish Kumarf56a4682020-03-20 20:07:46 +0000117 logger.Infow("device-loaded-from-dB", log.Fields{"device-id": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500118 } else {
Scott Baker80678602019-11-14 16:57:36 -0800119 // Create a new device
120 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
121 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
Kent Hagerman2b216042020-04-03 18:28:56 -0400122 // agent.deviceId will also have been set during newAgent().
Scott Baker80678602019-11-14 16:57:36 -0800123 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530124 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800125 device.AdminState = voltha.AdminState_PREPROVISIONED
126 device.FlowGroups = &ofp.FlowGroups{Items: nil}
127 device.Flows = &ofp.Flows{Items: nil}
128 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
129 // Set the default vlan ID to the one specified by the parent adapter. It can be
130 // overwritten by the child adapter during a device update request
131 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
132 }
133
khenaidoo297cd252019-02-07 22:10:23 -0500134 // Add the initial device to the local model
Kent Hagerman4f355f52020-03-30 16:01:33 -0400135 if err := agent.clusterDataProxy.AddWithID(ctx, "devices", agent.deviceID, device); err != nil {
136 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s: %s", agent.deviceID, err)
khenaidoo297cd252019-02-07 22:10:23 -0500137 }
khenaidoo442e7c72020-03-10 16:13:48 -0400138 agent.device = device
khenaidoob9203542018-09-17 22:56:37 -0400139 }
khenaidoo19d7b632018-10-30 10:49:50 -0400140
khenaidoo442e7c72020-03-10 16:13:48 -0400141 startSucceeded = true
Girish Kumarf56a4682020-03-20 20:07:46 +0000142 logger.Debugw("device-agent-started", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400143
144 return agent.getDevice(ctx)
khenaidoob9203542018-09-17 22:56:37 -0400145}
146
khenaidoo4d4802d2018-10-04 21:59:49 -0400147// stop stops the device agent. Not much to do for now
Kent Hagerman2b216042020-04-03 18:28:56 -0400148func (agent *Agent) stop(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400149 needToStop := false
150 if agent.stopOnce.Do(func() { needToStop = true }); !needToStop {
151 return nil
152 }
153 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
154 return err
155 }
156 defer agent.requestQueue.RequestComplete()
khenaidoo49085352020-01-13 19:15:43 -0500157
Girish Kumarf56a4682020-03-20 20:07:46 +0000158 logger.Infow("stopping-device-agent", log.Fields{"deviceId": agent.deviceID, "parentId": agent.parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500159
khenaidoo0a822f92019-05-08 15:15:57 -0400160 // Remove the device from the KV store
Kent Hagerman4f355f52020-03-30 16:01:33 -0400161 if err := agent.clusterDataProxy.Remove(ctx, "devices/"+agent.deviceID); err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400162 return err
Thomas Lee Se5a44012019-11-07 20:32:24 +0530163 }
khenaidoo442e7c72020-03-10 16:13:48 -0400164
khenaidoo442e7c72020-03-10 16:13:48 -0400165 close(agent.exitChannel)
166
167 agent.stopped = true
168
Girish Kumarf56a4682020-03-20 20:07:46 +0000169 logger.Infow("device-agent-stopped", log.Fields{"device-id": agent.deviceID, "parent-id": agent.parentID})
khenaidoo442e7c72020-03-10 16:13:48 -0400170
171 return nil
khenaidoob9203542018-09-17 22:56:37 -0400172}
173
Scott Baker80678602019-11-14 16:57:36 -0800174// Load the most recent state from the KVStore for the device.
Kent Hagerman2b216042020-04-03 18:28:56 -0400175func (agent *Agent) reconcileWithKVStore(ctx context.Context) {
khenaidoo442e7c72020-03-10 16:13:48 -0400176 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000177 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -0400178 return
179 }
180 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000181 logger.Debug("reconciling-device-agent-devicetype")
Scott Baker80678602019-11-14 16:57:36 -0800182 // TODO: context timeout
Kent Hagerman4f355f52020-03-30 16:01:33 -0400183 device := &voltha.Device{}
184 if have, err := agent.clusterDataProxy.Get(ctx, "devices/"+agent.deviceID, device); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000185 logger.Errorw("kv-get-failed", log.Fields{"device-id": agent.deviceID, "error": err})
Thomas Lee Se5a44012019-11-07 20:32:24 +0530186 return
Kent Hagerman4f355f52020-03-30 16:01:33 -0400187 } else if !have {
188 return // not found in kv
Thomas Lee Se5a44012019-11-07 20:32:24 +0530189 }
Kent Hagerman4f355f52020-03-30 16:01:33 -0400190
191 agent.deviceType = device.Adapter
192 agent.device = device
193 logger.Debugw("reconciled-device-agent-devicetype", log.Fields{"device-id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800194}
195
khenaidoo442e7c72020-03-10 16:13:48 -0400196// onSuccess is a common callback for scenarios where we receive a nil response following a request to an adapter
197// and the only action required is to publish a successful result on kafka
Kent Hagerman2b216042020-04-03 18:28:56 -0400198func (agent *Agent) onSuccess(rpc string, response interface{}, reqArgs ...interface{}) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000199 logger.Debugw("response successful", log.Fields{"rpc": rpc, "device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400200 // TODO: Post success message onto kafka
201}
202
203// onFailure is a common callback for scenarios where we receive an error response following a request to an adapter
204// and the only action required is to publish the failed result on kafka
Kent Hagerman2b216042020-04-03 18:28:56 -0400205func (agent *Agent) onFailure(rpc string, response interface{}, reqArgs ...interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -0400206 if res, ok := response.(error); ok {
Girish Kumarf56a4682020-03-20 20:07:46 +0000207 logger.Errorw("rpc-failed", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "error": res, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400208 } else {
Girish Kumarf56a4682020-03-20 20:07:46 +0000209 logger.Errorw("rpc-failed-invalid-error", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400210 }
211 // TODO: Post failure message onto kafka
212}
213
Kent Hagerman2b216042020-04-03 18:28:56 -0400214func (agent *Agent) waitForAdapterResponse(ctx context.Context, cancel context.CancelFunc, rpc string, ch chan *kafka.RpcResponse,
khenaidoo442e7c72020-03-10 16:13:48 -0400215 onSuccess coreutils.ResponseCallback, onFailure coreutils.ResponseCallback, reqArgs ...interface{}) {
216 defer cancel()
217 select {
218 case rpcResponse, ok := <-ch:
219 if !ok {
220 onFailure(rpc, status.Errorf(codes.Aborted, "channel-closed"), reqArgs)
221 } else if rpcResponse.Err != nil {
222 onFailure(rpc, rpcResponse.Err, reqArgs)
223 } else {
224 onSuccess(rpc, rpcResponse.Reply, reqArgs)
225 }
226 case <-ctx.Done():
227 onFailure(rpc, ctx.Err(), reqArgs)
228 }
229}
230
khenaidoo6e55d9e2019-12-12 18:26:26 -0500231// getDevice returns the device data from cache
Kent Hagerman2b216042020-04-03 18:28:56 -0400232func (agent *Agent) getDevice(ctx context.Context) (*voltha.Device, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400233 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
234 return nil, err
235 }
236 defer agent.requestQueue.RequestComplete()
237 return proto.Clone(agent.device).(*voltha.Device), nil
khenaidoo92e62c52018-10-03 14:02:54 -0400238}
239
khenaidoo4d4802d2018-10-04 21:59:49 -0400240// getDeviceWithoutLock is a helper function to be used ONLY by any device agent function AFTER it has acquired the device lock.
Kent Hagerman2b216042020-04-03 18:28:56 -0400241func (agent *Agent) getDeviceWithoutLock() *voltha.Device {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500242 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400243}
244
khenaidoo3ab34882019-05-02 21:33:30 -0400245// enableDevice activates a preprovisioned or a disable device
Kent Hagerman2b216042020-04-03 18:28:56 -0400246func (agent *Agent) enableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400247 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
248 return err
249 }
250 defer agent.requestQueue.RequestComplete()
251
Girish Kumarf56a4682020-03-20 20:07:46 +0000252 logger.Debugw("enableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500253
khenaidoo6e55d9e2019-12-12 18:26:26 -0500254 cloned := agent.getDeviceWithoutLock()
255
npujar1d86a522019-11-14 17:11:16 +0530256 // 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 -0400257 // pre-provisioned with the required adapter not registered. At this stage, since we need to communicate
npujar1d86a522019-11-14 17:11:16 +0530258 // with the adapter then we need to know the adapter that will handle this request
Kent Hagerman2b216042020-04-03 18:28:56 -0400259 adapterName, err := agent.adapterMgr.GetAdapterType(cloned.Type)
npujar1d86a522019-11-14 17:11:16 +0530260 if err != nil {
npujar1d86a522019-11-14 17:11:16 +0530261 return err
262 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500263 cloned.Adapter = adapterName
npujar1d86a522019-11-14 17:11:16 +0530264
khenaidoo6e55d9e2019-12-12 18:26:26 -0500265 if cloned.AdminState == voltha.AdminState_ENABLED {
Matteo Scandolod525ae32020-04-02 17:27:29 -0700266 logger.Warnw("device-already-enabled", log.Fields{"device-id": agent.deviceID})
267 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-an-already-enabled-device: %s ", cloned.Id))
268 return err
npujar1d86a522019-11-14 17:11:16 +0530269 }
270
khenaidoo6e55d9e2019-12-12 18:26:26 -0500271 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530272 // This is a temporary state when a device is deleted before it gets removed from the model.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500273 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", cloned.Id))
npujar1d86a522019-11-14 17:11:16 +0530274 return err
275 }
276
khenaidoo6e55d9e2019-12-12 18:26:26 -0500277 previousAdminState := cloned.AdminState
npujar1d86a522019-11-14 17:11:16 +0530278
279 // Update the Admin State and set the operational state to activating before sending the request to the
280 // Adapters
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500281 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_ENABLED, cloned.ConnectStatus, voltha.OperStatus_ACTIVATING); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530282 return err
283 }
284
khenaidoo442e7c72020-03-10 16:13:48 -0400285 // 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 -0500286 device := proto.Clone(cloned).(*voltha.Device)
khenaidoo442e7c72020-03-10 16:13:48 -0400287 var ch chan *kafka.RpcResponse
288 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
npujar1d86a522019-11-14 17:11:16 +0530289 if previousAdminState == voltha.AdminState_PREPROVISIONED {
Kent Hagerman2b216042020-04-03 18:28:56 -0400290 ch, err = agent.adapterProxy.AdoptDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400291 } else {
Kent Hagerman2b216042020-04-03 18:28:56 -0400292 ch, err = agent.adapterProxy.ReEnableDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400293 }
khenaidoo442e7c72020-03-10 16:13:48 -0400294 if err != nil {
295 cancel()
296 return err
297 }
298 // Wait for response
299 go agent.waitForAdapterResponse(subCtx, cancel, "enableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoob9203542018-09-17 22:56:37 -0400300 return nil
301}
302
Kent Hagerman2b216042020-04-03 18:28:56 -0400303func (agent *Agent) waitForAdapterFlowResponse(ctx context.Context, cancel context.CancelFunc, ch chan *kafka.RpcResponse, response coreutils.Response) {
khenaidoo442e7c72020-03-10 16:13:48 -0400304 defer cancel()
305 select {
306 case rpcResponse, ok := <-ch:
307 if !ok {
308 response.Error(status.Errorf(codes.Aborted, "channel-closed"))
309 } else if rpcResponse.Err != nil {
310 response.Error(rpcResponse.Err)
311 } else {
312 response.Done()
313 }
314 case <-ctx.Done():
315 response.Error(ctx.Err())
khenaidoo2c6a0992019-04-29 13:46:56 -0400316 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400317}
318
khenaidoob2121e52019-12-16 17:17:22 -0500319//deleteFlowWithoutPreservingOrder removes a flow specified by index from the flows slice. This function will
320//panic if the index is out of range.
321func deleteFlowWithoutPreservingOrder(flows []*ofp.OfpFlowStats, index int) []*ofp.OfpFlowStats {
322 flows[index] = flows[len(flows)-1]
323 flows[len(flows)-1] = nil
324 return flows[:len(flows)-1]
325}
326
327//deleteGroupWithoutPreservingOrder removes a group specified by index from the groups slice. This function will
328//panic if the index is out of range.
329func deleteGroupWithoutPreservingOrder(groups []*ofp.OfpGroupEntry, index int) []*ofp.OfpGroupEntry {
330 groups[index] = groups[len(groups)-1]
331 groups[len(groups)-1] = nil
332 return groups[:len(groups)-1]
333}
334
335func flowsToUpdateToDelete(newFlows, existingFlows []*ofp.OfpFlowStats) (updatedNewFlows, flowsToDelete, updatedAllFlows []*ofp.OfpFlowStats) {
336 // Process flows
337 for _, flow := range existingFlows {
338 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
339 updatedAllFlows = append(updatedAllFlows, flow)
340 } else {
341 // We have a matching flow (i.e. the following field matches: "TableId", "Priority", "Flags", "Cookie",
342 // "Match". If this is an exact match (i.e. all other fields matches as well) then this flow will be
343 // ignored. Otherwise, the previous flow will be deleted and the new one added
344 if proto.Equal(newFlows[idx], flow) {
345 // Flow already exist, remove it from the new flows but keep it in the updated flows slice
346 newFlows = deleteFlowWithoutPreservingOrder(newFlows, idx)
347 updatedAllFlows = append(updatedAllFlows, flow)
348 } else {
349 // Minor change to flow, delete old and add new one
350 flowsToDelete = append(flowsToDelete, flow)
351 }
352 }
353 }
354 updatedAllFlows = append(updatedAllFlows, newFlows...)
355 return newFlows, flowsToDelete, updatedAllFlows
356}
357
358func groupsToUpdateToDelete(newGroups, existingGroups []*ofp.OfpGroupEntry) (updatedNewGroups, groupsToDelete, updatedAllGroups []*ofp.OfpGroupEntry) {
359 for _, group := range existingGroups {
360 if idx := fu.FindGroup(newGroups, group.Desc.GroupId); idx == -1 { // does not exist now
361 updatedAllGroups = append(updatedAllGroups, group)
362 } else {
363 // Follow same logic as flows
364 if proto.Equal(newGroups[idx], group) {
365 // Group already exist, remove it from the new groups
366 newGroups = deleteGroupWithoutPreservingOrder(newGroups, idx)
367 updatedAllGroups = append(updatedAllGroups, group)
368 } else {
369 // Minor change to group, delete old and add new one
370 groupsToDelete = append(groupsToDelete, group)
371 }
372 }
373 }
374 updatedAllGroups = append(updatedAllGroups, newGroups...)
375 return newGroups, groupsToDelete, updatedAllGroups
376}
377
Kent Hagerman2b216042020-04-03 18:28:56 -0400378func (agent *Agent) addFlowsAndGroupsToAdapter(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000379 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 -0400380
khenaidoo2c6a0992019-04-29 13:46:56 -0400381 if (len(newFlows) | len(newGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000382 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800383 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400384 }
385
khenaidoo442e7c72020-03-10 16:13:48 -0400386 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
387 return coreutils.DoneResponse(), err
388 }
389 defer agent.requestQueue.RequestComplete()
khenaidoo2c6a0992019-04-29 13:46:56 -0400390
khenaidoo6e55d9e2019-12-12 18:26:26 -0500391 device := agent.getDeviceWithoutLock()
Kent Hagerman2b216042020-04-03 18:28:56 -0400392 dType := agent.adapterMgr.GetDeviceType(device.Type)
khenaidoo442e7c72020-03-10 16:13:48 -0400393 if dType == nil {
394 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
395 }
396
khenaidoo0458db62019-06-20 08:50:36 -0400397 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
398 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
399
khenaidoo0458db62019-06-20 08:50:36 -0400400 // Process flows
khenaidoob2121e52019-12-16 17:17:22 -0500401 newFlows, flowsToDelete, updatedAllFlows := flowsToUpdateToDelete(newFlows, existingFlows.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400402
403 // Process groups
khenaidoob2121e52019-12-16 17:17:22 -0500404 newGroups, groupsToDelete, updatedAllGroups := groupsToUpdateToDelete(newGroups, existingGroups.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400405
406 // Sanity check
khenaidoob2121e52019-12-16 17:17:22 -0500407 if (len(updatedAllFlows) | len(flowsToDelete) | len(updatedAllGroups) | len(groupsToDelete)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000408 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800409 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400410 }
411
khenaidoo442e7c72020-03-10 16:13:48 -0400412 // store the changed data
413 device.Flows = &voltha.Flows{Items: updatedAllFlows}
414 device.FlowGroups = &voltha.FlowGroups{Items: updatedAllGroups}
415 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
416 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-device-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500417 }
khenaidoo0458db62019-06-20 08:50:36 -0400418
khenaidoo442e7c72020-03-10 16:13:48 -0400419 // Send update to adapters
420 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
421 response := coreutils.NewResponse()
422 if !dType.AcceptsAddRemoveFlowUpdates {
khenaidoob2121e52019-12-16 17:17:22 -0500423 if len(updatedAllGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedAllGroups) && len(updatedAllFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedAllFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000424 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400425 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800426 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400427 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400428 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedAllFlows}, &voltha.FlowGroups{Items: updatedAllGroups}, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400429 if err != nil {
430 cancel()
431 return coreutils.DoneResponse(), err
432 }
433 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400434 } else {
435 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400436 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400437 ToRemove: &voltha.Flows{Items: flowsToDelete},
438 }
439 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400440 ToAdd: &voltha.FlowGroups{Items: newGroups},
441 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400442 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
443 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400444 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400445 if err != nil {
446 cancel()
447 return coreutils.DoneResponse(), err
448 }
449 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400450 }
A R Karthick5c28f552019-12-11 22:47:44 -0800451 return response, nil
452}
453
454//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
455//adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400456func (agent *Agent) addFlowsAndGroups(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530457 response, err := agent.addFlowsAndGroupsToAdapter(ctx, newFlows, newGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800458 if err != nil {
459 return err
460 }
khenaidoo442e7c72020-03-10 16:13:48 -0400461 if errs := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); errs != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000462 logger.Warnw("no-adapter-response", log.Fields{"device-id": agent.deviceID, "result": errs})
khenaidoo442e7c72020-03-10 16:13:48 -0400463 return status.Errorf(codes.Aborted, "flow-failure-device-%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400464 }
khenaidoo0458db62019-06-20 08:50:36 -0400465 return nil
466}
467
Kent Hagerman2b216042020-04-03 18:28:56 -0400468func (agent *Agent) deleteFlowsAndGroupsFromAdapter(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000469 logger.Debugw("delete-flows-groups-from-adapter", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400470
471 if (len(flowsToDel) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000472 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800473 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400474 }
475
khenaidoo442e7c72020-03-10 16:13:48 -0400476 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
477 return coreutils.DoneResponse(), err
478 }
479 defer agent.requestQueue.RequestComplete()
khenaidoo0458db62019-06-20 08:50:36 -0400480
khenaidoo6e55d9e2019-12-12 18:26:26 -0500481 device := agent.getDeviceWithoutLock()
Kent Hagerman2b216042020-04-03 18:28:56 -0400482 dType := agent.adapterMgr.GetDeviceType(device.Type)
khenaidoo442e7c72020-03-10 16:13:48 -0400483 if dType == nil {
484 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
485 }
khenaidoo0458db62019-06-20 08:50:36 -0400486
487 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
488 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
489
490 var flowsToKeep []*ofp.OfpFlowStats
491 var groupsToKeep []*ofp.OfpGroupEntry
492
493 // Process flows
494 for _, flow := range existingFlows.Items {
495 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
496 flowsToKeep = append(flowsToKeep, flow)
497 }
498 }
499
500 // Process groups
501 for _, group := range existingGroups.Items {
502 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
503 groupsToKeep = append(groupsToKeep, group)
504 }
505 }
506
Girish Kumarf56a4682020-03-20 20:07:46 +0000507 logger.Debugw("deleteFlowsAndGroups",
khenaidoo0458db62019-06-20 08:50:36 -0400508 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400509 "device-id": agent.deviceID,
510 "flows-to-del": len(flowsToDel),
511 "flows-to-keep": len(flowsToKeep),
512 "groups-to-del": len(groupsToDel),
513 "groups-to-keep": len(groupsToKeep),
khenaidoo0458db62019-06-20 08:50:36 -0400514 })
515
516 // Sanity check
517 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000518 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 -0800519 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400520 }
521
khenaidoo442e7c72020-03-10 16:13:48 -0400522 // store the changed data
523 device.Flows = &voltha.Flows{Items: flowsToKeep}
524 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
525 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
526 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500527 }
khenaidoo442e7c72020-03-10 16:13:48 -0400528
529 // Send update to adapters
530 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
531 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400532 if !dType.AcceptsAddRemoveFlowUpdates {
533 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000534 logger.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
khenaidoo442e7c72020-03-10 16:13:48 -0400535 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800536 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400537 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400538 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400539 if err != nil {
540 cancel()
541 return coreutils.DoneResponse(), err
542 }
543 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400544 } else {
545 flowChanges := &ofp.FlowChanges{
546 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
547 ToRemove: &voltha.Flows{Items: flowsToDel},
548 }
549 groupChanges := &ofp.FlowGroupChanges{
550 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
551 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
552 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
553 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400554 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400555 if err != nil {
556 cancel()
557 return coreutils.DoneResponse(), err
558 }
559 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400560 }
A R Karthick5c28f552019-12-11 22:47:44 -0800561 return response, nil
A R Karthick5c28f552019-12-11 22:47:44 -0800562}
563
564//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
565//adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400566func (agent *Agent) deleteFlowsAndGroups(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530567 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDel, groupsToDel, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800568 if err != nil {
569 return err
570 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500571 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400572 return status.Errorf(codes.Aborted, "errors-%s", res)
573 }
574 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400575}
576
khenaidoo787224a2020-04-16 18:08:47 -0400577//filterOutFlows removes flows from a device using the uni-port as filter
578func (agent *Agent) filterOutFlows(ctx context.Context, uniPort uint32, flowMetadata *voltha.FlowMetadata) error {
579 device, err := agent.getDevice(ctx)
580 if err != nil {
581 return err
582 }
583 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
584 var flowsToDelete []*ofp.OfpFlowStats
585
586 // If an existing flow has the uniPort as an InPort or OutPort or as a Tunnel ID then it needs to be removed
587 for _, flow := range existingFlows.Items {
588 if fu.GetInPort(flow) == uniPort || fu.GetOutPort(flow) == uniPort || fu.GetTunnelId(flow) == uint64(uniPort) {
589 flowsToDelete = append(flowsToDelete, flow)
590 }
591 }
592 logger.Debugw("flows-to-delete", log.Fields{"device-id": agent.deviceID, "uni-port": uniPort, "flows": flowsToDelete})
593 if len(flowsToDelete) == 0 {
594 return nil
595 }
596
597 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDelete, []*ofp.OfpGroupEntry{}, flowMetadata)
598 if err != nil {
599 return err
600 }
601 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
602 return status.Errorf(codes.Aborted, "errors-%s", res)
603 }
604 return nil
605}
606
Kent Hagerman2b216042020-04-03 18:28:56 -0400607func (agent *Agent) updateFlowsAndGroupsToAdapter(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) (coreutils.Response, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000608 logger.Debugw("updateFlowsAndGroups", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400609
610 if (len(updatedFlows) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000611 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800612 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400613 }
614
khenaidoo442e7c72020-03-10 16:13:48 -0400615 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
616 return coreutils.DoneResponse(), err
617 }
618 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500619
620 device := agent.getDeviceWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400621 if device.OperStatus != voltha.OperStatus_ACTIVE || device.ConnectStatus != voltha.ConnectStatus_REACHABLE || device.AdminState != voltha.AdminState_ENABLED {
622 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "invalid device states")
623 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400624 dType := agent.adapterMgr.GetDeviceType(device.Type)
khenaidoo442e7c72020-03-10 16:13:48 -0400625 if dType == nil {
626 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
627 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500628
khenaidoo0458db62019-06-20 08:50:36 -0400629 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
630 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
631
632 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000633 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800634 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400635 }
636
Girish Kumarf56a4682020-03-20 20:07:46 +0000637 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400638 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400639 "device-id": agent.deviceID,
640 "updated-flows": updatedFlows,
641 "updated-groups": updatedGroups,
khenaidoo0458db62019-06-20 08:50:36 -0400642 })
643
khenaidoo442e7c72020-03-10 16:13:48 -0400644 // store the updated data
645 device.Flows = &voltha.Flows{Items: updatedFlows}
646 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
647 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
648 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500649 }
khenaidoo0458db62019-06-20 08:50:36 -0400650
khenaidoo442e7c72020-03-10 16:13:48 -0400651 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
652 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400653 // Process bulk flow update differently than incremental update
654 if !dType.AcceptsAddRemoveFlowUpdates {
Kent Hagerman2b216042020-04-03 18:28:56 -0400655 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil)
khenaidoo442e7c72020-03-10 16:13:48 -0400656 if err != nil {
657 cancel()
658 return coreutils.DoneResponse(), err
659 }
660 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400661 } else {
662 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400663 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400664 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400665 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400666
667 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400668 for _, flow := range updatedFlows {
669 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
670 flowsToAdd = append(flowsToAdd, flow)
671 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400672 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400673 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400674 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400675 flowsToDelete = append(flowsToDelete, flow)
676 }
677 }
678
679 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400680 for _, g := range updatedGroups {
681 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
682 groupsToAdd = append(groupsToAdd, g)
683 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400684 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400685 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400686 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400687 groupsToDelete = append(groupsToDelete, group)
688 }
689 }
690
Girish Kumarf56a4682020-03-20 20:07:46 +0000691 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400692 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400693 "device-id": agent.deviceID,
694 "flows-to-add": flowsToAdd,
695 "flows-to-delete": flowsToDelete,
696 "groups-to-add": groupsToAdd,
697 "groups-to-delete": groupsToDelete,
khenaidoo0458db62019-06-20 08:50:36 -0400698 })
699
khenaidoo2c6a0992019-04-29 13:46:56 -0400700 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400701 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000702 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400703 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800704 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400705 }
706
khenaidoo0458db62019-06-20 08:50:36 -0400707 flowChanges := &ofp.FlowChanges{
708 ToAdd: &voltha.Flows{Items: flowsToAdd},
709 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400710 }
khenaidoo0458db62019-06-20 08:50:36 -0400711 groupChanges := &ofp.FlowGroupChanges{
712 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
713 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
714 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
715 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400716 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400717 if err != nil {
718 cancel()
719 return coreutils.DoneResponse(), err
720 }
721 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
Kent Hagerman3c513972019-11-25 13:49:41 -0500722 }
khenaidoo0458db62019-06-20 08:50:36 -0400723
A R Karthick5c28f552019-12-11 22:47:44 -0800724 return response, nil
725}
726
727//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
728//also sends the updates to the adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400729func (agent *Agent) updateFlowsAndGroups(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530730 response, err := agent.updateFlowsAndGroupsToAdapter(ctx, updatedFlows, updatedGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800731 if err != nil {
732 return err
733 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500734 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400735 return status.Errorf(codes.Aborted, "errors-%s", res)
736 }
737 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400738}
739
Girish Gowdra408cd962020-03-11 14:31:31 -0700740//deleteAllFlows deletes all flows in the device table
Kent Hagerman2b216042020-04-03 18:28:56 -0400741func (agent *Agent) deleteAllFlows(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000742 logger.Debugw("deleteAllFlows", log.Fields{"deviceId": agent.deviceID})
Girish Gowdra408cd962020-03-11 14:31:31 -0700743 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
744 return err
745 }
746 defer agent.requestQueue.RequestComplete()
747
748 device := agent.getDeviceWithoutLock()
749 // purge all flows on the device by setting it to nil
750 device.Flows = &ofp.Flows{Items: nil}
751 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
752 // The caller logs the error
753 return err
754 }
755 return nil
756}
757
khenaidoo4d4802d2018-10-04 21:59:49 -0400758//disableDevice disable a device
Kent Hagerman2b216042020-04-03 18:28:56 -0400759func (agent *Agent) disableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400760 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
761 return err
762 }
763 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000764 logger.Debugw("disableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500765
766 cloned := agent.getDeviceWithoutLock()
767
768 if cloned.AdminState == voltha.AdminState_DISABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000769 logger.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530770 return nil
771 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500772 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
773 cloned.AdminState == voltha.AdminState_DELETED {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500774 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530775 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400776
npujar1d86a522019-11-14 17:11:16 +0530777 // Update the Admin State and operational state before sending the request out
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500778 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DISABLED, cloned.ConnectStatus, voltha.OperStatus_UNKNOWN); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530779 return err
780 }
khenaidoo442e7c72020-03-10 16:13:48 -0400781
782 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400783 ch, err := agent.adapterProxy.DisableDevice(subCtx, proto.Clone(cloned).(*voltha.Device))
khenaidoo442e7c72020-03-10 16:13:48 -0400784 if err != nil {
785 cancel()
npujar1d86a522019-11-14 17:11:16 +0530786 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400787 }
khenaidoo442e7c72020-03-10 16:13:48 -0400788 go agent.waitForAdapterResponse(subCtx, cancel, "disableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo0a822f92019-05-08 15:15:57 -0400789
khenaidoo92e62c52018-10-03 14:02:54 -0400790 return nil
791}
792
Kent Hagerman2b216042020-04-03 18:28:56 -0400793func (agent *Agent) rebootDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400794 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530795 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400796 }
khenaidoo442e7c72020-03-10 16:13:48 -0400797 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000798 logger.Debugw("rebootDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400799
800 device := agent.getDeviceWithoutLock()
801 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400802 ch, err := agent.adapterProxy.RebootDevice(subCtx, device)
khenaidoo442e7c72020-03-10 16:13:48 -0400803 if err != nil {
804 cancel()
805 return err
806 }
807 go agent.waitForAdapterResponse(subCtx, cancel, "rebootDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo4d4802d2018-10-04 21:59:49 -0400808 return nil
809}
810
Kent Hagerman2b216042020-04-03 18:28:56 -0400811func (agent *Agent) deleteDevice(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000812 logger.Debugw("deleteDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400813 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
814 return err
815 }
816 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500817
818 cloned := agent.getDeviceWithoutLock()
Chaitrashree G S543df3e2020-02-24 22:36:54 -0500819
khenaidoo442e7c72020-03-10 16:13:48 -0400820 previousState := cloned.AdminState
821
822 // No check is required when deleting a device. Changing the state to DELETE will trigger the removal of this
823 // device by the state machine
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500824 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DELETED, cloned.ConnectStatus, cloned.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530825 return err
826 }
khenaidoo442e7c72020-03-10 16:13:48 -0400827
828 // If the device was in pre-prov state (only parent device are in that state) then do not send the request to the
829 // adapter
830 if previousState != ic.AdminState_PREPROVISIONED {
831 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400832 ch, err := agent.adapterProxy.DeleteDevice(subCtx, cloned)
khenaidoo442e7c72020-03-10 16:13:48 -0400833 if err != nil {
834 cancel()
835 return err
836 }
837 go agent.waitForAdapterResponse(subCtx, cancel, "deleteDevice", ch, agent.onSuccess, agent.onFailure)
838 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400839 return nil
840}
841
Kent Hagerman2b216042020-04-03 18:28:56 -0400842func (agent *Agent) setParentID(ctx context.Context, device *voltha.Device, parentID string) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400843 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
844 return err
845 }
846 defer agent.requestQueue.RequestComplete()
847
Girish Kumarf56a4682020-03-20 20:07:46 +0000848 logger.Debugw("setParentId", log.Fields{"device-id": device.Id, "parent-id": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500849
850 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530851 cloned.ParentId = parentID
852 // Store the device
npujar467fe752020-01-16 20:17:45 +0530853 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530854 return err
855 }
khenaidoo442e7c72020-03-10 16:13:48 -0400856
npujar1d86a522019-11-14 17:11:16 +0530857 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400858}
859
Kent Hagerman2b216042020-04-03 18:28:56 -0400860func (agent *Agent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400861 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
862 return err
863 }
864 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000865 logger.Debugw("updatePmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500866
867 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530868 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
869 // Store the device
npujar467fe752020-01-16 20:17:45 +0530870 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530871 return err
872 }
873 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400874 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400875 ch, err := agent.adapterProxy.UpdatePmConfigs(subCtx, cloned, pmConfigs)
khenaidoo442e7c72020-03-10 16:13:48 -0400876 if err != nil {
877 cancel()
npujar1d86a522019-11-14 17:11:16 +0530878 return err
879 }
khenaidoo442e7c72020-03-10 16:13:48 -0400880 go agent.waitForAdapterResponse(subCtx, cancel, "updatePmConfigs", ch, agent.onSuccess, agent.onFailure)
npujar1d86a522019-11-14 17:11:16 +0530881 return nil
khenaidoob3127472019-07-24 21:04:55 -0400882}
883
Kent Hagerman2b216042020-04-03 18:28:56 -0400884func (agent *Agent) initPmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400885 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
886 return err
887 }
888 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000889 logger.Debugw("initPmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500890
891 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530892 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
npujar467fe752020-01-16 20:17:45 +0530893 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500894 return agent.updateDeviceInStoreWithoutLock(updateCtx, cloned, false, "")
khenaidoob3127472019-07-24 21:04:55 -0400895}
896
Kent Hagerman2b216042020-04-03 18:28:56 -0400897func (agent *Agent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400898 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
899 return nil, err
900 }
901 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000902 logger.Debugw("listPmConfigs", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500903
904 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400905}
906
Kent Hagerman2b216042020-04-03 18:28:56 -0400907func (agent *Agent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400908 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
909 return nil, err
910 }
911 defer agent.requestQueue.RequestComplete()
912
Girish Kumarf56a4682020-03-20 20:07:46 +0000913 logger.Debugw("downloadImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500914
915 device := agent.getDeviceWithoutLock()
916
npujar1d86a522019-11-14 17:11:16 +0530917 if device.AdminState != voltha.AdminState_ENABLED {
khenaidoo442e7c72020-03-10 16:13:48 -0400918 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
npujar1d86a522019-11-14 17:11:16 +0530919 }
920 // Save the image
921 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
922 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
923 cloned := proto.Clone(device).(*voltha.Device)
924 if cloned.ImageDownloads == nil {
925 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500926 } else {
927 if device.AdminState != voltha.AdminState_ENABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000928 logger.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530929 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500930 }
931 // Save the image
932 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500933 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500934 if device.ImageDownloads == nil {
935 device.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500936 } else {
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500937 device.ImageDownloads = append(device.ImageDownloads, clonedImg)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500938 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500939 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DOWNLOADING_IMAGE, device.ConnectStatus, device.OperStatus); err != nil {
Mahir Gunyelb5851672019-07-24 10:46:26 +0300940 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500941 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500942
khenaidoof5a5bfa2019-01-23 22:20:29 -0500943 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400944 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400945 ch, err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg)
khenaidoo442e7c72020-03-10 16:13:48 -0400946 if err != nil {
947 cancel()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500948 return nil, err
949 }
khenaidoo442e7c72020-03-10 16:13:48 -0400950 go agent.waitForAdapterResponse(subCtx, cancel, "downloadImage", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500951 }
952 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
953}
954
955// isImageRegistered is a helper method to figure out if an image is already registered
956func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
957 for _, image := range device.ImageDownloads {
958 if image.Id == img.Id && image.Name == img.Name {
959 return true
960 }
961 }
962 return false
963}
964
Kent Hagerman2b216042020-04-03 18:28:56 -0400965func (agent *Agent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400966 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
967 return nil, err
968 }
969 defer agent.requestQueue.RequestComplete()
970
Girish Kumarf56a4682020-03-20 20:07:46 +0000971 logger.Debugw("cancelImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500972
973 device := agent.getDeviceWithoutLock()
974
npujar1d86a522019-11-14 17:11:16 +0530975 // Verify whether the Image is in the list of image being downloaded
976 if !isImageRegistered(img, device) {
khenaidoo442e7c72020-03-10 16:13:48 -0400977 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +0530978 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500979
npujar1d86a522019-11-14 17:11:16 +0530980 // Update image download state
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500981 for _, image := range device.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +0530982 if image.Id == img.Id && image.Name == img.Name {
983 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500984 }
npujar1d86a522019-11-14 17:11:16 +0530985 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500986
npujar1d86a522019-11-14 17:11:16 +0530987 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
988 // Set the device to Enabled
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500989 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, device, voltha.AdminState_ENABLED, device.ConnectStatus, device.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530990 return nil, err
991 }
khenaidoo442e7c72020-03-10 16:13:48 -0400992 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400993 ch, err := agent.adapterProxy.CancelImageDownload(subCtx, device, img)
khenaidoo442e7c72020-03-10 16:13:48 -0400994 if err != nil {
995 cancel()
npujar1d86a522019-11-14 17:11:16 +0530996 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500997 }
khenaidoo442e7c72020-03-10 16:13:48 -0400998 go agent.waitForAdapterResponse(subCtx, cancel, "cancelImageDownload", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500999 }
1000 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001001}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001002
Kent Hagerman2b216042020-04-03 18:28:56 -04001003func (agent *Agent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001004 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1005 return nil, err
1006 }
1007 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001008 logger.Debugw("activateImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001009 cloned := agent.getDeviceWithoutLock()
1010
npujar1d86a522019-11-14 17:11:16 +05301011 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001012 if !isImageRegistered(img, cloned) {
khenaidoo442e7c72020-03-10 16:13:48 -04001013 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301014 }
1015
khenaidoo6e55d9e2019-12-12 18:26:26 -05001016 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoo442e7c72020-03-10 16:13:48 -04001017 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301018 }
1019 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301020 for _, image := range cloned.ImageDownloads {
1021 if image.Id == img.Id && image.Name == img.Name {
1022 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
1023 }
1024 }
1025 // Set the device to downloading_image
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001026 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DOWNLOADING_IMAGE, cloned.ConnectStatus, cloned.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301027 return nil, err
1028 }
1029
khenaidoo442e7c72020-03-10 16:13:48 -04001030 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001031 ch, err := agent.adapterProxy.ActivateImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
khenaidoo442e7c72020-03-10 16:13:48 -04001032 if err != nil {
1033 cancel()
npujar1d86a522019-11-14 17:11:16 +05301034 return nil, err
1035 }
khenaidoo442e7c72020-03-10 16:13:48 -04001036 go agent.waitForAdapterResponse(subCtx, cancel, "activateImageUpdate", ch, agent.onSuccess, agent.onFailure)
1037
npujar1d86a522019-11-14 17:11:16 +05301038 // The status of the AdminState will be changed following the update_download_status response from the adapter
1039 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -07001040 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
1041}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001042
Kent Hagerman2b216042020-04-03 18:28:56 -04001043func (agent *Agent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001044 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1045 return nil, err
1046 }
1047 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001048 logger.Debugw("revertImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001049
1050 cloned := agent.getDeviceWithoutLock()
1051
npujar1d86a522019-11-14 17:11:16 +05301052 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001053 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +05301054 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
1055 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001056
khenaidoo6e55d9e2019-12-12 18:26:26 -05001057 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +05301058 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
1059 }
1060 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301061 for _, image := range cloned.ImageDownloads {
1062 if image.Id == img.Id && image.Name == img.Name {
1063 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -05001064 }
npujar1d86a522019-11-14 17:11:16 +05301065 }
Mahir Gunyelb5851672019-07-24 10:46:26 +03001066
npujar467fe752020-01-16 20:17:45 +05301067 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301068 return nil, err
1069 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001070
khenaidoo442e7c72020-03-10 16:13:48 -04001071 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001072 ch, err := agent.adapterProxy.RevertImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
khenaidoo442e7c72020-03-10 16:13:48 -04001073 if err != nil {
1074 cancel()
npujar1d86a522019-11-14 17:11:16 +05301075 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -05001076 }
khenaidoo442e7c72020-03-10 16:13:48 -04001077 go agent.waitForAdapterResponse(subCtx, cancel, "revertImageUpdate", ch, agent.onSuccess, agent.onFailure)
1078
khenaidoof5a5bfa2019-01-23 22:20:29 -05001079 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001080}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001081
Kent Hagerman2b216042020-04-03 18:28:56 -04001082func (agent *Agent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001083 logger.Debugw("getImageDownloadStatus", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001084
khenaidoo442e7c72020-03-10 16:13:48 -04001085 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301086 return nil, err
1087 }
khenaidoo442e7c72020-03-10 16:13:48 -04001088 device := agent.getDeviceWithoutLock()
Kent Hagerman2b216042020-04-03 18:28:56 -04001089 ch, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img)
khenaidoo442e7c72020-03-10 16:13:48 -04001090 agent.requestQueue.RequestComplete()
1091 if err != nil {
1092 return nil, err
1093 }
1094 // Wait for the adapter response
1095 rpcResponse, ok := <-ch
1096 if !ok {
1097 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1098 }
1099 if rpcResponse.Err != nil {
1100 return nil, rpcResponse.Err
1101 }
1102 // Successful response
1103 imgDownload := &voltha.ImageDownload{}
1104 if err := ptypes.UnmarshalAny(rpcResponse.Reply, imgDownload); err != nil {
1105 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1106 }
1107 return imgDownload, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001108}
1109
Kent Hagerman2b216042020-04-03 18:28:56 -04001110func (agent *Agent) updateImageDownload(ctx context.Context, img *voltha.ImageDownload) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001111 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1112 return err
1113 }
1114 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001115 logger.Debugw("updating-image-download", log.Fields{"device-id": agent.deviceID, "img": img})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001116
1117 cloned := agent.getDeviceWithoutLock()
1118
npujar1d86a522019-11-14 17:11:16 +05301119 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +05301120 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
1121 for _, image := range cloned.ImageDownloads {
1122 if image.Id == img.Id && image.Name == img.Name {
1123 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
1124 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001125 }
1126 }
npujar1d86a522019-11-14 17:11:16 +05301127 }
1128 cloned.ImageDownloads = clonedImages
1129 // Set the Admin state to enabled if required
1130 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
1131 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
1132 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001133 return agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_ENABLED, cloned.ConnectStatus, cloned.OperStatus)
npujar1d86a522019-11-14 17:11:16 +05301134 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001135 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoof5a5bfa2019-01-23 22:20:29 -05001136}
1137
Kent Hagerman2b216042020-04-03 18:28:56 -04001138func (agent *Agent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001139 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1140 return nil, err
1141 }
1142 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001143 logger.Debugw("getImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001144
1145 cloned := agent.getDeviceWithoutLock()
1146 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +05301147 if image.Id == img.Id && image.Name == img.Name {
1148 return image, nil
1149 }
1150 }
1151 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001152}
1153
Kent Hagerman2b216042020-04-03 18:28:56 -04001154func (agent *Agent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001155 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1156 return nil, err
1157 }
1158 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001159 logger.Debugw("listImageDownloads", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001160
1161 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001162}
1163
khenaidoo4d4802d2018-10-04 21:59:49 -04001164// getPorts retrieves the ports information of the device based on the port type.
Kent Hagerman2b216042020-04-03 18:28:56 -04001165func (agent *Agent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
Girish Kumarf56a4682020-03-20 20:07:46 +00001166 logger.Debugw("getPorts", log.Fields{"device-id": agent.deviceID, "port-type": portType})
khenaidoob9203542018-09-17 22:56:37 -04001167 ports := &voltha.Ports{}
npujar467fe752020-01-16 20:17:45 +05301168 if device, _ := agent.deviceMgr.GetDevice(ctx, agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -04001169 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -04001170 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -04001171 ports.Items = append(ports.Items, port)
1172 }
1173 }
1174 }
1175 return ports
1176}
1177
khenaidoo442e7c72020-03-10 16:13:48 -04001178// getSwitchCapability retrieves the switch capability of a parent device
Kent Hagerman2b216042020-04-03 18:28:56 -04001179func (agent *Agent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001180 logger.Debugw("getSwitchCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001181
1182 cloned, err := agent.getDevice(ctx)
1183 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001184 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001185 }
Kent Hagerman2b216042020-04-03 18:28:56 -04001186 ch, err := agent.adapterProxy.GetOfpDeviceInfo(ctx, cloned)
khenaidoo442e7c72020-03-10 16:13:48 -04001187 if err != nil {
1188 return nil, err
1189 }
1190
1191 // Wait for adapter response
1192 rpcResponse, ok := <-ch
1193 if !ok {
1194 return nil, status.Errorf(codes.Aborted, "channel-closed")
1195 }
1196 if rpcResponse.Err != nil {
1197 return nil, rpcResponse.Err
1198 }
1199 // Successful response
1200 switchCap := &ic.SwitchCapability{}
1201 if err := ptypes.UnmarshalAny(rpcResponse.Reply, switchCap); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301202 return nil, err
1203 }
1204 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001205}
1206
khenaidoo442e7c72020-03-10 16:13:48 -04001207// getPortCapability retrieves the port capability of a device
Kent Hagerman2b216042020-04-03 18:28:56 -04001208func (agent *Agent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001209 logger.Debugw("getPortCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001210 device, err := agent.getDevice(ctx)
1211 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001212 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001213 }
Kent Hagerman2b216042020-04-03 18:28:56 -04001214 ch, err := agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo)
khenaidoo442e7c72020-03-10 16:13:48 -04001215 if err != nil {
npujar1d86a522019-11-14 17:11:16 +05301216 return nil, err
1217 }
khenaidoo442e7c72020-03-10 16:13:48 -04001218 // Wait for adapter response
1219 rpcResponse, ok := <-ch
1220 if !ok {
1221 return nil, status.Errorf(codes.Aborted, "channel-closed")
1222 }
1223 if rpcResponse.Err != nil {
1224 return nil, rpcResponse.Err
1225 }
1226 // Successful response
1227 portCap := &ic.PortCapability{}
1228 if err := ptypes.UnmarshalAny(rpcResponse.Reply, portCap); err != nil {
1229 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1230 }
npujar1d86a522019-11-14 17:11:16 +05301231 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001232}
1233
Kent Hagerman2b216042020-04-03 18:28:56 -04001234func (agent *Agent) onPacketFailure(rpc string, response interface{}, args ...interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -04001235 // packet data is encoded in the args param as the first parameter
1236 var packet []byte
1237 if len(args) >= 1 {
1238 if pkt, ok := args[0].([]byte); ok {
1239 packet = pkt
1240 }
1241 }
1242 var errResp error
1243 if err, ok := response.(error); ok {
1244 errResp = err
1245 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001246 logger.Warnw("packet-out-error", log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -04001247 "device-id": agent.deviceID,
1248 "error": errResp,
1249 "packet": hex.EncodeToString(packet),
1250 })
1251}
1252
Kent Hagerman2b216042020-04-03 18:28:56 -04001253func (agent *Agent) packetOut(ctx context.Context, outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001254 // If deviceType=="" then we must have taken ownership of this device.
1255 // Fixes VOL-2226 where a core would take ownership and have stale data
1256 if agent.deviceType == "" {
npujar467fe752020-01-16 20:17:45 +05301257 agent.reconcileWithKVStore(ctx)
Scott Baker80678602019-11-14 16:57:36 -08001258 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001259 // Send packet to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001260 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001261 ch, err := agent.adapterProxy.PacketOut(subCtx, agent.deviceType, agent.deviceID, outPort, packet)
khenaidoo442e7c72020-03-10 16:13:48 -04001262 if err != nil {
1263 cancel()
1264 return nil
khenaidoofdbad6e2018-11-06 22:26:38 -05001265 }
khenaidoo442e7c72020-03-10 16:13:48 -04001266 go agent.waitForAdapterResponse(subCtx, cancel, "packetOut", ch, agent.onSuccess, agent.onPacketFailure, packet.Data)
khenaidoofdbad6e2018-11-06 22:26:38 -05001267 return nil
1268}
1269
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001270// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1271// TODO: May need a specific proto to handle only a subset of a device that can be changed by an adapter
Kent Hagerman2b216042020-04-03 18:28:56 -04001272func (agent *Agent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001273 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001274 cloned.Root = device.Root
1275 cloned.Vendor = device.Vendor
1276 cloned.Model = device.Model
1277 cloned.SerialNumber = device.SerialNumber
1278 cloned.MacAddress = device.MacAddress
1279 cloned.Vlan = device.Vlan
1280 cloned.Reason = device.Reason
1281 return cloned, nil
1282}
khenaidoo442e7c72020-03-10 16:13:48 -04001283
Kent Hagerman2b216042020-04-03 18:28:56 -04001284func (agent *Agent) updateDeviceUsingAdapterData(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001285 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1286 return err
1287 }
1288 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001289 logger.Debugw("updateDeviceUsingAdapterData", log.Fields{"device-id": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001290
npujar1d86a522019-11-14 17:11:16 +05301291 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1292 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001293 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001294 }
npujar1d86a522019-11-14 17:11:16 +05301295 cloned := proto.Clone(updatedDevice).(*voltha.Device)
npujar467fe752020-01-16 20:17:45 +05301296 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001297}
1298
Kent Hagerman2b216042020-04-03 18:28:56 -04001299func (agent *Agent) updateDeviceWithoutLock(ctx context.Context, device *voltha.Device) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001300 logger.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001301 //cloned := proto.Clone(device).(*voltha.Device)
1302 cloned := device
npujar467fe752020-01-16 20:17:45 +05301303 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001304}
1305
Kent Hagerman2b216042020-04-03 18:28:56 -04001306func (agent *Agent) updateDeviceStatus(ctx context.Context, operStatus voltha.OperStatus_Types, connStatus voltha.ConnectStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001307 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1308 return err
1309 }
1310 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001311
1312 cloned := agent.getDeviceWithoutLock()
1313
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001314 newConnStatus, newOperStatus := cloned.ConnectStatus, cloned.OperStatus
npujar1d86a522019-11-14 17:11:16 +05301315 // 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 -08001316 if s, ok := voltha.ConnectStatus_Types_value[connStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001317 logger.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001318 newConnStatus = connStatus
npujar1d86a522019-11-14 17:11:16 +05301319 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001320 if s, ok := voltha.OperStatus_Types_value[operStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001321 logger.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001322 newOperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301323 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001324 logger.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
npujar1d86a522019-11-14 17:11:16 +05301325 // Store the device
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001326 return agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, cloned.AdminState, newConnStatus, newOperStatus)
khenaidoo92e62c52018-10-03 14:02:54 -04001327}
1328
Kent Hagerman2b216042020-04-03 18:28:56 -04001329func (agent *Agent) updatePortsOperState(ctx context.Context, operStatus voltha.OperStatus_Types) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001330 logger.Debugw("updatePortsOperState", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001331 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1332 return err
1333 }
1334 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001335 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301336 for _, port := range cloned.Ports {
kesavandbc2d1622020-01-21 00:42:01 -05001337 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301338 }
1339 // Store the device
npujar467fe752020-01-16 20:17:45 +05301340 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001341}
1342
Kent Hagerman2b216042020-04-03 18:28:56 -04001343func (agent *Agent) updatePortState(ctx context.Context, portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001344 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1345 return err
1346 }
1347 defer agent.requestQueue.RequestComplete()
khenaidoo92e62c52018-10-03 14:02:54 -04001348 // Work only on latest data
1349 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001350 cloned := agent.getDeviceWithoutLock()
1351
npujar1d86a522019-11-14 17:11:16 +05301352 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1353 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1354 return status.Errorf(codes.InvalidArgument, "%s", portType)
1355 }
1356 for _, port := range cloned.Ports {
1357 if port.Type == portType && port.PortNo == portNo {
1358 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301359 }
1360 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001361 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301362 // Store the device
npujar467fe752020-01-16 20:17:45 +05301363 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001364}
1365
Kent Hagerman2b216042020-04-03 18:28:56 -04001366func (agent *Agent) deleteAllPorts(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001367 logger.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001368 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1369 return err
1370 }
1371 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001372
1373 cloned := agent.getDeviceWithoutLock()
1374
1375 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1376 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
Girish Kumarf56a4682020-03-20 20:07:46 +00001377 logger.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301378 return err
1379 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001380 if len(cloned.Ports) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +00001381 logger.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301382 return nil
1383 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001384
npujar1d86a522019-11-14 17:11:16 +05301385 cloned.Ports = []*voltha.Port{}
Girish Kumarf56a4682020-03-20 20:07:46 +00001386 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301387 // Store the device
npujar467fe752020-01-16 20:17:45 +05301388 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001389}
1390
Kent Hagerman2b216042020-04-03 18:28:56 -04001391func (agent *Agent) addPort(ctx context.Context, port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001392 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1393 return err
1394 }
1395 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001396 logger.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001397
1398 cloned := agent.getDeviceWithoutLock()
khenaidoo80b987d2020-02-20 10:52:52 -05001399 updatePort := false
npujar1d86a522019-11-14 17:11:16 +05301400 if cloned.Ports == nil {
1401 // First port
Girish Kumarf56a4682020-03-20 20:07:46 +00001402 logger.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301403 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001404 } else {
npujar1d86a522019-11-14 17:11:16 +05301405 for _, p := range cloned.Ports {
1406 if p.Type == port.Type && p.PortNo == port.PortNo {
khenaidoo80b987d2020-02-20 10:52:52 -05001407 if p.Label == "" && p.Type == voltha.Port_PON_OLT {
1408 //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 +00001409 logger.Infow("update-pon-port-created-by-default", log.Fields{"default-port": p, "port-to-add": port})
khenaidoo80b987d2020-02-20 10:52:52 -05001410 p.Label = port.Label
1411 p.OperStatus = port.OperStatus
1412 updatePort = true
1413 break
1414 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001415 logger.Debugw("port already exists", log.Fields{"port": port})
npujar1d86a522019-11-14 17:11:16 +05301416 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001417 }
khenaidoob9203542018-09-17 22:56:37 -04001418 }
khenaidoo92e62c52018-10-03 14:02:54 -04001419 }
khenaidoo80b987d2020-02-20 10:52:52 -05001420 if !updatePort {
1421 cp := proto.Clone(port).(*voltha.Port)
1422 // Set the admin state of the port to ENABLE
1423 cp.AdminState = voltha.AdminState_ENABLED
1424 cloned.Ports = append(cloned.Ports, cp)
1425 }
npujar1d86a522019-11-14 17:11:16 +05301426 // Store the device
npujar467fe752020-01-16 20:17:45 +05301427 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001428}
1429
Kent Hagerman2b216042020-04-03 18:28:56 -04001430func (agent *Agent) addPeerPort(ctx context.Context, peerPort *voltha.Port_PeerPort) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001431 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1432 return err
1433 }
1434 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001435 logger.Debugw("adding-peer-peerPort", log.Fields{"device-id": agent.deviceID, "peer-peerPort": peerPort})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001436
1437 cloned := agent.getDeviceWithoutLock()
1438
khenaidoo80b987d2020-02-20 10:52:52 -05001439 // Get the peer port on the device based on the peerPort no
1440 found := false
1441 for _, port := range cloned.Ports {
1442 if port.PortNo == peerPort.PortNo { // found peerPort
1443 cp := proto.Clone(peerPort).(*voltha.Port_PeerPort)
1444 port.Peers = append(port.Peers, cp)
Girish Kumarf56a4682020-03-20 20:07:46 +00001445 logger.Debugw("found-peer", log.Fields{"device-id": agent.deviceID, "portNo": peerPort.PortNo, "deviceId": agent.deviceID})
khenaidoo80b987d2020-02-20 10:52:52 -05001446 found = true
npujar1d86a522019-11-14 17:11:16 +05301447 break
1448 }
1449 }
khenaidoo80b987d2020-02-20 10:52:52 -05001450 if !found && agent.isRootdevice {
1451 // An ONU PON port has been created before the corresponding creation of the OLT PON port. Create the OLT PON port
1452 // with default values which will be updated once the OLT PON port creation is processed.
1453 ponPort := &voltha.Port{
1454 PortNo: peerPort.PortNo,
1455 Type: voltha.Port_PON_OLT,
1456 AdminState: voltha.AdminState_ENABLED,
1457 DeviceId: agent.deviceID,
1458 Peers: []*voltha.Port_PeerPort{proto.Clone(peerPort).(*voltha.Port_PeerPort)},
1459 }
1460 cloned.Ports = append(cloned.Ports, ponPort)
Girish Kumarf56a4682020-03-20 20:07:46 +00001461 logger.Infow("adding-default-pon-port", log.Fields{"device-id": agent.deviceID, "peer": peerPort, "pon-port": ponPort})
khenaidoo80b987d2020-02-20 10:52:52 -05001462 }
npujar1d86a522019-11-14 17:11:16 +05301463 // Store the device
npujar467fe752020-01-16 20:17:45 +05301464 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001465}
1466
1467// TODO: A generic device update by attribute
Kent Hagerman2b216042020-04-03 18:28:56 -04001468func (agent *Agent) updateDeviceAttribute(ctx context.Context, name string, value interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -04001469 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001470 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "name": name, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -04001471 return
1472 }
1473 defer agent.requestQueue.RequestComplete()
khenaidoob9203542018-09-17 22:56:37 -04001474 if value == nil {
1475 return
1476 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001477
1478 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001479 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001480 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001481 if s.Kind() == reflect.Struct {
1482 // exported field
1483 f := s.FieldByName(name)
1484 if f.IsValid() && f.CanSet() {
1485 switch f.Kind() {
1486 case reflect.String:
1487 f.SetString(value.(string))
1488 updated = true
1489 case reflect.Uint32:
1490 f.SetUint(uint64(value.(uint32)))
1491 updated = true
1492 case reflect.Bool:
1493 f.SetBool(value.(bool))
1494 updated = true
1495 }
1496 }
1497 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001498 logger.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001499 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001500
npujar467fe752020-01-16 20:17:45 +05301501 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001502 logger.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
khenaidoob9203542018-09-17 22:56:37 -04001503 }
khenaidoob9203542018-09-17 22:56:37 -04001504}
serkant.uluderya334479d2019-04-10 08:26:15 -07001505
Kent Hagerman2b216042020-04-03 18:28:56 -04001506func (agent *Agent) simulateAlarm(ctx context.Context, simulatereq *voltha.SimulateAlarmRequest) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001507 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1508 return err
1509 }
1510 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001511 logger.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001512
1513 cloned := agent.getDeviceWithoutLock()
1514
khenaidoo442e7c72020-03-10 16:13:48 -04001515 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001516 ch, err := agent.adapterProxy.SimulateAlarm(subCtx, cloned, simulatereq)
khenaidoo442e7c72020-03-10 16:13:48 -04001517 if err != nil {
1518 cancel()
npujar1d86a522019-11-14 17:11:16 +05301519 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001520 }
khenaidoo442e7c72020-03-10 16:13:48 -04001521 go agent.waitForAdapterResponse(subCtx, cancel, "simulateAlarm", ch, agent.onSuccess, agent.onFailure)
serkant.uluderya334479d2019-04-10 08:26:15 -07001522 return nil
1523}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001524
Kent Hagerman2b216042020-04-03 18:28:56 -04001525func (agent *Agent) updateDeviceStateInStoreWithoutLock(
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001526 ctx context.Context,
1527 device *voltha.Device,
1528 adminState voltha.AdminState_Types,
1529 connectStatus voltha.ConnectStatus_Types,
1530 operStatus voltha.OperStatus_Types,
1531) error {
1532 previousState := getDeviceStates(device)
1533 device.AdminState, device.ConnectStatus, device.OperStatus = adminState, connectStatus, operStatus
1534
1535 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
1536 return err
1537 }
1538
1539 // process state transition in its own thread
1540 go func() {
1541 if err := agent.deviceMgr.processTransition(context.Background(), device, previousState); err != nil {
1542 log.Errorw("failed-process-transition", log.Fields{"deviceId": device.Id, "previousAdminState": previousState.Admin, "currentAdminState": device.AdminState})
1543 }
1544 }()
1545 return nil
1546}
1547
Mahir Gunyelb5851672019-07-24 10:46:26 +03001548//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.
1549// It is an internal helper function.
Kent Hagerman2b216042020-04-03 18:28:56 -04001550func (agent *Agent) updateDeviceInStoreWithoutLock(ctx context.Context, device *voltha.Device, strict bool, txid string) error {
Kent Hagerman4f355f52020-03-30 16:01:33 -04001551 if agent.stopped {
1552 return errors.New("device agent stopped")
Thomas Lee Se5a44012019-11-07 20:32:24 +05301553 }
Kent Hagerman4f355f52020-03-30 16:01:33 -04001554
1555 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
1556 if err := agent.clusterDataProxy.Update(updateCtx, "devices/"+agent.deviceID, device); err != nil {
1557 return status.Errorf(codes.Internal, "failed-update-device:%s: %s", agent.deviceID, err)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001558 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001559 logger.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001560
khenaidoo6e55d9e2019-12-12 18:26:26 -05001561 agent.device = proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001562 return nil
1563}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001564
Kent Hagerman2b216042020-04-03 18:28:56 -04001565func (agent *Agent) updateDeviceReason(ctx context.Context, reason string) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001566 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1567 return err
1568 }
1569 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001570
1571 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301572 cloned.Reason = reason
Girish Kumarf56a4682020-03-20 20:07:46 +00001573 logger.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
npujar1d86a522019-11-14 17:11:16 +05301574 // Store the device
npujar467fe752020-01-16 20:17:45 +05301575 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001576}
kesavandbc2d1622020-01-21 00:42:01 -05001577
Kent Hagerman2b216042020-04-03 18:28:56 -04001578func (agent *Agent) disablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001579 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1580 return err
1581 }
1582 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001583 logger.Debugw("disablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001584 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001585 // Get the most up to date the device info
1586 device := agent.getDeviceWithoutLock()
1587 for _, port := range device.Ports {
1588 if port.PortNo == Port.PortNo {
1589 port.AdminState = voltha.AdminState_DISABLED
1590 cp = proto.Clone(port).(*voltha.Port)
1591 break
1592
1593 }
1594 }
1595 if cp == nil {
1596 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1597 }
1598
1599 if cp.Type != voltha.Port_PON_OLT {
1600 return status.Errorf(codes.InvalidArgument, "Disabling of Port Type %v unimplemented", cp.Type)
1601 }
1602 // Store the device
1603 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001604 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001605 return err
1606 }
khenaidoo442e7c72020-03-10 16:13:48 -04001607
kesavandbc2d1622020-01-21 00:42:01 -05001608 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001609 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001610 ch, err := agent.adapterProxy.DisablePort(ctx, device, cp)
khenaidoo442e7c72020-03-10 16:13:48 -04001611 if err != nil {
1612 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001613 return err
1614 }
khenaidoo442e7c72020-03-10 16:13:48 -04001615 go agent.waitForAdapterResponse(subCtx, cancel, "disablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001616 return nil
1617}
1618
Kent Hagerman2b216042020-04-03 18:28:56 -04001619func (agent *Agent) enablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001620 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1621 return err
1622 }
1623 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001624 logger.Debugw("enablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001625
1626 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001627 // Get the most up to date the device info
1628 device := agent.getDeviceWithoutLock()
1629 for _, port := range device.Ports {
1630 if port.PortNo == Port.PortNo {
1631 port.AdminState = voltha.AdminState_ENABLED
1632 cp = proto.Clone(port).(*voltha.Port)
1633 break
1634 }
1635 }
1636
1637 if cp == nil {
1638 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1639 }
1640
1641 if cp.Type != voltha.Port_PON_OLT {
1642 return status.Errorf(codes.InvalidArgument, "Enabling of Port Type %v unimplemented", cp.Type)
1643 }
1644 // Store the device
1645 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001646 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001647 return err
1648 }
1649 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001650 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001651 ch, err := agent.adapterProxy.EnablePort(ctx, device, cp)
khenaidoo442e7c72020-03-10 16:13:48 -04001652 if err != nil {
1653 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001654 return err
1655 }
khenaidoo442e7c72020-03-10 16:13:48 -04001656 go agent.waitForAdapterResponse(subCtx, cancel, "enablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001657 return nil
1658}
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001659
Kent Hagerman2b216042020-04-03 18:28:56 -04001660func (agent *Agent) ChildDeviceLost(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001661 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1662 return err
1663 }
1664 defer agent.requestQueue.RequestComplete()
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001665
Girish Kumarf56a4682020-03-20 20:07:46 +00001666 logger.Debugw("childDeviceLost", log.Fields{"child-device-id": device.Id, "parent-device-ud": agent.deviceID})
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001667
1668 //Remove the associated peer ports on the parent device
khenaidoo442e7c72020-03-10 16:13:48 -04001669 parentDevice := agent.getDeviceWithoutLock()
1670 var updatedPeers []*voltha.Port_PeerPort
1671 for _, port := range parentDevice.Ports {
1672 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1673 for _, peerPort := range port.Peers {
1674 if peerPort.DeviceId != device.Id {
1675 updatedPeers = append(updatedPeers, peerPort)
1676 }
1677 }
1678 port.Peers = updatedPeers
1679 }
1680 if err := agent.updateDeviceInStoreWithoutLock(ctx, parentDevice, false, ""); err != nil {
1681 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001682 }
1683
khenaidoo442e7c72020-03-10 16:13:48 -04001684 //send request to adapter
1685 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001686 ch, err := agent.adapterProxy.ChildDeviceLost(ctx, agent.deviceType, agent.deviceID, device.ParentPortNo, device.ProxyAddress.OnuId)
khenaidoo442e7c72020-03-10 16:13:48 -04001687 if err != nil {
1688 cancel()
1689 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001690 }
khenaidoo442e7c72020-03-10 16:13:48 -04001691 go agent.waitForAdapterResponse(subCtx, cancel, "childDeviceLost", ch, agent.onSuccess, agent.onFailure)
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001692 return nil
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001693}
onkarkundargi87285252020-01-27 11:34:52 +05301694
Kent Hagerman2b216042020-04-03 18:28:56 -04001695func (agent *Agent) startOmciTest(ctx context.Context, omcitestrequest *voltha.OmciTestRequest) (*voltha.TestResponse, error) {
onkarkundargi87285252020-01-27 11:34:52 +05301696 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1697 return nil, err
1698 }
1699
1700 device := agent.getDeviceWithoutLock()
Matteo Scandolod525ae32020-04-02 17:27:29 -07001701
1702 if device.Adapter == "" {
Kent Hagerman2b216042020-04-03 18:28:56 -04001703 adapterName, err := agent.adapterMgr.GetAdapterType(device.Type)
Matteo Scandolod525ae32020-04-02 17:27:29 -07001704 if err != nil {
1705 agent.requestQueue.RequestComplete()
1706 return nil, err
1707 }
Matteo Scandolod525ae32020-04-02 17:27:29 -07001708 device.Adapter = adapterName
onkarkundargi87285252020-01-27 11:34:52 +05301709 }
1710
1711 // Send request to the adapter
Kent Hagerman2b216042020-04-03 18:28:56 -04001712 ch, err := agent.adapterProxy.StartOmciTest(ctx, device, omcitestrequest)
onkarkundargi87285252020-01-27 11:34:52 +05301713 agent.requestQueue.RequestComplete()
1714 if err != nil {
1715 return nil, err
1716 }
1717
1718 // Wait for the adapter response
1719 rpcResponse, ok := <-ch
1720 if !ok {
1721 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1722 }
1723 if rpcResponse.Err != nil {
1724 return nil, rpcResponse.Err
1725 }
1726
1727 // Unmarshal and return the response
1728 testResp := &voltha.TestResponse{}
1729 if err := ptypes.UnmarshalAny(rpcResponse.Reply, testResp); err != nil {
1730 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1731 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001732 logger.Debugw("Omci_test_Request-Success-device-agent", log.Fields{"testResp": testResp})
onkarkundargi87285252020-01-27 11:34:52 +05301733 return testResp, nil
1734}
Dinesh Belwalkarc1129f12020-02-27 10:41:33 -08001735
1736func (agent *Agent) getExtValue(ctx context.Context, pdevice *voltha.Device, cdevice *voltha.Device, valueparam *voltha.ValueSpecifier) (*voltha.ReturnValues, error) {
1737 log.Debugw("getExtValue", log.Fields{"device-id": agent.deviceID, "onuid": valueparam.Id, "valuetype": valueparam.Value})
1738 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1739 return nil, err
1740 }
1741
1742 //send request to adapter
1743 ch, err := agent.adapterProxy.GetExtValue(ctx, pdevice, cdevice, valueparam.Id, valueparam.Value)
1744 agent.requestQueue.RequestComplete()
1745 if err != nil {
1746 return nil, err
1747 }
1748
1749 // Wait for the adapter response
1750 rpcResponse, ok := <-ch
1751 if !ok {
1752 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1753 }
1754 if rpcResponse.Err != nil {
1755 return nil, rpcResponse.Err
1756 }
1757
1758 // Unmarshal and return the response
1759 Resp := &voltha.ReturnValues{}
1760 if err := ptypes.UnmarshalAny(rpcResponse.Reply, Resp); err != nil {
1761 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1762 }
1763 logger.Debugw("getExtValue-Success-device-agent", log.Fields{"Resp": Resp})
1764 return Resp, nil
1765}