blob: 901b27f4b5dd95a6a031a24f4e777795d62b5c94 [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"
Mahir Gunyeladdb66a2020-04-29 18:08:50 -070024 "reflect"
25 "sync"
26 "time"
27
khenaidoo442e7c72020-03-10 16:13:48 -040028 "github.com/golang/protobuf/ptypes"
Kent Hagerman2b216042020-04-03 18:28:56 -040029 "github.com/opencord/voltha-go/rw_core/core/adapter"
30 "github.com/opencord/voltha-go/rw_core/core/device/remote"
khenaidoo442e7c72020-03-10 16:13:48 -040031 "github.com/opencord/voltha-lib-go/v3/pkg/kafka"
Chaitrashree G Sa773e992019-09-09 21:04:15 -040032
khenaidoob9203542018-09-17 22:56:37 -040033 "github.com/gogo/protobuf/proto"
sbarbari17d7e222019-11-05 10:02:29 -050034 "github.com/opencord/voltha-go/db/model"
Scott Bakerb671a862019-10-24 10:53:40 -070035 coreutils "github.com/opencord/voltha-go/rw_core/utils"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080036 fu "github.com/opencord/voltha-lib-go/v3/pkg/flows"
37 "github.com/opencord/voltha-lib-go/v3/pkg/log"
38 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
39 ofp "github.com/opencord/voltha-protos/v3/go/openflow_13"
40 "github.com/opencord/voltha-protos/v3/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040041 "google.golang.org/grpc/codes"
42 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040043)
44
Kent Hagerman2b216042020-04-03 18:28:56 -040045// Agent represents device agent attributes
46type Agent struct {
npujar1d86a522019-11-14 17:11:16 +053047 deviceID string
48 parentID string
khenaidoo43c82122018-11-22 18:38:28 -050049 deviceType string
khenaidoo2c6a0992019-04-29 13:46:56 -040050 isRootdevice bool
Kent Hagerman2b216042020-04-03 18:28:56 -040051 adapterProxy *remote.AdapterProxy
52 adapterMgr *adapter.Manager
53 deviceMgr *Manager
khenaidoo9a468962018-09-19 15:33:13 -040054 clusterDataProxy *model.Proxy
55 exitChannel chan int
khenaidoo6e55d9e2019-12-12 18:26:26 -050056 device *voltha.Device
khenaidoo442e7c72020-03-10 16:13:48 -040057 requestQueue *coreutils.RequestQueue
58 defaultTimeout time.Duration
59 startOnce sync.Once
60 stopOnce sync.Once
61 stopped bool
khenaidoob9203542018-09-17 22:56:37 -040062}
63
Kent Hagerman2b216042020-04-03 18:28:56 -040064//newAgent creates a new device agent. The device will be initialized when start() is called.
65func newAgent(ap *remote.AdapterProxy, device *voltha.Device, deviceMgr *Manager, cdProxy *model.Proxy, timeout time.Duration) *Agent {
66 var agent Agent
khenaidoob9203542018-09-17 22:56:37 -040067 agent.adapterProxy = ap
Scott Baker80678602019-11-14 16:57:36 -080068 if device.Id == "" {
Kent Hagerman2b216042020-04-03 18:28:56 -040069 agent.deviceID = coreutils.CreateDeviceID()
Scott Baker80678602019-11-14 16:57:36 -080070 } else {
npujar1d86a522019-11-14 17:11:16 +053071 agent.deviceID = device.Id
Stephane Barbarie1ab43272018-12-08 21:42:13 -050072 }
Scott Baker80678602019-11-14 16:57:36 -080073
khenaidoo2c6a0992019-04-29 13:46:56 -040074 agent.isRootdevice = device.Root
npujar1d86a522019-11-14 17:11:16 +053075 agent.parentID = device.ParentId
Scott Baker80678602019-11-14 16:57:36 -080076 agent.deviceType = device.Type
khenaidoob9203542018-09-17 22:56:37 -040077 agent.deviceMgr = deviceMgr
khenaidoo21d51152019-02-01 13:48:37 -050078 agent.adapterMgr = deviceMgr.adapterMgr
khenaidoob9203542018-09-17 22:56:37 -040079 agent.exitChannel = make(chan int, 1)
khenaidoo9a468962018-09-19 15:33:13 -040080 agent.clusterDataProxy = cdProxy
khenaidoo2c6a0992019-04-29 13:46:56 -040081 agent.defaultTimeout = timeout
khenaidoo6e55d9e2019-12-12 18:26:26 -050082 agent.device = proto.Clone(device).(*voltha.Device)
Kent Hagerman730cbdf2020-03-31 12:22:08 -040083 agent.requestQueue = coreutils.NewRequestQueue()
khenaidoob9203542018-09-17 22:56:37 -040084 return &agent
85}
86
khenaidoo442e7c72020-03-10 16:13:48 -040087// start() saves the device to the data model and registers for callbacks on that device if deviceToCreate!=nil.
88// 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 -080089// was started.
Kent Hagerman2b216042020-04-03 18:28:56 -040090func (agent *Agent) start(ctx context.Context, deviceToCreate *voltha.Device) (*voltha.Device, error) {
khenaidoo442e7c72020-03-10 16:13:48 -040091 needToStart := false
92 if agent.startOnce.Do(func() { needToStart = true }); !needToStart {
93 return agent.getDevice(ctx)
94 }
95 var startSucceeded bool
96 defer func() {
97 if !startSucceeded {
98 if err := agent.stop(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +000099 logger.Errorw("failed-to-cleanup-after-unsuccessful-start", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -0400100 }
101 }
102 }()
Scott Baker80678602019-11-14 16:57:36 -0800103
khenaidoo442e7c72020-03-10 16:13:48 -0400104 var device *voltha.Device
Scott Baker80678602019-11-14 16:57:36 -0800105 if deviceToCreate == nil {
106 // Load the existing device
Kent Hagerman4f355f52020-03-30 16:01:33 -0400107 device := &voltha.Device{}
108 have, err := agent.clusterDataProxy.Get(ctx, "devices/"+agent.deviceID, device)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530109 if err != nil {
Thomas Lee Se5a44012019-11-07 20:32:24 +0530110 return nil, err
Kent Hagerman4f355f52020-03-30 16:01:33 -0400111 } else if !have {
112 return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530113 }
Kent Hagerman4f355f52020-03-30 16:01:33 -0400114
115 agent.deviceType = device.Adapter
116 agent.device = proto.Clone(device).(*voltha.Device)
117
Girish Kumarf56a4682020-03-20 20:07:46 +0000118 logger.Infow("device-loaded-from-dB", log.Fields{"device-id": agent.deviceID})
khenaidoo297cd252019-02-07 22:10:23 -0500119 } else {
Scott Baker80678602019-11-14 16:57:36 -0800120 // Create a new device
121 // Assumption is that AdminState, FlowGroups, and Flows are unitialized since this
122 // is a new device, so populate them here before passing the device to clusterDataProxy.AddWithId.
Kent Hagerman2b216042020-04-03 18:28:56 -0400123 // agent.deviceId will also have been set during newAgent().
Scott Baker80678602019-11-14 16:57:36 -0800124 device = (proto.Clone(deviceToCreate)).(*voltha.Device)
npujar1d86a522019-11-14 17:11:16 +0530125 device.Id = agent.deviceID
Scott Baker80678602019-11-14 16:57:36 -0800126 device.AdminState = voltha.AdminState_PREPROVISIONED
127 device.FlowGroups = &ofp.FlowGroups{Items: nil}
128 device.Flows = &ofp.Flows{Items: nil}
129 if !deviceToCreate.GetRoot() && deviceToCreate.ProxyAddress != nil {
130 // Set the default vlan ID to the one specified by the parent adapter. It can be
131 // overwritten by the child adapter during a device update request
132 device.Vlan = deviceToCreate.ProxyAddress.ChannelId
133 }
134
khenaidoo297cd252019-02-07 22:10:23 -0500135 // Add the initial device to the local model
Kent Hagerman4f355f52020-03-30 16:01:33 -0400136 if err := agent.clusterDataProxy.AddWithID(ctx, "devices", agent.deviceID, device); err != nil {
137 return nil, status.Errorf(codes.Aborted, "failed-adding-device-%s: %s", agent.deviceID, err)
khenaidoo297cd252019-02-07 22:10:23 -0500138 }
khenaidoo442e7c72020-03-10 16:13:48 -0400139 agent.device = device
khenaidoob9203542018-09-17 22:56:37 -0400140 }
khenaidoo19d7b632018-10-30 10:49:50 -0400141
khenaidoo442e7c72020-03-10 16:13:48 -0400142 startSucceeded = true
Girish Kumarf56a4682020-03-20 20:07:46 +0000143 logger.Debugw("device-agent-started", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400144
145 return agent.getDevice(ctx)
khenaidoob9203542018-09-17 22:56:37 -0400146}
147
khenaidoo4d4802d2018-10-04 21:59:49 -0400148// stop stops the device agent. Not much to do for now
Kent Hagerman2b216042020-04-03 18:28:56 -0400149func (agent *Agent) stop(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400150 needToStop := false
151 if agent.stopOnce.Do(func() { needToStop = true }); !needToStop {
152 return nil
153 }
154 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
155 return err
156 }
157 defer agent.requestQueue.RequestComplete()
khenaidoo49085352020-01-13 19:15:43 -0500158
Girish Kumarf56a4682020-03-20 20:07:46 +0000159 logger.Infow("stopping-device-agent", log.Fields{"deviceId": agent.deviceID, "parentId": agent.parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500160
khenaidoo0a822f92019-05-08 15:15:57 -0400161 // Remove the device from the KV store
Kent Hagerman4f355f52020-03-30 16:01:33 -0400162 if err := agent.clusterDataProxy.Remove(ctx, "devices/"+agent.deviceID); err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400163 return err
Thomas Lee Se5a44012019-11-07 20:32:24 +0530164 }
khenaidoo442e7c72020-03-10 16:13:48 -0400165
khenaidoo442e7c72020-03-10 16:13:48 -0400166 close(agent.exitChannel)
167
168 agent.stopped = true
169
Girish Kumarf56a4682020-03-20 20:07:46 +0000170 logger.Infow("device-agent-stopped", log.Fields{"device-id": agent.deviceID, "parent-id": agent.parentID})
khenaidoo442e7c72020-03-10 16:13:48 -0400171
172 return nil
khenaidoob9203542018-09-17 22:56:37 -0400173}
174
Scott Baker80678602019-11-14 16:57:36 -0800175// Load the most recent state from the KVStore for the device.
Kent Hagerman2b216042020-04-03 18:28:56 -0400176func (agent *Agent) reconcileWithKVStore(ctx context.Context) {
khenaidoo442e7c72020-03-10 16:13:48 -0400177 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000178 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -0400179 return
180 }
181 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000182 logger.Debug("reconciling-device-agent-devicetype")
Scott Baker80678602019-11-14 16:57:36 -0800183 // TODO: context timeout
Kent Hagerman4f355f52020-03-30 16:01:33 -0400184 device := &voltha.Device{}
185 if have, err := agent.clusterDataProxy.Get(ctx, "devices/"+agent.deviceID, device); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000186 logger.Errorw("kv-get-failed", log.Fields{"device-id": agent.deviceID, "error": err})
Thomas Lee Se5a44012019-11-07 20:32:24 +0530187 return
Kent Hagerman4f355f52020-03-30 16:01:33 -0400188 } else if !have {
189 return // not found in kv
Thomas Lee Se5a44012019-11-07 20:32:24 +0530190 }
Kent Hagerman4f355f52020-03-30 16:01:33 -0400191
192 agent.deviceType = device.Adapter
193 agent.device = device
194 logger.Debugw("reconciled-device-agent-devicetype", log.Fields{"device-id": agent.deviceID, "type": agent.deviceType})
Scott Baker80678602019-11-14 16:57:36 -0800195}
196
khenaidoo442e7c72020-03-10 16:13:48 -0400197// onSuccess is a common callback for scenarios where we receive a nil response following a request to an adapter
198// and the only action required is to publish a successful result on kafka
Kent Hagerman2b216042020-04-03 18:28:56 -0400199func (agent *Agent) onSuccess(rpc string, response interface{}, reqArgs ...interface{}) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000200 logger.Debugw("response successful", log.Fields{"rpc": rpc, "device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400201 // TODO: Post success message onto kafka
202}
203
204// onFailure is a common callback for scenarios where we receive an error response following a request to an adapter
205// and the only action required is to publish the failed result on kafka
Kent Hagerman2b216042020-04-03 18:28:56 -0400206func (agent *Agent) onFailure(rpc string, response interface{}, reqArgs ...interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -0400207 if res, ok := response.(error); ok {
Girish Kumarf56a4682020-03-20 20:07:46 +0000208 logger.Errorw("rpc-failed", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "error": res, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400209 } else {
Girish Kumarf56a4682020-03-20 20:07:46 +0000210 logger.Errorw("rpc-failed-invalid-error", log.Fields{"rpc": rpc, "device-id": agent.deviceID, "args": reqArgs})
khenaidoo442e7c72020-03-10 16:13:48 -0400211 }
212 // TODO: Post failure message onto kafka
213}
214
Kent Hagerman2b216042020-04-03 18:28:56 -0400215func (agent *Agent) waitForAdapterResponse(ctx context.Context, cancel context.CancelFunc, rpc string, ch chan *kafka.RpcResponse,
khenaidoo442e7c72020-03-10 16:13:48 -0400216 onSuccess coreutils.ResponseCallback, onFailure coreutils.ResponseCallback, reqArgs ...interface{}) {
217 defer cancel()
218 select {
219 case rpcResponse, ok := <-ch:
220 if !ok {
221 onFailure(rpc, status.Errorf(codes.Aborted, "channel-closed"), reqArgs)
222 } else if rpcResponse.Err != nil {
223 onFailure(rpc, rpcResponse.Err, reqArgs)
224 } else {
225 onSuccess(rpc, rpcResponse.Reply, reqArgs)
226 }
227 case <-ctx.Done():
228 onFailure(rpc, ctx.Err(), reqArgs)
229 }
230}
231
khenaidoo6e55d9e2019-12-12 18:26:26 -0500232// getDevice returns the device data from cache
Kent Hagerman2b216042020-04-03 18:28:56 -0400233func (agent *Agent) getDevice(ctx context.Context) (*voltha.Device, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400234 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
235 return nil, err
236 }
237 defer agent.requestQueue.RequestComplete()
238 return proto.Clone(agent.device).(*voltha.Device), nil
khenaidoo92e62c52018-10-03 14:02:54 -0400239}
240
khenaidoo4d4802d2018-10-04 21:59:49 -0400241// 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 -0400242func (agent *Agent) getDeviceWithoutLock() *voltha.Device {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500243 return proto.Clone(agent.device).(*voltha.Device)
khenaidoo92e62c52018-10-03 14:02:54 -0400244}
245
khenaidoo3ab34882019-05-02 21:33:30 -0400246// enableDevice activates a preprovisioned or a disable device
Kent Hagerman2b216042020-04-03 18:28:56 -0400247func (agent *Agent) enableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400248 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
249 return err
250 }
251 defer agent.requestQueue.RequestComplete()
252
Girish Kumarf56a4682020-03-20 20:07:46 +0000253 logger.Debugw("enableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo21d51152019-02-01 13:48:37 -0500254
khenaidoo6e55d9e2019-12-12 18:26:26 -0500255 cloned := agent.getDeviceWithoutLock()
256
npujar1d86a522019-11-14 17:11:16 +0530257 // 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 -0400258 // pre-provisioned with the required adapter not registered. At this stage, since we need to communicate
npujar1d86a522019-11-14 17:11:16 +0530259 // with the adapter then we need to know the adapter that will handle this request
Kent Hagerman2b216042020-04-03 18:28:56 -0400260 adapterName, err := agent.adapterMgr.GetAdapterType(cloned.Type)
npujar1d86a522019-11-14 17:11:16 +0530261 if err != nil {
npujar1d86a522019-11-14 17:11:16 +0530262 return err
263 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500264 cloned.Adapter = adapterName
npujar1d86a522019-11-14 17:11:16 +0530265
khenaidoo6e55d9e2019-12-12 18:26:26 -0500266 if cloned.AdminState == voltha.AdminState_ENABLED {
Matteo Scandolod525ae32020-04-02 17:27:29 -0700267 logger.Warnw("device-already-enabled", log.Fields{"device-id": agent.deviceID})
268 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-an-already-enabled-device: %s ", cloned.Id))
269 return err
npujar1d86a522019-11-14 17:11:16 +0530270 }
271
khenaidoo6e55d9e2019-12-12 18:26:26 -0500272 if cloned.AdminState == voltha.AdminState_DELETED {
npujar1d86a522019-11-14 17:11:16 +0530273 // This is a temporary state when a device is deleted before it gets removed from the model.
khenaidoo6e55d9e2019-12-12 18:26:26 -0500274 err = status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot-enable-a-deleted-device: %s ", cloned.Id))
npujar1d86a522019-11-14 17:11:16 +0530275 return err
276 }
277
khenaidoo6e55d9e2019-12-12 18:26:26 -0500278 previousAdminState := cloned.AdminState
npujar1d86a522019-11-14 17:11:16 +0530279
280 // Update the Admin State and set the operational state to activating before sending the request to the
281 // Adapters
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500282 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_ENABLED, cloned.ConnectStatus, voltha.OperStatus_ACTIVATING); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530283 return err
284 }
285
khenaidoo442e7c72020-03-10 16:13:48 -0400286 // 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 -0500287 device := proto.Clone(cloned).(*voltha.Device)
khenaidoo442e7c72020-03-10 16:13:48 -0400288 var ch chan *kafka.RpcResponse
289 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
npujar1d86a522019-11-14 17:11:16 +0530290 if previousAdminState == voltha.AdminState_PREPROVISIONED {
Kent Hagerman2b216042020-04-03 18:28:56 -0400291 ch, err = agent.adapterProxy.AdoptDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400292 } else {
Kent Hagerman2b216042020-04-03 18:28:56 -0400293 ch, err = agent.adapterProxy.ReEnableDevice(subCtx, device)
khenaidoob9203542018-09-17 22:56:37 -0400294 }
khenaidoo442e7c72020-03-10 16:13:48 -0400295 if err != nil {
296 cancel()
297 return err
298 }
299 // Wait for response
300 go agent.waitForAdapterResponse(subCtx, cancel, "enableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoob9203542018-09-17 22:56:37 -0400301 return nil
302}
303
Kent Hagerman2b216042020-04-03 18:28:56 -0400304func (agent *Agent) waitForAdapterFlowResponse(ctx context.Context, cancel context.CancelFunc, ch chan *kafka.RpcResponse, response coreutils.Response) {
khenaidoo442e7c72020-03-10 16:13:48 -0400305 defer cancel()
306 select {
307 case rpcResponse, ok := <-ch:
308 if !ok {
309 response.Error(status.Errorf(codes.Aborted, "channel-closed"))
310 } else if rpcResponse.Err != nil {
311 response.Error(rpcResponse.Err)
312 } else {
313 response.Done()
314 }
315 case <-ctx.Done():
316 response.Error(ctx.Err())
khenaidoo2c6a0992019-04-29 13:46:56 -0400317 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400318}
319
khenaidoob2121e52019-12-16 17:17:22 -0500320//deleteFlowWithoutPreservingOrder removes a flow specified by index from the flows slice. This function will
321//panic if the index is out of range.
322func deleteFlowWithoutPreservingOrder(flows []*ofp.OfpFlowStats, index int) []*ofp.OfpFlowStats {
323 flows[index] = flows[len(flows)-1]
324 flows[len(flows)-1] = nil
325 return flows[:len(flows)-1]
326}
327
328//deleteGroupWithoutPreservingOrder removes a group specified by index from the groups slice. This function will
329//panic if the index is out of range.
330func deleteGroupWithoutPreservingOrder(groups []*ofp.OfpGroupEntry, index int) []*ofp.OfpGroupEntry {
331 groups[index] = groups[len(groups)-1]
332 groups[len(groups)-1] = nil
333 return groups[:len(groups)-1]
334}
335
336func flowsToUpdateToDelete(newFlows, existingFlows []*ofp.OfpFlowStats) (updatedNewFlows, flowsToDelete, updatedAllFlows []*ofp.OfpFlowStats) {
337 // Process flows
338 for _, flow := range existingFlows {
339 if idx := fu.FindFlows(newFlows, flow); idx == -1 {
340 updatedAllFlows = append(updatedAllFlows, flow)
341 } else {
342 // We have a matching flow (i.e. the following field matches: "TableId", "Priority", "Flags", "Cookie",
343 // "Match". If this is an exact match (i.e. all other fields matches as well) then this flow will be
344 // ignored. Otherwise, the previous flow will be deleted and the new one added
345 if proto.Equal(newFlows[idx], flow) {
346 // Flow already exist, remove it from the new flows but keep it in the updated flows slice
347 newFlows = deleteFlowWithoutPreservingOrder(newFlows, idx)
348 updatedAllFlows = append(updatedAllFlows, flow)
349 } else {
350 // Minor change to flow, delete old and add new one
351 flowsToDelete = append(flowsToDelete, flow)
352 }
353 }
354 }
355 updatedAllFlows = append(updatedAllFlows, newFlows...)
356 return newFlows, flowsToDelete, updatedAllFlows
357}
358
359func groupsToUpdateToDelete(newGroups, existingGroups []*ofp.OfpGroupEntry) (updatedNewGroups, groupsToDelete, updatedAllGroups []*ofp.OfpGroupEntry) {
360 for _, group := range existingGroups {
361 if idx := fu.FindGroup(newGroups, group.Desc.GroupId); idx == -1 { // does not exist now
362 updatedAllGroups = append(updatedAllGroups, group)
363 } else {
364 // Follow same logic as flows
365 if proto.Equal(newGroups[idx], group) {
366 // Group already exist, remove it from the new groups
367 newGroups = deleteGroupWithoutPreservingOrder(newGroups, idx)
368 updatedAllGroups = append(updatedAllGroups, group)
369 } else {
370 // Minor change to group, delete old and add new one
371 groupsToDelete = append(groupsToDelete, group)
372 }
373 }
374 }
375 updatedAllGroups = append(updatedAllGroups, newGroups...)
376 return newGroups, groupsToDelete, updatedAllGroups
377}
378
Kent Hagerman2b216042020-04-03 18:28:56 -0400379func (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 +0000380 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 -0400381
khenaidoo2c6a0992019-04-29 13:46:56 -0400382 if (len(newFlows) | len(newGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000383 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800384 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400385 }
386
khenaidoo442e7c72020-03-10 16:13:48 -0400387 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
388 return coreutils.DoneResponse(), err
389 }
390 defer agent.requestQueue.RequestComplete()
khenaidoo2c6a0992019-04-29 13:46:56 -0400391
khenaidoo6e55d9e2019-12-12 18:26:26 -0500392 device := agent.getDeviceWithoutLock()
Kent Hagerman45a13e42020-04-13 12:23:50 -0400393 dType, err := agent.adapterMgr.GetDeviceType(ctx, &voltha.ID{Id: device.Type})
394 if err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400395 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
396 }
397
khenaidoo0458db62019-06-20 08:50:36 -0400398 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
399 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
400
khenaidoo0458db62019-06-20 08:50:36 -0400401 // Process flows
khenaidoob2121e52019-12-16 17:17:22 -0500402 newFlows, flowsToDelete, updatedAllFlows := flowsToUpdateToDelete(newFlows, existingFlows.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400403
404 // Process groups
khenaidoob2121e52019-12-16 17:17:22 -0500405 newGroups, groupsToDelete, updatedAllGroups := groupsToUpdateToDelete(newGroups, existingGroups.Items)
khenaidoo0458db62019-06-20 08:50:36 -0400406
407 // Sanity check
khenaidoob2121e52019-12-16 17:17:22 -0500408 if (len(updatedAllFlows) | len(flowsToDelete) | len(updatedAllGroups) | len(groupsToDelete)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000409 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800410 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400411 }
412
khenaidoo442e7c72020-03-10 16:13:48 -0400413 // store the changed data
414 device.Flows = &voltha.Flows{Items: updatedAllFlows}
415 device.FlowGroups = &voltha.FlowGroups{Items: updatedAllGroups}
416 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
417 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-device-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500418 }
khenaidoo0458db62019-06-20 08:50:36 -0400419
khenaidoo442e7c72020-03-10 16:13:48 -0400420 // Send update to adapters
421 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
422 response := coreutils.NewResponse()
423 if !dType.AcceptsAddRemoveFlowUpdates {
khenaidoob2121e52019-12-16 17:17:22 -0500424 if len(updatedAllGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedAllGroups) && len(updatedAllFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedAllFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000425 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": newFlows, "groups": newGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400426 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800427 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400428 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400429 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedAllFlows}, &voltha.FlowGroups{Items: updatedAllGroups}, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400430 if err != nil {
431 cancel()
432 return coreutils.DoneResponse(), err
433 }
434 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400435 } else {
436 flowChanges := &ofp.FlowChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400437 ToAdd: &voltha.Flows{Items: newFlows},
khenaidoo0458db62019-06-20 08:50:36 -0400438 ToRemove: &voltha.Flows{Items: flowsToDelete},
439 }
440 groupChanges := &ofp.FlowGroupChanges{
Matt Jeanneret518b5a42019-10-29 10:30:46 -0400441 ToAdd: &voltha.FlowGroups{Items: newGroups},
442 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
khenaidoo0458db62019-06-20 08:50:36 -0400443 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
444 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400445 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400446 if err != nil {
447 cancel()
448 return coreutils.DoneResponse(), err
449 }
450 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400451 }
A R Karthick5c28f552019-12-11 22:47:44 -0800452 return response, nil
453}
454
455//addFlowsAndGroups adds the "newFlows" and "newGroups" from the existing flows/groups and sends the update to the
456//adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400457func (agent *Agent) addFlowsAndGroups(ctx context.Context, newFlows []*ofp.OfpFlowStats, newGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530458 response, err := agent.addFlowsAndGroupsToAdapter(ctx, newFlows, newGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800459 if err != nil {
460 return err
461 }
khenaidoo442e7c72020-03-10 16:13:48 -0400462 if errs := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); errs != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000463 logger.Warnw("no-adapter-response", log.Fields{"device-id": agent.deviceID, "result": errs})
khenaidoo442e7c72020-03-10 16:13:48 -0400464 return status.Errorf(codes.Aborted, "flow-failure-device-%s", agent.deviceID)
khenaidoo0458db62019-06-20 08:50:36 -0400465 }
khenaidoo0458db62019-06-20 08:50:36 -0400466 return nil
467}
468
Kent Hagerman2b216042020-04-03 18:28:56 -0400469func (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 +0000470 logger.Debugw("delete-flows-groups-from-adapter", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
khenaidoo0458db62019-06-20 08:50:36 -0400471
472 if (len(flowsToDel) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000473 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": flowsToDel, "groups": groupsToDel})
A R Karthick5c28f552019-12-11 22:47:44 -0800474 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400475 }
476
khenaidoo442e7c72020-03-10 16:13:48 -0400477 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
478 return coreutils.DoneResponse(), err
479 }
480 defer agent.requestQueue.RequestComplete()
khenaidoo0458db62019-06-20 08:50:36 -0400481
khenaidoo6e55d9e2019-12-12 18:26:26 -0500482 device := agent.getDeviceWithoutLock()
Kent Hagerman45a13e42020-04-13 12:23:50 -0400483 dType, err := agent.adapterMgr.GetDeviceType(ctx, &voltha.ID{Id: device.Type})
484 if err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400485 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
486 }
khenaidoo0458db62019-06-20 08:50:36 -0400487
488 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
489 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
490
491 var flowsToKeep []*ofp.OfpFlowStats
492 var groupsToKeep []*ofp.OfpGroupEntry
493
494 // Process flows
495 for _, flow := range existingFlows.Items {
496 if idx := fu.FindFlows(flowsToDel, flow); idx == -1 {
497 flowsToKeep = append(flowsToKeep, flow)
498 }
499 }
500
501 // Process groups
502 for _, group := range existingGroups.Items {
503 if fu.FindGroup(groupsToDel, group.Desc.GroupId) == -1 { // does not exist now
504 groupsToKeep = append(groupsToKeep, group)
505 }
506 }
507
Girish Kumarf56a4682020-03-20 20:07:46 +0000508 logger.Debugw("deleteFlowsAndGroups",
khenaidoo0458db62019-06-20 08:50:36 -0400509 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400510 "device-id": agent.deviceID,
511 "flows-to-del": len(flowsToDel),
512 "flows-to-keep": len(flowsToKeep),
513 "groups-to-del": len(groupsToDel),
514 "groups-to-keep": len(groupsToKeep),
khenaidoo0458db62019-06-20 08:50:36 -0400515 })
516
517 // Sanity check
518 if (len(flowsToKeep) | len(flowsToDel) | len(groupsToKeep) | len(groupsToDel)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000519 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 -0800520 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400521 }
522
khenaidoo442e7c72020-03-10 16:13:48 -0400523 // store the changed data
524 device.Flows = &voltha.Flows{Items: flowsToKeep}
525 device.FlowGroups = &voltha.FlowGroups{Items: groupsToKeep}
526 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
527 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500528 }
khenaidoo442e7c72020-03-10 16:13:48 -0400529
530 // Send update to adapters
531 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
532 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400533 if !dType.AcceptsAddRemoveFlowUpdates {
534 if len(groupsToKeep) != 0 && reflect.DeepEqual(existingGroups.Items, groupsToKeep) && len(flowsToKeep) != 0 && reflect.DeepEqual(existingFlows.Items, flowsToKeep) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000535 logger.Debugw("nothing-to-update", log.Fields{"deviceId": agent.deviceID, "flowsToDel": flowsToDel, "groupsToDel": groupsToDel})
khenaidoo442e7c72020-03-10 16:13:48 -0400536 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800537 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400538 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400539 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: flowsToKeep}, &voltha.FlowGroups{Items: groupsToKeep}, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400540 if err != nil {
541 cancel()
542 return coreutils.DoneResponse(), err
543 }
544 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400545 } else {
546 flowChanges := &ofp.FlowChanges{
547 ToAdd: &voltha.Flows{Items: []*ofp.OfpFlowStats{}},
548 ToRemove: &voltha.Flows{Items: flowsToDel},
549 }
550 groupChanges := &ofp.FlowGroupChanges{
551 ToAdd: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
552 ToRemove: &voltha.FlowGroups{Items: groupsToDel},
553 ToUpdate: &voltha.FlowGroups{Items: []*ofp.OfpGroupEntry{}},
554 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400555 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400556 if err != nil {
557 cancel()
558 return coreutils.DoneResponse(), err
559 }
560 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400561 }
A R Karthick5c28f552019-12-11 22:47:44 -0800562 return response, nil
A R Karthick5c28f552019-12-11 22:47:44 -0800563}
564
565//deleteFlowsAndGroups removes the "flowsToDel" and "groupsToDel" from the existing flows/groups and sends the update to the
566//adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400567func (agent *Agent) deleteFlowsAndGroups(ctx context.Context, flowsToDel []*ofp.OfpFlowStats, groupsToDel []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530568 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDel, groupsToDel, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800569 if err != nil {
570 return err
571 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500572 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400573 return status.Errorf(codes.Aborted, "errors-%s", res)
574 }
575 return nil
khenaidoo0458db62019-06-20 08:50:36 -0400576}
577
khenaidoo787224a2020-04-16 18:08:47 -0400578//filterOutFlows removes flows from a device using the uni-port as filter
579func (agent *Agent) filterOutFlows(ctx context.Context, uniPort uint32, flowMetadata *voltha.FlowMetadata) error {
580 device, err := agent.getDevice(ctx)
581 if err != nil {
582 return err
583 }
584 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
585 var flowsToDelete []*ofp.OfpFlowStats
586
587 // If an existing flow has the uniPort as an InPort or OutPort or as a Tunnel ID then it needs to be removed
588 for _, flow := range existingFlows.Items {
589 if fu.GetInPort(flow) == uniPort || fu.GetOutPort(flow) == uniPort || fu.GetTunnelId(flow) == uint64(uniPort) {
590 flowsToDelete = append(flowsToDelete, flow)
591 }
592 }
593 logger.Debugw("flows-to-delete", log.Fields{"device-id": agent.deviceID, "uni-port": uniPort, "flows": flowsToDelete})
594 if len(flowsToDelete) == 0 {
595 return nil
596 }
597
598 response, err := agent.deleteFlowsAndGroupsFromAdapter(ctx, flowsToDelete, []*ofp.OfpGroupEntry{}, flowMetadata)
599 if err != nil {
600 return err
601 }
602 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
603 return status.Errorf(codes.Aborted, "errors-%s", res)
604 }
605 return nil
606}
607
Kent Hagerman2b216042020-04-03 18:28:56 -0400608func (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 +0000609 logger.Debugw("updateFlowsAndGroups", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo0458db62019-06-20 08:50:36 -0400610
611 if (len(updatedFlows) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000612 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800613 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400614 }
615
khenaidoo442e7c72020-03-10 16:13:48 -0400616 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
617 return coreutils.DoneResponse(), err
618 }
619 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500620
621 device := agent.getDeviceWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400622 if device.OperStatus != voltha.OperStatus_ACTIVE || device.ConnectStatus != voltha.ConnectStatus_REACHABLE || device.AdminState != voltha.AdminState_ENABLED {
623 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "invalid device states")
624 }
Kent Hagerman45a13e42020-04-13 12:23:50 -0400625 dType, err := agent.adapterMgr.GetDeviceType(ctx, &voltha.ID{Id: device.Type})
626 if err != nil {
khenaidoo442e7c72020-03-10 16:13:48 -0400627 return coreutils.DoneResponse(), status.Errorf(codes.FailedPrecondition, "non-existent-device-type-%s", device.Type)
628 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500629
khenaidoo0458db62019-06-20 08:50:36 -0400630 existingFlows := proto.Clone(device.Flows).(*voltha.Flows)
631 existingGroups := proto.Clone(device.FlowGroups).(*ofp.FlowGroups)
632
633 if len(updatedGroups) != 0 && reflect.DeepEqual(existingGroups.Items, updatedGroups) && len(updatedFlows) != 0 && reflect.DeepEqual(existingFlows.Items, updatedFlows) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000634 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
A R Karthick5c28f552019-12-11 22:47:44 -0800635 return coreutils.DoneResponse(), nil
khenaidoo0458db62019-06-20 08:50:36 -0400636 }
637
Girish Kumarf56a4682020-03-20 20:07:46 +0000638 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400639 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400640 "device-id": agent.deviceID,
641 "updated-flows": updatedFlows,
642 "updated-groups": updatedGroups,
khenaidoo0458db62019-06-20 08:50:36 -0400643 })
644
khenaidoo442e7c72020-03-10 16:13:48 -0400645 // store the updated data
646 device.Flows = &voltha.Flows{Items: updatedFlows}
647 device.FlowGroups = &voltha.FlowGroups{Items: updatedGroups}
648 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
649 return coreutils.DoneResponse(), status.Errorf(codes.Internal, "failure-updating-%s", agent.deviceID)
khenaidooe7be1332020-01-24 18:58:33 -0500650 }
khenaidoo0458db62019-06-20 08:50:36 -0400651
khenaidoo442e7c72020-03-10 16:13:48 -0400652 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
653 response := coreutils.NewResponse()
khenaidoo0458db62019-06-20 08:50:36 -0400654 // Process bulk flow update differently than incremental update
655 if !dType.AcceptsAddRemoveFlowUpdates {
Kent Hagerman2b216042020-04-03 18:28:56 -0400656 rpcResponse, err := agent.adapterProxy.UpdateFlowsBulk(subCtx, device, &voltha.Flows{Items: updatedFlows}, &voltha.FlowGroups{Items: updatedGroups}, nil)
khenaidoo442e7c72020-03-10 16:13:48 -0400657 if err != nil {
658 cancel()
659 return coreutils.DoneResponse(), err
660 }
661 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
khenaidoo0458db62019-06-20 08:50:36 -0400662 } else {
663 var flowsToAdd []*ofp.OfpFlowStats
khenaidoo2c6a0992019-04-29 13:46:56 -0400664 var flowsToDelete []*ofp.OfpFlowStats
khenaidoo0458db62019-06-20 08:50:36 -0400665 var groupsToAdd []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400666 var groupsToDelete []*ofp.OfpGroupEntry
khenaidoo2c6a0992019-04-29 13:46:56 -0400667
668 // Process flows
khenaidoo0458db62019-06-20 08:50:36 -0400669 for _, flow := range updatedFlows {
670 if idx := fu.FindFlows(existingFlows.Items, flow); idx == -1 {
671 flowsToAdd = append(flowsToAdd, flow)
672 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400673 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400674 for _, flow := range existingFlows.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400675 if idx := fu.FindFlows(updatedFlows, flow); idx != -1 {
khenaidoo2c6a0992019-04-29 13:46:56 -0400676 flowsToDelete = append(flowsToDelete, flow)
677 }
678 }
679
680 // Process groups
khenaidoo0458db62019-06-20 08:50:36 -0400681 for _, g := range updatedGroups {
682 if fu.FindGroup(existingGroups.Items, g.Desc.GroupId) == -1 { // does not exist now
683 groupsToAdd = append(groupsToAdd, g)
684 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400685 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400686 for _, group := range existingGroups.Items {
khenaidoo0458db62019-06-20 08:50:36 -0400687 if fu.FindGroup(updatedGroups, group.Desc.GroupId) != -1 { // does not exist now
khenaidoo2c6a0992019-04-29 13:46:56 -0400688 groupsToDelete = append(groupsToDelete, group)
689 }
690 }
691
Girish Kumarf56a4682020-03-20 20:07:46 +0000692 logger.Debugw("updating-flows-and-groups",
khenaidoo0458db62019-06-20 08:50:36 -0400693 log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -0400694 "device-id": agent.deviceID,
695 "flows-to-add": flowsToAdd,
696 "flows-to-delete": flowsToDelete,
697 "groups-to-add": groupsToAdd,
698 "groups-to-delete": groupsToDelete,
khenaidoo0458db62019-06-20 08:50:36 -0400699 })
700
khenaidoo2c6a0992019-04-29 13:46:56 -0400701 // Sanity check
khenaidoo0458db62019-06-20 08:50:36 -0400702 if (len(flowsToAdd) | len(flowsToDelete) | len(groupsToAdd) | len(groupsToDelete) | len(updatedGroups)) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +0000703 logger.Debugw("nothing-to-update", log.Fields{"device-id": agent.deviceID, "flows": updatedFlows, "groups": updatedGroups})
khenaidoo442e7c72020-03-10 16:13:48 -0400704 cancel()
A R Karthick5c28f552019-12-11 22:47:44 -0800705 return coreutils.DoneResponse(), nil
khenaidoo2c6a0992019-04-29 13:46:56 -0400706 }
707
khenaidoo0458db62019-06-20 08:50:36 -0400708 flowChanges := &ofp.FlowChanges{
709 ToAdd: &voltha.Flows{Items: flowsToAdd},
710 ToRemove: &voltha.Flows{Items: flowsToDelete},
khenaidoo19d7b632018-10-30 10:49:50 -0400711 }
khenaidoo0458db62019-06-20 08:50:36 -0400712 groupChanges := &ofp.FlowGroupChanges{
713 ToAdd: &voltha.FlowGroups{Items: groupsToAdd},
714 ToRemove: &voltha.FlowGroups{Items: groupsToDelete},
715 ToUpdate: &voltha.FlowGroups{Items: updatedGroups},
716 }
Kent Hagerman2b216042020-04-03 18:28:56 -0400717 rpcResponse, err := agent.adapterProxy.UpdateFlowsIncremental(subCtx, device, flowChanges, groupChanges, flowMetadata)
khenaidoo442e7c72020-03-10 16:13:48 -0400718 if err != nil {
719 cancel()
720 return coreutils.DoneResponse(), err
721 }
722 go agent.waitForAdapterFlowResponse(subCtx, cancel, rpcResponse, response)
Kent Hagerman3c513972019-11-25 13:49:41 -0500723 }
khenaidoo0458db62019-06-20 08:50:36 -0400724
A R Karthick5c28f552019-12-11 22:47:44 -0800725 return response, nil
726}
727
728//updateFlowsAndGroups replaces the existing flows and groups with "updatedFlows" and "updatedGroups" respectively. It
729//also sends the updates to the adapters
Kent Hagerman2b216042020-04-03 18:28:56 -0400730func (agent *Agent) updateFlowsAndGroups(ctx context.Context, updatedFlows []*ofp.OfpFlowStats, updatedGroups []*ofp.OfpGroupEntry, flowMetadata *voltha.FlowMetadata) error {
npujar467fe752020-01-16 20:17:45 +0530731 response, err := agent.updateFlowsAndGroupsToAdapter(ctx, updatedFlows, updatedGroups, flowMetadata)
A R Karthick5c28f552019-12-11 22:47:44 -0800732 if err != nil {
733 return err
734 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500735 if res := coreutils.WaitForNilOrErrorResponses(agent.defaultTimeout, response); res != nil {
khenaidoo0458db62019-06-20 08:50:36 -0400736 return status.Errorf(codes.Aborted, "errors-%s", res)
737 }
738 return nil
khenaidoo19d7b632018-10-30 10:49:50 -0400739}
740
Girish Gowdra408cd962020-03-11 14:31:31 -0700741//deleteAllFlows deletes all flows in the device table
Kent Hagerman2b216042020-04-03 18:28:56 -0400742func (agent *Agent) deleteAllFlows(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000743 logger.Debugw("deleteAllFlows", log.Fields{"deviceId": agent.deviceID})
Girish Gowdra408cd962020-03-11 14:31:31 -0700744 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
745 return err
746 }
747 defer agent.requestQueue.RequestComplete()
748
749 device := agent.getDeviceWithoutLock()
750 // purge all flows on the device by setting it to nil
751 device.Flows = &ofp.Flows{Items: nil}
752 if err := agent.updateDeviceWithoutLock(ctx, device); err != nil {
753 // The caller logs the error
754 return err
755 }
756 return nil
757}
758
khenaidoo4d4802d2018-10-04 21:59:49 -0400759//disableDevice disable a device
Kent Hagerman2b216042020-04-03 18:28:56 -0400760func (agent *Agent) disableDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400761 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
762 return err
763 }
764 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000765 logger.Debugw("disableDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500766
767 cloned := agent.getDeviceWithoutLock()
768
769 if cloned.AdminState == voltha.AdminState_DISABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000770 logger.Debugw("device-already-disabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530771 return nil
772 }
khenaidoo6e55d9e2019-12-12 18:26:26 -0500773 if cloned.AdminState == voltha.AdminState_PREPROVISIONED ||
774 cloned.AdminState == voltha.AdminState_DELETED {
khenaidoo6e55d9e2019-12-12 18:26:26 -0500775 return status.Errorf(codes.FailedPrecondition, "deviceId:%s, invalid-admin-state:%s", agent.deviceID, cloned.AdminState)
npujar1d86a522019-11-14 17:11:16 +0530776 }
khenaidoo4554f7c2019-05-29 22:13:15 -0400777
npujar1d86a522019-11-14 17:11:16 +0530778 // Update the Admin State and operational state before sending the request out
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500779 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DISABLED, cloned.ConnectStatus, voltha.OperStatus_UNKNOWN); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530780 return err
781 }
khenaidoo442e7c72020-03-10 16:13:48 -0400782
783 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400784 ch, err := agent.adapterProxy.DisableDevice(subCtx, proto.Clone(cloned).(*voltha.Device))
khenaidoo442e7c72020-03-10 16:13:48 -0400785 if err != nil {
786 cancel()
npujar1d86a522019-11-14 17:11:16 +0530787 return err
khenaidoo0a822f92019-05-08 15:15:57 -0400788 }
khenaidoo442e7c72020-03-10 16:13:48 -0400789 go agent.waitForAdapterResponse(subCtx, cancel, "disableDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo0a822f92019-05-08 15:15:57 -0400790
khenaidoo92e62c52018-10-03 14:02:54 -0400791 return nil
792}
793
Kent Hagerman2b216042020-04-03 18:28:56 -0400794func (agent *Agent) rebootDevice(ctx context.Context) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400795 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530796 return err
khenaidoo4d4802d2018-10-04 21:59:49 -0400797 }
khenaidoo442e7c72020-03-10 16:13:48 -0400798 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000799 logger.Debugw("rebootDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400800
801 device := agent.getDeviceWithoutLock()
802 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400803 ch, err := agent.adapterProxy.RebootDevice(subCtx, device)
khenaidoo442e7c72020-03-10 16:13:48 -0400804 if err != nil {
805 cancel()
806 return err
807 }
808 go agent.waitForAdapterResponse(subCtx, cancel, "rebootDevice", ch, agent.onSuccess, agent.onFailure)
khenaidoo4d4802d2018-10-04 21:59:49 -0400809 return nil
810}
811
Kent Hagerman2b216042020-04-03 18:28:56 -0400812func (agent *Agent) deleteDevice(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000813 logger.Debugw("deleteDevice", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -0400814 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
815 return err
816 }
817 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -0500818
819 cloned := agent.getDeviceWithoutLock()
Chaitrashree G S543df3e2020-02-24 22:36:54 -0500820
khenaidoo442e7c72020-03-10 16:13:48 -0400821 previousState := cloned.AdminState
822
823 // No check is required when deleting a device. Changing the state to DELETE will trigger the removal of this
824 // device by the state machine
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500825 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DELETED, cloned.ConnectStatus, cloned.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530826 return err
827 }
khenaidoo442e7c72020-03-10 16:13:48 -0400828
829 // If the device was in pre-prov state (only parent device are in that state) then do not send the request to the
830 // adapter
831 if previousState != ic.AdminState_PREPROVISIONED {
832 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400833 ch, err := agent.adapterProxy.DeleteDevice(subCtx, cloned)
khenaidoo442e7c72020-03-10 16:13:48 -0400834 if err != nil {
835 cancel()
836 return err
837 }
838 go agent.waitForAdapterResponse(subCtx, cancel, "deleteDevice", ch, agent.onSuccess, agent.onFailure)
839 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400840 return nil
841}
842
Kent Hagerman2b216042020-04-03 18:28:56 -0400843func (agent *Agent) setParentID(ctx context.Context, device *voltha.Device, parentID string) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400844 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
845 return err
846 }
847 defer agent.requestQueue.RequestComplete()
848
Girish Kumarf56a4682020-03-20 20:07:46 +0000849 logger.Debugw("setParentId", log.Fields{"device-id": device.Id, "parent-id": parentID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500850
851 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530852 cloned.ParentId = parentID
853 // Store the device
npujar467fe752020-01-16 20:17:45 +0530854 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530855 return err
856 }
khenaidoo442e7c72020-03-10 16:13:48 -0400857
npujar1d86a522019-11-14 17:11:16 +0530858 return nil
khenaidooad06fd72019-10-28 12:26:05 -0400859}
860
Kent Hagerman2b216042020-04-03 18:28:56 -0400861func (agent *Agent) updatePmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400862 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
863 return err
864 }
865 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000866 logger.Debugw("updatePmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500867
868 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530869 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
870 // Store the device
npujar467fe752020-01-16 20:17:45 +0530871 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530872 return err
873 }
874 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400875 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400876 ch, err := agent.adapterProxy.UpdatePmConfigs(subCtx, cloned, pmConfigs)
khenaidoo442e7c72020-03-10 16:13:48 -0400877 if err != nil {
878 cancel()
npujar1d86a522019-11-14 17:11:16 +0530879 return err
880 }
khenaidoo442e7c72020-03-10 16:13:48 -0400881 go agent.waitForAdapterResponse(subCtx, cancel, "updatePmConfigs", ch, agent.onSuccess, agent.onFailure)
npujar1d86a522019-11-14 17:11:16 +0530882 return nil
khenaidoob3127472019-07-24 21:04:55 -0400883}
884
Kent Hagerman2b216042020-04-03 18:28:56 -0400885func (agent *Agent) initPmConfigs(ctx context.Context, pmConfigs *voltha.PmConfigs) error {
khenaidoo442e7c72020-03-10 16:13:48 -0400886 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
887 return err
888 }
889 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000890 logger.Debugw("initPmConfigs", log.Fields{"device-id": pmConfigs.Id})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500891
892 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +0530893 cloned.PmConfigs = proto.Clone(pmConfigs).(*voltha.PmConfigs)
npujar467fe752020-01-16 20:17:45 +0530894 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500895 return agent.updateDeviceInStoreWithoutLock(updateCtx, cloned, false, "")
khenaidoob3127472019-07-24 21:04:55 -0400896}
897
Kent Hagerman2b216042020-04-03 18:28:56 -0400898func (agent *Agent) listPmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400899 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
900 return nil, err
901 }
902 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +0000903 logger.Debugw("listPmConfigs", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500904
905 return agent.getDeviceWithoutLock().PmConfigs, nil
khenaidoob3127472019-07-24 21:04:55 -0400906}
907
Kent Hagerman2b216042020-04-03 18:28:56 -0400908func (agent *Agent) downloadImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400909 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
910 return nil, err
911 }
912 defer agent.requestQueue.RequestComplete()
913
Girish Kumarf56a4682020-03-20 20:07:46 +0000914 logger.Debugw("downloadImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500915
916 device := agent.getDeviceWithoutLock()
917
npujar1d86a522019-11-14 17:11:16 +0530918 if device.AdminState != voltha.AdminState_ENABLED {
khenaidoo442e7c72020-03-10 16:13:48 -0400919 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
npujar1d86a522019-11-14 17:11:16 +0530920 }
921 // Save the image
922 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
923 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
924 cloned := proto.Clone(device).(*voltha.Device)
925 if cloned.ImageDownloads == nil {
926 cloned.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500927 } else {
928 if device.AdminState != voltha.AdminState_ENABLED {
Girish Kumarf56a4682020-03-20 20:07:46 +0000929 logger.Debugw("device-not-enabled", log.Fields{"id": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +0530930 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, expected-admin-state:%s", agent.deviceID, voltha.AdminState_ENABLED)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500931 }
932 // Save the image
933 clonedImg := proto.Clone(img).(*voltha.ImageDownload)
Stephane Barbariedf5479f2019-01-29 22:13:00 -0500934 clonedImg.DownloadState = voltha.ImageDownload_DOWNLOAD_REQUESTED
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500935 if device.ImageDownloads == nil {
936 device.ImageDownloads = []*voltha.ImageDownload{clonedImg}
khenaidoof5a5bfa2019-01-23 22:20:29 -0500937 } else {
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500938 device.ImageDownloads = append(device.ImageDownloads, clonedImg)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500939 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500940 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DOWNLOADING_IMAGE, device.ConnectStatus, device.OperStatus); err != nil {
Mahir Gunyelb5851672019-07-24 10:46:26 +0300941 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500942 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500943
khenaidoof5a5bfa2019-01-23 22:20:29 -0500944 // Send the request to the adapter
khenaidoo442e7c72020-03-10 16:13:48 -0400945 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400946 ch, err := agent.adapterProxy.DownloadImage(ctx, cloned, clonedImg)
khenaidoo442e7c72020-03-10 16:13:48 -0400947 if err != nil {
948 cancel()
khenaidoof5a5bfa2019-01-23 22:20:29 -0500949 return nil, err
950 }
khenaidoo442e7c72020-03-10 16:13:48 -0400951 go agent.waitForAdapterResponse(subCtx, cancel, "downloadImage", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -0500952 }
953 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
954}
955
956// isImageRegistered is a helper method to figure out if an image is already registered
957func isImageRegistered(img *voltha.ImageDownload, device *voltha.Device) bool {
958 for _, image := range device.ImageDownloads {
959 if image.Id == img.Id && image.Name == img.Name {
960 return true
961 }
962 }
963 return false
964}
965
Kent Hagerman2b216042020-04-03 18:28:56 -0400966func (agent *Agent) cancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -0400967 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
968 return nil, err
969 }
970 defer agent.requestQueue.RequestComplete()
971
Girish Kumarf56a4682020-03-20 20:07:46 +0000972 logger.Debugw("cancelImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -0500973
974 device := agent.getDeviceWithoutLock()
975
npujar1d86a522019-11-14 17:11:16 +0530976 // Verify whether the Image is in the list of image being downloaded
977 if !isImageRegistered(img, device) {
khenaidoo442e7c72020-03-10 16:13:48 -0400978 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +0530979 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500980
npujar1d86a522019-11-14 17:11:16 +0530981 // Update image download state
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500982 for _, image := range device.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +0530983 if image.Id == img.Id && image.Name == img.Name {
984 image.DownloadState = voltha.ImageDownload_DOWNLOAD_CANCELLED
khenaidoof5a5bfa2019-01-23 22:20:29 -0500985 }
npujar1d86a522019-11-14 17:11:16 +0530986 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500987
npujar1d86a522019-11-14 17:11:16 +0530988 if device.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
989 // Set the device to Enabled
Kent Hagermand9cc2e92019-11-04 13:28:15 -0500990 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, device, voltha.AdminState_ENABLED, device.ConnectStatus, device.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +0530991 return nil, err
992 }
khenaidoo442e7c72020-03-10 16:13:48 -0400993 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -0400994 ch, err := agent.adapterProxy.CancelImageDownload(subCtx, device, img)
khenaidoo442e7c72020-03-10 16:13:48 -0400995 if err != nil {
996 cancel()
npujar1d86a522019-11-14 17:11:16 +0530997 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -0500998 }
khenaidoo442e7c72020-03-10 16:13:48 -0400999 go agent.waitForAdapterResponse(subCtx, cancel, "cancelImageDownload", ch, agent.onSuccess, agent.onFailure)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001000 }
1001 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001002}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001003
Kent Hagerman2b216042020-04-03 18:28:56 -04001004func (agent *Agent) activateImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001005 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1006 return nil, err
1007 }
1008 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001009 logger.Debugw("activateImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001010 cloned := agent.getDeviceWithoutLock()
1011
npujar1d86a522019-11-14 17:11:16 +05301012 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001013 if !isImageRegistered(img, cloned) {
khenaidoo442e7c72020-03-10 16:13:48 -04001014 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, image-not-registered:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301015 }
1016
khenaidoo6e55d9e2019-12-12 18:26:26 -05001017 if cloned.AdminState == voltha.AdminState_DOWNLOADING_IMAGE {
khenaidoo442e7c72020-03-10 16:13:48 -04001018 return nil, status.Errorf(codes.FailedPrecondition, "device-id:%s, device-in-downloading-state:%s", agent.deviceID, img.Name)
npujar1d86a522019-11-14 17:11:16 +05301019 }
1020 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301021 for _, image := range cloned.ImageDownloads {
1022 if image.Id == img.Id && image.Name == img.Name {
1023 image.ImageState = voltha.ImageDownload_IMAGE_ACTIVATING
1024 }
1025 }
1026 // Set the device to downloading_image
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001027 if err := agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_DOWNLOADING_IMAGE, cloned.ConnectStatus, cloned.OperStatus); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301028 return nil, err
1029 }
1030
khenaidoo442e7c72020-03-10 16:13:48 -04001031 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001032 ch, err := agent.adapterProxy.ActivateImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
khenaidoo442e7c72020-03-10 16:13:48 -04001033 if err != nil {
1034 cancel()
npujar1d86a522019-11-14 17:11:16 +05301035 return nil, err
1036 }
khenaidoo442e7c72020-03-10 16:13:48 -04001037 go agent.waitForAdapterResponse(subCtx, cancel, "activateImageUpdate", ch, agent.onSuccess, agent.onFailure)
1038
npujar1d86a522019-11-14 17:11:16 +05301039 // The status of the AdminState will be changed following the update_download_status response from the adapter
1040 // The image name will also be removed from the device list
serkant.uluderya334479d2019-04-10 08:26:15 -07001041 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
1042}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001043
Kent Hagerman2b216042020-04-03 18:28:56 -04001044func (agent *Agent) revertImage(ctx context.Context, img *voltha.ImageDownload) (*voltha.OperationResp, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001045 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1046 return nil, err
1047 }
1048 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001049 logger.Debugw("revertImage", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001050
1051 cloned := agent.getDeviceWithoutLock()
1052
npujar1d86a522019-11-14 17:11:16 +05301053 // Verify whether the Image is in the list of image being downloaded
khenaidoo6e55d9e2019-12-12 18:26:26 -05001054 if !isImageRegistered(img, cloned) {
npujar1d86a522019-11-14 17:11:16 +05301055 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, image-not-registered:%s", agent.deviceID, img.Name)
1056 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001057
khenaidoo6e55d9e2019-12-12 18:26:26 -05001058 if cloned.AdminState != voltha.AdminState_ENABLED {
npujar1d86a522019-11-14 17:11:16 +05301059 return nil, status.Errorf(codes.FailedPrecondition, "deviceId:%s, device-not-enabled-state:%s", agent.deviceID, img.Name)
1060 }
1061 // Update image download state
npujar1d86a522019-11-14 17:11:16 +05301062 for _, image := range cloned.ImageDownloads {
1063 if image.Id == img.Id && image.Name == img.Name {
1064 image.ImageState = voltha.ImageDownload_IMAGE_REVERTING
khenaidoof5a5bfa2019-01-23 22:20:29 -05001065 }
npujar1d86a522019-11-14 17:11:16 +05301066 }
Mahir Gunyelb5851672019-07-24 10:46:26 +03001067
npujar467fe752020-01-16 20:17:45 +05301068 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301069 return nil, err
1070 }
khenaidoof5a5bfa2019-01-23 22:20:29 -05001071
khenaidoo442e7c72020-03-10 16:13:48 -04001072 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001073 ch, err := agent.adapterProxy.RevertImageUpdate(subCtx, proto.Clone(cloned).(*voltha.Device), img)
khenaidoo442e7c72020-03-10 16:13:48 -04001074 if err != nil {
1075 cancel()
npujar1d86a522019-11-14 17:11:16 +05301076 return nil, err
khenaidoof5a5bfa2019-01-23 22:20:29 -05001077 }
khenaidoo442e7c72020-03-10 16:13:48 -04001078 go agent.waitForAdapterResponse(subCtx, cancel, "revertImageUpdate", ch, agent.onSuccess, agent.onFailure)
1079
khenaidoof5a5bfa2019-01-23 22:20:29 -05001080 return &voltha.OperationResp{Code: voltha.OperationResp_OPERATION_SUCCESS}, nil
serkant.uluderya334479d2019-04-10 08:26:15 -07001081}
khenaidoof5a5bfa2019-01-23 22:20:29 -05001082
Kent Hagerman2b216042020-04-03 18:28:56 -04001083func (agent *Agent) getImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001084 logger.Debugw("getImageDownloadStatus", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001085
khenaidoo442e7c72020-03-10 16:13:48 -04001086 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301087 return nil, err
1088 }
khenaidoo442e7c72020-03-10 16:13:48 -04001089 device := agent.getDeviceWithoutLock()
Kent Hagerman2b216042020-04-03 18:28:56 -04001090 ch, err := agent.adapterProxy.GetImageDownloadStatus(ctx, device, img)
khenaidoo442e7c72020-03-10 16:13:48 -04001091 agent.requestQueue.RequestComplete()
1092 if err != nil {
1093 return nil, err
1094 }
1095 // Wait for the adapter response
1096 rpcResponse, ok := <-ch
1097 if !ok {
1098 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1099 }
1100 if rpcResponse.Err != nil {
1101 return nil, rpcResponse.Err
1102 }
1103 // Successful response
1104 imgDownload := &voltha.ImageDownload{}
1105 if err := ptypes.UnmarshalAny(rpcResponse.Reply, imgDownload); err != nil {
1106 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1107 }
1108 return imgDownload, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001109}
1110
Kent Hagerman2b216042020-04-03 18:28:56 -04001111func (agent *Agent) updateImageDownload(ctx context.Context, img *voltha.ImageDownload) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001112 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1113 return err
1114 }
1115 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001116 logger.Debugw("updating-image-download", log.Fields{"device-id": agent.deviceID, "img": img})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001117
1118 cloned := agent.getDeviceWithoutLock()
1119
npujar1d86a522019-11-14 17:11:16 +05301120 // Update the image as well as remove it if the download was cancelled
npujar1d86a522019-11-14 17:11:16 +05301121 clonedImages := make([]*voltha.ImageDownload, len(cloned.ImageDownloads))
1122 for _, image := range cloned.ImageDownloads {
1123 if image.Id == img.Id && image.Name == img.Name {
1124 if image.DownloadState != voltha.ImageDownload_DOWNLOAD_CANCELLED {
1125 clonedImages = append(clonedImages, img)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001126 }
1127 }
npujar1d86a522019-11-14 17:11:16 +05301128 }
1129 cloned.ImageDownloads = clonedImages
1130 // Set the Admin state to enabled if required
1131 if (img.DownloadState != voltha.ImageDownload_DOWNLOAD_REQUESTED &&
1132 img.DownloadState != voltha.ImageDownload_DOWNLOAD_STARTED) ||
1133 (img.ImageState != voltha.ImageDownload_IMAGE_ACTIVATING) {
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001134 return agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, voltha.AdminState_ENABLED, cloned.ConnectStatus, cloned.OperStatus)
npujar1d86a522019-11-14 17:11:16 +05301135 }
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001136 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoof5a5bfa2019-01-23 22:20:29 -05001137}
1138
Kent Hagerman2b216042020-04-03 18:28:56 -04001139func (agent *Agent) getImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001140 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1141 return nil, err
1142 }
1143 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001144 logger.Debugw("getImageDownload", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001145
1146 cloned := agent.getDeviceWithoutLock()
1147 for _, image := range cloned.ImageDownloads {
npujar1d86a522019-11-14 17:11:16 +05301148 if image.Id == img.Id && image.Name == img.Name {
1149 return image, nil
1150 }
1151 }
1152 return nil, status.Errorf(codes.NotFound, "image-not-found:%s", img.Name)
khenaidoof5a5bfa2019-01-23 22:20:29 -05001153}
1154
Kent Hagerman2b216042020-04-03 18:28:56 -04001155func (agent *Agent) listImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
khenaidoo442e7c72020-03-10 16:13:48 -04001156 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1157 return nil, err
1158 }
1159 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001160 logger.Debugw("listImageDownloads", log.Fields{"device-id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001161
1162 return &voltha.ImageDownloads{Items: agent.getDeviceWithoutLock().ImageDownloads}, nil
khenaidoof5a5bfa2019-01-23 22:20:29 -05001163}
1164
khenaidoo4d4802d2018-10-04 21:59:49 -04001165// getPorts retrieves the ports information of the device based on the port type.
Kent Hagerman2b216042020-04-03 18:28:56 -04001166func (agent *Agent) getPorts(ctx context.Context, portType voltha.Port_PortType) *voltha.Ports {
Girish Kumarf56a4682020-03-20 20:07:46 +00001167 logger.Debugw("getPorts", log.Fields{"device-id": agent.deviceID, "port-type": portType})
khenaidoob9203542018-09-17 22:56:37 -04001168 ports := &voltha.Ports{}
Kent Hagerman45a13e42020-04-13 12:23:50 -04001169 if device, _ := agent.deviceMgr.getDevice(ctx, agent.deviceID); device != nil {
khenaidoob9203542018-09-17 22:56:37 -04001170 for _, port := range device.Ports {
khenaidoo92e62c52018-10-03 14:02:54 -04001171 if port.Type == portType {
khenaidoob9203542018-09-17 22:56:37 -04001172 ports.Items = append(ports.Items, port)
1173 }
1174 }
1175 }
1176 return ports
1177}
1178
khenaidoo442e7c72020-03-10 16:13:48 -04001179// getSwitchCapability retrieves the switch capability of a parent device
Kent Hagerman2b216042020-04-03 18:28:56 -04001180func (agent *Agent) getSwitchCapability(ctx context.Context) (*ic.SwitchCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001181 logger.Debugw("getSwitchCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001182
1183 cloned, err := agent.getDevice(ctx)
1184 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001185 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001186 }
Kent Hagerman2b216042020-04-03 18:28:56 -04001187 ch, err := agent.adapterProxy.GetOfpDeviceInfo(ctx, cloned)
khenaidoo442e7c72020-03-10 16:13:48 -04001188 if err != nil {
1189 return nil, err
1190 }
1191
1192 // Wait for adapter response
1193 rpcResponse, ok := <-ch
1194 if !ok {
1195 return nil, status.Errorf(codes.Aborted, "channel-closed")
1196 }
1197 if rpcResponse.Err != nil {
1198 return nil, rpcResponse.Err
1199 }
1200 // Successful response
1201 switchCap := &ic.SwitchCapability{}
1202 if err := ptypes.UnmarshalAny(rpcResponse.Reply, switchCap); err != nil {
npujar1d86a522019-11-14 17:11:16 +05301203 return nil, err
1204 }
1205 return switchCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001206}
1207
khenaidoo442e7c72020-03-10 16:13:48 -04001208// getPortCapability retrieves the port capability of a device
Kent Hagerman2b216042020-04-03 18:28:56 -04001209func (agent *Agent) getPortCapability(ctx context.Context, portNo uint32) (*ic.PortCapability, error) {
Girish Kumarf56a4682020-03-20 20:07:46 +00001210 logger.Debugw("getPortCapability", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001211 device, err := agent.getDevice(ctx)
1212 if err != nil {
khenaidoob9203542018-09-17 22:56:37 -04001213 return nil, err
khenaidoob9203542018-09-17 22:56:37 -04001214 }
Kent Hagerman2b216042020-04-03 18:28:56 -04001215 ch, err := agent.adapterProxy.GetOfpPortInfo(ctx, device, portNo)
khenaidoo442e7c72020-03-10 16:13:48 -04001216 if err != nil {
npujar1d86a522019-11-14 17:11:16 +05301217 return nil, err
1218 }
khenaidoo442e7c72020-03-10 16:13:48 -04001219 // Wait for adapter response
1220 rpcResponse, ok := <-ch
1221 if !ok {
1222 return nil, status.Errorf(codes.Aborted, "channel-closed")
1223 }
1224 if rpcResponse.Err != nil {
1225 return nil, rpcResponse.Err
1226 }
1227 // Successful response
1228 portCap := &ic.PortCapability{}
1229 if err := ptypes.UnmarshalAny(rpcResponse.Reply, portCap); err != nil {
1230 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1231 }
npujar1d86a522019-11-14 17:11:16 +05301232 return portCap, nil
khenaidoob9203542018-09-17 22:56:37 -04001233}
1234
Kent Hagerman2b216042020-04-03 18:28:56 -04001235func (agent *Agent) onPacketFailure(rpc string, response interface{}, args ...interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -04001236 // packet data is encoded in the args param as the first parameter
1237 var packet []byte
1238 if len(args) >= 1 {
1239 if pkt, ok := args[0].([]byte); ok {
1240 packet = pkt
1241 }
1242 }
1243 var errResp error
1244 if err, ok := response.(error); ok {
1245 errResp = err
1246 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001247 logger.Warnw("packet-out-error", log.Fields{
khenaidoo442e7c72020-03-10 16:13:48 -04001248 "device-id": agent.deviceID,
1249 "error": errResp,
1250 "packet": hex.EncodeToString(packet),
1251 })
1252}
1253
Kent Hagerman2b216042020-04-03 18:28:56 -04001254func (agent *Agent) packetOut(ctx context.Context, outPort uint32, packet *ofp.OfpPacketOut) error {
Scott Baker80678602019-11-14 16:57:36 -08001255 // If deviceType=="" then we must have taken ownership of this device.
1256 // Fixes VOL-2226 where a core would take ownership and have stale data
1257 if agent.deviceType == "" {
npujar467fe752020-01-16 20:17:45 +05301258 agent.reconcileWithKVStore(ctx)
Scott Baker80678602019-11-14 16:57:36 -08001259 }
khenaidoofdbad6e2018-11-06 22:26:38 -05001260 // Send packet to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001261 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001262 ch, err := agent.adapterProxy.PacketOut(subCtx, agent.deviceType, agent.deviceID, outPort, packet)
khenaidoo442e7c72020-03-10 16:13:48 -04001263 if err != nil {
1264 cancel()
1265 return nil
khenaidoofdbad6e2018-11-06 22:26:38 -05001266 }
khenaidoo442e7c72020-03-10 16:13:48 -04001267 go agent.waitForAdapterResponse(subCtx, cancel, "packetOut", ch, agent.onSuccess, agent.onPacketFailure, packet.Data)
khenaidoofdbad6e2018-11-06 22:26:38 -05001268 return nil
1269}
1270
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001271// updatePartialDeviceData updates a subset of a device that an Adapter can update.
1272// 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 -04001273func (agent *Agent) mergeDeviceInfoFromAdapter(device *voltha.Device) (*voltha.Device, error) {
khenaidoo6e55d9e2019-12-12 18:26:26 -05001274 cloned := agent.getDeviceWithoutLock()
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001275 cloned.Root = device.Root
1276 cloned.Vendor = device.Vendor
1277 cloned.Model = device.Model
1278 cloned.SerialNumber = device.SerialNumber
1279 cloned.MacAddress = device.MacAddress
1280 cloned.Vlan = device.Vlan
1281 cloned.Reason = device.Reason
1282 return cloned, nil
1283}
khenaidoo442e7c72020-03-10 16:13:48 -04001284
Kent Hagerman2b216042020-04-03 18:28:56 -04001285func (agent *Agent) updateDeviceUsingAdapterData(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001286 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1287 return err
1288 }
1289 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001290 logger.Debugw("updateDeviceUsingAdapterData", log.Fields{"device-id": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001291
npujar1d86a522019-11-14 17:11:16 +05301292 updatedDevice, err := agent.mergeDeviceInfoFromAdapter(device)
1293 if err != nil {
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001294 return status.Errorf(codes.Internal, "%s", err.Error())
Mahir Gunyel8e2707d2019-07-25 00:36:21 -07001295 }
npujar1d86a522019-11-14 17:11:16 +05301296 cloned := proto.Clone(updatedDevice).(*voltha.Device)
npujar467fe752020-01-16 20:17:45 +05301297 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo43c82122018-11-22 18:38:28 -05001298}
1299
Kent Hagerman2b216042020-04-03 18:28:56 -04001300func (agent *Agent) updateDeviceWithoutLock(ctx context.Context, device *voltha.Device) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001301 logger.Debugw("updateDevice", log.Fields{"deviceId": device.Id})
khenaidoo442e7c72020-03-10 16:13:48 -04001302 //cloned := proto.Clone(device).(*voltha.Device)
1303 cloned := device
npujar467fe752020-01-16 20:17:45 +05301304 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001305}
1306
Kent Hagerman2b216042020-04-03 18:28:56 -04001307func (agent *Agent) updateDeviceStatus(ctx context.Context, operStatus voltha.OperStatus_Types, connStatus voltha.ConnectStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001308 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1309 return err
1310 }
1311 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001312
1313 cloned := agent.getDeviceWithoutLock()
1314
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001315 newConnStatus, newOperStatus := cloned.ConnectStatus, cloned.OperStatus
npujar1d86a522019-11-14 17:11:16 +05301316 // 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 -08001317 if s, ok := voltha.ConnectStatus_Types_value[connStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001318 logger.Debugw("updateDeviceStatus-conn", log.Fields{"ok": ok, "val": s})
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001319 newConnStatus = connStatus
npujar1d86a522019-11-14 17:11:16 +05301320 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -08001321 if s, ok := voltha.OperStatus_Types_value[operStatus.String()]; ok {
Girish Kumarf56a4682020-03-20 20:07:46 +00001322 logger.Debugw("updateDeviceStatus-oper", log.Fields{"ok": ok, "val": s})
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001323 newOperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301324 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001325 logger.Debugw("updateDeviceStatus", log.Fields{"deviceId": cloned.Id, "operStatus": cloned.OperStatus, "connectStatus": cloned.ConnectStatus})
npujar1d86a522019-11-14 17:11:16 +05301326 // Store the device
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001327 return agent.updateDeviceStateInStoreWithoutLock(ctx, cloned, cloned.AdminState, newConnStatus, newOperStatus)
khenaidoo92e62c52018-10-03 14:02:54 -04001328}
1329
Kent Hagerman2b216042020-04-03 18:28:56 -04001330func (agent *Agent) updatePortsOperState(ctx context.Context, operStatus voltha.OperStatus_Types) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001331 logger.Debugw("updatePortsOperState", log.Fields{"device-id": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001332 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1333 return err
1334 }
1335 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001336 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301337 for _, port := range cloned.Ports {
kesavandbc2d1622020-01-21 00:42:01 -05001338 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301339 }
1340 // Store the device
npujar467fe752020-01-16 20:17:45 +05301341 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo3ab34882019-05-02 21:33:30 -04001342}
1343
Kent Hagerman2b216042020-04-03 18:28:56 -04001344func (agent *Agent) updatePortState(ctx context.Context, portType voltha.Port_PortType, portNo uint32, operStatus voltha.OperStatus_Types) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001345 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1346 return err
1347 }
1348 defer agent.requestQueue.RequestComplete()
khenaidoo92e62c52018-10-03 14:02:54 -04001349 // Work only on latest data
1350 // TODO: Get list of ports from device directly instead of the entire device
khenaidoo6e55d9e2019-12-12 18:26:26 -05001351 cloned := agent.getDeviceWithoutLock()
1352
npujar1d86a522019-11-14 17:11:16 +05301353 // Ensure the enums passed in are valid - they will be invalid if they are not set when this function is invoked
1354 if _, ok := voltha.Port_PortType_value[portType.String()]; !ok {
1355 return status.Errorf(codes.InvalidArgument, "%s", portType)
1356 }
1357 for _, port := range cloned.Ports {
1358 if port.Type == portType && port.PortNo == portNo {
1359 port.OperStatus = operStatus
npujar1d86a522019-11-14 17:11:16 +05301360 }
1361 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001362 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301363 // Store the device
npujar467fe752020-01-16 20:17:45 +05301364 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001365}
1366
Kent Hagerman2b216042020-04-03 18:28:56 -04001367func (agent *Agent) deleteAllPorts(ctx context.Context) error {
Girish Kumarf56a4682020-03-20 20:07:46 +00001368 logger.Debugw("deleteAllPorts", log.Fields{"deviceId": agent.deviceID})
khenaidoo442e7c72020-03-10 16:13:48 -04001369 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1370 return err
1371 }
1372 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001373
1374 cloned := agent.getDeviceWithoutLock()
1375
1376 if cloned.AdminState != voltha.AdminState_DISABLED && cloned.AdminState != voltha.AdminState_DELETED {
1377 err := status.Error(codes.FailedPrecondition, fmt.Sprintf("invalid-state-%v", cloned.AdminState))
Girish Kumarf56a4682020-03-20 20:07:46 +00001378 logger.Warnw("invalid-state-removing-ports", log.Fields{"state": cloned.AdminState, "error": err})
npujar1d86a522019-11-14 17:11:16 +05301379 return err
1380 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001381 if len(cloned.Ports) == 0 {
Girish Kumarf56a4682020-03-20 20:07:46 +00001382 logger.Debugw("no-ports-present", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301383 return nil
1384 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001385
npujar1d86a522019-11-14 17:11:16 +05301386 cloned.Ports = []*voltha.Port{}
Girish Kumarf56a4682020-03-20 20:07:46 +00001387 logger.Debugw("portStatusUpdate", log.Fields{"deviceId": cloned.Id})
npujar1d86a522019-11-14 17:11:16 +05301388 // Store the device
npujar467fe752020-01-16 20:17:45 +05301389 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo0a822f92019-05-08 15:15:57 -04001390}
1391
Kent Hagerman2b216042020-04-03 18:28:56 -04001392func (agent *Agent) addPort(ctx context.Context, port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001393 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1394 return err
1395 }
1396 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001397 logger.Debugw("addPort", log.Fields{"deviceId": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001398
1399 cloned := agent.getDeviceWithoutLock()
khenaidoo80b987d2020-02-20 10:52:52 -05001400 updatePort := false
npujar1d86a522019-11-14 17:11:16 +05301401 if cloned.Ports == nil {
1402 // First port
Girish Kumarf56a4682020-03-20 20:07:46 +00001403 logger.Debugw("addPort-first-port-to-add", log.Fields{"deviceId": agent.deviceID})
npujar1d86a522019-11-14 17:11:16 +05301404 cloned.Ports = make([]*voltha.Port, 0)
khenaidoob9203542018-09-17 22:56:37 -04001405 } else {
npujar1d86a522019-11-14 17:11:16 +05301406 for _, p := range cloned.Ports {
1407 if p.Type == port.Type && p.PortNo == port.PortNo {
khenaidoo80b987d2020-02-20 10:52:52 -05001408 if p.Label == "" && p.Type == voltha.Port_PON_OLT {
1409 //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 +00001410 logger.Infow("update-pon-port-created-by-default", log.Fields{"default-port": p, "port-to-add": port})
khenaidoo80b987d2020-02-20 10:52:52 -05001411 p.Label = port.Label
1412 p.OperStatus = port.OperStatus
1413 updatePort = true
1414 break
1415 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001416 logger.Debugw("port already exists", log.Fields{"port": port})
npujar1d86a522019-11-14 17:11:16 +05301417 return nil
manikkaraj k259a6f72019-05-06 09:55:44 -04001418 }
khenaidoob9203542018-09-17 22:56:37 -04001419 }
khenaidoo92e62c52018-10-03 14:02:54 -04001420 }
khenaidoo80b987d2020-02-20 10:52:52 -05001421 if !updatePort {
1422 cp := proto.Clone(port).(*voltha.Port)
1423 // Set the admin state of the port to ENABLE
1424 cp.AdminState = voltha.AdminState_ENABLED
1425 cloned.Ports = append(cloned.Ports, cp)
1426 }
npujar1d86a522019-11-14 17:11:16 +05301427 // Store the device
npujar467fe752020-01-16 20:17:45 +05301428 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoo92e62c52018-10-03 14:02:54 -04001429}
1430
Kent Hagerman2b216042020-04-03 18:28:56 -04001431func (agent *Agent) addPeerPort(ctx context.Context, peerPort *voltha.Port_PeerPort) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001432 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1433 return err
1434 }
1435 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001436 logger.Debugw("adding-peer-peerPort", log.Fields{"device-id": agent.deviceID, "peer-peerPort": peerPort})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001437
1438 cloned := agent.getDeviceWithoutLock()
1439
khenaidoo80b987d2020-02-20 10:52:52 -05001440 // Get the peer port on the device based on the peerPort no
1441 found := false
1442 for _, port := range cloned.Ports {
1443 if port.PortNo == peerPort.PortNo { // found peerPort
1444 cp := proto.Clone(peerPort).(*voltha.Port_PeerPort)
1445 port.Peers = append(port.Peers, cp)
Girish Kumarf56a4682020-03-20 20:07:46 +00001446 logger.Debugw("found-peer", log.Fields{"device-id": agent.deviceID, "portNo": peerPort.PortNo, "deviceId": agent.deviceID})
khenaidoo80b987d2020-02-20 10:52:52 -05001447 found = true
npujar1d86a522019-11-14 17:11:16 +05301448 break
1449 }
1450 }
khenaidoo80b987d2020-02-20 10:52:52 -05001451 if !found && agent.isRootdevice {
1452 // An ONU PON port has been created before the corresponding creation of the OLT PON port. Create the OLT PON port
1453 // with default values which will be updated once the OLT PON port creation is processed.
1454 ponPort := &voltha.Port{
1455 PortNo: peerPort.PortNo,
1456 Type: voltha.Port_PON_OLT,
1457 AdminState: voltha.AdminState_ENABLED,
1458 DeviceId: agent.deviceID,
1459 Peers: []*voltha.Port_PeerPort{proto.Clone(peerPort).(*voltha.Port_PeerPort)},
1460 }
1461 cloned.Ports = append(cloned.Ports, ponPort)
Girish Kumarf56a4682020-03-20 20:07:46 +00001462 logger.Infow("adding-default-pon-port", log.Fields{"device-id": agent.deviceID, "peer": peerPort, "pon-port": ponPort})
khenaidoo80b987d2020-02-20 10:52:52 -05001463 }
npujar1d86a522019-11-14 17:11:16 +05301464 // Store the device
npujar467fe752020-01-16 20:17:45 +05301465 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
khenaidoob9203542018-09-17 22:56:37 -04001466}
1467
1468// TODO: A generic device update by attribute
Kent Hagerman2b216042020-04-03 18:28:56 -04001469func (agent *Agent) updateDeviceAttribute(ctx context.Context, name string, value interface{}) {
khenaidoo442e7c72020-03-10 16:13:48 -04001470 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001471 logger.Warnw("request-aborted", log.Fields{"device-id": agent.deviceID, "name": name, "error": err})
khenaidoo442e7c72020-03-10 16:13:48 -04001472 return
1473 }
1474 defer agent.requestQueue.RequestComplete()
khenaidoob9203542018-09-17 22:56:37 -04001475 if value == nil {
1476 return
1477 }
khenaidoo6e55d9e2019-12-12 18:26:26 -05001478
1479 cloned := agent.getDeviceWithoutLock()
khenaidoob9203542018-09-17 22:56:37 -04001480 updated := false
khenaidoo6e55d9e2019-12-12 18:26:26 -05001481 s := reflect.ValueOf(cloned).Elem()
khenaidoob9203542018-09-17 22:56:37 -04001482 if s.Kind() == reflect.Struct {
1483 // exported field
1484 f := s.FieldByName(name)
1485 if f.IsValid() && f.CanSet() {
1486 switch f.Kind() {
1487 case reflect.String:
1488 f.SetString(value.(string))
1489 updated = true
1490 case reflect.Uint32:
1491 f.SetUint(uint64(value.(uint32)))
1492 updated = true
1493 case reflect.Bool:
1494 f.SetBool(value.(bool))
1495 updated = true
1496 }
1497 }
1498 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001499 logger.Debugw("update-field-status", log.Fields{"deviceId": cloned.Id, "name": name, "updated": updated})
khenaidoob9203542018-09-17 22:56:37 -04001500 // Save the data
khenaidoo6e55d9e2019-12-12 18:26:26 -05001501
npujar467fe752020-01-16 20:17:45 +05301502 if err := agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001503 logger.Warnw("attribute-update-failed", log.Fields{"attribute": name, "value": value})
khenaidoob9203542018-09-17 22:56:37 -04001504 }
khenaidoob9203542018-09-17 22:56:37 -04001505}
serkant.uluderya334479d2019-04-10 08:26:15 -07001506
Kent Hagerman45a13e42020-04-13 12:23:50 -04001507func (agent *Agent) simulateAlarm(ctx context.Context, simulateReq *voltha.SimulateAlarmRequest) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001508 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1509 return err
1510 }
1511 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001512 logger.Debugw("simulateAlarm", log.Fields{"id": agent.deviceID})
khenaidoo6e55d9e2019-12-12 18:26:26 -05001513
1514 cloned := agent.getDeviceWithoutLock()
1515
khenaidoo442e7c72020-03-10 16:13:48 -04001516 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman45a13e42020-04-13 12:23:50 -04001517 ch, err := agent.adapterProxy.SimulateAlarm(subCtx, cloned, simulateReq)
khenaidoo442e7c72020-03-10 16:13:48 -04001518 if err != nil {
1519 cancel()
npujar1d86a522019-11-14 17:11:16 +05301520 return err
serkant.uluderya334479d2019-04-10 08:26:15 -07001521 }
khenaidoo442e7c72020-03-10 16:13:48 -04001522 go agent.waitForAdapterResponse(subCtx, cancel, "simulateAlarm", ch, agent.onSuccess, agent.onFailure)
serkant.uluderya334479d2019-04-10 08:26:15 -07001523 return nil
1524}
Mahir Gunyelb5851672019-07-24 10:46:26 +03001525
Kent Hagerman2b216042020-04-03 18:28:56 -04001526func (agent *Agent) updateDeviceStateInStoreWithoutLock(
Kent Hagermand9cc2e92019-11-04 13:28:15 -05001527 ctx context.Context,
1528 device *voltha.Device,
1529 adminState voltha.AdminState_Types,
1530 connectStatus voltha.ConnectStatus_Types,
1531 operStatus voltha.OperStatus_Types,
1532) error {
1533 previousState := getDeviceStates(device)
1534 device.AdminState, device.ConnectStatus, device.OperStatus = adminState, connectStatus, operStatus
1535
1536 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
1537 return err
1538 }
1539
1540 // process state transition in its own thread
1541 go func() {
1542 if err := agent.deviceMgr.processTransition(context.Background(), device, previousState); err != nil {
1543 log.Errorw("failed-process-transition", log.Fields{"deviceId": device.Id, "previousAdminState": previousState.Admin, "currentAdminState": device.AdminState})
1544 }
1545 }()
1546 return nil
1547}
1548
Mahir Gunyelb5851672019-07-24 10:46:26 +03001549//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.
1550// It is an internal helper function.
Kent Hagerman2b216042020-04-03 18:28:56 -04001551func (agent *Agent) updateDeviceInStoreWithoutLock(ctx context.Context, device *voltha.Device, strict bool, txid string) error {
Kent Hagerman4f355f52020-03-30 16:01:33 -04001552 if agent.stopped {
1553 return errors.New("device agent stopped")
Thomas Lee Se5a44012019-11-07 20:32:24 +05301554 }
Kent Hagerman4f355f52020-03-30 16:01:33 -04001555
1556 updateCtx := context.WithValue(ctx, model.RequestTimestamp, time.Now().UnixNano())
1557 if err := agent.clusterDataProxy.Update(updateCtx, "devices/"+agent.deviceID, device); err != nil {
1558 return status.Errorf(codes.Internal, "failed-update-device:%s: %s", agent.deviceID, err)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001559 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001560 logger.Debugw("updated-device-in-store", log.Fields{"deviceId: ": agent.deviceID})
Mahir Gunyelb5851672019-07-24 10:46:26 +03001561
khenaidoo6e55d9e2019-12-12 18:26:26 -05001562 agent.device = proto.Clone(device).(*voltha.Device)
Mahir Gunyelb5851672019-07-24 10:46:26 +03001563 return nil
1564}
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001565
Kent Hagerman2b216042020-04-03 18:28:56 -04001566func (agent *Agent) updateDeviceReason(ctx context.Context, reason string) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001567 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1568 return err
1569 }
1570 defer agent.requestQueue.RequestComplete()
khenaidoo6e55d9e2019-12-12 18:26:26 -05001571
1572 cloned := agent.getDeviceWithoutLock()
npujar1d86a522019-11-14 17:11:16 +05301573 cloned.Reason = reason
Girish Kumarf56a4682020-03-20 20:07:46 +00001574 logger.Debugw("updateDeviceReason", log.Fields{"deviceId": cloned.Id, "reason": cloned.Reason})
npujar1d86a522019-11-14 17:11:16 +05301575 // Store the device
npujar467fe752020-01-16 20:17:45 +05301576 return agent.updateDeviceInStoreWithoutLock(ctx, cloned, false, "")
Mahir Gunyelfdee9212019-10-16 16:52:21 -07001577}
kesavandbc2d1622020-01-21 00:42:01 -05001578
Kent Hagerman2b216042020-04-03 18:28:56 -04001579func (agent *Agent) disablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001580 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1581 return err
1582 }
1583 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001584 logger.Debugw("disablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001585 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001586 // Get the most up to date the device info
1587 device := agent.getDeviceWithoutLock()
1588 for _, port := range device.Ports {
1589 if port.PortNo == Port.PortNo {
1590 port.AdminState = voltha.AdminState_DISABLED
1591 cp = proto.Clone(port).(*voltha.Port)
1592 break
1593
1594 }
1595 }
1596 if cp == nil {
1597 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1598 }
1599
1600 if cp.Type != voltha.Port_PON_OLT {
1601 return status.Errorf(codes.InvalidArgument, "Disabling of Port Type %v unimplemented", cp.Type)
1602 }
1603 // Store the device
1604 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001605 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001606 return err
1607 }
khenaidoo442e7c72020-03-10 16:13:48 -04001608
kesavandbc2d1622020-01-21 00:42:01 -05001609 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001610 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001611 ch, err := agent.adapterProxy.DisablePort(ctx, device, cp)
khenaidoo442e7c72020-03-10 16:13:48 -04001612 if err != nil {
1613 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001614 return err
1615 }
khenaidoo442e7c72020-03-10 16:13:48 -04001616 go agent.waitForAdapterResponse(subCtx, cancel, "disablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001617 return nil
1618}
1619
Kent Hagerman2b216042020-04-03 18:28:56 -04001620func (agent *Agent) enablePort(ctx context.Context, Port *voltha.Port) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001621 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1622 return err
1623 }
1624 defer agent.requestQueue.RequestComplete()
Girish Kumarf56a4682020-03-20 20:07:46 +00001625 logger.Debugw("enablePort", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo})
khenaidoo442e7c72020-03-10 16:13:48 -04001626
1627 var cp *voltha.Port
kesavandbc2d1622020-01-21 00:42:01 -05001628 // Get the most up to date the device info
1629 device := agent.getDeviceWithoutLock()
1630 for _, port := range device.Ports {
1631 if port.PortNo == Port.PortNo {
1632 port.AdminState = voltha.AdminState_ENABLED
1633 cp = proto.Clone(port).(*voltha.Port)
1634 break
1635 }
1636 }
1637
1638 if cp == nil {
1639 return status.Errorf(codes.InvalidArgument, "%v", Port.PortNo)
1640 }
1641
1642 if cp.Type != voltha.Port_PON_OLT {
1643 return status.Errorf(codes.InvalidArgument, "Enabling of Port Type %v unimplemented", cp.Type)
1644 }
1645 // Store the device
1646 if err := agent.updateDeviceInStoreWithoutLock(ctx, device, false, ""); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +00001647 logger.Debugw("updateDeviceInStoreWithoutLock error ", log.Fields{"device-id": agent.deviceID, "port-no": Port.PortNo, "error": err})
kesavandbc2d1622020-01-21 00:42:01 -05001648 return err
1649 }
1650 //send request to adapter
khenaidoo442e7c72020-03-10 16:13:48 -04001651 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001652 ch, err := agent.adapterProxy.EnablePort(ctx, device, cp)
khenaidoo442e7c72020-03-10 16:13:48 -04001653 if err != nil {
1654 cancel()
kesavandbc2d1622020-01-21 00:42:01 -05001655 return err
1656 }
khenaidoo442e7c72020-03-10 16:13:48 -04001657 go agent.waitForAdapterResponse(subCtx, cancel, "enablePort", ch, agent.onSuccess, agent.onFailure)
kesavandbc2d1622020-01-21 00:42:01 -05001658 return nil
1659}
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001660
Kent Hagerman2b216042020-04-03 18:28:56 -04001661func (agent *Agent) ChildDeviceLost(ctx context.Context, device *voltha.Device) error {
khenaidoo442e7c72020-03-10 16:13:48 -04001662 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1663 return err
1664 }
1665 defer agent.requestQueue.RequestComplete()
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001666
Girish Kumarf56a4682020-03-20 20:07:46 +00001667 logger.Debugw("childDeviceLost", log.Fields{"child-device-id": device.Id, "parent-device-ud": agent.deviceID})
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001668
1669 //Remove the associated peer ports on the parent device
khenaidoo442e7c72020-03-10 16:13:48 -04001670 parentDevice := agent.getDeviceWithoutLock()
1671 var updatedPeers []*voltha.Port_PeerPort
1672 for _, port := range parentDevice.Ports {
1673 updatedPeers = make([]*voltha.Port_PeerPort, 0)
1674 for _, peerPort := range port.Peers {
1675 if peerPort.DeviceId != device.Id {
1676 updatedPeers = append(updatedPeers, peerPort)
1677 }
1678 }
1679 port.Peers = updatedPeers
1680 }
1681 if err := agent.updateDeviceInStoreWithoutLock(ctx, parentDevice, false, ""); err != nil {
1682 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001683 }
1684
khenaidoo442e7c72020-03-10 16:13:48 -04001685 //send request to adapter
1686 subCtx, cancel := context.WithTimeout(context.Background(), agent.defaultTimeout)
Kent Hagerman2b216042020-04-03 18:28:56 -04001687 ch, err := agent.adapterProxy.ChildDeviceLost(ctx, agent.deviceType, agent.deviceID, device.ParentPortNo, device.ProxyAddress.OnuId)
khenaidoo442e7c72020-03-10 16:13:48 -04001688 if err != nil {
1689 cancel()
1690 return err
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001691 }
khenaidoo442e7c72020-03-10 16:13:48 -04001692 go agent.waitForAdapterResponse(subCtx, cancel, "childDeviceLost", ch, agent.onSuccess, agent.onFailure)
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001693 return nil
Chaitrashree G S543df3e2020-02-24 22:36:54 -05001694}
onkarkundargi87285252020-01-27 11:34:52 +05301695
Kent Hagerman2b216042020-04-03 18:28:56 -04001696func (agent *Agent) startOmciTest(ctx context.Context, omcitestrequest *voltha.OmciTestRequest) (*voltha.TestResponse, error) {
onkarkundargi87285252020-01-27 11:34:52 +05301697 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1698 return nil, err
1699 }
1700
1701 device := agent.getDeviceWithoutLock()
Matteo Scandolod525ae32020-04-02 17:27:29 -07001702
1703 if device.Adapter == "" {
Kent Hagerman2b216042020-04-03 18:28:56 -04001704 adapterName, err := agent.adapterMgr.GetAdapterType(device.Type)
Matteo Scandolod525ae32020-04-02 17:27:29 -07001705 if err != nil {
1706 agent.requestQueue.RequestComplete()
1707 return nil, err
1708 }
Matteo Scandolod525ae32020-04-02 17:27:29 -07001709 device.Adapter = adapterName
onkarkundargi87285252020-01-27 11:34:52 +05301710 }
1711
1712 // Send request to the adapter
Kent Hagerman2b216042020-04-03 18:28:56 -04001713 ch, err := agent.adapterProxy.StartOmciTest(ctx, device, omcitestrequest)
onkarkundargi87285252020-01-27 11:34:52 +05301714 agent.requestQueue.RequestComplete()
1715 if err != nil {
1716 return nil, err
1717 }
1718
1719 // Wait for the adapter response
1720 rpcResponse, ok := <-ch
1721 if !ok {
1722 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1723 }
1724 if rpcResponse.Err != nil {
1725 return nil, rpcResponse.Err
1726 }
1727
1728 // Unmarshal and return the response
1729 testResp := &voltha.TestResponse{}
1730 if err := ptypes.UnmarshalAny(rpcResponse.Reply, testResp); err != nil {
1731 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1732 }
Girish Kumarf56a4682020-03-20 20:07:46 +00001733 logger.Debugw("Omci_test_Request-Success-device-agent", log.Fields{"testResp": testResp})
onkarkundargi87285252020-01-27 11:34:52 +05301734 return testResp, nil
1735}
Dinesh Belwalkarc1129f12020-02-27 10:41:33 -08001736
1737func (agent *Agent) getExtValue(ctx context.Context, pdevice *voltha.Device, cdevice *voltha.Device, valueparam *voltha.ValueSpecifier) (*voltha.ReturnValues, error) {
1738 log.Debugw("getExtValue", log.Fields{"device-id": agent.deviceID, "onuid": valueparam.Id, "valuetype": valueparam.Value})
1739 if err := agent.requestQueue.WaitForGreenLight(ctx); err != nil {
1740 return nil, err
1741 }
1742
1743 //send request to adapter
1744 ch, err := agent.adapterProxy.GetExtValue(ctx, pdevice, cdevice, valueparam.Id, valueparam.Value)
1745 agent.requestQueue.RequestComplete()
1746 if err != nil {
1747 return nil, err
1748 }
1749
1750 // Wait for the adapter response
1751 rpcResponse, ok := <-ch
1752 if !ok {
1753 return nil, status.Errorf(codes.Aborted, "channel-closed-device-id-%s", agent.deviceID)
1754 }
1755 if rpcResponse.Err != nil {
1756 return nil, rpcResponse.Err
1757 }
1758
1759 // Unmarshal and return the response
1760 Resp := &voltha.ReturnValues{}
1761 if err := ptypes.UnmarshalAny(rpcResponse.Reply, Resp); err != nil {
1762 return nil, status.Errorf(codes.InvalidArgument, "%s", err.Error())
1763 }
1764 logger.Debugw("getExtValue-Success-device-agent", log.Fields{"Resp": Resp})
1765 return Resp, nil
1766}