blob: 23ba459fae3f4d4bedffc676daae5d587a710438 [file] [log] [blame]
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301/*
Joey Armstronga6af1522023-01-17 16:06:16 -05002 * Copyright 2018-2023 Open Networking Foundation (ONF) and the ONF Contributors
Phaneendra Manda4c62c802019-03-06 21:37:49 +05303
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 */
Girish Gowdru6a80bbd2019-07-02 07:36:09 -070016
Mahir Gunyela2e68702022-12-07 00:00:42 -080017// Package core provides the utility for olt devices, flows and statistics
Scott Bakerdbd960e2020-02-28 08:57:51 -080018package core
Phaneendra Manda4c62c802019-03-06 21:37:49 +053019
20import (
cuilin20187b2a8c32019-03-26 19:52:28 -070021 "context"
Matt Jeanneretceea2e02020-03-27 14:19:57 -040022 "encoding/binary"
Matt Jeanneret1359c732019-08-01 21:40:02 -040023 "encoding/hex"
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053024 "encoding/json"
Girish Gowdra491a9c62021-01-06 16:43:07 -080025 "errors"
cuilin20187b2a8c32019-03-26 19:52:28 -070026 "fmt"
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -040027 "net"
cuilin20187b2a8c32019-03-26 19:52:28 -070028 "strconv"
29 "strings"
30 "sync"
31 "time"
Phaneendra Manda4c62c802019-03-06 21:37:49 +053032
Elia Battiston599d25f2022-02-16 14:49:08 +010033 "github.com/opencord/voltha-lib-go/v7/pkg/db"
34 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
35
khenaidoo106c61a2021-08-11 18:05:46 -040036 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
khenaidoo106c61a2021-08-11 18:05:46 -040037
Matteo Scandolo945e4012019-12-12 14:16:11 -080038 "github.com/cenkalti/backoff/v3"
cuilin20187b2a8c32019-03-26 19:52:28 -070039 "github.com/gogo/protobuf/proto"
Girish Kumar93e91742020-07-27 16:43:19 +000040 grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
41 grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
khenaidoo106c61a2021-08-11 18:05:46 -040042 "github.com/opencord/voltha-lib-go/v7/pkg/config"
43 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
44 flow_utils "github.com/opencord/voltha-lib-go/v7/pkg/flows"
45 "github.com/opencord/voltha-lib-go/v7/pkg/log"
Mahir Gunyel85f61c12021-10-06 11:53:45 -070046 plt "github.com/opencord/voltha-lib-go/v7/pkg/platform"
khenaidoo106c61a2021-08-11 18:05:46 -040047 "github.com/opencord/voltha-lib-go/v7/pkg/pmmetrics"
Matteo Scandolodfa7a972020-11-06 13:03:40 -080048
nikesh.krishnand9812542023-08-01 18:31:39 +053049 grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
khenaidoo106c61a2021-08-11 18:05:46 -040050 conf "github.com/opencord/voltha-openolt-adapter/internal/pkg/config"
Thomas Lee S94109f12020-03-03 16:39:29 +053051 "github.com/opencord/voltha-openolt-adapter/internal/pkg/olterrors"
Scott Bakerdbd960e2020-02-28 08:57:51 -080052 rsrcMgr "github.com/opencord/voltha-openolt-adapter/internal/pkg/resourcemanager"
khenaidoo106c61a2021-08-11 18:05:46 -040053 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoodc2116e2021-10-19 17:33:19 -040054 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo106c61a2021-08-11 18:05:46 -040055 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoodc2116e2021-10-19 17:33:19 -040056 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
57 "github.com/opencord/voltha-protos/v5/go/onu_inter_adapter_service"
khenaidoo106c61a2021-08-11 18:05:46 -040058 of "github.com/opencord/voltha-protos/v5/go/openflow_13"
59 oop "github.com/opencord/voltha-protos/v5/go/openolt"
60 "github.com/opencord/voltha-protos/v5/go/voltha"
cuilin20187b2a8c32019-03-26 19:52:28 -070061 "google.golang.org/grpc"
nikesh.krishnand9812542023-08-01 18:31:39 +053062 codes "google.golang.org/grpc/codes"
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040063 "google.golang.org/grpc/status"
Phaneendra Manda4c62c802019-03-06 21:37:49 +053064)
65
salmansiddiqui7ac62132019-08-22 03:58:50 +000066// Constants for number of retries and for timeout
Manikkaraj kb1d51442019-07-23 10:41:02 -040067const (
Girish Gowdra491a9c62021-01-06 16:43:07 -080068 InvalidPort = 0xffffffff
69 MaxNumOfGroupHandlerChannels = 256
70
71 McastFlowOrGroupAdd = "McastFlowOrGroupAdd"
72 McastFlowOrGroupModify = "McastFlowOrGroupModify"
73 McastFlowOrGroupRemove = "McastFlowOrGroupRemove"
kesavand62126212021-01-12 04:56:06 -050074 oltPortInfoTimeout = 3
Elia Battiston596406d2022-02-02 12:19:00 +010075
76 defaultPortSpeedMbps = 1000
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053077 heartbeatPath = "heartbeat"
Manikkaraj kb1d51442019-07-23 10:41:02 -040078)
79
Mahir Gunyela2e68702022-12-07 00:00:42 -080080// DeviceHandler will interact with the OLT device.
Phaneendra Manda4c62c802019-03-06 21:37:49 +053081type DeviceHandler struct {
khenaidoo106c61a2021-08-11 18:05:46 -040082 cm *config.ConfigManager
83 device *voltha.Device
84 cfg *conf.AdapterFlags
85 coreClient *vgrpc.Client
86 childAdapterClients map[string]*vgrpc.Client
87 lockChildAdapterClients sync.RWMutex
88 EventProxy eventif.EventProxy
89 openOLT *OpenOLT
khenaidooefff76e2021-12-15 16:51:30 -050090 exitChannel chan struct{}
khenaidoo106c61a2021-08-11 18:05:46 -040091 lockDevice sync.RWMutex
92 Client oop.OpenoltClient
93 transitionMap *TransitionMap
94 clientCon *grpc.ClientConn
95 flowMgr []*OpenOltFlowMgr
96 groupMgr *OpenOltGroupMgr
97 eventMgr *OpenOltEventMgr
98 resourceMgr []*rsrcMgr.OpenOltResourceMgr
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053099 kvStore *db.Backend // backend kv store connection handle
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700100
101 deviceInfo *oop.DeviceInfo
Naga Manjunatha8dc9372019-10-31 23:01:18 +0530102
Matteo Scandolo7eaec532022-06-23 15:54:57 -0700103 // discOnus (map[onuSn]bool) contains a list of ONUs that have been discovered, indexed by ONU SerialNumber.
104 // if the value is true that means the OnuDiscovery indication
105 // is currently being processed and thus we can ignore concurrent requests
106 // if it's false it means the processing has completed and we shouldn't be receiving a new indication
107 // if we do it means something went wrong and we need to retry
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700108 discOnus sync.Map
109 onus sync.Map
110 portStats *OpenOltStatisticsMgr
111 metrics *pmmetrics.PmMetrics
112 stopCollector chan bool
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000113 isCollectorActive bool
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700114 stopHeartbeatCheck chan bool
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000115 isHeartbeatCheckActive bool
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700116 activePorts sync.Map
117 stopIndications chan bool
118 isReadIndicationRoutineActive bool
Girish Gowdracefae192020-03-19 18:14:10 -0700119
Mahir Gunyelb0046752021-02-26 13:51:05 -0800120 totalPonPorts uint32
121 perPonOnuIndicationChannel map[uint32]onuIndicationChannels
122 perPonOnuIndicationChannelLock sync.Mutex
Girish Gowdra491a9c62021-01-06 16:43:07 -0800123
124 // Slice of channels. Each channel in slice, index by (mcast-group-id modulo MaxNumOfGroupHandlerChannels)
125 // A go routine per index, waits on a unique channel for incoming mcast flow or group (add/modify/remove).
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700126 incomingMcastFlowOrGroup []chan McastFlowOrGroupControlBlock
127 stopMcastHandlerRoutine []chan bool
128 mcastHandlerRoutineActive []bool
Gamze Abakac2c32a62021-03-11 11:44:18 +0000129
130 adapterPreviouslyConnected bool
131 agentPreviouslyConnected bool
Girish Gowdra950326e2021-11-05 12:43:24 -0700132
133 isDeviceDeletionInProgress bool
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530134 heartbeatSignature uint32
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700135}
136
Mahir Gunyela2e68702022-12-07 00:00:42 -0800137// OnuDevice represents ONU related info
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700138type OnuDevice struct {
khenaidoo106c61a2021-08-11 18:05:46 -0400139 deviceID string
140 deviceType string
141 serialNumber string
142 onuID uint32
143 intfID uint32
144 proxyDeviceID string
145 losRaised bool
146 rdiRaised bool
147 adapterEndpoint string
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700148}
149
Mahir Gunyelb0046752021-02-26 13:51:05 -0800150type onuIndicationMsg struct {
151 ctx context.Context
152 indication *oop.Indication
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800153}
154
155type onuIndicationChannels struct {
Mahir Gunyelb0046752021-02-26 13:51:05 -0800156 indicationChannel chan onuIndicationMsg
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800157 stopChannel chan struct{}
158}
159
Mahir Gunyela2e68702022-12-07 00:00:42 -0800160// McastFlowOrGroupControlBlock is created per mcast flow/group add/modify/remove and pushed on the incomingMcastFlowOrGroup channel slice
161// The McastFlowOrGroupControlBlock is then picked by the mcastFlowOrGroupChannelHandlerRoutine for further processing.
162// There are MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine routines which monitor for any incoming mcast flow/group messages
163// and process them serially. The mcast flow/group are assigned these routines based on formula (group-id modulo MaxNumOfGroupHandlerChannels)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800164type McastFlowOrGroupControlBlock struct {
khenaidoodc2116e2021-10-19 17:33:19 -0400165 ctx context.Context // Flow/group handler context
166 flowOrGroupAction string // one of McastFlowOrGroupAdd, McastFlowOrGroupModify or McastFlowOrGroupDelete
167 flow *of.OfpFlowStats // Flow message (can be nil or valid flow)
168 group *of.OfpGroupEntry // Group message (can be nil or valid group)
169 errChan *chan error // channel to report the mcast Flow/group handling error
Girish Gowdra491a9c62021-01-06 16:43:07 -0800170}
171
Naga Manjunath7615e552019-10-11 22:35:47 +0530172var pmNames = []string{
173 "rx_bytes",
174 "rx_packets",
175 "rx_mcast_packets",
176 "rx_bcast_packets",
177 "tx_bytes",
178 "tx_packets",
179 "tx_mcast_packets",
180 "tx_bcast_packets",
181}
182
Mahir Gunyela2e68702022-12-07 00:00:42 -0800183// NewOnuDevice creates a new Onu Device
khenaidoo106c61a2021-08-11 18:05:46 -0400184func NewOnuDevice(devID, deviceTp, serialNum string, onuID, intfID uint32, proxyDevID string, losRaised bool, adapterEndpoint string) *OnuDevice {
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700185 var device OnuDevice
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700186 device.deviceID = devID
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700187 device.deviceType = deviceTp
188 device.serialNumber = serialNum
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700189 device.onuID = onuID
190 device.intfID = intfID
191 device.proxyDeviceID = proxyDevID
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +0530192 device.losRaised = losRaised
khenaidoo106c61a2021-08-11 18:05:46 -0400193 device.adapterEndpoint = adapterEndpoint
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700194 return &device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530195}
196
Mahir Gunyela2e68702022-12-07 00:00:42 -0800197// NewDeviceHandler creates a new device handler
khenaidoo106c61a2021-08-11 18:05:46 -0400198func NewDeviceHandler(cc *vgrpc.Client, ep eventif.EventProxy, device *voltha.Device, adapter *OpenOLT, cm *config.ConfigManager, cfg *conf.AdapterFlags) *DeviceHandler {
cuilin20187b2a8c32019-03-26 19:52:28 -0700199 var dh DeviceHandler
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530200 ctx := context.Background()
Matteo Scandolodfa7a972020-11-06 13:03:40 -0800201 dh.cm = cm
khenaidoo106c61a2021-08-11 18:05:46 -0400202 dh.coreClient = cc
Devmalya Paulfb990a52019-07-09 10:01:49 -0400203 dh.EventProxy = ep
cuilin20187b2a8c32019-03-26 19:52:28 -0700204 cloned := (proto.Clone(device)).(*voltha.Device)
cuilin20187b2a8c32019-03-26 19:52:28 -0700205 dh.device = cloned
206 dh.openOLT = adapter
khenaidooefff76e2021-12-15 16:51:30 -0500207 dh.exitChannel = make(chan struct{})
cuilin20187b2a8c32019-03-26 19:52:28 -0700208 dh.lockDevice = sync.RWMutex{}
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000209 dh.stopCollector = make(chan bool, 1) // TODO: Why buffered?
210 dh.stopHeartbeatCheck = make(chan bool, 1) // TODO: Why buffered?
Naga Manjunath7615e552019-10-11 22:35:47 +0530211 dh.metrics = pmmetrics.NewPmMetrics(cloned.Id, pmmetrics.Frequency(150), pmmetrics.FrequencyOverride(false), pmmetrics.Grouped(false), pmmetrics.Metrics(pmNames))
Chaitrashree G Sef088112020-02-03 21:39:27 -0500212 dh.activePorts = sync.Map{}
Girish Gowdraae56c722021-11-22 14:31:11 -0800213 dh.stopIndications = make(chan bool, 1) // TODO: Why buffered?
Mahir Gunyelb0046752021-02-26 13:51:05 -0800214 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
khenaidoo106c61a2021-08-11 18:05:46 -0400215 dh.childAdapterClients = make(map[string]*vgrpc.Client)
216 dh.cfg = cfg
Gustavo Silva41af9122022-10-11 11:05:13 -0300217 dh.kvStore = SetKVClient(ctx, dh.openOLT.KVStoreType, dh.openOLT.KVStoreAddress, dh.device.Id, dh.cm.Backend.PathPrefix)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530218 if dh.kvStore == nil {
219 logger.Error(ctx, "Failed to setup KV store")
220 return nil
221 }
222
Girish Gowdra491a9c62021-01-06 16:43:07 -0800223 // Create a slice of buffered channels for handling concurrent mcast flow/group.
224 dh.incomingMcastFlowOrGroup = make([]chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700225 dh.stopMcastHandlerRoutine = make([]chan bool, MaxNumOfGroupHandlerChannels)
226 dh.mcastHandlerRoutineActive = make([]bool, MaxNumOfGroupHandlerChannels)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800227 for i := range dh.incomingMcastFlowOrGroup {
228 dh.incomingMcastFlowOrGroup[i] = make(chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdraae56c722021-11-22 14:31:11 -0800229 dh.stopMcastHandlerRoutine[i] = make(chan bool)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800230 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
231 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
232 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
233 // for incoming mcast flow/group to be processed serially.
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700234 dh.mcastHandlerRoutineActive[i] = true
235 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
Girish Gowdra491a9c62021-01-06 16:43:07 -0800236 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700237 //TODO initialize the support classes.
238 return &dh
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530239}
240
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530241func newKVClient(ctx context.Context, storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
242 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
243 switch storeType {
244 case "etcd":
245 return kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)
246 }
247 return nil, errors.New("unsupported-kv-store")
248}
249
250// SetKVClient sets the KV client and return a kv backend
251func SetKVClient(ctx context.Context, backend string, addr string, DeviceID string, basePathKvStore string) *db.Backend {
252 kvClient, err := newKVClient(ctx, backend, addr, rsrcMgr.KvstoreTimeout)
253 if err != nil {
254 logger.Fatalw(ctx, "Failed to init KV client\n", log.Fields{"err": err})
255 return nil
256 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530257 kvbackend := &db.Backend{
258 Client: kvClient,
259 StoreType: backend,
260 Address: addr,
261 Timeout: rsrcMgr.KvstoreTimeout,
262 PathPrefix: fmt.Sprintf(rsrcMgr.BasePathKvStore, basePathKvStore, DeviceID)}
263
264 return kvbackend
265}
266
Holger Hildebrandt143b5be2023-02-10 08:28:15 +0000267// CloseKVClient closes open KV clients
268func (dh *DeviceHandler) CloseKVClient(ctx context.Context) {
269 if dh.resourceMgr != nil {
270 for _, rscMgr := range dh.resourceMgr {
271 if rscMgr != nil {
272 rscMgr.CloseKVClient(ctx)
273 }
274 }
275 }
276 if dh.flowMgr != nil {
277 for _, flMgr := range dh.flowMgr {
278 if flMgr != nil {
279 flMgr.CloseKVClient(ctx)
280 }
281 }
282 }
283}
284
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530285// start save the device to the data model
286func (dh *DeviceHandler) start(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700287 dh.lockDevice.Lock()
288 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000289 logger.Debugw(ctx, "starting-device-agent", log.Fields{"device": dh.device})
cuilin20187b2a8c32019-03-26 19:52:28 -0700290 // Add the initial device to the local model
Neha Sharma96b7bf22020-06-15 10:37:32 +0000291 logger.Debug(ctx, "device-agent-started")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530292}
293
khenaidooefff76e2021-12-15 16:51:30 -0500294// Stop stops the device handler
295func (dh *DeviceHandler) Stop(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700296 dh.lockDevice.Lock()
297 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000298 logger.Debug(ctx, "stopping-device-agent")
khenaidooefff76e2021-12-15 16:51:30 -0500299 close(dh.exitChannel)
khenaidoo106c61a2021-08-11 18:05:46 -0400300
khenaidooefff76e2021-12-15 16:51:30 -0500301 // Delete (which will stop also) all grpc connections to the child adapters
302 dh.deleteAdapterClients(ctx)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000303 logger.Debug(ctx, "device-agent-stopped")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530304}
305
ssiddiqui04386ee2021-08-23 21:58:25 +0530306func (dh *DeviceHandler) getPonTechnology(intfID uint32) string {
307 for _, resourceRanges := range dh.deviceInfo.GetRanges() {
308 for _, pooledIntfID := range resourceRanges.GetIntfIds() {
309 if pooledIntfID == intfID {
310 return resourceRanges.GetTechnology()
311 }
312 }
313 }
314 return ""
315}
316
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400317func macifyIP(ip net.IP) string {
318 if len(ip) > 0 {
319 oct1 := strconv.FormatInt(int64(ip[12]), 16)
320 oct2 := strconv.FormatInt(int64(ip[13]), 16)
321 oct3 := strconv.FormatInt(int64(ip[14]), 16)
322 oct4 := strconv.FormatInt(int64(ip[15]), 16)
323 return fmt.Sprintf("00:00:%02v:%02v:%02v:%02v", oct1, oct2, oct3, oct4)
324 }
325 return ""
326}
327
Neha Sharma96b7bf22020-06-15 10:37:32 +0000328func generateMacFromHost(ctx context.Context, host string) (string, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400329 var genmac string
330 var addr net.IP
331 var ips []string
332 var err error
333
Neha Sharma96b7bf22020-06-15 10:37:32 +0000334 logger.Debugw(ctx, "generating-mac-from-host", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400335
336 if addr = net.ParseIP(host); addr == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000337 logger.Debugw(ctx, "looking-up-hostname", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400338
339 if ips, err = net.LookupHost(host); err == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000340 logger.Debugw(ctx, "dns-result-ips", log.Fields{"ips": ips})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400341 if addr = net.ParseIP(ips[0]); addr == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000342 return "", olterrors.NewErrInvalidValue(log.Fields{"ip": ips[0]}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400343 }
344 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000345 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530346 log.Fields{"host": ips[0],
347 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400348 return genmac, nil
349 }
Girish Kumarf26e4882020-03-05 06:49:10 +0000350 return "", olterrors.NewErrAdapter("cannot-resolve-hostname-to-ip", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400351 }
352
353 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000354 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530355 log.Fields{"host": host,
356 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400357 return genmac, nil
358}
359
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530360func macAddressToUint32Array(mac string) []uint32 {
cuilin20187b2a8c32019-03-26 19:52:28 -0700361 slist := strings.Split(mac, ":")
362 result := make([]uint32, len(slist))
363 var err error
364 var tmp int64
365 for index, val := range slist {
366 if tmp, err = strconv.ParseInt(val, 16, 32); err != nil {
367 return []uint32{1, 2, 3, 4, 5, 6}
368 }
369 result[index] = uint32(tmp)
370 }
371 return result
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530372}
373
Mahir Gunyela2e68702022-12-07 00:00:42 -0800374// GetportLabel returns the label for the NNI and the PON port based on port number and port type
David K. Bainbridge794735f2020-02-11 21:01:37 -0800375func GetportLabel(portNum uint32, portType voltha.Port_PortType) (string, error) {
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530376
David K. Bainbridge794735f2020-02-11 21:01:37 -0800377 switch portType {
378 case voltha.Port_ETHERNET_NNI:
379 return fmt.Sprintf("nni-%d", portNum), nil
380 case voltha.Port_PON_OLT:
381 return fmt.Sprintf("pon-%d", portNum), nil
cuilin20187b2a8c32019-03-26 19:52:28 -0700382 }
David K. Bainbridge794735f2020-02-11 21:01:37 -0800383
Girish Kumarf26e4882020-03-05 06:49:10 +0000384 return "", olterrors.NewErrInvalidValue(log.Fields{"port-type": portType}, nil)
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530385}
386
Elia Battiston596406d2022-02-02 12:19:00 +0100387func makeOfpPort(macAddress string, speedMbps uint32) *of.OfpPort {
388 if speedMbps == 0 {
389 //In case it was not set in the indication
390 //and no other value was provided
391 speedMbps = defaultPortSpeedMbps
392 }
393
394 ofpPortSpeed := of.OfpPortFeatures_OFPPF_OTHER
395 switch speedMbps {
396 case 1000000:
397 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1TB_FD
398 case 100000:
399 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100GB_FD
400 case 40000:
401 ofpPortSpeed = of.OfpPortFeatures_OFPPF_40GB_FD
402 case 10000:
403 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10GB_FD
404 case 1000:
405 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1GB_FD
406 case 100:
407 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100MB_FD
408 case 10:
409 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10MB_FD
410 }
411
412 capacity := uint32(ofpPortSpeed | of.OfpPortFeatures_OFPPF_FIBER)
413
414 port := &of.OfpPort{
415 HwAddr: macAddressToUint32Array(macAddress),
416 Config: 0,
417 State: uint32(of.OfpPortState_OFPPS_LIVE),
418 Curr: capacity,
419 Advertised: capacity,
420 Peer: capacity,
421 CurrSpeed: speedMbps * 1000, //kbps
422 MaxSpeed: speedMbps * 1000, //kbps
423 }
424
425 return port
426}
427
428func (dh *DeviceHandler) addPort(ctx context.Context, intfID uint32, portType voltha.Port_PortType, state string, speedMbps uint32) error {
Esin Karamanccb714b2019-11-29 15:02:06 +0000429 var operStatus common.OperStatus_Types
cuilin20187b2a8c32019-03-26 19:52:28 -0700430 if state == "up" {
431 operStatus = voltha.OperStatus_ACTIVE
kesavand39e0aa32020-01-28 20:58:50 -0500432 //populating the intfStatus map
Chaitrashree G Sef088112020-02-03 21:39:27 -0500433 dh.activePorts.Store(intfID, true)
cuilin20187b2a8c32019-03-26 19:52:28 -0700434 } else {
435 operStatus = voltha.OperStatus_DISCOVERED
Chaitrashree G Sef088112020-02-03 21:39:27 -0500436 dh.activePorts.Store(intfID, false)
cuilin20187b2a8c32019-03-26 19:52:28 -0700437 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -0700438 portNum := plt.IntfIDToPortNo(intfID, portType)
Chaitrashree G Sc0878ec2020-05-21 04:59:53 -0400439 label, err := GetportLabel(intfID, portType)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800440 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000441 return olterrors.NewErrNotFound("port-label", log.Fields{"port-number": portNum, "port-type": portType}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400442 }
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500443
khenaidoo106c61a2021-08-11 18:05:46 -0400444 // Check if port exists
khenaidoodc2116e2021-10-19 17:33:19 -0400445 port, err := dh.getPortFromCore(ctx, &ca.PortFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400446 DeviceId: dh.device.Id,
447 Port: portNum,
448 })
449 if err == nil && port.Type == portType {
Girish Kumara1ea2aa2020-08-19 18:14:22 +0000450 logger.Debug(ctx, "port-already-exists-updating-oper-status-of-port")
khenaidoodc2116e2021-10-19 17:33:19 -0400451 err = dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -0400452 DeviceId: dh.device.Id,
453 PortType: portType,
454 PortNo: portNum,
455 OperStatus: operStatus})
456 if err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400457 return olterrors.NewErrAdapter("failed-to-update-port-state", log.Fields{
458 "device-id": dh.device.Id,
459 "port-type": portType,
460 "port-number": portNum,
461 "oper-status": operStatus}, err).Log()
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500462 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400463 return nil
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500464 }
khenaidoo106c61a2021-08-11 18:05:46 -0400465
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400466 // Now create Port
khenaidoo106c61a2021-08-11 18:05:46 -0400467 port = &voltha.Port{
468 DeviceId: dh.device.Id,
cuilin20187b2a8c32019-03-26 19:52:28 -0700469 PortNo: portNum,
470 Label: label,
471 Type: portType,
472 OperStatus: operStatus,
Elia Battiston596406d2022-02-02 12:19:00 +0100473 OfpPort: makeOfpPort(dh.device.MacAddress, speedMbps),
cuilin20187b2a8c32019-03-26 19:52:28 -0700474 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000475 logger.Debugw(ctx, "sending-port-update-to-core", log.Fields{"port": port})
cuilin20187b2a8c32019-03-26 19:52:28 -0700476 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -0400477 err = dh.createPortInCore(ctx, port)
478 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000479 return olterrors.NewErrAdapter("error-creating-port", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -0800480 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +0000481 "port-type": portType}, err)
Girish Gowdru1110ef22019-06-24 11:17:59 -0400482 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000483 go dh.updateLocalDevice(ctx)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530484 return nil
485}
486
Kent Hagermane6ff1012020-07-14 15:07:53 -0400487func (dh *DeviceHandler) updateLocalDevice(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -0400488 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530489 if err != nil || device == nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400490 logger.Errorf(ctx, "device-not-found", log.Fields{"device-id": dh.device.Id}, err)
491 return
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530492 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800493 dh.lockDevice.Lock()
494 defer dh.lockDevice.Unlock()
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530495 dh.device = device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530496}
497
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700498// nolint: gocyclo
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530499// readIndications to read the indications from the OLT device
David K. Bainbridge794735f2020-02-11 21:01:37 -0800500func (dh *DeviceHandler) readIndications(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000501 defer logger.Debugw(ctx, "indications-ended", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700502 defer func() {
503 dh.lockDevice.Lock()
504 dh.isReadIndicationRoutineActive = false
505 dh.lockDevice.Unlock()
506 }()
Girish Gowdra3f974912020-03-23 20:35:18 -0700507 indications, err := dh.startOpenOltIndicationStream(ctx)
cuilin20187b2a8c32019-03-26 19:52:28 -0700508 if err != nil {
Girish Gowdra3f974912020-03-23 20:35:18 -0700509 return err
cuilin20187b2a8c32019-03-26 19:52:28 -0700510 }
Girish Gowdru5ba46c92019-04-25 05:00:05 -0400511
David Bainbridgef5879ca2019-12-13 21:17:54 +0000512 // Create an exponential backoff around re-enabling indications. The
513 // maximum elapsed time for the back off is set to 0 so that we will
514 // continue to retry. The max interval defaults to 1m, but is set
515 // here for code clarity
516 indicationBackoff := backoff.NewExponentialBackOff()
517 indicationBackoff.MaxElapsedTime = 0
518 indicationBackoff.MaxInterval = 1 * time.Minute
Girish Gowdra3f974912020-03-23 20:35:18 -0700519
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700520 dh.lockDevice.Lock()
521 dh.isReadIndicationRoutineActive = true
522 dh.lockDevice.Unlock()
523
Girish Gowdra3f974912020-03-23 20:35:18 -0700524Loop:
cuilin20187b2a8c32019-03-26 19:52:28 -0700525 for {
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400526 select {
527 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000528 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700529 break Loop
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400530 default:
531 indication, err := indications.Recv()
Elia Battiston599d25f2022-02-16 14:49:08 +0100532
533 select {
534 case <-indications.Context().Done():
535 if err != nil {
536 logger.Warnw(ctx, "error-during-enable-indications",
537 log.Fields{"err": err,
538 "device-id": dh.device.Id})
539 }
540
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400541 // Use an exponential back off to prevent getting into a tight loop
542 duration := indicationBackoff.NextBackOff()
Elia Battiston599d25f2022-02-16 14:49:08 +0100543 logger.Infow(ctx, "backing-off-enable-indication", log.Fields{
544 "device-id": dh.device.Id,
545 "duration": duration,
546 })
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400547 if duration == backoff.Stop {
548 // If we reach a maximum then warn and reset the backoff
549 // timer and keep attempting.
Elia Battiston599d25f2022-02-16 14:49:08 +0100550 logger.Warnw(ctx, "maximum-indication-backoff-reached-resetting-backoff-timer",
Shrey Baid807a2a02020-04-09 12:52:45 +0530551 log.Fields{"max-indication-backoff": indicationBackoff.MaxElapsedTime,
Thomas Lee S985938d2020-05-04 11:40:41 +0530552 "device-id": dh.device.Id})
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400553 indicationBackoff.Reset()
554 }
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700555
556 // On failure process a backoff timer while watching for stopIndications
557 // events
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700558 backoffTimer := time.NewTimer(indicationBackoff.NextBackOff())
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700559 select {
560 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000561 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700562 if !backoffTimer.Stop() {
563 <-backoffTimer.C
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700564 }
565 break Loop
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700566 case <-backoffTimer.C:
567 // backoffTimer expired continue
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700568 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700569 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
570 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400571 }
572 continue
Elia Battiston599d25f2022-02-16 14:49:08 +0100573 default:
574 if err != nil {
575 logger.Errorw(ctx, "read-indication-error",
Shrey Baid807a2a02020-04-09 12:52:45 +0530576 log.Fields{"err": err,
Thomas Lee S985938d2020-05-04 11:40:41 +0530577 "device-id": dh.device.Id})
Elia Battiston599d25f2022-02-16 14:49:08 +0100578 // Close the stream, and re-initialize it
579 if err = indications.CloseSend(); err != nil {
580 // Ok to ignore here, because we landed here due to a problem on the stream
581 // In all probability, the closeSend call may fail
582 logger.Debugw(ctx, "error-closing-send stream--error-ignored",
583 log.Fields{"err": err,
584 "device-id": dh.device.Id})
585 }
586 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
587 return err
588 }
589 // once we re-initialized the indication stream, continue to read indications
590 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700591 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100592 // Reset backoff if we have a successful receive
593 indicationBackoff.Reset()
594 // When OLT is admin down, ignore all indications.
595 if dh.device.AdminState == voltha.AdminState_DISABLED && !isIndicationAllowedDuringOltAdminDown(indication) {
596 logger.Debugw(ctx, "olt-is-admin-down, ignore indication",
597 log.Fields{"indication": indication,
598 "device-id": dh.device.Id})
599 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700600 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100601 dh.handleIndication(ctx, indication)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +0530602 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700603 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700604 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700605 // Close the send stream
606 _ = indications.CloseSend() // Ok to ignore error, as we stopping the readIndication anyway
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700607
Girish Gowdra3f974912020-03-23 20:35:18 -0700608 return nil
609}
610
611func (dh *DeviceHandler) startOpenOltIndicationStream(ctx context.Context) (oop.Openolt_EnableIndicationClient, error) {
Girish Gowdra852ad912021-05-04 00:05:50 -0700612 logger.Infow(ctx, "enabling read indications", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700613 indications, err := dh.Client.EnableIndication(ctx, new(oop.Empty))
614 if err != nil {
615 return nil, olterrors.NewErrCommunication("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).Log()
616 }
617 if indications == nil {
618 return nil, olterrors.NewErrInvalidValue(log.Fields{"indications": nil, "device-id": dh.device.Id}, nil).Log()
619 }
Girish Gowdra852ad912021-05-04 00:05:50 -0700620 logger.Infow(ctx, "read indication started successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700621 return indications, nil
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400622}
623
624// isIndicationAllowedDuringOltAdminDown returns true if the indication is allowed during OLT Admin down, else false
625func isIndicationAllowedDuringOltAdminDown(indication *oop.Indication) bool {
626 switch indication.Data.(type) {
627 case *oop.Indication_OltInd, *oop.Indication_IntfInd, *oop.Indication_IntfOperInd:
628 return true
629
630 default:
631 return false
632 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700633}
634
David K. Bainbridge794735f2020-02-11 21:01:37 -0800635func (dh *DeviceHandler) handleOltIndication(ctx context.Context, oltIndication *oop.OltIndication) error {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700636 raisedTs := time.Now().Unix()
Gamze Abakaa1a50522019-10-03 19:28:27 +0000637 if oltIndication.OperState == "up" && dh.transitionMap.currentDeviceState != deviceStateUp {
npujarec5762e2020-01-01 14:08:48 +0530638 dh.transitionMap.Handle(ctx, DeviceUpInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700639 } else if oltIndication.OperState == "down" {
npujarec5762e2020-01-01 14:08:48 +0530640 dh.transitionMap.Handle(ctx, DeviceDownInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700641 }
Daniele Rossi051466a2019-07-26 13:39:37 +0000642 // Send or clear Alarm
Neha Sharma96b7bf22020-06-15 10:37:32 +0000643 if err := dh.eventMgr.oltUpDownIndication(ctx, oltIndication, dh.device.Id, raisedTs); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +0530644 return olterrors.NewErrAdapter("failed-indication", log.Fields{
divyadesai3af43e12020-08-18 07:10:54 +0000645 "device-id": dh.device.Id,
David K. Bainbridge794735f2020-02-11 21:01:37 -0800646 "indication": oltIndication,
Girish Kumarf26e4882020-03-05 06:49:10 +0000647 "timestamp": raisedTs}, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800648 }
649 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700650}
651
David K. Bainbridge794735f2020-02-11 21:01:37 -0800652// nolint: gocyclo
npujarec5762e2020-01-01 14:08:48 +0530653func (dh *DeviceHandler) handleIndication(ctx context.Context, indication *oop.Indication) {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700654 raisedTs := time.Now().Unix()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700655 switch indication.Data.(type) {
656 case *oop.Indication_OltInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000657 span, ctx := log.CreateChildSpan(ctx, "olt-indication", log.Fields{"device-id": dh.device.Id})
658 defer span.Finish()
Girish Gowdra852ad912021-05-04 00:05:50 -0700659 logger.Infow(ctx, "received olt indication", log.Fields{"device-id": dh.device.Id, "olt-ind": indication.GetOltInd()})
David K. Bainbridge794735f2020-02-11 21:01:37 -0800660 if err := dh.handleOltIndication(ctx, indication.GetOltInd()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400661 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "olt", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800662 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700663 case *oop.Indication_IntfInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000664 span, ctx := log.CreateChildSpan(ctx, "interface-indication", log.Fields{"device-id": dh.device.Id})
665 defer span.Finish()
666
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700667 intfInd := indication.GetIntfInd()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800668 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100669 if err := dh.addPort(ctx, intfInd.GetIntfId(), voltha.Port_PON_OLT, intfInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400670 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800671 }
672 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000673 logger.Infow(ctx, "received-interface-indication", log.Fields{"InterfaceInd": intfInd, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700674 case *oop.Indication_IntfOperInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000675 span, ctx := log.CreateChildSpan(ctx, "interface-oper-indication", log.Fields{"device-id": dh.device.Id})
676 defer span.Finish()
677
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700678 intfOperInd := indication.GetIntfOperInd()
679 if intfOperInd.GetType() == "nni" {
David K. Bainbridge794735f2020-02-11 21:01:37 -0800680 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100681 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_ETHERNET_NNI, intfOperInd.GetOperState(), intfOperInd.GetSpeed()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400682 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface-oper-nni", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800683 }
684 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700685 } else if intfOperInd.GetType() == "pon" {
686 // TODO: Check what needs to be handled here for When PON PORT down, ONU will be down
687 // Handle pon port update
David K. Bainbridge794735f2020-02-11 21:01:37 -0800688 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100689 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_PON_OLT, intfOperInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400690 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface-oper-pon", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800691 }
692 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000693 go dh.eventMgr.oltIntfOperIndication(ctx, indication.GetIntfOperInd(), dh.device.Id, raisedTs)
cuilin20187b2a8c32019-03-26 19:52:28 -0700694 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000695 logger.Infow(ctx, "received-interface-oper-indication",
Shrey Baid807a2a02020-04-09 12:52:45 +0530696 log.Fields{"interfaceOperInd": intfOperInd,
Thomas Lee S985938d2020-05-04 11:40:41 +0530697 "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700698 case *oop.Indication_OnuDiscInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000699 span, ctx := log.CreateChildSpan(ctx, "onu-discovery-indication", log.Fields{"device-id": dh.device.Id})
700 defer span.Finish()
701
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700702 onuDiscInd := indication.GetOnuDiscInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000703 logger.Infow(ctx, "received-onu-discovery-indication", log.Fields{"OnuDiscInd": onuDiscInd, "device-id": dh.device.Id})
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800704 //put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800705 dh.putOnuIndicationToChannel(ctx, indication, onuDiscInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700706 case *oop.Indication_OnuInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000707 span, ctx := log.CreateChildSpan(ctx, "onu-indication", log.Fields{"device-id": dh.device.Id})
708 defer span.Finish()
709
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700710 onuInd := indication.GetOnuInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000711 logger.Infow(ctx, "received-onu-indication", log.Fields{"OnuInd": onuInd, "device-id": dh.device.Id})
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800712 //put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800713 dh.putOnuIndicationToChannel(ctx, indication, onuInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700714 case *oop.Indication_OmciInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000715 span, ctx := log.CreateChildSpan(ctx, "omci-indication", log.Fields{"device-id": dh.device.Id})
716 defer span.Finish()
717
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700718 omciInd := indication.GetOmciInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000719 logger.Debugw(ctx, "received-omci-indication", log.Fields{"intf-id": omciInd.IntfId, "onu-id": omciInd.OnuId, "device-id": dh.device.Id})
David K. Bainbridge794735f2020-02-11 21:01:37 -0800720 go func() {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000721 if err := dh.omciIndication(ctx, omciInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400722 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "omci", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800723 }
724 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700725 case *oop.Indication_PktInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000726 span, ctx := log.CreateChildSpan(ctx, "packet-indication", log.Fields{"device-id": dh.device.Id})
727 defer span.Finish()
728
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700729 pktInd := indication.GetPktInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000730 logger.Debugw(ctx, "received-packet-indication", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700731 "intf-type": pktInd.IntfId,
732 "intf-id": pktInd.IntfId,
733 "gem-port-id": pktInd.GemportId,
734 "port-no": pktInd.PortNo,
735 "device-id": dh.device.Id,
736 })
737
738 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000739 logger.Debugw(ctx, "received-packet-indication-packet", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700740 "intf-type": pktInd.IntfId,
741 "intf-id": pktInd.IntfId,
742 "gem-port-id": pktInd.GemportId,
743 "port-no": pktInd.PortNo,
744 "packet": hex.EncodeToString(pktInd.Pkt),
745 "device-id": dh.device.Id,
746 })
747 }
748
David K. Bainbridge794735f2020-02-11 21:01:37 -0800749 go func() {
750 if err := dh.handlePacketIndication(ctx, pktInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400751 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "packet", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800752 }
753 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700754 case *oop.Indication_PortStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000755 span, ctx := log.CreateChildSpan(ctx, "port-statistics-indication", log.Fields{"device-id": dh.device.Id})
756 defer span.Finish()
757
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700758 portStats := indication.GetPortStats()
Girish Gowdra9602eb42020-09-09 15:50:39 -0700759 go dh.portStats.PortStatisticsIndication(ctx, portStats, dh.totalPonPorts)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700760 case *oop.Indication_FlowStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000761 span, ctx := log.CreateChildSpan(ctx, "flow-stats-indication", log.Fields{"device-id": dh.device.Id})
762 defer span.Finish()
763
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700764 flowStats := indication.GetFlowStats()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000765 logger.Infow(ctx, "received-flow-stats", log.Fields{"FlowStats": flowStats, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700766 case *oop.Indication_AlarmInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000767 span, ctx := log.CreateChildSpan(ctx, "alarm-indication", log.Fields{"device-id": dh.device.Id})
768 defer span.Finish()
769
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700770 alarmInd := indication.GetAlarmInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000771 logger.Infow(ctx, "received-alarm-indication", log.Fields{"AlarmInd": alarmInd, "device-id": dh.device.Id})
772 go dh.eventMgr.ProcessEvents(ctx, alarmInd, dh.device.Id, raisedTs)
cuilin20187b2a8c32019-03-26 19:52:28 -0700773 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530774}
775
nikesh.krishnanc8473432023-06-14 12:14:54 +0530776func generateOnuIndication(intfID, onuID uint32, operState, adminState string) *oop.Indication {
777 onuInd := &oop.OnuIndication{
778 IntfId: intfID,
779 OnuId: onuID,
780 OperState: operState,
781 AdminState: adminState,
782 }
783 indication := &oop.Indication{
784 Data: &oop.Indication_OnuInd{
785 OnuInd: onuInd,
786 },
787 }
788 return indication
789}
790
791func generateOnuAlarmIndication(intfID uint32, onuID uint32, losStatus string) *oop.AlarmIndication {
792 onuAlarmInd := &oop.OnuAlarmIndication{
793 IntfId: intfID,
794 OnuId: onuID,
795 LosStatus: losStatus,
796 }
797 alarmInd := &oop.AlarmIndication{
798 Data: &oop.AlarmIndication_OnuAlarmInd{
799 OnuAlarmInd: onuAlarmInd,
800 },
801 }
802 return alarmInd
803}
804func generatePonLosAlarmIndication(intfID uint32, losStatus string) *oop.AlarmIndication {
805
806 ponlosAlarmInd := &oop.LosIndication{
807 IntfId: intfID,
808 Status: losStatus,
809 }
810 alarmInd := &oop.AlarmIndication{
811 Data: &oop.AlarmIndication_LosInd{
812 LosInd: ponlosAlarmInd,
813 },
814 }
815 return alarmInd
816}
817func (dh *DeviceHandler) updateIntfOperStateAndRaiseIndication(ctx context.Context, operState string, intfID uint32) {
818 go func() {
819 if err := dh.addPort(ctx, intfID, voltha.Port_PON_OLT, operState, defaultPortSpeedMbps); err != nil {
820 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface-oper-pon", "device-id": dh.device.Id}, err).Log()
821 }
822 }()
823
824 raisedTs := time.Now().Unix()
825 go dh.eventMgr.oltIntfOperIndication(ctx, &oop.IntfOperIndication{Type: "pon", IntfId: intfID, OperState: operState}, dh.device.Id, raisedTs)
826}
827
828func (dh *DeviceHandler) reconcileOnus(ctx context.Context) error {
829
830 onuDevicesFromCore, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
831 if err != nil {
832
833 logger.Error(ctx, "unable to fetch child device", log.Fields{"eeror": err})
834
835 return err
836 }
837 for _, onuDeviceFromCore := range onuDevicesFromCore.Items {
838
839 onuOperStatusFromCore := onuDeviceFromCore.OperStatus
840 onuConnectStatusFromCore := onuDeviceFromCore.ConnectStatus
841 intfID := plt.PortNoToIntfID(onuDeviceFromCore.ParentPortNo, voltha.Port_PON_OLT)
842
843 onuID := onuDeviceFromCore.ProxyAddress.OnuId
844 onuDeviceFromOlt, err := dh.getOnuInfo(ctx, intfID, &onuID)
845 if err != nil {
846 logger.Error(ctx, "unable to get onu object from olt agent", log.Fields{"eeror": err})
847
848 } else {
849 onuOperStatusFromOlt := onuDeviceFromOlt.GetState()
850 onuLosFromOlt := onuDeviceFromOlt.GetLosi()
851 switch {
852 case onuOperStatusFromOlt.String() == "ACTIVE" && onuOperStatusFromCore.String() != "ACTIVE":
853 OnuIndication := generateOnuIndication(intfID, onuID, "up", "up")
854 dh.putOnuIndicationToChannel(ctx, OnuIndication, intfID)
855
856 case onuLosFromOlt.String() == "ON" && onuConnectStatusFromCore.String() == "REACHABLE":
857 OnuIndication := generateOnuIndication(intfID, onuID, "down", "down") //check bal cli login notepad
858 alarmInd := generateOnuAlarmIndication(intfID, onuID, "on")
859 raisedTs := time.Now().Unix()
860 go dh.eventMgr.ProcessEvents(ctx, alarmInd, dh.device.Id, raisedTs)
861
862 dh.putOnuIndicationToChannel(ctx, OnuIndication, intfID)
863 }
864
865 }
866
867 }
868
869 return nil
870}
871
872func (dh *DeviceHandler) reconcilePonPorts(ctx context.Context) error { // need onuid and pon id
873 portsFromCore, err := dh.getAllPortsFromCore(ctx, &ca.PortFilter{
874 DeviceId: dh.device.Id,
875 PortType: voltha.Port_PON_OLT,
876 })
877 if err != nil {
878 logger.Error(ctx, "unable to fetch ports from core", log.Fields{"eeror": err})
879
880 return err
881
882 }
883 for _, portFromCore := range portsFromCore.Items {
884 portNum := portFromCore.GetPortNo()
885 intfID := plt.PortNoToIntfID(portNum, voltha.Port_PON_OLT)
886 portOperStatusFromCore := portFromCore.OperStatus
887 portAdminStateFromCore := portFromCore.AdminState
888 ponPortFromOlt, err := dh.getIntfInfo(ctx, intfID)
889 if err != nil {
890 logger.Error(ctx, "unable to get pon objects from olt agent", log.Fields{"eeror": err})
891 } else {
892 portLosFromOlt := ponPortFromOlt.GetLos()
893 portStateFromOlt := ponPortFromOlt.GetState()
894 if portOperStatusFromCore.String() == "ACTIVE" && portLosFromOlt.String() == "ON" {
895 logger.Debug(ctx, "port is active in core but los is fired from olt", log.Fields{
896 "portStateFromOlt": portStateFromOlt.String(),
897 "portOperStatusFromCore": portOperStatusFromCore.String(),
898 "device-id": dh.device.Id,
899 "port": portNum})
900 ponLosindication := generatePonLosAlarmIndication(intfID, "on")
901 raisedTs := time.Now().Unix()
902 go dh.eventMgr.ProcessEvents(ctx, ponLosindication, dh.device.Id, raisedTs)
903
904 }
905 switch {
906 case portStateFromOlt.String() == "ACTIVE_WORKING" && portOperStatusFromCore.String() != "ACTIVE":
907 logger.Debug(ctx, "mismatch between port state in voltha core and raising port up event", log.Fields{
908 "portStateFromOlt": portStateFromOlt.String(),
909 "portOperStatusFromCore": portOperStatusFromCore.String(),
910 "device-id": dh.device.Id,
911 "port": portNum})
912 dh.updateIntfOperStateAndRaiseIndication(ctx, "up", intfID)
913 case (portStateFromOlt.String() == "INACTIVE" || portStateFromOlt.String() == "UNKNOWN") && portOperStatusFromCore.String() == "ACTIVE":
914 logger.Debug(ctx, "mismatch between port state in voltha core and raising port down event", log.Fields{
915 "portStateFromOlt": portStateFromOlt.String(),
916 "portOperStatusFromCore": portOperStatusFromCore.String(),
917 "device-id": dh.device.Id,
918 "port": portNum})
919 dh.updateIntfOperStateAndRaiseIndication(ctx, "down", intfID)
920 case portStateFromOlt.String() == "DISABLED" && portAdminStateFromCore.String() == "ENABLED":
921 logger.Error(ctx, "port enabled in device but disabled at votlha core", log.Fields{
922 "device-id": dh.device.Id,
923 "port": portNum})
924 default:
925 logger.Error(ctx, "mismatch between port state in voltha core and voltha device", log.Fields{
926 "portStateFromOlt": portStateFromOlt.String(),
927 "portOperStatusFromCore": portOperStatusFromCore.String(),
928 "device-id": dh.device.Id,
929 "port": portNum})
930
931 }
932
933 }
934
935 }
936
937 return nil
938}
939
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530940// doStateUp handle the olt up indication and update to voltha core
npujarec5762e2020-01-01 14:08:48 +0530941func (dh *DeviceHandler) doStateUp(ctx context.Context) error {
Thomas Lee S85f37312020-04-03 17:06:12 +0530942 //starting the stat collector
Neha Sharma96b7bf22020-06-15 10:37:32 +0000943 go startCollector(ctx, dh)
nikesh.krishnanc8473432023-06-14 12:14:54 +0530944 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
945 if err == nil {
946 if device.OperStatus == voltha.OperStatus_RECONCILING {
947 err = dh.reconcileOnus(ctx)
948 if err != nil {
949 logger.Error(ctx, "unable to reconcile onu", log.Fields{"eeror": err})
950 }
951 err = dh.reconcilePonPorts(ctx)
952 if err != nil {
953 logger.Error(ctx, "unable to reconcile pon ports", log.Fields{"eeror": err})
954 }
955 }
956 }
Girish Gowdra618fa572021-09-01 17:19:29 -0700957 // instantiate the mcast handler routines.
958 for i := range dh.incomingMcastFlowOrGroup {
959 // We land inside the below "if" code path, after the OLT comes back from a reboot, otherwise the routines
960 // are already active when the DeviceHandler module is first instantiated (as part of Adopt_device RPC invocation).
961 if !dh.mcastHandlerRoutineActive[i] {
962 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
963 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
964 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
965 // for incoming mcast flow/group to be processed serially.
966 dh.mcastHandlerRoutineActive[i] = true
967 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
968 }
969 }
970
Girish Gowdru0c588b22019-04-23 23:24:56 -0400971 // Synchronous call to update device state - this method is run in its own go routine
khenaidoodc2116e2021-10-19 17:33:19 -0400972 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400973 DeviceId: dh.device.Id,
974 OperStatus: voltha.OperStatus_ACTIVE,
975 ConnStatus: voltha.ConnectStatus_REACHABLE,
976 }); err != nil {
977 return olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400978 }
Gamze Abaka07868a52020-12-17 14:19:28 +0000979
980 //Clear olt communication failure event
981 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
982 dh.device.OperStatus = voltha.OperStatus_ACTIVE
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700983 raisedTs := time.Now().Unix()
Gamze Abaka07868a52020-12-17 14:19:28 +0000984 go dh.eventMgr.oltCommunicationEvent(ctx, dh.device, raisedTs)
985
Girish Gowdru0c588b22019-04-23 23:24:56 -0400986 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530987}
988
989// doStateDown handle the olt down indication
npujarec5762e2020-01-01 14:08:48 +0530990func (dh *DeviceHandler) doStateDown(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000991 logger.Debugw(ctx, "do-state-down-start", log.Fields{"device-id": dh.device.Id})
Girish Gowdrud4245152019-05-10 00:47:31 -0400992
khenaidoo106c61a2021-08-11 18:05:46 -0400993 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Girish Gowdrud4245152019-05-10 00:47:31 -0400994 if err != nil || device == nil {
995 /*TODO: needs to handle error scenarios */
Girish Kumarf26e4882020-03-05 06:49:10 +0000996 return olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -0400997 }
998
999 cloned := proto.Clone(device).(*voltha.Device)
Girish Gowdrud4245152019-05-10 00:47:31 -04001000
1001 //Update the device oper state and connection status
1002 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001003 dh.lockDevice.Lock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001004 dh.device = cloned
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001005 dh.lockDevice.Unlock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001006
khenaidoodc2116e2021-10-19 17:33:19 -04001007 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001008 DeviceId: cloned.Id,
1009 OperStatus: cloned.OperStatus,
1010 ConnStatus: cloned.ConnectStatus,
1011 }); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001012 return olterrors.NewErrAdapter("state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001013 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001014
1015 //get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04001016 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001017 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001018 return olterrors.NewErrAdapter("child-device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001019 }
1020 for _, onuDevice := range onuDevices.Items {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001021 // Update onu state as down in onu adapter
1022 onuInd := oop.OnuIndication{}
1023 onuInd.OperState = "down"
khenaidoo106c61a2021-08-11 18:05:46 -04001024
1025 ogClient, err := dh.getChildAdapterServiceClient(onuDevice.AdapterEndpoint)
1026 if err != nil {
1027 return err
1028 }
1029 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
khenaidoodc2116e2021-10-19 17:33:19 -04001030 _, err = ogClient.OnuIndication(subCtx, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001031 DeviceId: onuDevice.Id,
1032 OnuIndication: &onuInd,
1033 })
1034 cancel()
David K. Bainbridge794735f2020-02-11 21:01:37 -08001035 if err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001036 _ = olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001037 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001038 "onu-indicator": onuInd,
1039 "device-type": onuDevice.Type,
1040 "device-id": onuDevice.Id}, err).LogAt(log.ErrorLevel)
serkant.uluderya245caba2019-09-24 23:15:29 -07001041 //Do not return here and continue to process other ONUs
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001042 } else {
1043 logger.Debugw(ctx, "sending inter adapter down ind to onu success", log.Fields{"olt-device-id": device.Id, "onu-device-id": onuDevice.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001044 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001045 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001046 dh.lockDevice.Lock()
serkant.uluderya245caba2019-09-24 23:15:29 -07001047 /* Discovered ONUs entries need to be cleared , since after OLT
1048 is up, it starts sending discovery indications again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301049 dh.discOnus = sync.Map{}
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001050 dh.lockDevice.Unlock()
1051
Neha Sharma96b7bf22020-06-15 10:37:32 +00001052 logger.Debugw(ctx, "do-state-down-end", log.Fields{"device-id": device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001053 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301054}
1055
1056// doStateInit dial the grpc before going to init state
npujarec5762e2020-01-01 14:08:48 +05301057func (dh *DeviceHandler) doStateInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001058 var err error
Gamze Abaka49c40b32021-05-06 09:30:41 +00001059
1060 // if the connection is already available, close the previous connection (olt reboot case)
1061 if dh.clientCon != nil {
1062 if err = dh.clientCon.Close(); err != nil {
1063 logger.Errorw(ctx, "failed-to-close-previous-connection", log.Fields{"device-id": dh.device.Id})
1064 } else {
1065 logger.Debugw(ctx, "previous-grpc-channel-closed-successfully", log.Fields{"device-id": dh.device.Id})
1066 }
1067 }
1068
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301069 logger.Debugw(ctx, "Dailing grpc", log.Fields{"device-id": dh.device.Id})
Gamze Abaka49c40b32021-05-06 09:30:41 +00001070 // Use Interceptors to automatically inject and publish Open Tracing Spans by this GRPC client
Girish Kumar93e91742020-07-27 16:43:19 +00001071 dh.clientCon, err = grpc.Dial(dh.device.GetHostAndPort(),
1072 grpc.WithInsecure(),
1073 grpc.WithBlock(),
1074 grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001075 grpc_opentracing.StreamClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Girish Kumar93e91742020-07-27 16:43:19 +00001076 )),
1077 grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001078 grpc_opentracing.UnaryClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Girish Kumar93e91742020-07-27 16:43:19 +00001079 )))
1080
1081 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301082 return olterrors.NewErrCommunication("dial-failure", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05301083 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00001084 "host-and-port": dh.device.GetHostAndPort()}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001085 }
1086 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301087}
1088
1089// postInit create olt client instance to invoke RPC on the olt device
npujarec5762e2020-01-01 14:08:48 +05301090func (dh *DeviceHandler) postInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001091 dh.Client = oop.NewOpenoltClient(dh.clientCon)
npujarec5762e2020-01-01 14:08:48 +05301092 dh.transitionMap.Handle(ctx, GrpcConnected)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001093 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301094}
1095
1096// doStateConnected get the device info and update to voltha core
npujarec5762e2020-01-01 14:08:48 +05301097func (dh *DeviceHandler) doStateConnected(ctx context.Context) error {
Thomas Lee S985938d2020-05-04 11:40:41 +05301098 var err error
Neha Sharma96b7bf22020-06-15 10:37:32 +00001099 logger.Debugw(ctx, "olt-device-connected", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001100
1101 // Case where OLT is disabled and then rebooted.
khenaidoo106c61a2021-08-11 18:05:46 -04001102 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Thomas Lee S985938d2020-05-04 11:40:41 +05301103 if err != nil || device == nil {
1104 /*TODO: needs to handle error scenarios */
1105 return olterrors.NewErrAdapter("device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
1106 }
1107 if device.AdminState == voltha.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001108 logger.Debugln(ctx, "do-state-connected--device-admin-state-down")
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001109
1110 cloned := proto.Clone(device).(*voltha.Device)
1111 cloned.ConnectStatus = voltha.ConnectStatus_REACHABLE
1112 cloned.OperStatus = voltha.OperStatus_UNKNOWN
1113 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04001114
khenaidoodc2116e2021-10-19 17:33:19 -04001115 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001116 DeviceId: cloned.Id,
1117 OperStatus: cloned.OperStatus,
1118 ConnStatus: cloned.ConnectStatus,
1119 }); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301120 return olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001121 }
1122
Chaitrashree G S44124192019-08-07 20:21:36 -04001123 // Since the device was disabled before the OLT was rebooted, enforce the OLT to be Disabled after re-connection.
npujarec5762e2020-01-01 14:08:48 +05301124 _, err = dh.Client.DisableOlt(ctx, new(oop.Empty))
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001125 if err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301126 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001127 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001128 // We should still go ahead an initialize various device handler modules so that when OLT is re-enabled, we have
1129 // all the modules initialized and ready to handle incoming ONUs.
1130
Thomas Lee S985938d2020-05-04 11:40:41 +05301131 err = dh.initializeDeviceHandlerModules(ctx)
1132 if err != nil {
1133 return olterrors.NewErrAdapter("device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001134 }
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001135
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001136 go startHeartbeatCheck(ctx, dh)
1137
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001138 return nil
1139 }
1140
khenaidoo106c61a2021-08-11 18:05:46 -04001141 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001142 if err != nil {
Girish Gowdrud4245152019-05-10 00:47:31 -04001143 /*TODO: needs to handle error scenarios */
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001144 return olterrors.NewErrAdapter("fetch-ports-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001145 }
khenaidoo106c61a2021-08-11 18:05:46 -04001146 dh.populateActivePorts(ctx, ports.Items)
1147 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001148 return olterrors.NewErrAdapter("port-status-update-failed", log.Fields{"ports": ports}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001149 }
1150
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001151 if err := dh.initializeDeviceHandlerModules(ctx); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301152 return olterrors.NewErrAdapter("device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001153 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301154
Neha Sharma96b7bf22020-06-15 10:37:32 +00001155 go dh.updateLocalDevice(ctx)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001156
1157 if device.PmConfigs != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001158 dh.UpdatePmConfig(ctx, device.PmConfigs)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001159 }
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001160
1161 go startHeartbeatCheck(ctx, dh)
1162
cuilin20187b2a8c32019-03-26 19:52:28 -07001163 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301164}
1165
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001166func (dh *DeviceHandler) initializeDeviceHandlerModules(ctx context.Context) error {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001167 var err error
1168 dh.deviceInfo, err = dh.populateDeviceInfo(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001169
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00001170 if dh.flowMgr != nil {
1171 dh.StopAllFlowRoutines(ctx)
1172 }
1173
1174 dh.CloseKVClient(ctx)
1175
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001176 if err != nil {
1177 return olterrors.NewErrAdapter("populate-device-info-failed", log.Fields{"device-id": dh.device.Id}, err)
1178 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001179 dh.totalPonPorts = dh.deviceInfo.GetPonPorts()
1180 dh.agentPreviouslyConnected = dh.deviceInfo.PreviouslyConnected
yasin saplid0566272021-12-21 09:10:30 +00001181 // +1 is for NNI
1182 dh.resourceMgr = make([]*rsrcMgr.OpenOltResourceMgr, dh.totalPonPorts+1)
1183 dh.flowMgr = make([]*OpenOltFlowMgr, dh.totalPonPorts+1)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001184 var i uint32
yasin saplid0566272021-12-21 09:10:30 +00001185 // Index from 0 to until totalPonPorts ( Ex: 0 .. 15 ) -> PonPort Managers
1186 // Index totalPonPorts ( Ex: 16 ) -> NniPort Manager
1187 // There is only one NNI manager since multiple NNI is not supported for now
1188 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001189 // Instantiate resource manager
1190 if dh.resourceMgr[i] = rsrcMgr.NewResourceMgr(ctx, i, dh.device.Id, dh.openOLT.KVStoreAddress, dh.openOLT.KVStoreType, dh.device.Type, dh.deviceInfo, dh.cm.Backend.PathPrefix); dh.resourceMgr[i] == nil {
Girish Gowdra9602eb42020-09-09 15:50:39 -07001191 return olterrors.ErrResourceManagerInstantiating
1192 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001193 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001194 // GroupManager instance is per OLT. But it needs a reference to any instance of resourceMgr to interface with
1195 // the KV store to manage mcast group data. Provide the first instance (0th index)
1196 if dh.groupMgr = NewGroupManager(ctx, dh, dh.resourceMgr[0]); dh.groupMgr == nil {
1197 return olterrors.ErrGroupManagerInstantiating
1198 }
yasin saplid0566272021-12-21 09:10:30 +00001199 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001200 // Instantiate flow manager
1201 if dh.flowMgr[i] = NewFlowManager(ctx, dh, dh.resourceMgr[i], dh.groupMgr, i); dh.flowMgr[i] == nil {
Mahir Gunyela2e68702022-12-07 00:00:42 -08001202 //Continue to check the rest of the ports
1203 logger.Errorw(ctx, "error-initializing-flow-manager-for-intf", log.Fields{"intfID": i, "device-id": dh.device.Id})
1204 } else {
1205 dh.resourceMgr[i].TechprofileRef = dh.flowMgr[i].techprofile
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001206 }
1207 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001208 /* TODO: Instantiate Alarm , stats , BW managers */
1209 /* Instantiating Event Manager to handle Alarms and KPIs */
1210 dh.eventMgr = NewEventMgr(dh.EventProxy, dh)
1211
1212 // Stats config for new device
Neha Sharma96b7bf22020-06-15 10:37:32 +00001213 dh.portStats = NewOpenOltStatsMgr(ctx, dh)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001214
1215 return nil
1216
1217}
1218
Neha Sharma96b7bf22020-06-15 10:37:32 +00001219func (dh *DeviceHandler) populateDeviceInfo(ctx context.Context) (*oop.DeviceInfo, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001220 var err error
1221 var deviceInfo *oop.DeviceInfo
1222
Neha Sharma8f4e4322020-08-06 10:51:53 +00001223 deviceInfo, err = dh.Client.GetDeviceInfo(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty))
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001224
1225 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001226 return nil, olterrors.NewErrPersistence("get", "device", 0, nil, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001227 }
1228 if deviceInfo == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001229 return nil, olterrors.NewErrInvalidValue(log.Fields{"device": nil}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001230 }
1231
Neha Sharma96b7bf22020-06-15 10:37:32 +00001232 logger.Debugw(ctx, "fetched-device-info", log.Fields{"deviceInfo": deviceInfo, "device-id": dh.device.Id})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001233 dh.device.Root = true
1234 dh.device.Vendor = deviceInfo.Vendor
1235 dh.device.Model = deviceInfo.Model
1236 dh.device.SerialNumber = deviceInfo.DeviceSerialNumber
1237 dh.device.HardwareVersion = deviceInfo.HardwareVersion
1238 dh.device.FirmwareVersion = deviceInfo.FirmwareVersion
1239
1240 if deviceInfo.DeviceId == "" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001241 logger.Warnw(ctx, "no-device-id-provided-using-host", log.Fields{"hostport": dh.device.GetHostAndPort()})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001242 host := strings.Split(dh.device.GetHostAndPort(), ":")[0]
Neha Sharma96b7bf22020-06-15 10:37:32 +00001243 genmac, err := generateMacFromHost(ctx, host)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001244 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001245 return nil, olterrors.NewErrAdapter("failed-to-generate-mac-host", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001246 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001247 logger.Debugw(ctx, "using-host-for-mac-address", log.Fields{"host": host, "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001248 dh.device.MacAddress = genmac
1249 } else {
1250 dh.device.MacAddress = deviceInfo.DeviceId
1251 }
1252
1253 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -04001254 if err = dh.updateDeviceInCore(ctx, dh.device); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001255 return nil, olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001256 }
1257
1258 return deviceInfo, nil
1259}
1260
Neha Sharma96b7bf22020-06-15 10:37:32 +00001261func startCollector(ctx context.Context, dh *DeviceHandler) {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07001262 logger.Debugw(ctx, "starting-collector", log.Fields{"device-id": dh.device.Id})
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001263
1264 defer func() {
1265 dh.lockDevice.Lock()
1266 dh.isCollectorActive = false
1267 dh.lockDevice.Unlock()
1268 }()
1269
1270 dh.lockDevice.Lock()
1271 dh.isCollectorActive = true
1272 dh.lockDevice.Unlock()
1273
Naga Manjunath7615e552019-10-11 22:35:47 +05301274 for {
1275 select {
1276 case <-dh.stopCollector:
divyadesai3af43e12020-08-18 07:10:54 +00001277 logger.Debugw(ctx, "stopping-collector-for-olt", log.Fields{"device-id": dh.device.Id})
Naga Manjunath7615e552019-10-11 22:35:47 +05301278 return
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001279 case <-time.After(time.Duration(dh.metrics.ToPmConfigs().DefaultFreq) * time.Second):
Girish Gowdra34815db2020-05-11 17:18:04 -07001280
khenaidoo106c61a2021-08-11 18:05:46 -04001281 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001282 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001283 logger.Warnw(ctx, "failed-to-list-ports", log.Fields{"device-id": dh.device.Id, "err": err})
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001284 continue
1285 }
khenaidoo106c61a2021-08-11 18:05:46 -04001286 for _, port := range ports.Items {
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301287 // NNI Stats
1288 if port.Type == voltha.Port_ETHERNET_NNI {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001289 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301290 cmnni := dh.portStats.collectNNIMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001291 logger.Debugw(ctx, "collect-nni-metrics", log.Fields{"metrics": cmnni})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001292 go dh.portStats.publishMetrics(ctx, NNIStats, cmnni, port, dh.device.Id, dh.device.Type)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001293 logger.Debugw(ctx, "publish-nni-metrics", log.Fields{"nni-port": port.Label})
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301294 }
1295 // PON Stats
1296 if port.Type == voltha.Port_PON_OLT {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001297 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301298 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
1299 cmpon := dh.portStats.collectPONMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001300 logger.Debugw(ctx, "collect-pon-metrics", log.Fields{"metrics": cmpon})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001301 go dh.portStats.publishMetrics(ctx, PONStats, cmpon, port, dh.device.Id, dh.device.Type)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301302 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001303 logger.Debugw(ctx, "publish-pon-metrics", log.Fields{"pon-port": port.Label})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001304
yasin sapli9e4c5092022-02-01 13:52:33 +00001305 onuGemInfoLst := dh.resourceMgr[intfID].GetOnuGemInfoList(ctx)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001306 if len(onuGemInfoLst) > 0 {
1307 go dh.portStats.collectOnuAndGemStats(ctx, onuGemInfoLst)
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001308 }
Chaitrashree G Sef088112020-02-03 21:39:27 -05001309 }
Naga Manjunath7615e552019-10-11 22:35:47 +05301310 }
1311 }
1312 }
1313}
1314
Mahir Gunyela2e68702022-12-07 00:00:42 -08001315// AdoptDevice adopts the OLT device
npujarec5762e2020-01-01 14:08:48 +05301316func (dh *DeviceHandler) AdoptDevice(ctx context.Context, device *voltha.Device) {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001317 dh.transitionMap = NewTransitionMap(dh)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001318 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id, "Address": device.GetHostAndPort()})
npujarec5762e2020-01-01 14:08:48 +05301319 dh.transitionMap.Handle(ctx, DeviceInit)
Naga Manjunath7615e552019-10-11 22:35:47 +05301320
1321 // Now, set the initial PM configuration for that device
khenaidoo106c61a2021-08-11 18:05:46 -04001322 cgClient, err := dh.coreClient.GetCoreServiceClient()
1323 if err != nil {
1324 logger.Errorw(ctx, "no-core-connection", log.Fields{"device-id": dh.device.Id, "error": err})
1325 return
1326 }
1327
1328 // Now, set the initial PM configuration for that device
1329 if _, err := cgClient.DevicePMConfigUpdate(ctx, dh.metrics.ToPmConfigs()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001330 _ = olterrors.NewErrAdapter("error-updating-performance-metrics", log.Fields{"device-id": device.Id}, err).LogAt(log.ErrorLevel)
Naga Manjunath7615e552019-10-11 22:35:47 +05301331 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301332}
1333
Mahir Gunyela2e68702022-12-07 00:00:42 -08001334// GetOfpDeviceInfo Gets the Ofp information of the given device
khenaidoodc2116e2021-10-19 17:33:19 -04001335func (dh *DeviceHandler) GetOfpDeviceInfo(device *voltha.Device) (*ca.SwitchCapability, error) {
1336 return &ca.SwitchCapability{
cuilin20187b2a8c32019-03-26 19:52:28 -07001337 Desc: &of.OfpDesc{
Devmalya Paul70dd4972019-06-10 15:19:17 +05301338 MfrDesc: "VOLTHA Project",
cuilin20187b2a8c32019-03-26 19:52:28 -07001339 HwDesc: "open_pon",
1340 SwDesc: "open_pon",
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001341 SerialNum: device.SerialNumber,
cuilin20187b2a8c32019-03-26 19:52:28 -07001342 },
1343 SwitchFeatures: &of.OfpSwitchFeatures{
1344 NBuffers: 256,
1345 NTables: 2,
1346 Capabilities: uint32(of.OfpCapabilities_OFPC_FLOW_STATS |
1347 of.OfpCapabilities_OFPC_TABLE_STATS |
1348 of.OfpCapabilities_OFPC_PORT_STATS |
1349 of.OfpCapabilities_OFPC_GROUP_STATS),
1350 },
1351 }, nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301352}
1353
khenaidoo106c61a2021-08-11 18:05:46 -04001354// GetTechProfileDownloadMessage fetches the TechProfileDownloadMessage for the caller.
khenaidoodc2116e2021-10-19 17:33:19 -04001355func (dh *DeviceHandler) GetTechProfileDownloadMessage(ctx context.Context, request *ia.TechProfileInstanceRequestMessage) (*ia.TechProfileDownloadMessage, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001356 ifID, err := plt.IntfIDFromPonPortNum(ctx, request.ParentPonPort)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001357 if err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001358 return nil, err
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001359 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08001360 if dh.flowMgr == nil || dh.flowMgr[ifID] == nil {
1361 return nil, olterrors.NewErrNotFound("no-flow-manager-found", log.Fields{"intf-id": ifID, "parent-device-id": request.ParentDeviceId, "child-device-id": request.DeviceId}, nil).Log()
1362 }
khenaidoo106c61a2021-08-11 18:05:46 -04001363 return dh.flowMgr[ifID].getTechProfileDownloadMessage(ctx, request.TpInstancePath, request.OnuId, request.DeviceId)
Mahir Gunyela2e68702022-12-07 00:00:42 -08001364
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001365}
1366
Neha Sharma96b7bf22020-06-15 10:37:32 +00001367func (dh *DeviceHandler) omciIndication(ctx context.Context, omciInd *oop.OmciIndication) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001368 logger.Debugw(ctx, "omci-indication", log.Fields{"intf-id": omciInd.IntfId, "onu-id": omciInd.OnuId, "parent-device-id": dh.device.Id})
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001369 var deviceType string
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001370 var deviceID string
1371 var proxyDeviceID string
khenaidoo106c61a2021-08-11 18:05:46 -04001372 var childAdapterEndpoint string
cuilin20187b2a8c32019-03-26 19:52:28 -07001373
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001374 transid := extractOmciTransactionID(omciInd.Pkt)
Matteo Scandolo92186242020-06-12 10:54:18 -07001375 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001376 logger.Debugw(ctx, "recv-omci-msg", log.Fields{"intf-id": omciInd.IntfId, "onu-id": omciInd.OnuId, "device-id": dh.device.Id,
Matteo Scandolo92186242020-06-12 10:54:18 -07001377 "omci-transaction-id": transid, "omci-msg": hex.EncodeToString(omciInd.Pkt)})
1378 }
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001379
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001380 onuKey := dh.formOnuKey(omciInd.IntfId, omciInd.OnuId)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301381
1382 if onuInCache, ok := dh.onus.Load(onuKey); !ok {
1383
Neha Sharma96b7bf22020-06-15 10:37:32 +00001384 logger.Debugw(ctx, "omci-indication-for-a-device-not-in-cache.", log.Fields{"intf-id": omciInd.IntfId, "onu-id": omciInd.OnuId, "device-id": dh.device.Id})
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001385 ponPort := plt.IntfIDToPortNo(omciInd.GetIntfId(), voltha.Port_PON_OLT)
cuilin20187b2a8c32019-03-26 19:52:28 -07001386
khenaidoodc2116e2021-10-19 17:33:19 -04001387 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001388 ParentId: dh.device.Id,
1389 OnuId: omciInd.OnuId,
1390 ParentPortNo: ponPort,
1391 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001392 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301393 return olterrors.NewErrNotFound("onu", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001394 "intf-id": omciInd.IntfId,
1395 "onu-id": omciInd.OnuId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001396 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001397 deviceType = onuDevice.Type
1398 deviceID = onuDevice.Id
1399 proxyDeviceID = onuDevice.ProxyAddress.DeviceId
khenaidoo106c61a2021-08-11 18:05:46 -04001400 childAdapterEndpoint = onuDevice.AdapterEndpoint
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001401 //if not exist in cache, then add to cache.
khenaidoo106c61a2021-08-11 18:05:46 -04001402 dh.onus.Store(onuKey, NewOnuDevice(deviceID, deviceType, onuDevice.SerialNumber, omciInd.OnuId, omciInd.IntfId, proxyDeviceID, false, onuDevice.AdapterEndpoint))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001403 } else {
1404 //found in cache
Neha Sharma96b7bf22020-06-15 10:37:32 +00001405 logger.Debugw(ctx, "omci-indication-for-a-device-in-cache.", log.Fields{"intf-id": omciInd.IntfId, "onu-id": omciInd.OnuId, "device-id": dh.device.Id})
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301406 deviceType = onuInCache.(*OnuDevice).deviceType
1407 deviceID = onuInCache.(*OnuDevice).deviceID
1408 proxyDeviceID = onuInCache.(*OnuDevice).proxyDeviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001409 childAdapterEndpoint = onuInCache.(*OnuDevice).adapterEndpoint
cuilin20187b2a8c32019-03-26 19:52:28 -07001410 }
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001411
khenaidoodc2116e2021-10-19 17:33:19 -04001412 if err := dh.sendOmciIndicationToChildAdapter(ctx, childAdapterEndpoint, &ia.OmciMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001413 ParentDeviceId: proxyDeviceID,
1414 ChildDeviceId: deviceID,
1415 Message: omciInd.Pkt,
1416 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301417 return olterrors.NewErrCommunication("omci-request", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001418 "source": dh.openOLT.config.AdapterEndpoint,
1419 "device-type": deviceType,
1420 "destination": childAdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001421 "onu-id": deviceID,
Girish Kumarf26e4882020-03-05 06:49:10 +00001422 "proxy-device-id": proxyDeviceID}, err)
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001423 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001424 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301425}
1426
khenaidoo106c61a2021-08-11 18:05:46 -04001427// //ProcessInterAdapterMessage sends the proxied messages to the target device
1428// // If the proxy address is not found in the unmarshalled message, it first fetches the onu device for which the message
1429// // is meant, and then send the unmarshalled omci message to this onu
khenaidoodc2116e2021-10-19 17:33:19 -04001430// func (dh *DeviceHandler) ProcessInterAdapterMessage(ctx context.Context, msg *ca.InterAdapterMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001431// logger.Debugw(ctx, "process-inter-adapter-message", log.Fields{"msgID": msg.Header.Id})
khenaidoodc2116e2021-10-19 17:33:19 -04001432// if msg.Header.Type == ca.InterAdapterMessageType_OMCI_REQUEST {
khenaidoo106c61a2021-08-11 18:05:46 -04001433// return dh.handleInterAdapterOmciMsg(ctx, msg)
1434// }
1435// return olterrors.NewErrInvalidValue(log.Fields{"inter-adapter-message-type": msg.Header.Type}, nil)
1436// }
cuilin20187b2a8c32019-03-26 19:52:28 -07001437
kesavandb9f54fd2021-11-25 20:08:04 +05301438// ProxyOmciRequests sends the proxied OMCI message to the target device
1439func (dh *DeviceHandler) ProxyOmciRequests(ctx context.Context, omciMsgs *ia.OmciMessages) error {
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301440 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) {
1441 return status.Error(codes.Unavailable, "OLT unreachable")
1442 }
kesavandb9f54fd2021-11-25 20:08:04 +05301443 if omciMsgs.GetProxyAddress() == nil {
1444 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsgs.ChildDeviceId)
1445 if err != nil {
1446 return olterrors.NewErrNotFound("onu", log.Fields{
1447 "parent-device-id": dh.device.Id,
1448 "child-device-id": omciMsgs.ChildDeviceId}, err)
1449 }
1450 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1451 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsgs); err != nil {
1452 return olterrors.NewErrCommunication("send-failed", log.Fields{
1453 "parent-device-id": dh.device.Id,
1454 "child-device-id": omciMsgs.ChildDeviceId}, err)
1455 }
1456 } else {
1457 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsgs.ProxyAddress})
1458 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsgs); err != nil {
1459 return olterrors.NewErrCommunication("send-failed", log.Fields{
1460 "parent-device-id": dh.device.Id,
1461 "child-device-id": omciMsgs.ChildDeviceId}, err)
1462 }
1463 }
1464 return nil
1465}
1466
1467func (dh *DeviceHandler) sendProxyOmciRequests(ctx context.Context, onuDevice *voltha.Device, omciMsgs *ia.OmciMessages) error {
1468 var intfID uint32
1469 var onuID uint32
1470 var connectStatus common.ConnectStatus_Types
1471 if onuDevice != nil {
1472 intfID = onuDevice.ProxyAddress.GetChannelId()
1473 onuID = onuDevice.ProxyAddress.GetOnuId()
1474 connectStatus = onuDevice.ConnectStatus
1475 } else {
1476 intfID = omciMsgs.GetProxyAddress().GetChannelId()
1477 onuID = omciMsgs.GetProxyAddress().GetOnuId()
1478 connectStatus = omciMsgs.GetConnectStatus()
1479 }
1480 if connectStatus != voltha.ConnectStatus_REACHABLE {
1481 logger.Debugw(ctx, "onu-not-reachable--cannot-send-omci", log.Fields{"intf-id": intfID, "onu-id": onuID})
1482
1483 return olterrors.NewErrCommunication("unreachable", log.Fields{
1484 "intf-id": intfID,
1485 "onu-id": onuID}, nil)
1486 }
1487
1488 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1489 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
1490
1491 onuSecOmciMsgList := omciMsgs.GetMessages()
1492
1493 for _, onuSecOmciMsg := range onuSecOmciMsgList {
1494
1495 var omciMessage *oop.OmciMsg
1496 hexPkt := make([]byte, hex.EncodedLen(len(onuSecOmciMsg)))
1497 hex.Encode(hexPkt, onuSecOmciMsg)
1498 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1499
1500 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1501 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1502 //https://jira.opencord.org/browse/VOL-4604
1503 transid := extractOmciTransactionID(onuSecOmciMsg)
1504 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
1505 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
1506
1507 _, err := dh.Client.OmciMsgOut(log.WithSpanFromContext(context.Background(), ctx), omciMessage)
1508 if err != nil {
1509 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
1510 "intf-id": intfID,
1511 "onu-id": onuID,
1512 "message": omciMessage}, err)
1513 }
1514 }
1515 return nil
1516}
1517
khenaidoo106c61a2021-08-11 18:05:46 -04001518// ProxyOmciMessage sends the proxied OMCI message to the target device
khenaidoodc2116e2021-10-19 17:33:19 -04001519func (dh *DeviceHandler) ProxyOmciMessage(ctx context.Context, omciMsg *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001520 logger.Debugw(ctx, "proxy-omci-message", log.Fields{"parent-device-id": omciMsg.ParentDeviceId, "child-device-id": omciMsg.ChildDeviceId, "proxy-address": omciMsg.ProxyAddress, "connect-status": omciMsg.ConnectStatus})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001521
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301522 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) {
1523 return status.Error(codes.Unavailable, "OLT unreachable")
1524 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001525 if omciMsg.GetProxyAddress() == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001526 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsg.ChildDeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001527 if err != nil {
1528 return olterrors.NewErrNotFound("onu", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001529 "parent-device-id": dh.device.Id,
1530 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001531 }
khenaidoo106c61a2021-08-11 18:05:46 -04001532 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1533 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001534 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001535 "parent-device-id": dh.device.Id,
1536 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001537 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001538 } else {
khenaidoo106c61a2021-08-11 18:05:46 -04001539 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsg.ProxyAddress})
1540 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001541 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001542 "parent-device-id": dh.device.Id,
1543 "child-device-id": omciMsg.ChildDeviceId}, err)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001544 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001545 }
1546 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301547}
1548
khenaidoodc2116e2021-10-19 17:33:19 -04001549func (dh *DeviceHandler) sendProxiedMessage(ctx context.Context, onuDevice *voltha.Device, omciMsg *ia.OmciMessage) error {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001550 var intfID uint32
1551 var onuID uint32
Esin Karamanccb714b2019-11-29 15:02:06 +00001552 var connectStatus common.ConnectStatus_Types
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001553 if onuDevice != nil {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001554 intfID = onuDevice.ProxyAddress.GetChannelId()
1555 onuID = onuDevice.ProxyAddress.GetOnuId()
1556 connectStatus = onuDevice.ConnectStatus
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001557 } else {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001558 intfID = omciMsg.GetProxyAddress().GetChannelId()
1559 onuID = omciMsg.GetProxyAddress().GetOnuId()
1560 connectStatus = omciMsg.GetConnectStatus()
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001561 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001562 if connectStatus != voltha.ConnectStatus_REACHABLE {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001563 logger.Debugw(ctx, "onu-not-reachable--cannot-send-omci", log.Fields{"intf-id": intfID, "onu-id": onuID})
David K. Bainbridge794735f2020-02-11 21:01:37 -08001564
Thomas Lee S94109f12020-03-03 16:39:29 +05301565 return olterrors.NewErrCommunication("unreachable", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001566 "intf-id": intfID,
1567 "onu-id": onuID}, nil)
cuilin20187b2a8c32019-03-26 19:52:28 -07001568 }
1569
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001570 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1571 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
kesavandb9f54fd2021-11-25 20:08:04 +05301572 // https://jira.opencord.org/browse/VOL-4604
lcuie24ef182019-04-29 22:58:36 -07001573 var omciMessage *oop.OmciMsg
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001574 hexPkt := make([]byte, hex.EncodedLen(len(omciMsg.Message)))
1575 hex.Encode(hexPkt, omciMsg.Message)
1576 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1577
1578 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1579 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1580 transid := extractOmciTransactionID(omciMsg.Message)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001581 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001582 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
cuilin20187b2a8c32019-03-26 19:52:28 -07001583
Neha Sharma8f4e4322020-08-06 10:51:53 +00001584 _, err := dh.Client.OmciMsgOut(log.WithSpanFromContext(context.Background(), ctx), omciMessage)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001585 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301586 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001587 "intf-id": intfID,
1588 "onu-id": onuID,
1589 "message": omciMessage}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001590 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001591 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001592}
1593
David K. Bainbridge794735f2020-02-11 21:01:37 -08001594func (dh *DeviceHandler) activateONU(ctx context.Context, intfID uint32, onuID int64, serialNum *oop.SerialNumber, serialNumber string) error {
kesavand494c2082020-08-31 11:16:12 +05301595 logger.Debugw(ctx, "activate-onu", log.Fields{"intf-id": intfID, "onu-id": onuID, "serialNum": serialNum, "serialNumber": serialNumber, "device-id": dh.device.Id, "OmccEncryption": dh.openOLT.config.OmccEncryption})
yasin saplibddc2d72022-02-08 13:10:17 +00001596 if err := dh.resourceMgr[intfID].AddNewOnuGemInfoToCacheAndKvStore(ctx, uint32(onuID), serialNumber); err != nil {
Matteo Scandolo92186242020-06-12 10:54:18 -07001597 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": onuID, "intf-id": intfID}, err)
Andrea Campanellab83b39d2020-03-30 11:41:16 +02001598 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001599 var pir uint32 = 1000000
kesavand494c2082020-08-31 11:16:12 +05301600 Onu := oop.Onu{IntfId: intfID, OnuId: uint32(onuID), SerialNumber: serialNum, Pir: pir, OmccEncryption: dh.openOLT.config.OmccEncryption}
npujarec5762e2020-01-01 14:08:48 +05301601 if _, err := dh.Client.ActivateOnu(ctx, &Onu); err != nil {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001602 st, _ := status.FromError(err)
1603 if st.Code() == codes.AlreadyExists {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001604 logger.Debugw(ctx, "onu-activation-in-progress", log.Fields{"SerialNumber": serialNumber, "onu-id": onuID, "device-id": dh.device.Id})
1605
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001606 } else {
Thomas Lee S985938d2020-05-04 11:40:41 +05301607 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": Onu, "device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001608 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001609 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001610 logger.Infow(ctx, "activated-onu", log.Fields{"SerialNumber": serialNumber, "device-id": dh.device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001611 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001612 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001613}
1614
Mahir Gunyela2e68702022-12-07 00:00:42 -08001615// getChildDevice function can be used in general to get child device, if not found in cache the function will
1616// get from core and update the cache and return the child device.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301617func (dh *DeviceHandler) getChildDevice(ctx context.Context, sn string, parentPortNo uint32) *OnuDevice {
1618 var InCacheOnuDev *OnuDevice
1619 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1620 if onuInCache.(*OnuDevice).serialNumber == sn {
1621 InCacheOnuDev = onuInCache.(*OnuDevice)
1622 return false
1623 }
1624 return true
1625 })
1626 //Got the onu device from cache return
1627 if InCacheOnuDev != nil {
1628 logger.Debugw(ctx, "Got child device from cache", log.Fields{"onudev": InCacheOnuDev.serialNumber})
1629 return InCacheOnuDev
1630 }
1631 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1632 ParentId: dh.device.Id,
1633 SerialNumber: sn,
1634 ParentPortNo: parentPortNo,
1635 })
1636 //No device found in core return nil
1637 if onuDevice == nil {
1638 return nil
1639 }
1640 onuID := onuDevice.ProxyAddress.OnuId
1641 intfID := plt.PortNoToIntfID(parentPortNo, voltha.Port_PON_OLT)
1642 onuKey := dh.formOnuKey(intfID, onuID)
1643
1644 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuDevice.ProxyAddress.OnuId, intfID, onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
1645 dh.onus.Store(onuKey, onuDev)
1646 logger.Debugw(ctx, "got child device from core", log.Fields{"onudev": onuDevice})
1647 return onuDev
1648}
1649
1650func (dh *DeviceHandler) checkForResourceExistance(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) (bool, error) {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001651 channelID := onuDiscInd.GetIntfId()
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001652 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301653 tpInstExists := false
Matt Jeanneret53539512019-07-20 14:47:02 -04001654
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301655 //CheckOnuDevExistenceAtOnuDiscovery if true , a check will be made for the existence of the onu device. If the onu device
1656 // still exists , the onu discovery will be ignored, else a check for active techprofiles for ONU is checked.
1657 if !dh.openOLT.CheckOnuDevExistenceAtOnuDiscovery {
1658 onuDev := dh.getChildDevice(ctx, sn, parentPortNo)
1659 if onuDev != nil {
1660 var onuGemInfo *rsrcMgr.OnuGemInfo
1661 var err error
1662 if onuGemInfo, err = dh.resourceMgr[channelID].GetOnuGemInfo(ctx, onuDev.onuID); err != nil {
1663 logger.Warnw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuDev.onuID})
1664 return false, err
1665 }
1666 if onuGemInfo != nil {
1667 for _, uni := range onuGemInfo.UniPorts {
1668 uniID := plt.UniIDFromPortNum(uni)
1669 tpIDs := dh.resourceMgr[channelID].GetTechProfileIDForOnu(ctx, onuDev.onuID, uniID)
1670 if len(tpIDs) != 0 {
1671 logger.Warnw(ctx, "Techprofile present for ONU, ignoring onu discovery", log.Fields{"onuID": onuDev.onuID})
1672 tpInstExists = true
1673 break
1674 }
1675 }
1676 }
1677 }
1678 return tpInstExists, nil
1679 }
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301680
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301681 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1682 ParentId: dh.device.Id,
1683 SerialNumber: sn,
1684 ParentPortNo: parentPortNo,
1685 })
1686 if onuDevice != nil {
1687 logger.Infow(ctx, "Child device still present ignoring discovery indication", log.Fields{"sn": sn})
1688 return true, nil
1689 }
1690 logger.Infow(ctx, "No device present in core , continuing with discovery", log.Fields{"sn": sn})
1691
1692 return false, nil
1693
1694}
1695
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001696// processDiscONULOSClear clears the LOS Alarm if it's needed
1697func (dh *DeviceHandler) processDiscONULOSClear(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) {
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301698 var alarmInd oop.OnuAlarmIndication
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001699 raisedTs := time.Now().Unix()
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301700
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001701 /* When PON cable disconnected and connected back from OLT, it was expected OnuAlarmIndication
1702 with "los_status: off" should be raised but BAL does not raise this Alarm hence manually sending
1703 OnuLosClear event on receiving OnuDiscoveryIndication for the Onu after checking whether
1704 OnuLosRaise event sent for it */
1705 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1706 if onuInCache.(*OnuDevice).serialNumber == sn && onuInCache.(*OnuDevice).losRaised {
1707 if onuDiscInd.GetIntfId() != onuInCache.(*OnuDevice).intfID {
1708 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
1709 "previousIntfId": onuInCache.(*OnuDevice).intfID,
1710 "currentIntfId": onuDiscInd.GetIntfId()})
1711 // TODO:: Should we need to ignore raising OnuLosClear event
1712 // when onu connected to different PON?
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301713 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001714 alarmInd.IntfId = onuInCache.(*OnuDevice).intfID
1715 alarmInd.OnuId = onuInCache.(*OnuDevice).onuID
1716 alarmInd.LosStatus = statusCheckOff
1717 go func() {
1718 if err := dh.eventMgr.onuAlarmIndication(ctx, &alarmInd, onuInCache.(*OnuDevice).deviceID, raisedTs); err != nil {
1719 logger.Errorw(ctx, "indication-failed", log.Fields{"err": err})
1720 }
1721 }()
1722 // stop iterating
1723 return false
1724 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301725 return true
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001726 })
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301727}
1728
1729func (dh *DeviceHandler) onuDiscIndication(ctx context.Context, onuDiscInd *oop.OnuDiscIndication) error {
1730 channelID := onuDiscInd.GetIntfId()
1731 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
1732
1733 sn := dh.stringifySerialNumber(onuDiscInd.SerialNumber)
1734 logger.Infow(ctx, "new-discovery-indication", log.Fields{"sn": sn})
1735
1736 tpInstExists, errtp := dh.checkForResourceExistance(ctx, onuDiscInd, sn)
1737 if errtp != nil {
1738 return errtp
1739 }
1740 if tpInstExists {
1741 //ignore the discovery if tpinstance is present.
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001742 logger.Debugw(ctx, "ignoring-onu-indication-as-tp-already-exists", log.Fields{"sn": sn})
David K. Bainbridge794735f2020-02-11 21:01:37 -08001743 return nil
Amit Ghoshe5c6a852020-02-10 15:09:46 +00001744 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001745 inProcess, existing := dh.discOnus.LoadOrStore(sn, true)
1746
1747 // if the ONU existed, handle the LOS Alarm
1748 if existing {
1749
1750 if inProcess.(bool) {
1751 // if we're currently processing the ONU on a different thread, do nothing
1752 logger.Warnw(ctx, "onu-sn-is-being-processed", log.Fields{"sn": sn})
1753 return nil
1754 }
1755 // if we had dealt with this ONU before, but the process didn't complete (this happens in case of errors)
1756 // then continue processing it
1757 logger.Debugw(ctx, "onu-processing-had-completed-but-new-indication", log.Fields{"sn": sn})
1758
1759 dh.processDiscONULOSClear(ctx, onuDiscInd, sn)
serkantule333d152022-10-12 01:44:00 +03001760 return nil
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301761 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001762
1763 defer func() {
1764 // once the function completes set the value to false so that
1765 // we know the processing has inProcess.
1766 // Note that this is done after checking if we are already processing
1767 // to avoid changing the value from a different thread
1768 logger.Infow(ctx, "onu-processing-completed", log.Fields{"sn": sn})
1769 dh.discOnus.Store(sn, false)
1770 }()
1771
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001772 var onuID uint32
Matteo Scandolo945e4012019-12-12 14:16:11 -08001773
1774 // check the ONU is already know to the OLT
1775 // NOTE the second time the ONU is discovered this should return a device
khenaidoodc2116e2021-10-19 17:33:19 -04001776 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001777 ParentId: dh.device.Id,
1778 SerialNumber: sn,
1779 })
Matteo Scandolo945e4012019-12-12 14:16:11 -08001780
1781 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001782 logger.Debugw(ctx, "core-proxy-get-child-device-failed", log.Fields{"parentDevice": dh.device.Id, "err": err, "sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001783 if e, ok := status.FromError(err); ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001784 logger.Debugw(ctx, "core-proxy-get-child-device-failed-with-code", log.Fields{"errCode": e.Code(), "sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001785 switch e.Code() {
1786 case codes.Internal:
1787 // this probably means NOT FOUND, so just create a new device
1788 onuDevice = nil
1789 case codes.DeadlineExceeded:
1790 // if the call times out, cleanup and exit
1791 dh.discOnus.Delete(sn)
Girish Kumarf26e4882020-03-05 06:49:10 +00001792 return olterrors.NewErrTimeout("get-child-device", log.Fields{"device-id": dh.device.Id}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001793 }
1794 }
1795 }
1796
1797 if onuDevice == nil {
1798 // NOTE this should happen a single time, and only if GetChildDevice returns NotFound
Neha Sharma96b7bf22020-06-15 10:37:32 +00001799 logger.Debugw(ctx, "creating-new-onu", log.Fields{"sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001800 // we need to create a new ChildDevice
Matt Jeanneret53539512019-07-20 14:47:02 -04001801 ponintfid := onuDiscInd.GetIntfId()
yasin saplibddc2d72022-02-08 13:10:17 +00001802 onuID, err = dh.resourceMgr[ponintfid].GetONUID(ctx)
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001803
Neha Sharma96b7bf22020-06-15 10:37:32 +00001804 logger.Infow(ctx, "creating-new-onu-got-onu-id", log.Fields{"sn": sn, "onuId": onuID})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001805
1806 if err != nil {
1807 // if we can't create an ID in resource manager,
1808 // cleanup and exit
Matteo Scandolo945e4012019-12-12 14:16:11 -08001809 dh.discOnus.Delete(sn)
Girish Kumarf26e4882020-03-05 06:49:10 +00001810 return olterrors.NewErrAdapter("resource-manager-get-onu-id-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001811 "pon-intf-id": ponintfid,
1812 "serial-number": sn}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001813 }
1814
khenaidoodc2116e2021-10-19 17:33:19 -04001815 if onuDevice, err = dh.sendChildDeviceDetectedToCore(ctx, &ca.DeviceDiscovery{
khenaidoo106c61a2021-08-11 18:05:46 -04001816 ParentId: dh.device.Id,
1817 ParentPortNo: parentPortNo,
1818 ChannelId: channelID,
1819 VendorId: string(onuDiscInd.SerialNumber.GetVendorId()),
1820 SerialNumber: sn,
1821 OnuId: onuID,
1822 }); err != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08001823 dh.discOnus.Delete(sn)
yasin saplibddc2d72022-02-08 13:10:17 +00001824 dh.resourceMgr[ponintfid].FreeonuID(ctx, []uint32{onuID}) // NOTE I'm not sure this method is actually cleaning up the right thing
Thomas Lee S94109f12020-03-03 16:39:29 +05301825 return olterrors.NewErrAdapter("core-proxy-child-device-detected-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001826 "pon-intf-id": ponintfid,
1827 "serial-number": sn}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001828 }
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001829 if err := dh.eventMgr.OnuDiscoveryIndication(ctx, onuDiscInd, dh.device.Id, onuDevice.Id, onuID, sn, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001830 logger.Warnw(ctx, "discovery-indication-failed", log.Fields{"err": err})
Kent Hagermane6ff1012020-07-14 15:07:53 -04001831 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001832 logger.Infow(ctx, "onu-child-device-added",
Shrey Baid807a2a02020-04-09 12:52:45 +05301833 log.Fields{"onuDevice": onuDevice,
1834 "sn": sn,
Matteo Scandolo92186242020-06-12 10:54:18 -07001835 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05301836 "device-id": dh.device.Id})
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001837 }
Matteo Scandolo945e4012019-12-12 14:16:11 -08001838
khenaidoo106c61a2021-08-11 18:05:46 -04001839 // Setup the gRPC connection to the adapter responsible for that onuDevice, if not setup yet
1840 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1841 err = dh.setupChildInterAdapterClient(subCtx, onuDevice.AdapterEndpoint)
1842 cancel()
1843 if err != nil {
1844 return olterrors.NewErrCommunication("no-connection-to-child-adapter", log.Fields{"device-id": onuDevice.Id}, err)
1845 }
1846
Matteo Scandolo945e4012019-12-12 14:16:11 -08001847 // we can now use the existing ONU Id
1848 onuID = onuDevice.ProxyAddress.OnuId
Mahir Gunyele77977b2019-06-27 05:36:22 -07001849 //Insert the ONU into cache to use in OnuIndication.
1850 //TODO: Do we need to remove this from the cache on ONU change, or wait for overwritten on next discovery.
Neha Sharma96b7bf22020-06-15 10:37:32 +00001851 logger.Debugw(ctx, "onu-discovery-indication-key-create",
Matteo Scandolo92186242020-06-12 10:54:18 -07001852 log.Fields{"onu-id": onuID,
Shrey Baid807a2a02020-04-09 12:52:45 +05301853 "intfId": onuDiscInd.GetIntfId(),
1854 "sn": sn})
Mahir Gunyele77977b2019-06-27 05:36:22 -07001855 onuKey := dh.formOnuKey(onuDiscInd.GetIntfId(), onuID)
Matt Jeanneret53539512019-07-20 14:47:02 -04001856
khenaidoo106c61a2021-08-11 18:05:46 -04001857 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuID, onuDiscInd.GetIntfId(), onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301858 dh.onus.Store(onuKey, onuDev)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001859 logger.Debugw(ctx, "new-onu-device-discovered",
Shrey Baid807a2a02020-04-09 12:52:45 +05301860 log.Fields{"onu": onuDev,
1861 "sn": sn})
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001862
khenaidoodc2116e2021-10-19 17:33:19 -04001863 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001864 DeviceId: onuDevice.Id,
1865 ParentDeviceId: dh.device.Id,
1866 OperStatus: common.OperStatus_DISCOVERED,
1867 ConnStatus: common.ConnectStatus_REACHABLE,
1868 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301869 return olterrors.NewErrAdapter("failed-to-update-device-state", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001870 "device-id": onuDevice.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00001871 "serial-number": sn}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001872 }
khenaidoo106c61a2021-08-11 18:05:46 -04001873
Neha Sharma96b7bf22020-06-15 10:37:32 +00001874 logger.Infow(ctx, "onu-discovered-reachable", log.Fields{"device-id": onuDevice.Id, "sn": sn})
Kent Hagermane6ff1012020-07-14 15:07:53 -04001875 if err := dh.activateONU(ctx, onuDiscInd.IntfId, int64(onuID), onuDiscInd.SerialNumber, sn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301876 return olterrors.NewErrAdapter("onu-activation-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001877 "device-id": onuDevice.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00001878 "serial-number": sn}, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08001879 }
1880 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001881}
1882
Mahir Gunyelb0046752021-02-26 13:51:05 -08001883func (dh *DeviceHandler) onuIndication(ctx context.Context, onuInd *oop.OnuIndication) error {
cuilin20187b2a8c32019-03-26 19:52:28 -07001884
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001885 ponPort := plt.IntfIDToPortNo(onuInd.GetIntfId(), voltha.Port_PON_OLT)
Mahir Gunyele77977b2019-06-27 05:36:22 -07001886 var onuDevice *voltha.Device
David K. Bainbridge794735f2020-02-11 21:01:37 -08001887 var err error
Mahir Gunyele77977b2019-06-27 05:36:22 -07001888 foundInCache := false
Neha Sharma96b7bf22020-06-15 10:37:32 +00001889 logger.Debugw(ctx, "onu-indication-key-create",
Shrey Baid807a2a02020-04-09 12:52:45 +05301890 log.Fields{"onuId": onuInd.OnuId,
1891 "intfId": onuInd.GetIntfId(),
Thomas Lee S985938d2020-05-04 11:40:41 +05301892 "device-id": dh.device.Id})
Mahir Gunyele77977b2019-06-27 05:36:22 -07001893 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.OnuId)
Mahir Gunyelb0046752021-02-26 13:51:05 -08001894 serialNumber := dh.stringifySerialNumber(onuInd.SerialNumber)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301895
David K. Bainbridge794735f2020-02-11 21:01:37 -08001896 errFields := log.Fields{"device-id": dh.device.Id}
1897
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301898 if onuInCache, ok := dh.onus.Load(onuKey); ok {
1899
Mahir Gunyele77977b2019-06-27 05:36:22 -07001900 //If ONU id is discovered before then use GetDevice to get onuDevice because it is cheaper.
1901 foundInCache = true
David K. Bainbridge794735f2020-02-11 21:01:37 -08001902 errFields["onu-id"] = onuInCache.(*OnuDevice).deviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001903 onuDevice, err = dh.getDeviceFromCore(ctx, onuInCache.(*OnuDevice).deviceID)
cuilin20187b2a8c32019-03-26 19:52:28 -07001904 } else {
Mahir Gunyele77977b2019-06-27 05:36:22 -07001905 //If ONU not found in adapter cache then we have to use GetChildDevice to get onuDevice
1906 if serialNumber != "" {
David K. Bainbridge794735f2020-02-11 21:01:37 -08001907 errFields["serial-number"] = serialNumber
Mahir Gunyele77977b2019-06-27 05:36:22 -07001908 } else {
David K. Bainbridge794735f2020-02-11 21:01:37 -08001909 errFields["onu-id"] = onuInd.OnuId
1910 errFields["parent-port-no"] = ponPort
Mahir Gunyele77977b2019-06-27 05:36:22 -07001911 }
khenaidoodc2116e2021-10-19 17:33:19 -04001912 onuDevice, err = dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001913 ParentId: dh.device.Id,
1914 SerialNumber: serialNumber,
1915 OnuId: onuInd.OnuId,
1916 ParentPortNo: ponPort,
1917 })
cuilin20187b2a8c32019-03-26 19:52:28 -07001918 }
Mahir Gunyele77977b2019-06-27 05:36:22 -07001919
David K. Bainbridge794735f2020-02-11 21:01:37 -08001920 if err != nil || onuDevice == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001921 return olterrors.NewErrNotFound("onu-device", errFields, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001922 }
1923
David K. Bainbridge794735f2020-02-11 21:01:37 -08001924 if onuDevice.ParentPortNo != ponPort {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001925 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001926 "previousIntfId": onuDevice.ParentPortNo,
1927 "currentIntfId": ponPort})
1928 }
1929
1930 if onuDevice.ProxyAddress.OnuId != onuInd.OnuId {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001931 logger.Warnw(ctx, "onu-id-mismatch-possible-if-voltha-and-olt-rebooted", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05301932 "expected-onu-id": onuDevice.ProxyAddress.OnuId,
1933 "received-onu-id": onuInd.OnuId,
Thomas Lee S985938d2020-05-04 11:40:41 +05301934 "device-id": dh.device.Id})
David K. Bainbridge794735f2020-02-11 21:01:37 -08001935 }
1936 if !foundInCache {
1937 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.GetOnuId())
1938
khenaidoo106c61a2021-08-11 18:05:46 -04001939 dh.onus.Store(onuKey, NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuInd.GetOnuId(), onuInd.GetIntfId(), onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint))
David K. Bainbridge794735f2020-02-11 21:01:37 -08001940
1941 }
kesavand7cf3a052020-08-28 12:49:18 +05301942 if onuInd.OperState == "down" && onuInd.FailReason != oop.OnuIndication_ONU_ACTIVATION_FAIL_REASON_NONE {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001943 if err := dh.eventMgr.onuActivationIndication(ctx, onuActivationFailEvent, onuInd, dh.device.Id, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001944 logger.Warnw(ctx, "onu-activation-indication-reporting-failed", log.Fields{"err": err})
kesavand7cf3a052020-08-28 12:49:18 +05301945 }
1946 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001947 if err := dh.updateOnuStates(ctx, onuDevice, onuInd); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001948 return olterrors.NewErrCommunication("state-update-failed", errFields, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08001949 }
1950 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001951}
1952
Neha Sharma96b7bf22020-06-15 10:37:32 +00001953func (dh *DeviceHandler) updateOnuStates(ctx context.Context, onuDevice *voltha.Device, onuInd *oop.OnuIndication) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001954 logger.Debugw(ctx, "onu-indication-for-state", log.Fields{"onuIndication": onuInd, "device-id": onuDevice.Id, "operStatus": onuDevice.OperStatus, "adminStatus": onuDevice.AdminState})
Girish Gowdra748de5c2020-07-01 10:27:52 -07001955 if onuInd.AdminState == "down" || onuInd.OperState == "down" {
1956 // The ONU has gone admin_state "down" or oper_state "down" - we expect the ONU to send discovery again
1957 // The ONU admin_state is "up" while "oper_state" is down in cases where ONU activation fails. In this case
1958 // the ONU sends Discovery again.
Girish Gowdra429f9502020-05-04 13:22:16 -07001959 dh.discOnus.Delete(onuDevice.SerialNumber)
Amit Ghosh9bbc5652020-02-17 13:37:32 +00001960 // Tests have shown that we sometimes get OperState as NOT down even if AdminState is down, forcing it
1961 if onuInd.OperState != "down" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001962 logger.Warnw(ctx, "onu-admin-state-down", log.Fields{"operState": onuInd.OperState})
Amit Ghosh9bbc5652020-02-17 13:37:32 +00001963 onuInd.OperState = "down"
1964 }
1965 }
1966
David K. Bainbridge794735f2020-02-11 21:01:37 -08001967 switch onuInd.OperState {
khenaidoo106c61a2021-08-11 18:05:46 -04001968 case "up", "down":
Neha Sharma96b7bf22020-06-15 10:37:32 +00001969 logger.Debugw(ctx, "sending-interadapter-onu-indication", log.Fields{"onuIndication": onuInd, "device-id": onuDevice.Id, "operStatus": onuDevice.OperStatus, "adminStatus": onuDevice.AdminState})
khenaidoo106c61a2021-08-11 18:05:46 -04001970
khenaidoodc2116e2021-10-19 17:33:19 -04001971 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001972 DeviceId: onuDevice.Id,
1973 OnuIndication: onuInd,
1974 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001975 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301976 return olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001977 "onu-indicator": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04001978 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001979 "device-type": onuDevice.Type,
Girish Kumarf26e4882020-03-05 06:49:10 +00001980 "device-id": onuDevice.Id}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001981 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001982 default:
Girish Kumarf26e4882020-03-05 06:49:10 +00001983 return olterrors.NewErrInvalidValue(log.Fields{"oper-state": onuInd.OperState}, nil)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001984 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001985 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001986}
1987
cuilin20187b2a8c32019-03-26 19:52:28 -07001988func (dh *DeviceHandler) stringifySerialNumber(serialNum *oop.SerialNumber) string {
1989 if serialNum != nil {
1990 return string(serialNum.VendorId) + dh.stringifyVendorSpecific(serialNum.VendorSpecific)
cuilin20187b2a8c32019-03-26 19:52:28 -07001991 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001992 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07001993}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05001994func (dh *DeviceHandler) deStringifySerialNumber(serialNum string) (*oop.SerialNumber, error) {
1995 decodedStr, err := hex.DecodeString(serialNum[4:])
1996 if err != nil {
1997 return nil, err
1998 }
1999 return &oop.SerialNumber{
2000 VendorId: []byte(serialNum[:4]),
Girish Gowdraa09aeab2020-09-14 16:30:52 -07002001 VendorSpecific: decodedStr,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002002 }, nil
2003}
cuilin20187b2a8c32019-03-26 19:52:28 -07002004
2005func (dh *DeviceHandler) stringifyVendorSpecific(vendorSpecific []byte) string {
Mahir Gunyelb0046752021-02-26 13:51:05 -08002006 if len(vendorSpecific) > 3 {
2007 tmp := fmt.Sprintf("%x", (uint32(vendorSpecific[0])>>4)&0x0f) +
2008 fmt.Sprintf("%x", uint32(vendorSpecific[0]&0x0f)) +
2009 fmt.Sprintf("%x", (uint32(vendorSpecific[1])>>4)&0x0f) +
2010 fmt.Sprintf("%x", (uint32(vendorSpecific[1]))&0x0f) +
2011 fmt.Sprintf("%x", (uint32(vendorSpecific[2])>>4)&0x0f) +
2012 fmt.Sprintf("%x", (uint32(vendorSpecific[2]))&0x0f) +
2013 fmt.Sprintf("%x", (uint32(vendorSpecific[3])>>4)&0x0f) +
2014 fmt.Sprintf("%x", (uint32(vendorSpecific[3]))&0x0f)
2015 return tmp
2016 }
2017 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07002018}
2019
Mahir Gunyela2e68702022-12-07 00:00:42 -08002020// UpdateFlowsBulk upates the bulk flow
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002021func (dh *DeviceHandler) UpdateFlowsBulk() error {
Thomas Lee S94109f12020-03-03 16:39:29 +05302022 return olterrors.ErrNotImplemented
cuilin20187b2a8c32019-03-26 19:52:28 -07002023}
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002024
Mahir Gunyela2e68702022-12-07 00:00:42 -08002025// GetChildDevice returns the child device for given parent port and onu id
Neha Sharma96b7bf22020-06-15 10:37:32 +00002026func (dh *DeviceHandler) GetChildDevice(ctx context.Context, parentPort, onuID uint32) (*voltha.Device, error) {
2027 logger.Debugw(ctx, "getchilddevice",
Shrey Baid807a2a02020-04-09 12:52:45 +05302028 log.Fields{"pon-port": parentPort,
Matteo Scandolo92186242020-06-12 10:54:18 -07002029 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05302030 "device-id": dh.device.Id})
khenaidoo106c61a2021-08-11 18:05:46 -04002031
khenaidoodc2116e2021-10-19 17:33:19 -04002032 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002033 ParentId: dh.device.Id,
2034 OnuId: onuID,
2035 ParentPortNo: parentPort,
2036 })
2037
Girish Gowdru0c588b22019-04-23 23:24:56 -04002038 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002039 return nil, olterrors.NewErrNotFound("onu-device", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002040 "intf-id": parentPort,
2041 "onu-id": onuID}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04002042 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002043 logger.Debugw(ctx, "successfully-received-child-device-from-core", log.Fields{"child-device-id": onuDevice.Id, "child-device-sn": onuDevice.SerialNumber})
David K. Bainbridge794735f2020-02-11 21:01:37 -08002044 return onuDevice, nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302045}
2046
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002047// SendPacketInToCore sends packet-in to core
2048// For this, it calls SendPacketIn of the core-proxy which uses a device specific topic to send the request.
2049// The adapter handling the device creates a device specific topic
Neha Sharma96b7bf22020-06-15 10:37:32 +00002050func (dh *DeviceHandler) SendPacketInToCore(ctx context.Context, logicalPort uint32, packetPayload []byte) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002051 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002052 logger.Debugw(ctx, "send-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002053 "port": logicalPort,
2054 "packet": hex.EncodeToString(packetPayload),
2055 "device-id": dh.device.Id,
2056 })
2057 }
khenaidoo106c61a2021-08-11 18:05:46 -04002058
khenaidoodc2116e2021-10-19 17:33:19 -04002059 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002060 DeviceId: dh.device.Id,
2061 Port: logicalPort,
2062 Packet: packetPayload,
2063 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302064 return olterrors.NewErrCommunication("packet-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002065 "source": "adapter",
2066 "destination": "core",
2067 "device-id": dh.device.Id,
2068 "logical-port": logicalPort,
Girish Kumarf26e4882020-03-05 06:49:10 +00002069 "packet": hex.EncodeToString(packetPayload)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002070 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002071 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002072 logger.Debugw(ctx, "sent-packet-in-to-core-successfully", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002073 "packet": hex.EncodeToString(packetPayload),
2074 "device-id": dh.device.Id,
2075 })
2076 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002077 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002078}
2079
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002080// UpdatePmConfig updates the pm metrics.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002081func (dh *DeviceHandler) UpdatePmConfig(ctx context.Context, pmConfigs *voltha.PmConfigs) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002082 logger.Infow(ctx, "update-pm-configs", log.Fields{"device-id": dh.device.Id, "pm-configs": pmConfigs})
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002083
2084 if pmConfigs.DefaultFreq != dh.metrics.ToPmConfigs().DefaultFreq {
2085 dh.metrics.UpdateFrequency(pmConfigs.DefaultFreq)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002086 logger.Debugf(ctx, "frequency-updated")
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002087 }
2088
Kent Hagermane6ff1012020-07-14 15:07:53 -04002089 if !pmConfigs.Grouped {
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002090 metrics := dh.metrics.GetSubscriberMetrics()
2091 for _, m := range pmConfigs.Metrics {
2092 metrics[m.Name].Enabled = m.Enabled
2093
2094 }
2095 }
2096}
2097
khenaidoodc2116e2021-10-19 17:33:19 -04002098func (dh *DeviceHandler) handleFlows(ctx context.Context, device *voltha.Device, flows *of.FlowChanges, flowMetadata *of.FlowMetadata) []error {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002099 var err error
Andrea Campanellac63bba92020-03-10 17:01:04 +01002100 var errorsList []error
2101
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002102 if dh.getDeviceDeletionInProgressFlag() {
2103 // The device itself is going to be reset as part of deletion. So nothing to be done.
2104 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2105 return nil
2106 }
2107
Girish Gowdru0c588b22019-04-23 23:24:56 -04002108 if flows != nil {
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002109 for _, flow := range flows.ToRemove.Items {
yasin saplid0566272021-12-21 09:10:30 +00002110 intfID := dh.getIntfIDFromFlow(ctx, flow)
Girish Gowdracefae192020-03-19 18:14:10 -07002111
Neha Sharma96b7bf22020-06-15 10:37:32 +00002112 logger.Debugw(ctx, "removing-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302113 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002114 "intfId": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302115 "flowToRemove": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002116 if flow_utils.HasGroup(flow) {
2117 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupRemove)
2118 } else {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002119 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
2120 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2121 } else {
2122 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, false, nil)
2123 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002124 }
Girish Gowdracefae192020-03-19 18:14:10 -07002125 if err != nil {
Elia Battiston2aaf4342022-02-07 15:16:38 +01002126 if werr, ok := err.(olterrors.WrappedError); ok && status.Code(werr.Unwrap()) == codes.NotFound {
2127 //The flow we want to remove is not there, there is no need to throw an error
2128 logger.Warnw(ctx, "flow-to-remove-not-found",
2129 log.Fields{
2130 "ponIf": intfID,
2131 "flowToRemove": flow,
2132 "error": err,
2133 })
2134 } else {
2135 errorsList = append(errorsList, err)
2136 }
Girish Gowdracefae192020-03-19 18:14:10 -07002137 }
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002138 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302139
2140 for _, flow := range flows.ToAdd.Items {
yasin saplid0566272021-12-21 09:10:30 +00002141 intfID := dh.getIntfIDFromFlow(ctx, flow)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002142 logger.Debugw(ctx, "adding-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302143 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002144 "ponIf": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302145 "flowToAdd": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002146 if flow_utils.HasGroup(flow) {
2147 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupAdd)
2148 } else {
yasin saplid0566272021-12-21 09:10:30 +00002149 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002150 // The flow manager module could be uninitialized if the flow arrives too soon before the device has reconciled fully
2151 logger.Errorw(ctx, "flow-manager-uninitialized", log.Fields{"device-id": device.Id})
2152 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2153 } else {
yasin saplid0566272021-12-21 09:10:30 +00002154 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, true, flowMetadata)
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002155 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002156 }
Andrea Campanellac63bba92020-03-10 17:01:04 +01002157 if err != nil {
2158 errorsList = append(errorsList, err)
2159 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302160 }
Girish Gowdru0c588b22019-04-23 23:24:56 -04002161 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002162
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002163 return errorsList
2164}
2165
2166func (dh *DeviceHandler) handleGroups(ctx context.Context, groups *of.FlowGroupChanges) []error {
2167 var err error
2168 var errorsList []error
2169
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002170 if dh.getDeviceDeletionInProgressFlag() {
2171 // The device itself is going to be reset as part of deletion. So nothing to be done.
2172 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
2173 return nil
2174 }
2175
Girish Gowdracefae192020-03-19 18:14:10 -07002176 // Whether we need to synchronize multicast group adds and modifies like flow add and delete needs to be investigated
Esin Karamanccb714b2019-11-29 15:02:06 +00002177 if groups != nil {
2178 for _, group := range groups.ToAdd.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002179 // err = dh.groupMgr.AddGroup(ctx, group)
2180 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupAdd)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002181 if err != nil {
2182 errorsList = append(errorsList, err)
2183 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002184 }
2185 for _, group := range groups.ToUpdate.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002186 // err = dh.groupMgr.ModifyGroup(ctx, group)
2187 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupModify)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002188 if err != nil {
2189 errorsList = append(errorsList, err)
2190 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002191 }
Esin Karamand519bbf2020-07-01 11:16:03 +00002192 for _, group := range groups.ToRemove.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002193 // err = dh.groupMgr.DeleteGroup(ctx, group)
2194 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupRemove)
Esin Karamand519bbf2020-07-01 11:16:03 +00002195 if err != nil {
2196 errorsList = append(errorsList, err)
2197 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002198 }
2199 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002200
2201 return errorsList
2202}
2203
Mahir Gunyela2e68702022-12-07 00:00:42 -08002204// UpdateFlowsIncrementally updates the device flow
khenaidoodc2116e2021-10-19 17:33:19 -04002205func (dh *DeviceHandler) UpdateFlowsIncrementally(ctx context.Context, device *voltha.Device, flows *of.FlowChanges, groups *of.FlowGroupChanges, flowMetadata *of.FlowMetadata) error {
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002206
2207 var errorsList []error
Girish Gowdra950326e2021-11-05 12:43:24 -07002208
2209 if dh.getDeviceDeletionInProgressFlag() {
2210 // The device itself is going to be reset as part of deletion. So nothing to be done.
2211 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2212 return nil
2213 }
nikesh.krishnan0897d472023-09-05 18:35:08 +05302214 if dh.transitionMap.currentDeviceState != deviceStateUp {
2215 logger.Error(ctx, "device-is-not-up--not-handling-flows-or-groups", log.Fields{"device-id": device.Id, "current-device-state": dh.transitionMap.currentDeviceState})
2216 return fmt.Errorf("device-is-not-up--not-handling-flows-or-groups")
2217 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002218 logger.Debugw(ctx, "received-incremental-flowupdate-in-device-handler", log.Fields{"device-id": device.Id, "flows": flows, "groups": groups, "flowMetadata": flowMetadata})
2219 errorsList = append(errorsList, dh.handleFlows(ctx, device, flows, flowMetadata)...)
2220 errorsList = append(errorsList, dh.handleGroups(ctx, groups)...)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002221 if len(errorsList) > 0 {
2222 return fmt.Errorf("errors-installing-flows-groups, errors:%v", errorsList)
2223 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002224 logger.Debugw(ctx, "updated-flows-incrementally-successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0c588b22019-04-23 23:24:56 -04002225 return nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302226}
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002227
Mahir Gunyela2e68702022-12-07 00:00:42 -08002228// DisableDevice disables the given device
2229// It marks the following for the given device:
2230// Device-Handler Admin-State : down
2231// Device Port-State: UNKNOWN
2232// Device Oper-State: UNKNOWN
Neha Sharma96b7bf22020-06-15 10:37:32 +00002233func (dh *DeviceHandler) DisableDevice(ctx context.Context, device *voltha.Device) error {
Chaitrashree G S44124192019-08-07 20:21:36 -04002234 /* On device disable ,admin state update has to be done prior sending request to agent since
2235 the indication thread may processes invalid indications of ONU and OLT*/
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002236 if dh.Client != nil {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002237 if _, err := dh.Client.DisableOlt(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002238 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
Girish Kumarf26e4882020-03-05 06:49:10 +00002239 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": device.Id}, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002240 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002241 }
Chaitrashree G S44124192019-08-07 20:21:36 -04002242 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002243 logger.Debugw(ctx, "olt-disabled", log.Fields{"device-id": device.Id})
Chaitrashree G S44124192019-08-07 20:21:36 -04002244 /* Discovered ONUs entries need to be cleared , since on device disable the child devices goes to
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002245 UNREACHABLE state which needs to be configured again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302246
2247 dh.discOnus = sync.Map{}
2248 dh.onus = sync.Map{}
2249
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002250 dh.lockDevice.RLock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302251 //stopping the stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002252 if dh.isCollectorActive {
2253 dh.stopCollector <- true
2254 }
2255 dh.lockDevice.RUnlock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302256
Neha Sharma96b7bf22020-06-15 10:37:32 +00002257 go dh.notifyChildDevices(ctx, "unreachable")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002258 cloned := proto.Clone(device).(*voltha.Device)
Thomas Lee S985938d2020-05-04 11:40:41 +05302259 //Update device Admin state
2260 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04002261
kdarapu1afeceb2020-02-12 01:38:09 -05002262 // Update the all pon ports state on that device to disable and NNI remains active as NNI remains active in openolt agent.
khenaidoodc2116e2021-10-19 17:33:19 -04002263 if err := dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002264 DeviceId: cloned.Id,
2265 PortTypeFilter: ^uint32(1 << voltha.Port_PON_OLT),
2266 OperStatus: voltha.OperStatus_UNKNOWN,
2267 }); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002268 return olterrors.NewErrAdapter("ports-state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002269 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002270 logger.Debugw(ctx, "disable-device-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002271 return nil
2272}
2273
Neha Sharma96b7bf22020-06-15 10:37:32 +00002274func (dh *DeviceHandler) notifyChildDevices(ctx context.Context, state string) {
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002275 // Update onu state as unreachable in onu adapter
2276 onuInd := oop.OnuIndication{}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302277 onuInd.OperState = state
khenaidoo106c61a2021-08-11 18:05:46 -04002278
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002279 //get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04002280 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002281 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002282 logger.Errorw(ctx, "failed-to-get-child-devices-information", log.Fields{"device-id": dh.device.Id, "err": err})
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002283 }
2284 if onuDevices != nil {
2285 for _, onuDevice := range onuDevices.Items {
khenaidoodc2116e2021-10-19 17:33:19 -04002286 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002287 DeviceId: onuDevice.Id,
2288 OnuIndication: &onuInd,
2289 })
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002290 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002291 logger.Errorw(ctx, "failed-to-send-inter-adapter-message", log.Fields{"OnuInd": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002292 "From Adapter": dh.openOLT.config.AdapterEndpoint, "DeviceType": onuDevice.Type, "device-id": onuDevice.Id})
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002293 }
2294
2295 }
2296 }
2297
2298}
2299
Mahir Gunyela2e68702022-12-07 00:00:42 -08002300// ReenableDevice re-enables the olt device after disable
2301// It marks the following for the given device:
2302// Device-Handler Admin-State : up
2303// Device Port-State: ACTIVE
2304// Device Oper-State: ACTIVE
Neha Sharma96b7bf22020-06-15 10:37:32 +00002305func (dh *DeviceHandler) ReenableDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302306 if dh.Client != nil {
2307 if _, err := dh.Client.ReenableOlt(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
2308 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
2309 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, err)
2310 }
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302311 }
nikesh.krishnane363ace2023-02-28 03:12:38 +05302312 } else {
2313 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, errors.New("nil device client"))
2314
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302315 }
nikesh.krishnane363ace2023-02-28 03:12:38 +05302316
Neha Sharma96b7bf22020-06-15 10:37:32 +00002317 logger.Debug(ctx, "olt-reenabled")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002318
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002319 // Update the all ports state on that device to enable
khenaidoo106c61a2021-08-11 18:05:46 -04002320 ports, err := dh.listDevicePortsFromCore(ctx, device.Id)
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002321 var retError error
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002322 if err != nil {
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002323 retError = olterrors.NewErrAdapter("list-ports-failed", log.Fields{"device-id": device.Id}, err)
2324 } else {
2325 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
2326 retError = olterrors.NewErrAdapter("port-status-update-failed-after-olt-reenable", log.Fields{"device": device}, err)
2327 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002328 }
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002329 if retError == nil {
2330 //Update the device oper status as ACTIVE
2331 device.OperStatus = voltha.OperStatus_ACTIVE
2332 } else {
2333 //Update the device oper status as FAILED
2334 device.OperStatus = voltha.OperStatus_FAILED
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002335 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002336 dh.device = device
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002337
khenaidoodc2116e2021-10-19 17:33:19 -04002338 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002339 DeviceId: device.Id,
2340 OperStatus: device.OperStatus,
2341 ConnStatus: device.ConnectStatus,
2342 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302343 return olterrors.NewErrAdapter("state-update-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002344 "device-id": device.Id,
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002345 "connect-status": device.ConnectStatus,
2346 "oper-status": device.OperStatus}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002347 }
kesavand39e0aa32020-01-28 20:58:50 -05002348
Neha Sharma96b7bf22020-06-15 10:37:32 +00002349 logger.Debugw(ctx, "reenabledevice-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002350
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002351 return retError
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002352}
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002353
npujarec5762e2020-01-01 14:08:48 +05302354func (dh *DeviceHandler) clearUNIData(ctx context.Context, onu *rsrcMgr.OnuGemInfo) error {
Devmalya Paul495b94a2019-08-27 19:42:00 -04002355 var uniID uint32
2356 var err error
Gustavo Silva41af9122022-10-11 11:05:13 -03002357 var errs []error
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302358 for _, port := range onu.UniPorts {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002359 uniID = plt.UniIDFromPortNum(port)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002360 logger.Debugw(ctx, "clearing-resource-data-for-uni-port", log.Fields{"port": port, "uni-id": uniID})
A R Karthick1f85b802019-10-11 05:06:05 +00002361 /* Delete tech-profile instance from the KV store */
Mahir Gunyela2e68702022-12-07 00:00:42 -08002362 if dh.flowMgr == nil || dh.flowMgr[onu.IntfID] == nil {
2363 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu-no-flowmng", log.Fields{"onu-id": onu.OnuID})
2364 } else {
2365 if err = dh.flowMgr[onu.IntfID].DeleteTechProfileInstances(ctx, onu.IntfID, onu.OnuID, uniID); err != nil {
2366 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002367 errs = append(errs, err)
Mahir Gunyela2e68702022-12-07 00:00:42 -08002368 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002369 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002370 logger.Debugw(ctx, "deleted-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002371 tpIDList := dh.resourceMgr[onu.IntfID].GetTechProfileIDForOnu(ctx, onu.OnuID, uniID)
Gamze Abakafee36392019-10-03 11:17:24 +00002372 for _, tpID := range tpIDList {
yasin saplibddc2d72022-02-08 13:10:17 +00002373 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "upstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002374 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002375 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002376 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002377 logger.Debugw(ctx, "removed-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002378 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "downstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002379 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002380 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002381 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002382 logger.Debugw(ctx, "removed-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302383 }
yasin saplibddc2d72022-02-08 13:10:17 +00002384 dh.resourceMgr[onu.IntfID].FreePONResourcesForONU(ctx, onu.OnuID, uniID)
2385 if err = dh.resourceMgr[onu.IntfID].RemoveTechProfileIDsForOnu(ctx, onu.OnuID, uniID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002386 logger.Debugw(ctx, "failed-to-remove-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002387 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302388 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002389 logger.Debugw(ctx, "removed-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002390 if err = dh.resourceMgr[onu.IntfID].DeletePacketInGemPortForOnu(ctx, onu.OnuID, port); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002391 logger.Debugw(ctx, "failed-to-remove-gemport-pkt-in", log.Fields{"intfid": onu.IntfID, "onuid": onu.OnuID, "uniId": uniID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002392 errs = append(errs, err)
A R Karthick1f85b802019-10-11 05:06:05 +00002393 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002394 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002395 if len(errs) > 0 {
2396 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-clear-uni-data, errors:%v",
2397 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2398 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002399 return nil
2400}
2401
Devmalya Paul495b94a2019-08-27 19:42:00 -04002402// DeleteDevice deletes the device instance from openolt handler array. Also clears allocated resource manager resources. Also reboots the OLT hardware!
npujarec5762e2020-01-01 14:08:48 +05302403func (dh *DeviceHandler) DeleteDevice(ctx context.Context, device *voltha.Device) error {
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002404 logger.Debugw(ctx, "function-entry-delete-device", log.Fields{"device-id": dh.device.Id})
Devmalya Paul495b94a2019-08-27 19:42:00 -04002405 /* Clear the KV store data associated with the all the UNI ports
2406 This clears up flow data and also resource map data for various
2407 other pon resources like alloc_id and gemport_id
2408 */
Girish Gowdra950326e2021-11-05 12:43:24 -07002409
2410 dh.setDeviceDeletionInProgressFlag(true)
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002411
2412 dh.StopAllFlowRoutines(ctx)
Girish Gowdra950326e2021-11-05 12:43:24 -07002413
Gustavo Silva41af9122022-10-11 11:05:13 -03002414 err := dh.cleanupDeviceResources(ctx)
2415 if err != nil {
2416 logger.Errorw(ctx, "could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id, "err": err})
2417 } else {
2418 logger.Debugw(ctx, "successfully-removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
2419 }
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002420
Himani Chawla49a5d562020-11-25 11:53:44 +05302421 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002422 // Stop the Stats collector
2423 if dh.isCollectorActive {
2424 dh.stopCollector <- true
2425 }
2426 // stop the heartbeat check routine
2427 if dh.isHeartbeatCheckActive {
2428 dh.stopHeartbeatCheck <- true
2429 }
Himani Chawla49a5d562020-11-25 11:53:44 +05302430 // Stop the read indication only if it the routine is active
2431 if dh.isReadIndicationRoutineActive {
2432 dh.stopIndications <- true
2433 }
2434 dh.lockDevice.RUnlock()
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002435 dh.removeOnuIndicationChannels(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002436 //Reset the state
2437 if dh.Client != nil {
2438 if _, err := dh.Client.Reboot(ctx, new(oop.Empty)); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002439 go func() {
2440 failureReason := fmt.Sprintf("Failed to reboot during device delete request with error: %s", err.Error())
2441 if err = dh.eventMgr.oltRebootFailedEvent(ctx, dh.device.Id, failureReason, time.Now().Unix()); err != nil {
2442 logger.Errorw(ctx, "on-olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err})
2443 }
2444 }()
2445 logger.Errorw(ctx, "olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002446 }
2447 }
Girish Gowdrab1caa442020-10-19 12:24:39 -07002448 // There is no need to update the core about operation status and connection status of the OLT.
2449 // The OLT is getting deleted anyway and the core might have already cleared the OLT device from its DB.
2450 // So any attempt to update the operation status and connection status of the OLT will result in core throwing an error back,
2451 // because the device does not exist in DB.
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002452
khenaidoo7eb2d672021-10-22 19:08:50 -04002453 // Stop the adapter grpc clients for that parent device
2454 dh.deleteAdapterClients(ctx)
Gustavo Silva41af9122022-10-11 11:05:13 -03002455 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002456}
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002457
2458// StopAllFlowRoutines stops all flow routines
2459func (dh *DeviceHandler) StopAllFlowRoutines(ctx context.Context) {
2460 var wg sync.WaitGroup
2461 wg.Add(1) // for the mcast routine below to finish
2462 go dh.StopAllMcastHandlerRoutines(ctx, &wg)
2463 for _, flMgr := range dh.flowMgr {
2464 if flMgr != nil {
2465 wg.Add(1) // for the flow handler routine below to finish
2466 go flMgr.StopAllFlowHandlerRoutines(ctx, &wg)
2467 }
2468 }
2469 if !dh.waitForTimeoutOrCompletion(&wg, time.Second*30) {
2470 logger.Warnw(ctx, "timed out waiting for stopping flow and group handlers", log.Fields{"deviceID": dh.device.Id})
2471 } else {
2472 logger.Infow(ctx, "all flow and group handlers shutdown gracefully", log.Fields{"deviceID": dh.device.Id})
2473 }
2474}
2475
Gustavo Silva41af9122022-10-11 11:05:13 -03002476func (dh *DeviceHandler) cleanupDeviceResources(ctx context.Context) error {
2477 var errs []error
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002478 if dh.resourceMgr != nil {
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302479 var ponPort uint32
Girish Gowdra9602eb42020-09-09 15:50:39 -07002480 for ponPort = 0; ponPort < dh.totalPonPorts; ponPort++ {
yasin sapli9e4c5092022-02-01 13:52:33 +00002481 onuGemData := dh.resourceMgr[ponPort].GetOnuGemInfoList(ctx)
Andrey Pozolotin32b36562021-06-02 10:23:26 +03002482 for i, onu := range onuGemData {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002483 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
Gustavo Silva41af9122022-10-11 11:05:13 -03002484 if err := dh.clearUNIData(ctx, &onuGemData[i]); err != nil {
2485 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302486 }
2487 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002488 if err := dh.resourceMgr[ponPort].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2489 errs = append(errs, err)
2490 }
2491 if err := dh.resourceMgr[ponPort].DeleteAllOnuGemInfoForIntf(ctx); err != nil {
2492 errs = append(errs, err)
2493 }
2494 if err := dh.resourceMgr[ponPort].DeleteMcastQueueForIntf(ctx); err != nil {
2495 errs = append(errs, err)
2496 }
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002497 if err := dh.resourceMgr[ponPort].Delete(ctx, ponPort); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002498 errs = append(errs, err)
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002499 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002500 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002501 }
2502 // Clean up NNI manager's data
2503 if err := dh.resourceMgr[dh.totalPonPorts].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2504 errs = append(errs, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002505 }
A R Karthick1f85b802019-10-11 05:06:05 +00002506
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002507 dh.CloseKVClient(ctx)
2508
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002509 // Take one final sweep at cleaning up KV store for the OLT device
2510 // Clean everything at <base-path-prefix>/openolt/<device-id>
Gustavo Silva41af9122022-10-11 11:05:13 -03002511 if err := dh.kvStore.DeleteWithPrefix(ctx, ""); err != nil {
2512 errs = append(errs, err)
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002513 }
2514
Devmalya Paul495b94a2019-08-27 19:42:00 -04002515 /*Delete ONU map for the device*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302516 dh.onus.Range(func(key interface{}, value interface{}) bool {
2517 dh.onus.Delete(key)
2518 return true
2519 })
2520
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002521 /*Delete discovered ONU map for the device*/
2522 dh.discOnus.Range(func(key interface{}, value interface{}) bool {
2523 dh.discOnus.Delete(key)
2524 return true
2525 })
Gustavo Silva41af9122022-10-11 11:05:13 -03002526 if len(errs) > 0 {
2527 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-device-delete, errors:%v",
2528 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2529 }
2530 return nil
Devmalya Paul495b94a2019-08-27 19:42:00 -04002531}
2532
Mahir Gunyela2e68702022-12-07 00:00:42 -08002533// RebootDevice reboots the given device
Neha Sharma96b7bf22020-06-15 10:37:32 +00002534func (dh *DeviceHandler) RebootDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302535 if dh.Client != nil {
2536 if _, err := dh.Client.Reboot(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
2537 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, err)
2538 }
2539 } else {
2540 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, errors.New("nil device client"))
2541
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002542 }
nikesh.krishnane363ace2023-02-28 03:12:38 +05302543
Neha Sharma96b7bf22020-06-15 10:37:32 +00002544 logger.Debugw(ctx, "rebooted-device-successfully", log.Fields{"device-id": device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002545 return nil
2546}
2547
David K. Bainbridge794735f2020-02-11 21:01:37 -08002548func (dh *DeviceHandler) handlePacketIndication(ctx context.Context, packetIn *oop.PacketIndication) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002549 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002550 logger.Debugw(ctx, "received-packet-in", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002551 "packet-indication": *packetIn,
2552 "device-id": dh.device.Id,
2553 "packet": hex.EncodeToString(packetIn.Pkt),
2554 })
2555 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002556 if dh.flowMgr == nil || dh.flowMgr[packetIn.IntfId] == nil {
2557 return olterrors.NewErrNotFound("flow-manager", log.Fields{"intf-id": packetIn.IntfId, "packet": hex.EncodeToString(packetIn.Pkt)}, nil)
2558 }
Girish Gowdra9602eb42020-09-09 15:50:39 -07002559 logicalPortNum, err := dh.flowMgr[packetIn.IntfId].GetLogicalPortFromPacketIn(ctx, packetIn)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002560 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002561 return olterrors.NewErrNotFound("logical-port", log.Fields{"packet": hex.EncodeToString(packetIn.Pkt)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002562 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002563 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002564 logger.Debugw(ctx, "sending-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002565 "logical-port-num": logicalPortNum,
2566 "device-id": dh.device.Id,
2567 "packet": hex.EncodeToString(packetIn.Pkt),
2568 })
2569 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002570
khenaidoodc2116e2021-10-19 17:33:19 -04002571 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002572 DeviceId: dh.device.Id,
2573 Port: logicalPortNum,
2574 Packet: packetIn.Pkt,
2575 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302576 return olterrors.NewErrCommunication("send-packet-in", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002577 "destination": "core",
Thomas Lee S985938d2020-05-04 11:40:41 +05302578 "source": dh.device.Type,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002579 "device-id": dh.device.Id,
2580 "packet": hex.EncodeToString(packetIn.Pkt),
2581 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002582 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002583
Matteo Scandolo92186242020-06-12 10:54:18 -07002584 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002585 logger.Debugw(ctx, "success-sending-packet-in-to-core!", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002586 "packet": hex.EncodeToString(packetIn.Pkt),
2587 "device-id": dh.device.Id,
2588 })
2589 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002590 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002591}
2592
Mahir Gunyela2e68702022-12-07 00:00:42 -08002593// PacketOutNNI sends packet-out from VOLTHA to OLT on the NNI provided
2594func (dh *DeviceHandler) PacketOutNNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2595 nniIntfID, err := plt.IntfIDFromNniPortNum(ctx, uint32(egressPortNo))
2596 if err != nil {
2597 return olterrors.NewErrInvalidValue(log.Fields{
2598 "egress-nni-port": egressPortNo,
2599 "device-id": dh.device.Id,
2600 }, err)
2601 }
2602 uplinkPkt := oop.UplinkPacket{IntfId: nniIntfID, Pkt: packet.Data}
2603
2604 if logger.V(log.DebugLevel) {
2605 logger.Debugw(ctx, "sending-packet-to-nni", log.Fields{
2606 "uplink-pkt": uplinkPkt,
2607 "packet": hex.EncodeToString(packet.Data),
2608 "device-id": dh.device.Id,
2609 })
2610 }
2611
2612 if _, err := dh.Client.UplinkPacketOut(ctx, &uplinkPkt); err != nil {
2613 return olterrors.NewErrCommunication("packet-out-to-nni", log.Fields{
2614 "packet": hex.EncodeToString(packet.Data),
2615 "device-id": dh.device.Id,
2616 }, err)
2617 }
2618 return nil
2619}
2620
2621// PacketOutUNI sends packet-out from VOLTHA to OLT on the UNI provided
2622func (dh *DeviceHandler) PacketOutUNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2623 outerEthType := (uint16(packet.Data[12]) << 8) | uint16(packet.Data[13])
2624 innerEthType := (uint16(packet.Data[16]) << 8) | uint16(packet.Data[17])
2625 if outerEthType == 0x8942 || outerEthType == 0x88cc {
2626 // Do not packet-out lldp packets on uni port.
2627 // ONOS has no clue about uni/nni ports, it just packets out on all
2628 // available ports on the Logical Switch. It should not be interested
2629 // in the UNI links.
2630 logger.Debugw(ctx, "dropping-lldp-packet-out-on-uni", log.Fields{
2631 "device-id": dh.device.Id,
2632 })
2633 return nil
2634 }
2635 if outerEthType == 0x88a8 || outerEthType == 0x8100 {
2636 if innerEthType == 0x8100 {
2637 // q-in-q 802.1ad or 802.1q double tagged packet.
2638 // slice out the outer tag.
2639 packet.Data = append(packet.Data[:12], packet.Data[16:]...)
2640 if logger.V(log.DebugLevel) {
2641 logger.Debugw(ctx, "packet-now-single-tagged", log.Fields{
2642 "packet-data": hex.EncodeToString(packet.Data),
2643 "device-id": dh.device.Id,
2644 })
2645 }
2646 }
2647 }
2648 intfID := plt.IntfIDFromUniPortNum(uint32(egressPortNo))
2649 onuID := plt.OnuIDFromPortNum(uint32(egressPortNo))
2650 uniID := plt.UniIDFromPortNum(uint32(egressPortNo))
2651 var gemPortID uint32
2652 err := olterrors.NewErrNotFound("no-flow-manager-found-for-packet-out", log.Fields{"device-id": dh.device.Id}, nil).(error)
2653 if dh.flowMgr != nil && dh.flowMgr[intfID] != nil {
2654 gemPortID, err = dh.flowMgr[intfID].GetPacketOutGemPortID(ctx, intfID, onuID, uint32(egressPortNo), packet.Data)
2655 }
2656 if err != nil {
2657 // In this case the openolt agent will receive the gemPortID as 0.
2658 // The agent tries to retrieve the gemPortID in this case.
2659 // This may not always succeed at the agent and packetOut may fail.
2660 logger.Errorw(ctx, "failed-to-retrieve-gemport-id-for-packet-out", log.Fields{
2661 "intf-id": intfID,
2662 "onu-id": onuID,
2663 "uni-id": uniID,
2664 "packet": hex.EncodeToString(packet.Data),
2665 "device-id": dh.device.Id,
2666 "error": err,
2667 })
2668 }
2669
2670 onuPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, PortNo: uint32(egressPortNo), GemportId: gemPortID, Pkt: packet.Data}
2671 if logger.V(log.DebugLevel) {
2672 logger.Debugw(ctx, "sending-packet-to-onu", log.Fields{
2673 "egress-port-no": egressPortNo,
2674 "intf-id": intfID,
2675 "onu-id": onuID,
2676 "uni-id": uniID,
2677 "gem-port-id": gemPortID,
2678 "packet": hex.EncodeToString(packet.Data),
2679 "device-id": dh.device.Id,
2680 })
2681 }
2682
2683 if _, err := dh.Client.OnuPacketOut(ctx, &onuPkt); err != nil {
2684 return olterrors.NewErrCommunication("packet-out-send", log.Fields{
2685 "source": "adapter",
2686 "destination": "onu",
2687 "egress-port-number": egressPortNo,
2688 "intf-id": intfID,
2689 "oni-id": onuID,
2690 "uni-id": uniID,
2691 "gem-port-id": gemPortID,
2692 "packet": hex.EncodeToString(packet.Data),
2693 "device-id": dh.device.Id,
2694 }, err)
2695 }
2696 return nil
2697}
2698
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002699// PacketOut sends packet-out from VOLTHA to OLT on the egress port provided
khenaidoo106c61a2021-08-11 18:05:46 -04002700func (dh *DeviceHandler) PacketOut(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002701 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002702 logger.Debugw(ctx, "incoming-packet-out", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002703 "device-id": dh.device.Id,
2704 "egress-port-no": egressPortNo,
2705 "pkt-length": len(packet.Data),
2706 "packet": hex.EncodeToString(packet.Data),
2707 })
2708 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002709
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002710 egressPortType := plt.IntfIDToPortTypeName(uint32(egressPortNo))
Mahir Gunyela2e68702022-12-07 00:00:42 -08002711 var err error
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002712 if egressPortType == voltha.Port_ETHERNET_UNI {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002713 err = dh.PacketOutUNI(ctx, egressPortNo, packet)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002714 } else if egressPortType == voltha.Port_ETHERNET_NNI {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002715 err = dh.PacketOutNNI(ctx, egressPortNo, packet)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002716 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002717 logger.Warnw(ctx, "packet-out-to-this-interface-type-not-implemented", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302718 "egress-port-no": egressPortNo,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002719 "egressPortType": egressPortType,
2720 "packet": hex.EncodeToString(packet.Data),
Thomas Lee S985938d2020-05-04 11:40:41 +05302721 "device-id": dh.device.Id,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002722 })
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002723 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002724 return err
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002725}
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002726
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002727func (dh *DeviceHandler) formOnuKey(intfID, onuID uint32) string {
2728 return "" + strconv.Itoa(int(intfID)) + "." + strconv.Itoa(int(onuID))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002729}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302730
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002731func startHeartbeatCheck(ctx context.Context, dh *DeviceHandler) {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002732
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002733 defer func() {
2734 dh.lockDevice.Lock()
2735 dh.isHeartbeatCheckActive = false
2736 dh.lockDevice.Unlock()
2737 }()
2738
2739 dh.lockDevice.Lock()
2740 dh.isHeartbeatCheckActive = true
2741 dh.lockDevice.Unlock()
2742
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302743 // start the heartbeat check towards the OLT.
2744 var timerCheck *time.Timer
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302745 dh.heartbeatSignature = dh.getHeartbeatSignature(ctx)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302746
2747 for {
2748 heartbeatTimer := time.NewTimer(dh.openOLT.HeartbeatCheckInterval)
2749 select {
2750 case <-heartbeatTimer.C:
Neha Sharma8f4e4322020-08-06 10:51:53 +00002751 ctxWithTimeout, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.openOLT.GrpcTimeoutInterval)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002752 if heartBeat, err := dh.Client.HeartbeatCheck(ctxWithTimeout, new(oop.Empty)); err != nil {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002753 logger.Warnw(ctx, "heartbeat-failed", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302754 if timerCheck == nil {
2755 // start a after func, when expired will update the state to the core
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002756 timerCheck = time.AfterFunc(dh.openOLT.HeartbeatFailReportInterval, func() { dh.updateStateUnreachable(ctx) })
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302757 }
2758 } else {
2759 if timerCheck != nil {
2760 if timerCheck.Stop() {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002761 logger.Debugw(ctx, "got-heartbeat-within-timeout", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302762 }
2763 timerCheck = nil
2764 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302765 if dh.heartbeatSignature == 0 || dh.heartbeatSignature == heartBeat.HeartbeatSignature {
2766 if dh.heartbeatSignature == 0 {
2767 // First time the signature will be 0, update the signture to DB when not found.
2768 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
2769 dh.heartbeatSignature = heartBeat.HeartbeatSignature
2770 }
2771 logger.Infow(ctx, "heartbeat signature", log.Fields{"sign": dh.heartbeatSignature})
2772
2773 dh.lockDevice.RLock()
2774 // Stop the read indication only if it the routine is active
2775 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2776 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2777 // on next execution of the readIndication routine.
2778 if !dh.isReadIndicationRoutineActive {
2779 // Start reading indications
2780 go func() {
2781 if err = dh.readIndications(ctx); err != nil {
2782 _ = olterrors.NewErrAdapter("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
2783 }
2784 }()
2785 }
2786 dh.lockDevice.RUnlock()
2787
2788 } else {
2789 logger.Warn(ctx, "Heartbeat signature changed, OLT is rebooted. Cleaningup resources.")
2790 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
2791 dh.heartbeatSignature = heartBeat.HeartbeatSignature
2792 go dh.updateStateRebooted(ctx)
2793 }
2794
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302795 }
2796 cancel()
2797 case <-dh.stopHeartbeatCheck:
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002798 logger.Debugw(ctx, "stopping-heartbeat-check", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302799 return
2800 }
2801 }
2802}
2803
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002804func (dh *DeviceHandler) updateStateUnreachable(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -04002805 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002806 if err != nil || device == nil {
Girish Gowdrab1caa442020-10-19 12:24:39 -07002807 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
2808 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
2809 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
2810 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
2811 // cleanup in the adapter was already done during DeleteDevice API handler routine.
Kent Hagermane6ff1012020-07-14 15:07:53 -04002812 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
Girish Gowdrab1caa442020-10-19 12:24:39 -07002813 // Immediately return, otherwise accessing a null 'device' struct would cause panic
2814 return
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002815 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302816
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302817 logger.Warnw(ctx, "update-state-unreachable", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002818 "admin-state": device.AdminState, "oper-status": device.OperStatus})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002819 if device.ConnectStatus == voltha.ConnectStatus_REACHABLE {
khenaidoodc2116e2021-10-19 17:33:19 -04002820 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002821 DeviceId: dh.device.Id,
2822 OperStatus: voltha.OperStatus_UNKNOWN,
2823 ConnStatus: voltha.ConnectStatus_UNREACHABLE,
2824 }); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04002825 _ = olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002826 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302827 /*
2828 if err = dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
2829 DeviceId: dh.device.Id,
2830 PortTypeFilter: 0,
2831 OperStatus: voltha.OperStatus_UNKNOWN,
2832 }); err != nil {
2833 _ = olterrors.NewErrAdapter("port-update-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
2834 }
2835 */
Gamze Abaka07868a52020-12-17 14:19:28 +00002836
2837 //raise olt communication failure event
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07002838 raisedTs := time.Now().Unix()
khenaidoo106c61a2021-08-11 18:05:46 -04002839 cloned := proto.Clone(device).(*voltha.Device)
2840 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
2841 cloned.OperStatus = voltha.OperStatus_UNKNOWN
2842 dh.device = cloned // update local copy of the device
2843 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
Gamze Abaka07868a52020-12-17 14:19:28 +00002844
Girish Gowdra3ab6d212020-03-24 17:33:15 -07002845 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002846 // Stop the Stats collector
2847 if dh.isCollectorActive {
2848 dh.stopCollector <- true
2849 }
2850 // stop the heartbeat check routine
2851 if dh.isHeartbeatCheckActive {
2852 dh.stopHeartbeatCheck <- true
2853 }
Girish Gowdra3ab6d212020-03-24 17:33:15 -07002854 // Stop the read indication only if it the routine is active
2855 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2856 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2857 // on next execution of the readIndication routine.
2858 if dh.isReadIndicationRoutineActive {
2859 dh.stopIndications <- true
2860 }
2861 dh.lockDevice.RUnlock()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002862 dh.transitionMap.Handle(ctx, DeviceInit)
2863
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302864 }
2865}
kesavand39e0aa32020-01-28 20:58:50 -05002866
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302867func (dh *DeviceHandler) updateStateRebooted(ctx context.Context) {
2868 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
2869 if err != nil || device == nil {
2870 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
2871 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
2872 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
2873 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
2874 // cleanup in the adapter was already done during DeleteDevice API handler routine.
2875 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
2876 // Immediately return, otherwise accessing a null 'device' struct would cause panic
2877 return
2878 }
Mahir Gunyel701df862023-09-07 16:16:04 -07002879 //Starting the cleanup process
2880 dh.setDeviceDeletionInProgressFlag(true)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302881
2882 logger.Warnw(ctx, "update-state-rebooted", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
2883 "admin-state": device.AdminState, "oper-status": device.OperStatus, "conn-status": voltha.ConnectStatus_UNREACHABLE})
2884 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
2885 DeviceId: dh.device.Id,
2886 OperStatus: voltha.OperStatus_REBOOTED,
2887 ConnStatus: voltha.ConnectStatus_REACHABLE,
2888 }); err != nil {
2889 _ = olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
2890 }
2891
2892 dh.lockDevice.RLock()
2893 // Stop the read indication only if it the routine is active
2894 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2895 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2896 // on next execution of the readIndication routine.
2897 if dh.isReadIndicationRoutineActive {
2898 dh.stopIndications <- true
2899 }
2900 dh.lockDevice.RUnlock()
2901
2902 //raise olt communication failure event
2903 raisedTs := time.Now().Unix()
2904 cloned := proto.Clone(device).(*voltha.Device)
2905 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
2906 cloned.OperStatus = voltha.OperStatus_UNKNOWN
2907 dh.device = cloned // update local copy of the device
2908 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
2909
Gustavo Silva41af9122022-10-11 11:05:13 -03002910 if err := dh.cleanupDeviceResources(ctx); err != nil {
2911 logger.Errorw(ctx, "failure-in-cleanup-device-resources", log.Fields{"device-id": dh.device.Id, "err": err})
2912 } else {
2913 logger.Debugw(ctx, "removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
2914 }
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002915
2916 dh.lockDevice.RLock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302917 // Stop the Stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002918 if dh.isCollectorActive {
2919 dh.stopCollector <- true
2920 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302921 // stop the heartbeat check routine
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002922 if dh.isHeartbeatCheckActive {
2923 dh.stopHeartbeatCheck <- true
2924 }
2925 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302926
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002927 dh.StopAllFlowRoutines(ctx)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302928
2929 //reset adapter reconcile flag
2930 dh.adapterPreviouslyConnected = false
2931 for {
2932
2933 childDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
2934 if err != nil || childDevices == nil {
2935 logger.Errorw(ctx, "Failed to get child devices from core", log.Fields{"deviceID": dh.device.Id})
2936 continue
2937 }
2938 if len(childDevices.Items) == 0 {
2939 logger.Infow(ctx, "All childDevices cleared from core, proceed with device init", log.Fields{"deviceID": dh.device.Id})
2940 break
2941 } else {
2942 logger.Warn(ctx, "Not all child devices are cleared, continuing to wait")
2943 time.Sleep(5 * time.Second)
2944 }
2945
2946 }
Mahir Gunyel701df862023-09-07 16:16:04 -07002947 //Cleanup completed , reset the flag
2948 dh.setDeviceDeletionInProgressFlag(false)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302949 logger.Infow(ctx, "cleanup complete after reboot , moving to init", log.Fields{"deviceID": device.Id})
2950 dh.transitionMap.Handle(ctx, DeviceInit)
2951
2952}
2953
kesavand39e0aa32020-01-28 20:58:50 -05002954// EnablePort to enable Pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00002955func (dh *DeviceHandler) EnablePort(ctx context.Context, port *voltha.Port) error {
2956 logger.Debugw(ctx, "enable-port", log.Fields{"Device": dh.device, "port": port})
2957 return dh.modifyPhyPort(ctx, port, true)
kesavand39e0aa32020-01-28 20:58:50 -05002958}
2959
2960// DisablePort to disable pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00002961func (dh *DeviceHandler) DisablePort(ctx context.Context, port *voltha.Port) error {
2962 logger.Debugw(ctx, "disable-port", log.Fields{"Device": dh.device, "port": port})
2963 return dh.modifyPhyPort(ctx, port, false)
kesavand39e0aa32020-01-28 20:58:50 -05002964}
2965
Mahir Gunyela2e68702022-12-07 00:00:42 -08002966// modifyPhyPort is common function to enable and disable the port. parm :enablePort, true to enablePort and false to disablePort.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002967func (dh *DeviceHandler) modifyPhyPort(ctx context.Context, port *voltha.Port, enablePort bool) error {
2968 logger.Infow(ctx, "modifyPhyPort", log.Fields{"port": port, "Enable": enablePort, "device-id": dh.device.Id})
kesavand39e0aa32020-01-28 20:58:50 -05002969 if port.GetType() == voltha.Port_ETHERNET_NNI {
2970 // Bug is opened for VOL-2505 to support NNI disable feature.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002971 logger.Infow(ctx, "voltha-supports-single-nni-hence-disable-of-nni-not-allowed",
Shrey Baid807a2a02020-04-09 12:52:45 +05302972 log.Fields{"device": dh.device, "port": port})
Thomas Lee S94109f12020-03-03 16:39:29 +05302973 return olterrors.NewErrAdapter("illegal-port-request", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002974 "port-type": port.GetType,
Girish Kumarf26e4882020-03-05 06:49:10 +00002975 "enable-state": enablePort}, nil)
kesavand39e0aa32020-01-28 20:58:50 -05002976 }
2977 // fetch interfaceid from PortNo
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002978 ponID := plt.PortNoToIntfID(port.GetPortNo(), voltha.Port_PON_OLT)
kesavand39e0aa32020-01-28 20:58:50 -05002979 ponIntf := &oop.Interface{IntfId: ponID}
2980 var operStatus voltha.OperStatus_Types
2981 if enablePort {
2982 operStatus = voltha.OperStatus_ACTIVE
npujarec5762e2020-01-01 14:08:48 +05302983 out, err := dh.Client.EnablePonIf(ctx, ponIntf)
kesavand39e0aa32020-01-28 20:58:50 -05002984
2985 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302986 return olterrors.NewErrAdapter("pon-port-enable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002987 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002988 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05002989 }
2990 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05002991 dh.activePorts.Store(ponID, true)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002992 logger.Infow(ctx, "enabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05002993 } else {
2994 operStatus = voltha.OperStatus_UNKNOWN
npujarec5762e2020-01-01 14:08:48 +05302995 out, err := dh.Client.DisablePonIf(ctx, ponIntf)
kesavand39e0aa32020-01-28 20:58:50 -05002996 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302997 return olterrors.NewErrAdapter("pon-port-disable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002998 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002999 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003000 }
3001 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05003002 dh.activePorts.Store(ponID, false)
Neha Sharma96b7bf22020-06-15 10:37:32 +00003003 logger.Infow(ctx, "disabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05003004 }
khenaidoodc2116e2021-10-19 17:33:19 -04003005 if err := dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -04003006 DeviceId: dh.device.Id,
3007 PortType: voltha.Port_PON_OLT,
3008 PortNo: port.PortNo,
3009 OperStatus: operStatus,
3010 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303011 return olterrors.NewErrAdapter("port-state-update-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303012 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003013 "port": port.PortNo}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003014 }
3015 return nil
3016}
3017
Mahir Gunyela2e68702022-12-07 00:00:42 -08003018// disableAdminDownPorts disables the ports, if the corresponding port Adminstate is disabled on reboot and Renable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003019func (dh *DeviceHandler) disableAdminDownPorts(ctx context.Context, ports []*voltha.Port) error {
kesavand39e0aa32020-01-28 20:58:50 -05003020 // Disable the port and update the oper_port_status to core
3021 // if the Admin state of the port is disabled on reboot and re-enable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003022 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003023 if port.AdminState == common.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00003024 if err := dh.DisablePort(ctx, port); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303025 return olterrors.NewErrAdapter("port-disable-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303026 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003027 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003028 }
3029 }
3030 }
3031 return nil
3032}
3033
Mahir Gunyela2e68702022-12-07 00:00:42 -08003034// populateActivePorts to populate activePorts map
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003035func (dh *DeviceHandler) populateActivePorts(ctx context.Context, ports []*voltha.Port) {
3036 logger.Infow(ctx, "populateActivePorts", log.Fields{"device-id": dh.device.Id})
3037 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003038 if port.Type == voltha.Port_ETHERNET_NNI {
3039 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003040 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), true)
kesavand39e0aa32020-01-28 20:58:50 -05003041 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003042 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), false)
kesavand39e0aa32020-01-28 20:58:50 -05003043 }
3044 }
3045 if port.Type == voltha.Port_PON_OLT {
3046 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003047 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), true)
kesavand39e0aa32020-01-28 20:58:50 -05003048 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003049 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), false)
kesavand39e0aa32020-01-28 20:58:50 -05003050 }
3051 }
3052 }
3053}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003054
3055// ChildDeviceLost deletes ONU and clears pon resources related to it.
Girish Gowdraa0870562021-03-11 14:30:14 -08003056func (dh *DeviceHandler) ChildDeviceLost(ctx context.Context, pPortNo uint32, onuID uint32, onuSn string) error {
divyadesai3af43e12020-08-18 07:10:54 +00003057 logger.Debugw(ctx, "child-device-lost", log.Fields{"parent-device-id": dh.device.Id})
Girish Gowdrab4c33302022-03-18 15:07:38 -07003058 if dh.getDeviceDeletionInProgressFlag() {
3059 // Given that the OLT device itself is getting deleted, everything will be cleaned up in the DB and the OLT
3060 // will reboot, so everything will be reset on the pOLT too.
3061 logger.Infow(ctx, "olt-device-delete-in-progress-not-handling-child-device-lost",
3062 log.Fields{"parent-device-id": dh.device.Id, "pon-port": pPortNo, "onuID": onuID, "onuSN": onuSn})
3063 return nil
3064 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003065 intfID := plt.PortNoToIntfID(pPortNo, voltha.Port_PON_OLT)
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003066 onuKey := dh.formOnuKey(intfID, onuID)
Girish Gowdraa0870562021-03-11 14:30:14 -08003067
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003068 var sn *oop.SerialNumber
3069 var err error
Girish Gowdraa0870562021-03-11 14:30:14 -08003070 if sn, err = dh.deStringifySerialNumber(onuSn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303071 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003072 log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303073 "devicer-id": dh.device.Id,
Girish Gowdraa0870562021-03-11 14:30:14 -08003074 "serial-number": onuSn}, err).Log()
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003075 }
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003076
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003077 onu := &oop.Onu{IntfId: intfID, OnuId: onuID, SerialNumber: sn}
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003078 //clear PON resources associated with ONU
yasin saplibddc2d72022-02-08 13:10:17 +00003079 onuGem, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003080 if err != nil || onuGem == nil || onuGem.OnuID != onuID {
3081 logger.Warnw(ctx, "failed-to-get-onu-info-for-pon-port", log.Fields{
3082 "device-id": dh.device.Id,
3083 "intf-id": intfID,
3084 "onuID": onuID,
3085 "err": err})
3086 } else {
3087 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
yasin saplie87d4bd2021-12-06 09:04:03 +00003088 // Delete flows from device before schedulers and queue
3089 // Clear flowids for gem cache.
3090 removedFlows := []uint64{}
3091 for _, gem := range onuGem.GemPorts {
3092 if flowIDs, err := dh.resourceMgr[intfID].GetFlowIDsForGem(ctx, gem); err == nil {
3093 for _, flowID := range flowIDs {
3094 //multiple gem port can have the same flow id
3095 //it is better to send only one flowRemove request to the agent
3096 var alreadyRemoved bool
3097 for _, removedFlowID := range removedFlows {
3098 if removedFlowID == flowID {
3099 logger.Debugw(ctx, "flow-is-already-removed-due-to-another-gem", log.Fields{"flowID": flowID})
3100 alreadyRemoved = true
3101 break
3102 }
3103 }
3104 if !alreadyRemoved {
Mahir Gunyela2e68702022-12-07 00:00:42 -08003105 dh.removeFlowFromDevice(ctx, flowID, intfID)
yasin saplie87d4bd2021-12-06 09:04:03 +00003106 removedFlows = appendUnique64bit(removedFlows, flowID)
3107 }
3108 }
3109 }
3110 _ = dh.resourceMgr[intfID].DeleteFlowIDsForGem(ctx, gem)
3111 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003112 if err := dh.clearUNIData(ctx, onuGem); err != nil {
3113 logger.Warnw(ctx, "failed-to-clear-uni-data-for-onu", log.Fields{
3114 "device-id": dh.device.Id,
3115 "onu-device": onu,
3116 "err": err})
3117 }
yasin saplibddc2d72022-02-08 13:10:17 +00003118 if err := dh.resourceMgr[intfID].DelOnuGemInfo(ctx, onuID); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003119 logger.Warnw(ctx, "persistence-update-onu-gem-info-failed", log.Fields{
3120 "intf-id": intfID,
3121 "onu-device": onu,
3122 "onu-gem": onuGem,
3123 "err": err})
3124 //Not returning error on cleanup.
3125 }
3126 logger.Debugw(ctx, "removed-onu-gem-info", log.Fields{"intf": intfID, "onu-device": onu, "onugem": onuGem})
Himani Chawlabcc95852021-10-27 10:55:40 +05303127
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003128 }
yasin saplibddc2d72022-02-08 13:10:17 +00003129 dh.resourceMgr[intfID].FreeonuID(ctx, []uint32{onuID})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003130 dh.onus.Delete(onuKey)
3131 dh.discOnus.Delete(onuSn)
3132
3133 // Now clear the ONU on the OLT
Neha Sharma8f4e4322020-08-06 10:51:53 +00003134 if _, err := dh.Client.DeleteOnu(log.WithSpanFromContext(context.Background(), ctx), onu); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303135 return olterrors.NewErrAdapter("failed-to-delete-onu", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303136 "device-id": dh.device.Id,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003137 "onu-id": onuID}, err).Log()
3138 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003139
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003140 return nil
3141}
Mahir Gunyela2e68702022-12-07 00:00:42 -08003142func (dh *DeviceHandler) removeFlowFromDevice(ctx context.Context, flowID uint64, intfID uint32) {
3143 flow := &oop.Flow{FlowId: flowID}
3144 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
3145 logger.Warnw(ctx, "failed-to-get-flow-mgr-to-remove-flow-from-device", log.Fields{
3146 "device-id": dh.device.Id})
3147 } else {
3148 if err := dh.flowMgr[intfID].removeFlowFromDevice(ctx, flow, flowID); err != nil {
3149 logger.Warnw(ctx, "failed-to-remove-flow-from-device", log.Fields{
3150 "device-id": dh.device.Id,
3151 "err": err})
3152 }
3153 }
3154}
Girish Gowdracefae192020-03-19 18:14:10 -07003155
3156func getInPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003157 for _, field := range flow_utils.GetOfbFields(flow) {
3158 if field.Type == flow_utils.IN_PORT {
Girish Gowdracefae192020-03-19 18:14:10 -07003159 return field.GetPort()
3160 }
3161 }
3162 return InvalidPort
3163}
3164
3165func getOutPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003166 for _, action := range flow_utils.GetActions(flow) {
3167 if action.Type == flow_utils.OUTPUT {
Girish Gowdracefae192020-03-19 18:14:10 -07003168 if out := action.GetOutput(); out != nil {
3169 return out.GetPort()
3170 }
3171 }
3172 }
3173 return InvalidPort
3174}
3175
Girish Gowdracefae192020-03-19 18:14:10 -07003176func getPorts(flow *of.OfpFlowStats) (uint32, uint32) {
3177 inPort := getInPortFromFlow(flow)
3178 outPort := getOutPortFromFlow(flow)
3179
3180 if inPort == InvalidPort || outPort == InvalidPort {
3181 return inPort, outPort
3182 }
3183
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003184 if isControllerFlow := plt.IsControllerBoundFlow(outPort); isControllerFlow {
Girish Gowdracefae192020-03-19 18:14:10 -07003185 /* Get UNI port/ IN Port from tunnel ID field for upstream controller bound flows */
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003186 if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003187 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003188 return uniPort, outPort
3189 }
3190 }
3191 } else {
3192 // Downstream flow from NNI to PON port , Use tunnel ID as new OUT port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003193 if portType := plt.IntfIDToPortTypeName(outPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003194 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003195 return inPort, uniPort
3196 }
3197 // Upstream flow from PON to NNI port , Use tunnel ID as new IN port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003198 } else if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003199 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003200 return uniPort, outPort
3201 }
3202 }
3203 }
3204
3205 return InvalidPort, InvalidPort
3206}
Matt Jeanneretceea2e02020-03-27 14:19:57 -04003207
3208func extractOmciTransactionID(omciPkt []byte) uint16 {
3209 if len(omciPkt) > 3 {
3210 d := omciPkt[0:2]
3211 transid := binary.BigEndian.Uint16(d)
3212 return transid
3213 }
3214 return 0
3215}
Mahir Gunyel0f89fd22020-04-11 18:24:42 -07003216
3217// StoreOnuDevice stores the onu parameters to the local cache.
3218func (dh *DeviceHandler) StoreOnuDevice(onuDevice *OnuDevice) {
3219 onuKey := dh.formOnuKey(onuDevice.intfID, onuDevice.onuID)
3220 dh.onus.Store(onuKey, onuDevice)
3221}
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003222
khenaidoodc2116e2021-10-19 17:33:19 -04003223func (dh *DeviceHandler) getExtValue(ctx context.Context, device *voltha.Device, value extension.ValueType_Type) (*extension.ReturnValues, error) {
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003224 var err error
Andrea Campanella9931ad62020-04-28 15:11:06 +02003225 var sn *oop.SerialNumber
Gamze Abaka78a1d2a2020-04-27 10:17:27 +00003226 var ID uint32
khenaidoodc2116e2021-10-19 17:33:19 -04003227 resp := new(extension.ReturnValues)
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003228 valueparam := new(oop.ValueParam)
Neha Sharma8f4e4322020-08-06 10:51:53 +00003229 ctx = log.WithSpanFromContext(context.Background(), ctx)
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003230 logger.Infow(ctx, "getExtValue", log.Fields{"onu-id": device.Id, "pon-intf": device.ParentPortNo})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003231 if sn, err = dh.deStringifySerialNumber(device.SerialNumber); err != nil {
3232 return nil, err
3233 }
3234 ID = device.ProxyAddress.GetOnuId()
3235 Onu := oop.Onu{IntfId: device.ParentPortNo, OnuId: ID, SerialNumber: sn}
3236 valueparam.Onu = &Onu
3237 valueparam.Value = value
3238
3239 // This API is unsupported until agent patch is added
3240 resp.Unsupported = uint32(value)
3241 _ = ctx
3242
3243 // Uncomment this code once agent changes are complete and tests
3244 /*
3245 resp, err = dh.Client.GetValue(ctx, valueparam)
3246 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003247 logger.Errorw("error-while-getValue", log.Fields{"DeviceID": dh.device, "onu-id": onuid, "err": err})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003248 return nil, err
3249 }
3250 */
3251
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003252 logger.Infow(ctx, "get-ext-value", log.Fields{"resp": resp, "device-id": dh.device, "onu-id": device.Id, "pon-intf": device.ParentPortNo})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003253 return resp, nil
3254}
Girish Gowdra9602eb42020-09-09 15:50:39 -07003255
yasin saplid0566272021-12-21 09:10:30 +00003256func (dh *DeviceHandler) getIntfIDFromFlow(ctx context.Context, flow *of.OfpFlowStats) uint32 {
3257 // Default to NNI
3258 var intfID = dh.totalPonPorts
Girish Gowdra9602eb42020-09-09 15:50:39 -07003259 inPort, outPort := getPorts(flow)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003260 if inPort != InvalidPort && outPort != InvalidPort {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003261 _, intfID, _, _ = plt.ExtractAccessFromFlow(inPort, outPort)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003262 }
3263 return intfID
3264}
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003265
Mahir Gunyelb0046752021-02-26 13:51:05 -08003266func (dh *DeviceHandler) getOnuIndicationChannel(ctx context.Context, intfID uint32) chan onuIndicationMsg {
3267 dh.perPonOnuIndicationChannelLock.Lock()
3268 if ch, ok := dh.perPonOnuIndicationChannel[intfID]; ok {
3269 dh.perPonOnuIndicationChannelLock.Unlock()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003270 return ch.indicationChannel
3271 }
3272 channels := onuIndicationChannels{
3273 //We create a buffered channel here to avoid calling function to be blocked
Mahir Gunyelb0046752021-02-26 13:51:05 -08003274 //in case of multiple indications from the ONUs,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003275 //especially in the case where indications are buffered in OLT.
Mahir Gunyelb0046752021-02-26 13:51:05 -08003276 indicationChannel: make(chan onuIndicationMsg, 500),
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003277 stopChannel: make(chan struct{}),
3278 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003279 dh.perPonOnuIndicationChannel[intfID] = channels
3280 dh.perPonOnuIndicationChannelLock.Unlock()
3281 go dh.onuIndicationsRoutine(&channels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003282 return channels.indicationChannel
3283
3284}
3285
Mahir Gunyelb0046752021-02-26 13:51:05 -08003286func (dh *DeviceHandler) removeOnuIndicationChannels(ctx context.Context) {
3287 logger.Debug(ctx, "remove-onu-indication-channels", log.Fields{"device-id": dh.device.Id})
3288 dh.perPonOnuIndicationChannelLock.Lock()
3289 defer dh.perPonOnuIndicationChannelLock.Unlock()
3290 for _, v := range dh.perPonOnuIndicationChannel {
3291 close(v.stopChannel)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003292 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003293 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003294}
3295
Mahir Gunyelb0046752021-02-26 13:51:05 -08003296func (dh *DeviceHandler) putOnuIndicationToChannel(ctx context.Context, indication *oop.Indication, intfID uint32) {
3297 ind := onuIndicationMsg{
3298 ctx: ctx,
3299 indication: indication,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003300 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003301 logger.Debugw(ctx, "put-onu-indication-to-channel", log.Fields{"indication": indication, "intfID": intfID})
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003302 // Send the onuIndication on the ONU channel
Mahir Gunyelb0046752021-02-26 13:51:05 -08003303 dh.getOnuIndicationChannel(ctx, intfID) <- ind
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003304}
3305
Mahir Gunyelb0046752021-02-26 13:51:05 -08003306func (dh *DeviceHandler) onuIndicationsRoutine(onuChannels *onuIndicationChannels) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003307 for {
3308 select {
3309 // process one indication per onu, before proceeding to the next one
3310 case onuInd := <-onuChannels.indicationChannel:
Andrea Campanella46b01402021-11-15 16:58:05 -08003311 indication := *(proto.Clone(onuInd.indication)).(*oop.Indication)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003312 logger.Debugw(onuInd.ctx, "calling-indication", log.Fields{"device-id": dh.device.Id,
Andrea Campanella46b01402021-11-15 16:58:05 -08003313 "ind": indication})
3314 switch indication.Data.(type) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003315 case *oop.Indication_OnuInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003316 if err := dh.onuIndication(onuInd.ctx, indication.GetOnuInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003317 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3318 "type": "onu-indication",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003319 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003320 }
3321 case *oop.Indication_OnuDiscInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003322 if err := dh.onuDiscIndication(onuInd.ctx, indication.GetOnuDiscInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003323 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3324 "type": "onu-discovery",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003325 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003326 }
3327 }
3328 case <-onuChannels.stopChannel:
3329 logger.Debugw(context.Background(), "stop-signal-received-for-onu-channel", log.Fields{"device-id": dh.device.Id})
3330 close(onuChannels.indicationChannel)
3331 return
3332 }
3333 }
3334}
Girish Gowdra491a9c62021-01-06 16:43:07 -08003335
3336// RouteMcastFlowOrGroupMsgToChannel routes incoming mcast flow or group to a channel to be handled by the a specific
3337// instance of mcastFlowOrGroupChannelHandlerRoutine meant to handle messages for that group.
khenaidoodc2116e2021-10-19 17:33:19 -04003338func (dh *DeviceHandler) RouteMcastFlowOrGroupMsgToChannel(ctx context.Context, flow *of.OfpFlowStats, group *of.OfpGroupEntry, action string) error {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003339 if dh.getDeviceDeletionInProgressFlag() {
3340 // The device itself is going to be reset as part of deletion. So nothing to be done.
3341 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
3342 return nil
3343 }
3344
Girish Gowdra491a9c62021-01-06 16:43:07 -08003345 // Step1 : Fill McastFlowOrGroupControlBlock
3346 // Step2 : Push the McastFlowOrGroupControlBlock to appropriate channel
3347 // Step3 : Wait on response channel for response
3348 // Step4 : Return error value
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003349 startTime := time.Now()
Girish Gowdra491a9c62021-01-06 16:43:07 -08003350 logger.Debugw(ctx, "process-flow-or-group", log.Fields{"flow": flow, "group": group, "action": action})
3351 errChan := make(chan error)
3352 var groupID uint32
3353 mcastFlowOrGroupCb := McastFlowOrGroupControlBlock{
3354 ctx: ctx,
3355 flowOrGroupAction: action,
3356 flow: flow,
3357 group: group,
3358 errChan: &errChan,
3359 }
3360 if flow != nil {
3361 groupID = flow_utils.GetGroup(flow)
3362 } else if group != nil {
3363 groupID = group.Desc.GroupId
3364 } else {
3365 return errors.New("flow-and-group-both-nil")
3366 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003367 mcastRoutineIdx := groupID % MaxNumOfGroupHandlerChannels
3368 if dh.mcastHandlerRoutineActive[mcastRoutineIdx] {
3369 // Derive the appropriate go routine to handle the request by a simple module operation.
3370 // There are only MaxNumOfGroupHandlerChannels number of channels to handle the mcast flow or group
3371 dh.incomingMcastFlowOrGroup[groupID%MaxNumOfGroupHandlerChannels] <- mcastFlowOrGroupCb
3372 // Wait for handler to return error value
3373 err := <-errChan
3374 logger.Debugw(ctx, "process-flow-or-group--received-resp", log.Fields{"err": err, "totalTimeInSeconds": time.Since(startTime).Milliseconds()})
3375 return err
3376 }
3377 logger.Errorw(ctx, "mcast handler routine not active for onu", log.Fields{"mcastRoutineIdx": mcastRoutineIdx})
3378 return fmt.Errorf("mcast-handler-routine-not-active-for-index-%v", mcastRoutineIdx)
Girish Gowdra491a9c62021-01-06 16:43:07 -08003379}
3380
3381// mcastFlowOrGroupChannelHandlerRoutine routine to handle incoming mcast flow/group message
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003382func (dh *DeviceHandler) mcastFlowOrGroupChannelHandlerRoutine(routineIndex int, mcastFlowOrGroupChannel chan McastFlowOrGroupControlBlock, stopHandler chan bool) {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003383 for {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003384 select {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003385 // block on the channel to receive an incoming mcast flow/group
3386 // process the flow completely before proceeding to handle the next flow
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003387 case mcastFlowOrGroupCb := <-mcastFlowOrGroupChannel:
3388 if mcastFlowOrGroupCb.flow != nil {
3389 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3390 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-flow",
3391 log.Fields{"device-id": dh.device.Id,
3392 "flowToAdd": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003393 err := olterrors.NewErrNotFound("no-flow-manager-found-to-add-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3394 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3395 for _, flMgr := range dh.flowMgr {
3396 if flMgr != nil {
3397 err = flMgr.AddFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow, nil)
3398 break
3399 }
3400 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003401 // Pass the return value over the return channel
3402 *mcastFlowOrGroupCb.errChan <- err
3403 } else { // flow remove
3404 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-flow",
3405 log.Fields{"device-id": dh.device.Id,
3406 "flowToRemove": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003407 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3408 err := olterrors.NewErrNotFound("no-flow-manager-found-to-remove-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3409 for _, flMgr := range dh.flowMgr {
3410 if flMgr != nil {
3411 err = flMgr.RemoveFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow)
3412 break
3413 }
3414 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003415 // Pass the return value over the return channel
3416 *mcastFlowOrGroupCb.errChan <- err
3417 }
3418 } else { // mcast group
3419 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3420 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-group",
3421 log.Fields{"device-id": dh.device.Id,
3422 "groupToAdd": mcastFlowOrGroupCb.group})
3423 err := dh.groupMgr.AddGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3424 // Pass the return value over the return channel
3425 *mcastFlowOrGroupCb.errChan <- err
3426 } else if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupModify { // group modify
3427 logger.Debugw(mcastFlowOrGroupCb.ctx, "modifying-mcast-group",
3428 log.Fields{"device-id": dh.device.Id,
3429 "groupToModify": mcastFlowOrGroupCb.group})
3430 err := dh.groupMgr.ModifyGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3431 // Pass the return value over the return channel
3432 *mcastFlowOrGroupCb.errChan <- err
3433 } else { // group remove
3434 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-group",
3435 log.Fields{"device-id": dh.device.Id,
3436 "groupToRemove": mcastFlowOrGroupCb.group})
3437 err := dh.groupMgr.DeleteGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3438 // Pass the return value over the return channel
3439 *mcastFlowOrGroupCb.errChan <- err
3440 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08003441 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003442 case <-stopHandler:
3443 dh.mcastHandlerRoutineActive[routineIndex] = false
3444 return
Girish Gowdra491a9c62021-01-06 16:43:07 -08003445 }
3446 }
3447}
kesavand62126212021-01-12 04:56:06 -05003448
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003449// StopAllMcastHandlerRoutines stops all flow handler routines. Call this when device is being rebooted or deleted
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003450func (dh *DeviceHandler) StopAllMcastHandlerRoutines(ctx context.Context, wg *sync.WaitGroup) {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003451 for i, v := range dh.stopMcastHandlerRoutine {
3452 if dh.mcastHandlerRoutineActive[i] {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003453 select {
3454 case v <- true:
3455 case <-time.After(time.Second * 5):
3456 logger.Warnw(ctx, "timeout stopping mcast handler routine", log.Fields{"idx": i, "deviceID": dh.device.Id})
3457 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003458 }
3459 }
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00003460
3461 if dh.incomingMcastFlowOrGroup != nil {
3462 for k := range dh.incomingMcastFlowOrGroup {
3463 if dh.incomingMcastFlowOrGroup[k] != nil {
3464 dh.incomingMcastFlowOrGroup[k] = nil
3465 }
3466 }
3467 dh.incomingMcastFlowOrGroup = nil
3468 }
3469
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003470 wg.Done()
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003471 logger.Debug(ctx, "stopped all mcast handler routines")
3472}
3473
kesavand62126212021-01-12 04:56:06 -05003474func (dh *DeviceHandler) getOltPortCounters(ctx context.Context, oltPortInfo *extension.GetOltPortCounters) *extension.SingleGetValueResponse {
3475
3476 singleValResp := extension.SingleGetValueResponse{
3477 Response: &extension.GetValueResponse{
3478 Response: &extension.GetValueResponse_PortCoutners{
3479 PortCoutners: &extension.GetOltPortCountersResponse{},
3480 },
3481 },
3482 }
3483
3484 errResp := func(status extension.GetValueResponse_Status,
3485 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3486 return &extension.SingleGetValueResponse{
3487 Response: &extension.GetValueResponse{
3488 Status: status,
3489 ErrReason: reason,
3490 },
3491 }
3492 }
3493
3494 if oltPortInfo.PortType != extension.GetOltPortCounters_Port_ETHERNET_NNI &&
3495 oltPortInfo.PortType != extension.GetOltPortCounters_Port_PON_OLT {
3496 //send error response
3497 logger.Debugw(ctx, "getOltPortCounters invalid portType", log.Fields{"oltPortInfo": oltPortInfo.PortType})
3498 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
3499 }
3500 statIndChn := make(chan bool, 1)
3501 dh.portStats.RegisterForStatIndication(ctx, portStatsType, statIndChn, oltPortInfo.PortNo, oltPortInfo.PortType)
3502 defer dh.portStats.DeRegisterFromStatIndication(ctx, portStatsType, statIndChn)
3503 //request openOlt agent to send the the port statistics indication
3504
3505 go func() {
3506 _, err := dh.Client.CollectStatistics(ctx, new(oop.Empty))
3507 if err != nil {
3508 logger.Errorw(ctx, "getOltPortCounters CollectStatistics failed ", log.Fields{"err": err})
3509 }
3510 }()
3511 select {
3512 case <-statIndChn:
3513 //indication received for ports stats
3514 logger.Debugw(ctx, "getOltPortCounters recvd statIndChn", log.Fields{"oltPortInfo": oltPortInfo})
3515 case <-time.After(oltPortInfoTimeout * time.Second):
3516 logger.Debugw(ctx, "getOltPortCounters timeout happened", log.Fields{"oltPortInfo": oltPortInfo})
3517 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3518 case <-ctx.Done():
3519 logger.Debugw(ctx, "getOltPortCounters ctx Done ", log.Fields{"oltPortInfo": oltPortInfo})
3520 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3521 }
3522 if oltPortInfo.PortType == extension.GetOltPortCounters_Port_ETHERNET_NNI {
3523 //get nni stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003524 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_ETHERNET_NNI)
kesavand62126212021-01-12 04:56:06 -05003525 logger.Debugw(ctx, "getOltPortCounters intfID ", log.Fields{"intfID": intfID})
3526 cmnni := dh.portStats.collectNNIMetrics(intfID)
3527 if cmnni == nil {
3528 //TODO define the error reason
3529 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3530 }
3531 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmnni)
3532 return &singleValResp
3533
3534 } else if oltPortInfo.PortType == extension.GetOltPortCounters_Port_PON_OLT {
3535 // get pon stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003536 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_PON_OLT)
kesavand62126212021-01-12 04:56:06 -05003537 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
3538 cmpon := dh.portStats.collectPONMetrics(intfID)
3539 if cmpon == nil {
3540 //TODO define the error reason
3541 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3542 }
3543 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmpon)
3544 return &singleValResp
3545 }
3546 }
3547 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3548}
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303549
3550func (dh *DeviceHandler) getOnuPonCounters(ctx context.Context, onuPonInfo *extension.GetOnuCountersRequest) *extension.SingleGetValueResponse {
3551
3552 singleValResp := extension.SingleGetValueResponse{
3553 Response: &extension.GetValueResponse{
3554 Response: &extension.GetValueResponse_OnuPonCounters{
3555 OnuPonCounters: &extension.GetOnuCountersResponse{},
3556 },
3557 },
3558 }
3559
3560 errResp := func(status extension.GetValueResponse_Status,
3561 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3562 return &extension.SingleGetValueResponse{
3563 Response: &extension.GetValueResponse{
3564 Status: status,
3565 ErrReason: reason,
3566 },
3567 }
3568 }
3569 intfID := onuPonInfo.IntfId
3570 onuID := onuPonInfo.OnuId
3571 onuKey := dh.formOnuKey(intfID, onuID)
3572
3573 if _, ok := dh.onus.Load(onuKey); !ok {
3574 logger.Errorw(ctx, "get-onui-pon-counters-request-invalid-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3575 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3576 }
3577 logger.Debugw(ctx, "get-onui-pon-counters-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3578 cmnni := dh.portStats.collectOnDemandOnuStats(ctx, intfID, onuID)
3579 if cmnni == nil {
3580 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3581 }
3582 dh.portStats.updateGetOnuPonCountersResponse(ctx, &singleValResp, cmnni)
3583 return &singleValResp
3584
3585}
Gamze Abaka85e9a142021-05-26 13:41:39 +00003586
nikesh.krishnanc8473432023-06-14 12:14:54 +05303587func (dh *DeviceHandler) getOnuInfo(ctx context.Context, intfID uint32, onuID *uint32) (*oop.OnuInfo, error) {
3588
3589 Onu := oop.Onu{IntfId: intfID, OnuId: *onuID}
3590 OnuInfo, err := dh.Client.GetOnuInfo(ctx, &Onu)
3591 if err != nil {
3592 return nil, err
3593 }
3594 return OnuInfo, nil
3595
3596}
3597
3598func (dh *DeviceHandler) getIntfInfo(ctx context.Context, intfID uint32) (*oop.PonIntfInfo, error) {
3599
3600 Intf := oop.Interface{IntfId: intfID}
3601 IntfInfo, err := dh.Client.GetPonInterfaceInfo(ctx, &Intf)
3602 if err != nil {
3603 return nil, err
3604 }
3605 return IntfInfo, nil
3606
3607}
3608
Gamze Abaka85e9a142021-05-26 13:41:39 +00003609func (dh *DeviceHandler) getRxPower(ctx context.Context, rxPowerRequest *extension.GetRxPowerRequest) *extension.SingleGetValueResponse {
3610
3611 Onu := oop.Onu{IntfId: rxPowerRequest.IntfId, OnuId: rxPowerRequest.OnuId}
3612 rxPower, err := dh.Client.GetPonRxPower(ctx, &Onu)
3613 if err != nil {
3614 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
3615 return generateSingleGetValueErrorResponse(err)
3616 }
3617 return &extension.SingleGetValueResponse{
3618 Response: &extension.GetValueResponse{
3619 Status: extension.GetValueResponse_OK,
3620 Response: &extension.GetValueResponse_RxPower{
3621 RxPower: &extension.GetRxPowerResponse{
3622 IntfId: rxPowerRequest.IntfId,
3623 OnuId: rxPowerRequest.OnuId,
3624 Status: rxPower.Status,
3625 FailReason: rxPower.FailReason.String(),
3626 RxPower: rxPower.RxPowerMeanDbm,
3627 },
3628 },
3629 },
3630 }
3631}
3632
praneeth nalmas55616d62023-02-06 09:19:18 +05303633func (dh *DeviceHandler) getPONRxPower(ctx context.Context, OltRxPowerRequest *extension.GetOltRxPowerRequest) *extension.SingleGetValueResponse {
3634
3635 errResp := func(status extension.GetValueResponse_Status,
3636 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3637 return &extension.SingleGetValueResponse{
3638 Response: &extension.GetValueResponse{
3639 Status: status,
3640 ErrReason: reason,
3641 },
3642 }
3643 }
3644
3645 resp := extension.SingleGetValueResponse{
3646 Response: &extension.GetValueResponse{
3647 Status: extension.GetValueResponse_OK,
3648 Response: &extension.GetValueResponse_OltRxPower{
3649 OltRxPower: &extension.GetOltRxPowerResponse{},
3650 },
3651 },
3652 }
3653
3654 logger.Debugw(ctx, "getPONRxPower", log.Fields{"portLabel": OltRxPowerRequest.PortLabel, "OnuSerialNumber": OltRxPowerRequest.OnuSn, "device-id": dh.device.Id})
3655 portLabel := OltRxPowerRequest.PortLabel
3656 serialNumber := OltRxPowerRequest.OnuSn
3657
3658 portInfo := strings.Split(portLabel, "-")
3659 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
3660
3661 if err != nil {
3662 logger.Errorw(ctx, "getPONRxPower invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
3663 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
3664 }
3665
3666 if portInfo[0] != "pon" {
3667 logger.Errorw(ctx, "getPONRxPower invalid portType", log.Fields{"oltPortType": portInfo[0]})
3668 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
3669 }
3670 ponIntdID := plt.PortNoToIntfID((uint32)(portNumber), voltha.Port_PON_OLT)
3671
3672 if serialNumber != "" {
3673
3674 onuDev := dh.getChildDevice(ctx, serialNumber, (uint32)(portNumber))
3675 if onuDev != nil {
3676
3677 Onu := oop.Onu{IntfId: uint32(portNumber), OnuId: onuDev.onuID}
3678 rxPower, err := dh.Client.GetPonRxPower(ctx, &Onu)
3679 if err != nil {
3680
3681 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
3682 return generateSingleGetValueErrorResponse(err)
3683
3684 }
3685
3686 rxPowerValue := extension.RxPower{}
3687 rxPowerValue.OnuSn = onuDev.serialNumber
3688 rxPowerValue.Status = rxPower.GetStatus()
3689 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
3690 rxPowerValue.FailReason = rxPower.GetFailReason().String()
3691
3692 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
3693
3694 } else {
3695
3696 logger.Errorw(ctx, "getPONRxPower invalid Device", log.Fields{"portLabel": portLabel, "serialNumber": serialNumber})
3697 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3698 }
3699
3700 } else {
3701
3702 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
3703 if onuInCache.(*OnuDevice).intfID == ponIntdID {
3704
3705 Onu := oop.Onu{IntfId: ponIntdID, OnuId: onuInCache.(*OnuDevice).onuID}
3706 rxPower, err := dh.Client.GetPonRxPower(ctx, &Onu)
3707 if err != nil {
3708 logger.Errorw(ctx, "error-while-getting-rx-power, however considering to proceed further with other ONUs on PON", log.Fields{"Onu": Onu, "err": err})
3709 } else {
3710
3711 rxPowerValue := extension.RxPower{}
3712 rxPowerValue.OnuSn = onuInCache.(*OnuDevice).serialNumber
3713 rxPowerValue.Status = rxPower.GetStatus()
3714 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
3715 rxPowerValue.FailReason = rxPower.GetFailReason().String()
3716
3717 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
3718 }
3719
3720 }
3721 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
3722 return true
3723 })
3724 }
3725 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
3726 return &resp
3727}
3728
Gamze Abaka85e9a142021-05-26 13:41:39 +00003729func generateSingleGetValueErrorResponse(err error) *extension.SingleGetValueResponse {
3730 errResp := func(status extension.GetValueResponse_Status,
3731 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3732 return &extension.SingleGetValueResponse{
3733 Response: &extension.GetValueResponse{
3734 Status: status,
3735 ErrReason: reason,
3736 },
3737 }
3738 }
3739
3740 if err != nil {
3741 if e, ok := status.FromError(err); ok {
3742 switch e.Code() {
3743 case codes.Internal:
3744 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3745 case codes.DeadlineExceeded:
3746 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3747 case codes.Unimplemented:
3748 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_UNSUPPORTED)
3749 case codes.NotFound:
3750 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3751 }
3752 }
3753 }
3754
3755 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_REASON_UNDEFINED)
3756}
khenaidoo106c61a2021-08-11 18:05:46 -04003757
3758/*
3759Helper functions to communicate with Core
3760*/
3761
3762func (dh *DeviceHandler) getDeviceFromCore(ctx context.Context, deviceID string) (*voltha.Device, error) {
3763 cClient, err := dh.coreClient.GetCoreServiceClient()
3764 if err != nil || cClient == nil {
3765 return nil, err
3766 }
3767 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3768 defer cancel()
3769 return cClient.GetDevice(subCtx, &common.ID{Id: deviceID})
3770}
3771
khenaidoodc2116e2021-10-19 17:33:19 -04003772func (dh *DeviceHandler) getChildDeviceFromCore(ctx context.Context, childDeviceFilter *ca.ChildDeviceFilter) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003773 cClient, err := dh.coreClient.GetCoreServiceClient()
3774 if err != nil || cClient == nil {
3775 return nil, err
3776 }
3777 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3778 defer cancel()
3779 return cClient.GetChildDevice(subCtx, childDeviceFilter)
3780}
3781
khenaidoodc2116e2021-10-19 17:33:19 -04003782func (dh *DeviceHandler) updateDeviceStateInCore(ctx context.Context, deviceStateFilter *ca.DeviceStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003783 cClient, err := dh.coreClient.GetCoreServiceClient()
3784 if err != nil || cClient == nil {
3785 return err
3786 }
3787 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3788 defer cancel()
3789 _, err = cClient.DeviceStateUpdate(subCtx, deviceStateFilter)
3790 return err
3791}
3792
3793func (dh *DeviceHandler) getChildDevicesFromCore(ctx context.Context, deviceID string) (*voltha.Devices, error) {
3794 cClient, err := dh.coreClient.GetCoreServiceClient()
3795 if err != nil || cClient == nil {
3796 return nil, err
3797 }
3798 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3799 defer cancel()
3800 return cClient.GetChildDevices(subCtx, &common.ID{Id: deviceID})
3801}
3802
3803func (dh *DeviceHandler) listDevicePortsFromCore(ctx context.Context, deviceID string) (*voltha.Ports, error) {
3804 cClient, err := dh.coreClient.GetCoreServiceClient()
3805 if err != nil || cClient == nil {
3806 return nil, err
3807 }
3808 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3809 defer cancel()
3810 return cClient.ListDevicePorts(subCtx, &common.ID{Id: deviceID})
3811}
3812
3813func (dh *DeviceHandler) updateDeviceInCore(ctx context.Context, device *voltha.Device) error {
3814 cClient, err := dh.coreClient.GetCoreServiceClient()
3815 if err != nil || cClient == nil {
3816 return err
3817 }
3818 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3819 defer cancel()
3820 _, err = cClient.DeviceUpdate(subCtx, device)
3821 return err
3822}
3823
khenaidoodc2116e2021-10-19 17:33:19 -04003824func (dh *DeviceHandler) sendChildDeviceDetectedToCore(ctx context.Context, deviceDiscoveryInfo *ca.DeviceDiscovery) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003825 cClient, err := dh.coreClient.GetCoreServiceClient()
3826 if err != nil || cClient == nil {
3827 return nil, err
3828 }
3829 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3830 defer cancel()
3831 return cClient.ChildDeviceDetected(subCtx, deviceDiscoveryInfo)
3832}
3833
khenaidoodc2116e2021-10-19 17:33:19 -04003834func (dh *DeviceHandler) sendPacketToCore(ctx context.Context, pkt *ca.PacketIn) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003835 cClient, err := dh.coreClient.GetCoreServiceClient()
3836 if err != nil || cClient == nil {
3837 return err
3838 }
3839 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3840 defer cancel()
3841 _, err = cClient.SendPacketIn(subCtx, pkt)
3842 return err
3843}
3844
3845func (dh *DeviceHandler) createPortInCore(ctx context.Context, port *voltha.Port) error {
3846 cClient, err := dh.coreClient.GetCoreServiceClient()
3847 if err != nil || cClient == nil {
3848 return err
3849 }
3850 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3851 defer cancel()
3852 _, err = cClient.PortCreated(subCtx, port)
3853 return err
3854}
3855
khenaidoodc2116e2021-10-19 17:33:19 -04003856func (dh *DeviceHandler) updatePortsStateInCore(ctx context.Context, portFilter *ca.PortStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003857 cClient, err := dh.coreClient.GetCoreServiceClient()
3858 if err != nil || cClient == nil {
3859 return err
3860 }
3861 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3862 defer cancel()
3863 _, err = cClient.PortsStateUpdate(subCtx, portFilter)
3864 return err
3865}
3866
khenaidoodc2116e2021-10-19 17:33:19 -04003867func (dh *DeviceHandler) updatePortStateInCore(ctx context.Context, portState *ca.PortState) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003868 cClient, err := dh.coreClient.GetCoreServiceClient()
3869 if err != nil || cClient == nil {
3870 return err
3871 }
3872 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3873 defer cancel()
3874 _, err = cClient.PortStateUpdate(subCtx, portState)
3875 return err
3876}
3877
khenaidoodc2116e2021-10-19 17:33:19 -04003878func (dh *DeviceHandler) getPortFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Port, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003879 cClient, err := dh.coreClient.GetCoreServiceClient()
3880 if err != nil || cClient == nil {
3881 return nil, err
3882 }
3883 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3884 defer cancel()
3885 return cClient.GetDevicePort(subCtx, portFilter)
3886}
3887
nikesh.krishnanc8473432023-06-14 12:14:54 +05303888func (dh *DeviceHandler) getAllPortsFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Ports, error) {
3889 cClient, err := dh.coreClient.GetCoreServiceClient()
3890 if err != nil || cClient == nil {
3891 return nil, err
3892 }
3893 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3894 defer cancel()
3895 return cClient.GetPorts(subCtx, portFilter)
3896}
3897
khenaidoo106c61a2021-08-11 18:05:46 -04003898/*
3899Helper functions to communicate with child adapter
3900*/
3901
khenaidoodc2116e2021-10-19 17:33:19 -04003902func (dh *DeviceHandler) sendOmciIndicationToChildAdapter(ctx context.Context, childEndpoint string, response *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003903 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3904 if err != nil || aClient == nil {
3905 return err
3906 }
3907 logger.Debugw(ctx, "sending-omci-response", log.Fields{"response": response, "child-endpoint": childEndpoint})
3908 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3909 defer cancel()
3910 _, err = aClient.OmciIndication(subCtx, response)
3911 return err
3912}
3913
khenaidoodc2116e2021-10-19 17:33:19 -04003914func (dh *DeviceHandler) sendOnuIndicationToChildAdapter(ctx context.Context, childEndpoint string, onuInd *ia.OnuIndicationMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003915 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3916 if err != nil || aClient == nil {
3917 return err
3918 }
3919 logger.Debugw(ctx, "sending-onu-indication", log.Fields{"onu-indication": onuInd, "child-endpoint": childEndpoint})
3920 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3921 defer cancel()
3922 _, err = aClient.OnuIndication(subCtx, onuInd)
3923 return err
3924}
3925
khenaidoodc2116e2021-10-19 17:33:19 -04003926func (dh *DeviceHandler) sendDeleteTContToChildAdapter(ctx context.Context, childEndpoint string, tContInfo *ia.DeleteTcontMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003927 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3928 if err != nil || aClient == nil {
3929 return err
3930 }
3931 logger.Debugw(ctx, "sending-delete-tcont", log.Fields{"tcont": tContInfo, "child-endpoint": childEndpoint})
3932 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3933 defer cancel()
3934 _, err = aClient.DeleteTCont(subCtx, tContInfo)
3935 return err
3936}
3937
khenaidoodc2116e2021-10-19 17:33:19 -04003938func (dh *DeviceHandler) sendDeleteGemPortToChildAdapter(ctx context.Context, childEndpoint string, gemPortInfo *ia.DeleteGemPortMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003939 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3940 if err != nil || aClient == nil {
3941 return err
3942 }
3943 logger.Debugw(ctx, "sending-delete-gem-port", log.Fields{"gem-port-info": gemPortInfo, "child-endpoint": childEndpoint})
3944 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3945 defer cancel()
3946 _, err = aClient.DeleteGemPort(subCtx, gemPortInfo)
3947 return err
3948}
3949
khenaidoodc2116e2021-10-19 17:33:19 -04003950func (dh *DeviceHandler) sendDownloadTechProfileToChildAdapter(ctx context.Context, childEndpoint string, tpDownloadInfo *ia.TechProfileDownloadMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003951 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3952 if err != nil || aClient == nil {
3953 return err
3954 }
3955 logger.Debugw(ctx, "sending-tech-profile-download", log.Fields{"tp-download-info": tpDownloadInfo, "child-endpoint": childEndpoint})
3956 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3957 defer cancel()
3958 _, err = aClient.DownloadTechProfile(subCtx, tpDownloadInfo)
3959 return err
3960}
3961
3962/*
3963Helper functions for remote communication
3964*/
3965
3966// TODO: Use a connection tracker such that the adapter connection is stopped when the last device that adapter
3967// supports is deleted
3968func (dh *DeviceHandler) setupChildInterAdapterClient(ctx context.Context, endpoint string) error {
3969 logger.Infow(ctx, "setting-child-adapter-connection", log.Fields{"child-endpoint": endpoint})
3970
3971 dh.lockChildAdapterClients.Lock()
3972 defer dh.lockChildAdapterClients.Unlock()
3973 if _, ok := dh.childAdapterClients[endpoint]; ok {
3974 // Already set
3975 return nil
3976 }
3977
3978 // Setup child's adapter grpc connection
3979 var err error
khenaidoo27e7ac92021-12-08 14:43:09 -05003980 if dh.childAdapterClients[endpoint], err = vgrpc.NewClient(
3981 dh.cfg.AdapterEndpoint,
3982 endpoint,
khenaidooefff76e2021-12-15 16:51:30 -05003983 "onu_inter_adapter_service.OnuInterAdapterService",
3984 dh.onuInterAdapterRestarted,
3985 vgrpc.ClientContextData(dh.device.Id)); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04003986 logger.Errorw(ctx, "grpc-client-not-created", log.Fields{"error": err, "endpoint": endpoint})
3987 return err
3988 }
nikesh.krishnand9812542023-08-01 18:31:39 +05303989 retryCodes := []codes.Code{
3990 codes.Unavailable, // server is currently unavailable
3991 codes.DeadlineExceeded, // deadline for the operation was exceeded
3992 }
3993 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(dh.cfg.PerRPCRetryTimeout, 0.2))
3994 grpcRetryOptions := grpc_retry.UnaryClientInterceptor(grpc_retry.WithMax(dh.cfg.MaxRetries), grpc_retry.WithPerRetryTimeout(dh.cfg.PerRPCRetryTimeout), grpc_retry.WithCodes(retryCodes...), backoffCtxOption)
khenaidoo106c61a2021-08-11 18:05:46 -04003995
nikesh.krishnand9812542023-08-01 18:31:39 +05303996 go dh.childAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), dh.getOnuInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo106c61a2021-08-11 18:05:46 -04003997 // Wait until we have a connection to the child adapter.
3998 // Unlimited retries or until context expires
3999 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
4000 backoff := vgrpc.NewBackoff(dh.cfg.MinBackoffRetryDelay, dh.cfg.MaxBackoffRetryDelay, 0)
4001 for {
4002 client, err := dh.childAdapterClients[endpoint].GetOnuInterAdapterServiceClient()
4003 if err == nil && client != nil {
4004 logger.Infow(subCtx, "connected-to-child-adapter", log.Fields{"child-endpoint": endpoint})
4005 break
4006 }
4007 logger.Warnw(subCtx, "connection-to-child-adapter-not-ready", log.Fields{"error": err, "child-endpoint": endpoint})
4008 // Backoff
4009 if err = backoff.Backoff(subCtx); err != nil {
4010 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "child-endpoint": endpoint})
4011 break
4012 }
4013 }
4014 return nil
4015}
4016
khenaidoodc2116e2021-10-19 17:33:19 -04004017func (dh *DeviceHandler) getChildAdapterServiceClient(endpoint string) (onu_inter_adapter_service.OnuInterAdapterServiceClient, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004018
4019 // First check from cache
4020 dh.lockChildAdapterClients.RLock()
4021 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4022 dh.lockChildAdapterClients.RUnlock()
4023 return cgClient.GetOnuInterAdapterServiceClient()
4024 }
4025 dh.lockChildAdapterClients.RUnlock()
4026
4027 // Set the child connection - can occur on restarts
4028 ctx, cancel := context.WithTimeout(context.Background(), dh.cfg.RPCTimeout)
4029 err := dh.setupChildInterAdapterClient(ctx, endpoint)
4030 cancel()
4031 if err != nil {
4032 return nil, err
4033 }
4034
4035 // Get the child client now
4036 dh.lockChildAdapterClients.RLock()
4037 defer dh.lockChildAdapterClients.RUnlock()
4038 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4039 return cgClient.GetOnuInterAdapterServiceClient()
4040 }
4041 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
4042}
4043
4044func (dh *DeviceHandler) deleteAdapterClients(ctx context.Context) {
4045 dh.lockChildAdapterClients.Lock()
4046 defer dh.lockChildAdapterClients.Unlock()
4047 for key, client := range dh.childAdapterClients {
4048 client.Stop(ctx)
4049 delete(dh.childAdapterClients, key)
4050 }
4051}
4052
khenaidooefff76e2021-12-15 16:51:30 -05004053// TODO: Any action the adapter needs to do following a onu adapter inter adapter service restart?
4054func (dh *DeviceHandler) onuInterAdapterRestarted(ctx context.Context, endPoint string) error {
4055 logger.Warnw(ctx, "onu-inter-adapter-service-reconnected", log.Fields{"endpoint": endPoint})
khenaidoo106c61a2021-08-11 18:05:46 -04004056 return nil
4057}
4058
khenaidooefff76e2021-12-15 16:51:30 -05004059// getOnuInterAdapterServiceClientHandler is used to setup the remote gRPC service
4060func (dh *DeviceHandler) getOnuInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
4061 if conn == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04004062 return nil
4063 }
khenaidooefff76e2021-12-15 16:51:30 -05004064 return onu_inter_adapter_service.NewOnuInterAdapterServiceClient(conn)
khenaidoo106c61a2021-08-11 18:05:46 -04004065}
Girish Gowdra950326e2021-11-05 12:43:24 -07004066
4067func (dh *DeviceHandler) setDeviceDeletionInProgressFlag(flag bool) {
4068 dh.lockDevice.Lock()
4069 defer dh.lockDevice.Unlock()
4070 dh.isDeviceDeletionInProgress = flag
4071}
4072
4073func (dh *DeviceHandler) getDeviceDeletionInProgressFlag() bool {
4074 dh.lockDevice.RLock()
4075 defer dh.lockDevice.RUnlock()
4076 return dh.isDeviceDeletionInProgress
4077}
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08004078
4079// waitForTimeoutOrCompletion waits for the waitgroup for the specified max timeout.
4080// Returns false if waiting timed out.
4081func (dh *DeviceHandler) waitForTimeoutOrCompletion(wg *sync.WaitGroup, timeout time.Duration) bool {
4082 c := make(chan struct{})
4083 go func() {
4084 defer close(c)
4085 wg.Wait()
4086 }()
4087 select {
4088 case <-c:
4089 return true // completed normally
4090 case <-time.After(timeout):
4091 return false // timed out
4092 }
4093}
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05304094
4095func (dh *DeviceHandler) updateHeartbeatSignature(ctx context.Context, signature uint32) {
4096 val, err := json.Marshal(signature)
4097 if err != nil {
4098 logger.Error(ctx, "failed-to-marshal")
4099 return
4100 }
4101 if err = dh.kvStore.Put(ctx, heartbeatPath, val); err != nil {
4102 logger.Error(ctx, "failed-to-store-hearbeat-signature")
4103 }
4104}
4105
4106func (dh *DeviceHandler) getHeartbeatSignature(ctx context.Context) uint32 {
4107 var signature uint32
4108
4109 Value, er := dh.kvStore.Get(ctx, heartbeatPath)
4110 if er == nil {
4111 if Value != nil {
4112 Val, er := kvstore.ToByte(Value.Value)
4113 if er != nil {
4114 logger.Errorw(ctx, "Failed to convert into byte array", log.Fields{"err": er})
4115 return signature
4116 }
4117 if er = json.Unmarshal(Val, &signature); er != nil {
4118 logger.Error(ctx, "Failed to unmarshal signature", log.Fields{"err": er})
4119 return signature
4120 }
4121 }
4122 }
4123 return signature
4124}