blob: d7ea8449832bf7fa32a94e2bac5901ddb9fb4621 [file] [log] [blame]
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301/*
Joey Armstrong11f5a572024-01-12 19:11:32 -05002 * Copyright 2018-2024 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"
Abhay Kumard3f18512025-12-09 07:51:12 +000042 grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
khenaidoo106c61a2021-08-11 18:05:46 -040043 "github.com/opencord/voltha-lib-go/v7/pkg/config"
44 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
45 flow_utils "github.com/opencord/voltha-lib-go/v7/pkg/flows"
46 "github.com/opencord/voltha-lib-go/v7/pkg/log"
Mahir Gunyel85f61c12021-10-06 11:53:45 -070047 plt "github.com/opencord/voltha-lib-go/v7/pkg/platform"
khenaidoo106c61a2021-08-11 18:05:46 -040048 "github.com/opencord/voltha-lib-go/v7/pkg/pmmetrics"
Matteo Scandolodfa7a972020-11-06 13:03:40 -080049
nikesh.krishnand9812542023-08-01 18:31:39 +053050 grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
khenaidoo106c61a2021-08-11 18:05:46 -040051 conf "github.com/opencord/voltha-openolt-adapter/internal/pkg/config"
Thomas Lee S94109f12020-03-03 16:39:29 +053052 "github.com/opencord/voltha-openolt-adapter/internal/pkg/olterrors"
Scott Bakerdbd960e2020-02-28 08:57:51 -080053 rsrcMgr "github.com/opencord/voltha-openolt-adapter/internal/pkg/resourcemanager"
khenaidoo106c61a2021-08-11 18:05:46 -040054 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoodc2116e2021-10-19 17:33:19 -040055 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo106c61a2021-08-11 18:05:46 -040056 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoodc2116e2021-10-19 17:33:19 -040057 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
58 "github.com/opencord/voltha-protos/v5/go/onu_inter_adapter_service"
khenaidoo106c61a2021-08-11 18:05:46 -040059 of "github.com/opencord/voltha-protos/v5/go/openflow_13"
60 oop "github.com/opencord/voltha-protos/v5/go/openolt"
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +053061 tp_pb "github.com/opencord/voltha-protos/v5/go/tech_profile"
khenaidoo106c61a2021-08-11 18:05:46 -040062 "github.com/opencord/voltha-protos/v5/go/voltha"
cuilin20187b2a8c32019-03-26 19:52:28 -070063 "google.golang.org/grpc"
nikesh.krishnand9812542023-08-01 18:31:39 +053064 codes "google.golang.org/grpc/codes"
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040065 "google.golang.org/grpc/status"
Phaneendra Manda4c62c802019-03-06 21:37:49 +053066)
67
salmansiddiqui7ac62132019-08-22 03:58:50 +000068// Constants for number of retries and for timeout
Manikkaraj kb1d51442019-07-23 10:41:02 -040069const (
Girish Gowdra491a9c62021-01-06 16:43:07 -080070 InvalidPort = 0xffffffff
71 MaxNumOfGroupHandlerChannels = 256
72
73 McastFlowOrGroupAdd = "McastFlowOrGroupAdd"
74 McastFlowOrGroupModify = "McastFlowOrGroupModify"
75 McastFlowOrGroupRemove = "McastFlowOrGroupRemove"
kesavand62126212021-01-12 04:56:06 -050076 oltPortInfoTimeout = 3
Elia Battiston596406d2022-02-02 12:19:00 +010077
78 defaultPortSpeedMbps = 1000
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053079 heartbeatPath = "heartbeat"
Manikkaraj kb1d51442019-07-23 10:41:02 -040080)
81
Mahir Gunyela2e68702022-12-07 00:00:42 -080082// DeviceHandler will interact with the OLT device.
Phaneendra Manda4c62c802019-03-06 21:37:49 +053083type DeviceHandler struct {
Akash Kankanala041a2122024-10-16 15:49:22 +053084 EventProxy eventif.EventProxy
85 Client oop.OpenoltClient
86 cm *config.ConfigManager
87 device *voltha.Device
88 cfg *conf.AdapterFlags
89 coreClient *vgrpc.Client
90 childAdapterClients map[string]*vgrpc.Client
91 openOLT *OpenOLT
92 exitChannel chan struct{}
93 transitionMap *TransitionMap
94 clientCon *grpc.ClientConn
95 groupMgr *OpenOltGroupMgr
96 eventMgr *OpenOltEventMgr
97 kvStore *db.Backend // backend kv store connection handle
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -070098
99 deviceInfo *oop.DeviceInfo
Naga Manjunatha8dc9372019-10-31 23:01:18 +0530100
Akash Kankanala041a2122024-10-16 15:49:22 +0530101 portStats *OpenOltStatisticsMgr
102 metrics *pmmetrics.PmMetrics
103 stopCollector chan bool
104 stopHeartbeatCheck chan bool
105 stopIndications chan bool
106 perPonOnuIndicationChannel map[uint32]onuIndicationChannels
107
Matteo Scandolo7eaec532022-06-23 15:54:57 -0700108 // discOnus (map[onuSn]bool) contains a list of ONUs that have been discovered, indexed by ONU SerialNumber.
109 // if the value is true that means the OnuDiscovery indication
110 // is currently being processed and thus we can ignore concurrent requests
111 // if it's false it means the processing has completed and we shouldn't be receiving a new indication
112 // if we do it means something went wrong and we need to retry
Akash Kankanala041a2122024-10-16 15:49:22 +0530113 discOnus sync.Map
114 onus sync.Map
115 activePorts sync.Map
116 flowMgr []*OpenOltFlowMgr
117 resourceMgr []*rsrcMgr.OpenOltResourceMgr
Girish Gowdra491a9c62021-01-06 16:43:07 -0800118
119 // Slice of channels. Each channel in slice, index by (mcast-group-id modulo MaxNumOfGroupHandlerChannels)
120 // 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 -0700121 incomingMcastFlowOrGroup []chan McastFlowOrGroupControlBlock
122 stopMcastHandlerRoutine []chan bool
123 mcastHandlerRoutineActive []bool
Gamze Abakac2c32a62021-03-11 11:44:18 +0000124
Akash Kankanala041a2122024-10-16 15:49:22 +0530125 lockChildAdapterClients sync.RWMutex
126 lockDevice sync.RWMutex
127 perPonOnuIndicationChannelLock sync.Mutex
128
129 totalPonPorts uint32
130 heartbeatSignature uint32
131 isCollectorActive bool
132 isHeartbeatCheckActive bool
133 isReadIndicationRoutineActive bool
134
Gamze Abakac2c32a62021-03-11 11:44:18 +0000135 adapterPreviouslyConnected bool
136 agentPreviouslyConnected bool
Girish Gowdra950326e2021-11-05 12:43:24 -0700137
138 isDeviceDeletionInProgress bool
Nandita Biradar1b590f12024-09-27 10:56:28 +0530139 prevOperStatus common.OperStatus_Types
bseenivaaa9165b2025-09-18 17:28:12 +0530140 collectorWaitGroup sync.WaitGroup
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +0000141 transitionHandlerCancel context.CancelFunc
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700142}
143
Mahir Gunyela2e68702022-12-07 00:00:42 -0800144// OnuDevice represents ONU related info
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700145type OnuDevice struct {
khenaidoo106c61a2021-08-11 18:05:46 -0400146 deviceID string
147 deviceType string
148 serialNumber string
Akash Kankanala041a2122024-10-16 15:49:22 +0530149 proxyDeviceID string
150 adapterEndpoint string
khenaidoo106c61a2021-08-11 18:05:46 -0400151 onuID uint32
152 intfID uint32
khenaidoo106c61a2021-08-11 18:05:46 -0400153 losRaised bool
154 rdiRaised bool
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700155}
156
Mahir Gunyelb0046752021-02-26 13:51:05 -0800157type onuIndicationMsg struct {
158 ctx context.Context
159 indication *oop.Indication
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800160}
161
162type onuIndicationChannels struct {
Mahir Gunyelb0046752021-02-26 13:51:05 -0800163 indicationChannel chan onuIndicationMsg
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800164 stopChannel chan struct{}
165}
166
Mahir Gunyela2e68702022-12-07 00:00:42 -0800167// McastFlowOrGroupControlBlock is created per mcast flow/group add/modify/remove and pushed on the incomingMcastFlowOrGroup channel slice
168// The McastFlowOrGroupControlBlock is then picked by the mcastFlowOrGroupChannelHandlerRoutine for further processing.
169// There are MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine routines which monitor for any incoming mcast flow/group messages
170// 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 -0800171type McastFlowOrGroupControlBlock struct {
khenaidoodc2116e2021-10-19 17:33:19 -0400172 ctx context.Context // Flow/group handler context
khenaidoodc2116e2021-10-19 17:33:19 -0400173 flow *of.OfpFlowStats // Flow message (can be nil or valid flow)
174 group *of.OfpGroupEntry // Group message (can be nil or valid group)
175 errChan *chan error // channel to report the mcast Flow/group handling error
Akash Kankanala041a2122024-10-16 15:49:22 +0530176 flowOrGroupAction string // one of McastFlowOrGroupAdd, McastFlowOrGroupModify or McastFlowOrGroupDelete
Girish Gowdra491a9c62021-01-06 16:43:07 -0800177}
178
Naga Manjunath7615e552019-10-11 22:35:47 +0530179var pmNames = []string{
180 "rx_bytes",
181 "rx_packets",
akashreddyk302516f2025-11-17 15:18:44 +0530182 "rx_ucast_packets",
Naga Manjunath7615e552019-10-11 22:35:47 +0530183 "rx_mcast_packets",
184 "rx_bcast_packets",
akashreddyk302516f2025-11-17 15:18:44 +0530185 "rx_error_packets",
186 "rx_crc_errors",
187 "rx_packets_dropped",
Naga Manjunath7615e552019-10-11 22:35:47 +0530188 "tx_bytes",
189 "tx_packets",
akashreddyk302516f2025-11-17 15:18:44 +0530190 "tx_ucast_packets",
Naga Manjunath7615e552019-10-11 22:35:47 +0530191 "tx_mcast_packets",
192 "tx_bcast_packets",
akashreddyk302516f2025-11-17 15:18:44 +0530193 "tx_error_packets",
194 "tx_dropped_total",
Naga Manjunath7615e552019-10-11 22:35:47 +0530195}
196
Mahir Gunyela2e68702022-12-07 00:00:42 -0800197// NewOnuDevice creates a new Onu Device
khenaidoo106c61a2021-08-11 18:05:46 -0400198func NewOnuDevice(devID, deviceTp, serialNum string, onuID, intfID uint32, proxyDevID string, losRaised bool, adapterEndpoint string) *OnuDevice {
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700199 var device OnuDevice
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700200 device.deviceID = devID
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700201 device.deviceType = deviceTp
202 device.serialNumber = serialNum
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700203 device.onuID = onuID
204 device.intfID = intfID
205 device.proxyDeviceID = proxyDevID
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +0530206 device.losRaised = losRaised
khenaidoo106c61a2021-08-11 18:05:46 -0400207 device.adapterEndpoint = adapterEndpoint
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700208 return &device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530209}
210
Mahir Gunyela2e68702022-12-07 00:00:42 -0800211// NewDeviceHandler creates a new device handler
khenaidoo106c61a2021-08-11 18:05:46 -0400212func 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 -0700213 var dh DeviceHandler
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530214 ctx := context.Background()
Matteo Scandolodfa7a972020-11-06 13:03:40 -0800215 dh.cm = cm
khenaidoo106c61a2021-08-11 18:05:46 -0400216 dh.coreClient = cc
Devmalya Paulfb990a52019-07-09 10:01:49 -0400217 dh.EventProxy = ep
cuilin20187b2a8c32019-03-26 19:52:28 -0700218 cloned := (proto.Clone(device)).(*voltha.Device)
cuilin20187b2a8c32019-03-26 19:52:28 -0700219 dh.device = cloned
220 dh.openOLT = adapter
khenaidooefff76e2021-12-15 16:51:30 -0500221 dh.exitChannel = make(chan struct{})
cuilin20187b2a8c32019-03-26 19:52:28 -0700222 dh.lockDevice = sync.RWMutex{}
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000223 dh.stopCollector = make(chan bool, 1) // TODO: Why buffered?
224 dh.stopHeartbeatCheck = make(chan bool, 1) // TODO: Why buffered?
Naga Manjunath7615e552019-10-11 22:35:47 +0530225 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 -0500226 dh.activePorts = sync.Map{}
Girish Gowdraae56c722021-11-22 14:31:11 -0800227 dh.stopIndications = make(chan bool, 1) // TODO: Why buffered?
Mahir Gunyelb0046752021-02-26 13:51:05 -0800228 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
khenaidoo106c61a2021-08-11 18:05:46 -0400229 dh.childAdapterClients = make(map[string]*vgrpc.Client)
230 dh.cfg = cfg
Gustavo Silva41af9122022-10-11 11:05:13 -0300231 dh.kvStore = SetKVClient(ctx, dh.openOLT.KVStoreType, dh.openOLT.KVStoreAddress, dh.device.Id, dh.cm.Backend.PathPrefix)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530232 if dh.kvStore == nil {
233 logger.Error(ctx, "Failed to setup KV store")
234 return nil
235 }
236
Girish Gowdra491a9c62021-01-06 16:43:07 -0800237 // Create a slice of buffered channels for handling concurrent mcast flow/group.
238 dh.incomingMcastFlowOrGroup = make([]chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700239 dh.stopMcastHandlerRoutine = make([]chan bool, MaxNumOfGroupHandlerChannels)
240 dh.mcastHandlerRoutineActive = make([]bool, MaxNumOfGroupHandlerChannels)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800241 for i := range dh.incomingMcastFlowOrGroup {
242 dh.incomingMcastFlowOrGroup[i] = make(chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdraae56c722021-11-22 14:31:11 -0800243 dh.stopMcastHandlerRoutine[i] = make(chan bool)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800244 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
245 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
246 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
247 // for incoming mcast flow/group to be processed serially.
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700248 dh.mcastHandlerRoutineActive[i] = true
249 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
Girish Gowdra491a9c62021-01-06 16:43:07 -0800250 }
Akash Kankanala041a2122024-10-16 15:49:22 +0530251 // TODO initialize the support classes.
cuilin20187b2a8c32019-03-26 19:52:28 -0700252 return &dh
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530253}
254
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530255func newKVClient(ctx context.Context, storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
256 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
257 switch storeType {
258 case "etcd":
259 return kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)
Abhay Kumar9bcfeb22024-07-12 09:14:25 +0530260 case "redis":
261 return kvstore.NewRedisClient(address, timeout, false)
262 case "redis-sentinel":
263 return kvstore.NewRedisClient(address, timeout, true)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530264 }
265 return nil, errors.New("unsupported-kv-store")
266}
267
268// SetKVClient sets the KV client and return a kv backend
269func SetKVClient(ctx context.Context, backend string, addr string, DeviceID string, basePathKvStore string) *db.Backend {
270 kvClient, err := newKVClient(ctx, backend, addr, rsrcMgr.KvstoreTimeout)
271 if err != nil {
272 logger.Fatalw(ctx, "Failed to init KV client\n", log.Fields{"err": err})
273 return nil
274 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530275 kvbackend := &db.Backend{
276 Client: kvClient,
277 StoreType: backend,
278 Address: addr,
279 Timeout: rsrcMgr.KvstoreTimeout,
280 PathPrefix: fmt.Sprintf(rsrcMgr.BasePathKvStore, basePathKvStore, DeviceID)}
281
282 return kvbackend
283}
284
Holger Hildebrandt143b5be2023-02-10 08:28:15 +0000285// CloseKVClient closes open KV clients
Abhay Kumarb87ac882025-10-30 09:55:07 +0000286// This method is thread-safe and can be called concurrently
Holger Hildebrandt143b5be2023-02-10 08:28:15 +0000287func (dh *DeviceHandler) CloseKVClient(ctx context.Context) {
Abhay Kumarb87ac882025-10-30 09:55:07 +0000288 // Acquire read lock to safely iterate over resourceMgr and flowMgr slices
289 // Use RLock since we're only reading the slices, not modifying them
290 dh.lockDevice.RLock()
291 defer dh.lockDevice.RUnlock()
292
Holger Hildebrandt143b5be2023-02-10 08:28:15 +0000293 if dh.resourceMgr != nil {
294 for _, rscMgr := range dh.resourceMgr {
295 if rscMgr != nil {
296 rscMgr.CloseKVClient(ctx)
297 }
298 }
299 }
300 if dh.flowMgr != nil {
301 for _, flMgr := range dh.flowMgr {
302 if flMgr != nil {
303 flMgr.CloseKVClient(ctx)
304 }
305 }
306 }
307}
308
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530309// start save the device to the data model
310func (dh *DeviceHandler) start(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700311 dh.lockDevice.Lock()
312 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000313 logger.Debugw(ctx, "starting-device-agent", log.Fields{"device": dh.device})
cuilin20187b2a8c32019-03-26 19:52:28 -0700314 // Add the initial device to the local model
Neha Sharma96b7bf22020-06-15 10:37:32 +0000315 logger.Debug(ctx, "device-agent-started")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530316}
317
khenaidooefff76e2021-12-15 16:51:30 -0500318// Stop stops the device handler
319func (dh *DeviceHandler) Stop(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700320 dh.lockDevice.Lock()
321 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000322 logger.Debug(ctx, "stopping-device-agent")
khenaidooefff76e2021-12-15 16:51:30 -0500323 close(dh.exitChannel)
khenaidoo106c61a2021-08-11 18:05:46 -0400324
khenaidooefff76e2021-12-15 16:51:30 -0500325 // Delete (which will stop also) all grpc connections to the child adapters
326 dh.deleteAdapterClients(ctx)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000327 logger.Debug(ctx, "device-agent-stopped")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530328}
329
ssiddiqui04386ee2021-08-23 21:58:25 +0530330func (dh *DeviceHandler) getPonTechnology(intfID uint32) string {
331 for _, resourceRanges := range dh.deviceInfo.GetRanges() {
332 for _, pooledIntfID := range resourceRanges.GetIntfIds() {
333 if pooledIntfID == intfID {
334 return resourceRanges.GetTechnology()
335 }
336 }
337 }
338 return ""
339}
340
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400341func macifyIP(ip net.IP) string {
342 if len(ip) > 0 {
343 oct1 := strconv.FormatInt(int64(ip[12]), 16)
344 oct2 := strconv.FormatInt(int64(ip[13]), 16)
345 oct3 := strconv.FormatInt(int64(ip[14]), 16)
346 oct4 := strconv.FormatInt(int64(ip[15]), 16)
347 return fmt.Sprintf("00:00:%02v:%02v:%02v:%02v", oct1, oct2, oct3, oct4)
348 }
349 return ""
350}
351
Neha Sharma96b7bf22020-06-15 10:37:32 +0000352func generateMacFromHost(ctx context.Context, host string) (string, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400353 var genmac string
354 var addr net.IP
355 var ips []string
356 var err error
357
Neha Sharma96b7bf22020-06-15 10:37:32 +0000358 logger.Debugw(ctx, "generating-mac-from-host", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400359
360 if addr = net.ParseIP(host); addr == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000361 logger.Debugw(ctx, "looking-up-hostname", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400362
363 if ips, err = net.LookupHost(host); err == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000364 logger.Debugw(ctx, "dns-result-ips", log.Fields{"ips": ips})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400365 if addr = net.ParseIP(ips[0]); addr == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000366 return "", olterrors.NewErrInvalidValue(log.Fields{"ip": ips[0]}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400367 }
368 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000369 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530370 log.Fields{"host": ips[0],
371 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400372 return genmac, nil
373 }
Girish Kumarf26e4882020-03-05 06:49:10 +0000374 return "", olterrors.NewErrAdapter("cannot-resolve-hostname-to-ip", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400375 }
376
377 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000378 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530379 log.Fields{"host": host,
380 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400381 return genmac, nil
382}
383
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530384func macAddressToUint32Array(mac string) []uint32 {
cuilin20187b2a8c32019-03-26 19:52:28 -0700385 slist := strings.Split(mac, ":")
386 result := make([]uint32, len(slist))
387 var err error
388 var tmp int64
389 for index, val := range slist {
390 if tmp, err = strconv.ParseInt(val, 16, 32); err != nil {
391 return []uint32{1, 2, 3, 4, 5, 6}
392 }
393 result[index] = uint32(tmp)
394 }
395 return result
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530396}
397
Mahir Gunyela2e68702022-12-07 00:00:42 -0800398// 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 -0800399func GetportLabel(portNum uint32, portType voltha.Port_PortType) (string, error) {
David K. Bainbridge794735f2020-02-11 21:01:37 -0800400 switch portType {
401 case voltha.Port_ETHERNET_NNI:
402 return fmt.Sprintf("nni-%d", portNum), nil
403 case voltha.Port_PON_OLT:
404 return fmt.Sprintf("pon-%d", portNum), nil
cuilin20187b2a8c32019-03-26 19:52:28 -0700405 }
David K. Bainbridge794735f2020-02-11 21:01:37 -0800406
Girish Kumarf26e4882020-03-05 06:49:10 +0000407 return "", olterrors.NewErrInvalidValue(log.Fields{"port-type": portType}, nil)
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530408}
409
Elia Battiston596406d2022-02-02 12:19:00 +0100410func makeOfpPort(macAddress string, speedMbps uint32) *of.OfpPort {
411 if speedMbps == 0 {
Akash Kankanala041a2122024-10-16 15:49:22 +0530412 // In case it was not set in the indication
413 // and no other value was provided
Elia Battiston596406d2022-02-02 12:19:00 +0100414 speedMbps = defaultPortSpeedMbps
415 }
416
417 ofpPortSpeed := of.OfpPortFeatures_OFPPF_OTHER
418 switch speedMbps {
419 case 1000000:
420 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1TB_FD
421 case 100000:
422 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100GB_FD
423 case 40000:
424 ofpPortSpeed = of.OfpPortFeatures_OFPPF_40GB_FD
425 case 10000:
426 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10GB_FD
427 case 1000:
428 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1GB_FD
429 case 100:
430 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100MB_FD
431 case 10:
432 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10MB_FD
433 }
434
435 capacity := uint32(ofpPortSpeed | of.OfpPortFeatures_OFPPF_FIBER)
436
437 port := &of.OfpPort{
438 HwAddr: macAddressToUint32Array(macAddress),
439 Config: 0,
440 State: uint32(of.OfpPortState_OFPPS_LIVE),
441 Curr: capacity,
442 Advertised: capacity,
443 Peer: capacity,
Akash Kankanala041a2122024-10-16 15:49:22 +0530444 CurrSpeed: speedMbps * 1000, // kbps
445 MaxSpeed: speedMbps * 1000, // kbps
Elia Battiston596406d2022-02-02 12:19:00 +0100446 }
447
448 return port
449}
450
451func (dh *DeviceHandler) addPort(ctx context.Context, intfID uint32, portType voltha.Port_PortType, state string, speedMbps uint32) error {
Esin Karamanccb714b2019-11-29 15:02:06 +0000452 var operStatus common.OperStatus_Types
cuilin20187b2a8c32019-03-26 19:52:28 -0700453 if state == "up" {
454 operStatus = voltha.OperStatus_ACTIVE
Akash Kankanala041a2122024-10-16 15:49:22 +0530455 // populating the intfStatus map
Chaitrashree G Sef088112020-02-03 21:39:27 -0500456 dh.activePorts.Store(intfID, true)
cuilin20187b2a8c32019-03-26 19:52:28 -0700457 } else {
458 operStatus = voltha.OperStatus_DISCOVERED
Chaitrashree G Sef088112020-02-03 21:39:27 -0500459 dh.activePorts.Store(intfID, false)
cuilin20187b2a8c32019-03-26 19:52:28 -0700460 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -0700461 portNum := plt.IntfIDToPortNo(intfID, portType)
Chaitrashree G Sc0878ec2020-05-21 04:59:53 -0400462 label, err := GetportLabel(intfID, portType)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800463 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000464 return olterrors.NewErrNotFound("port-label", log.Fields{"port-number": portNum, "port-type": portType}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400465 }
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500466
khenaidoo106c61a2021-08-11 18:05:46 -0400467 // Check if port exists
khenaidoodc2116e2021-10-19 17:33:19 -0400468 port, err := dh.getPortFromCore(ctx, &ca.PortFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400469 DeviceId: dh.device.Id,
470 Port: portNum,
471 })
472 if err == nil && port.Type == portType {
Girish Kumara1ea2aa2020-08-19 18:14:22 +0000473 logger.Debug(ctx, "port-already-exists-updating-oper-status-of-port")
khenaidoodc2116e2021-10-19 17:33:19 -0400474 err = dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -0400475 DeviceId: dh.device.Id,
476 PortType: portType,
477 PortNo: portNum,
478 OperStatus: operStatus})
479 if err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400480 return olterrors.NewErrAdapter("failed-to-update-port-state", log.Fields{
481 "device-id": dh.device.Id,
482 "port-type": portType,
483 "port-number": portNum,
484 "oper-status": operStatus}, err).Log()
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500485 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400486 return nil
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500487 }
khenaidoo106c61a2021-08-11 18:05:46 -0400488
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400489 // Now create Port
khenaidoo106c61a2021-08-11 18:05:46 -0400490 port = &voltha.Port{
491 DeviceId: dh.device.Id,
cuilin20187b2a8c32019-03-26 19:52:28 -0700492 PortNo: portNum,
493 Label: label,
494 Type: portType,
495 OperStatus: operStatus,
Elia Battiston596406d2022-02-02 12:19:00 +0100496 OfpPort: makeOfpPort(dh.device.MacAddress, speedMbps),
cuilin20187b2a8c32019-03-26 19:52:28 -0700497 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000498 logger.Debugw(ctx, "sending-port-update-to-core", log.Fields{"port": port})
cuilin20187b2a8c32019-03-26 19:52:28 -0700499 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -0400500 err = dh.createPortInCore(ctx, port)
501 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000502 return olterrors.NewErrAdapter("error-creating-port", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -0800503 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +0000504 "port-type": portType}, err)
Girish Gowdru1110ef22019-06-24 11:17:59 -0400505 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000506 go dh.updateLocalDevice(ctx)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530507 return nil
508}
509
Kent Hagermane6ff1012020-07-14 15:07:53 -0400510func (dh *DeviceHandler) updateLocalDevice(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -0400511 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530512 if err != nil || device == nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400513 logger.Errorf(ctx, "device-not-found", log.Fields{"device-id": dh.device.Id}, err)
514 return
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530515 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800516 dh.lockDevice.Lock()
517 defer dh.lockDevice.Unlock()
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530518 dh.device = device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530519}
520
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700521// nolint: gocyclo
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530522// readIndications to read the indications from the OLT device
David K. Bainbridge794735f2020-02-11 21:01:37 -0800523func (dh *DeviceHandler) readIndications(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000524 defer logger.Debugw(ctx, "indications-ended", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700525 defer func() {
526 dh.lockDevice.Lock()
527 dh.isReadIndicationRoutineActive = false
Nandita Biradar1b590f12024-09-27 10:56:28 +0530528 logger.Debugw(ctx, "isReadIndicationRoutineActive set to false", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700529 dh.lockDevice.Unlock()
530 }()
Girish Gowdra3f974912020-03-23 20:35:18 -0700531 indications, err := dh.startOpenOltIndicationStream(ctx)
cuilin20187b2a8c32019-03-26 19:52:28 -0700532 if err != nil {
Girish Gowdra3f974912020-03-23 20:35:18 -0700533 return err
cuilin20187b2a8c32019-03-26 19:52:28 -0700534 }
Girish Gowdru5ba46c92019-04-25 05:00:05 -0400535
David Bainbridgef5879ca2019-12-13 21:17:54 +0000536 // Create an exponential backoff around re-enabling indications. The
537 // maximum elapsed time for the back off is set to 0 so that we will
538 // continue to retry. The max interval defaults to 1m, but is set
539 // here for code clarity
540 indicationBackoff := backoff.NewExponentialBackOff()
541 indicationBackoff.MaxElapsedTime = 0
542 indicationBackoff.MaxInterval = 1 * time.Minute
Girish Gowdra3f974912020-03-23 20:35:18 -0700543
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700544 dh.lockDevice.Lock()
545 dh.isReadIndicationRoutineActive = true
Nandita Biradar1b590f12024-09-27 10:56:28 +0530546 logger.Debugw(ctx, "isReadIndicationRoutineActive set to true", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700547 dh.lockDevice.Unlock()
548
Girish Gowdra3f974912020-03-23 20:35:18 -0700549Loop:
cuilin20187b2a8c32019-03-26 19:52:28 -0700550 for {
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400551 select {
552 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000553 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700554 break Loop
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400555 default:
556 indication, err := indications.Recv()
Elia Battiston599d25f2022-02-16 14:49:08 +0100557
558 select {
559 case <-indications.Context().Done():
560 if err != nil {
561 logger.Warnw(ctx, "error-during-enable-indications",
562 log.Fields{"err": err,
563 "device-id": dh.device.Id})
564 }
565
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400566 // Use an exponential back off to prevent getting into a tight loop
567 duration := indicationBackoff.NextBackOff()
Elia Battiston599d25f2022-02-16 14:49:08 +0100568 logger.Infow(ctx, "backing-off-enable-indication", log.Fields{
569 "device-id": dh.device.Id,
570 "duration": duration,
571 })
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400572 if duration == backoff.Stop {
573 // If we reach a maximum then warn and reset the backoff
574 // timer and keep attempting.
Elia Battiston599d25f2022-02-16 14:49:08 +0100575 logger.Warnw(ctx, "maximum-indication-backoff-reached-resetting-backoff-timer",
Shrey Baid807a2a02020-04-09 12:52:45 +0530576 log.Fields{"max-indication-backoff": indicationBackoff.MaxElapsedTime,
Thomas Lee S985938d2020-05-04 11:40:41 +0530577 "device-id": dh.device.Id})
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400578 indicationBackoff.Reset()
579 }
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700580
581 // On failure process a backoff timer while watching for stopIndications
582 // events
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700583 backoffTimer := time.NewTimer(indicationBackoff.NextBackOff())
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700584 select {
585 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000586 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700587 if !backoffTimer.Stop() {
588 <-backoffTimer.C
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700589 }
590 break Loop
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700591 case <-backoffTimer.C:
592 // backoffTimer expired continue
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700593 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700594 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
595 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400596 }
597 continue
Elia Battiston599d25f2022-02-16 14:49:08 +0100598 default:
599 if err != nil {
600 logger.Errorw(ctx, "read-indication-error",
Shrey Baid807a2a02020-04-09 12:52:45 +0530601 log.Fields{"err": err,
Thomas Lee S985938d2020-05-04 11:40:41 +0530602 "device-id": dh.device.Id})
Elia Battiston599d25f2022-02-16 14:49:08 +0100603 // Close the stream, and re-initialize it
604 if err = indications.CloseSend(); err != nil {
605 // Ok to ignore here, because we landed here due to a problem on the stream
606 // In all probability, the closeSend call may fail
607 logger.Debugw(ctx, "error-closing-send stream--error-ignored",
608 log.Fields{"err": err,
609 "device-id": dh.device.Id})
610 }
611 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
612 return err
613 }
614 // once we re-initialized the indication stream, continue to read indications
615 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700616 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100617 // Reset backoff if we have a successful receive
618 indicationBackoff.Reset()
619 // When OLT is admin down, ignore all indications.
620 if dh.device.AdminState == voltha.AdminState_DISABLED && !isIndicationAllowedDuringOltAdminDown(indication) {
621 logger.Debugw(ctx, "olt-is-admin-down, ignore indication",
622 log.Fields{"indication": indication,
623 "device-id": dh.device.Id})
624 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700625 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100626 dh.handleIndication(ctx, indication)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +0530627 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700628 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700629 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700630 // Close the send stream
631 _ = indications.CloseSend() // Ok to ignore error, as we stopping the readIndication anyway
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700632
Girish Gowdra3f974912020-03-23 20:35:18 -0700633 return nil
634}
635
636func (dh *DeviceHandler) startOpenOltIndicationStream(ctx context.Context) (oop.Openolt_EnableIndicationClient, error) {
Girish Gowdra852ad912021-05-04 00:05:50 -0700637 logger.Infow(ctx, "enabling read indications", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700638 indications, err := dh.Client.EnableIndication(ctx, new(oop.Empty))
639 if err != nil {
640 return nil, olterrors.NewErrCommunication("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).Log()
641 }
642 if indications == nil {
643 return nil, olterrors.NewErrInvalidValue(log.Fields{"indications": nil, "device-id": dh.device.Id}, nil).Log()
644 }
Girish Gowdra852ad912021-05-04 00:05:50 -0700645 logger.Infow(ctx, "read indication started successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700646 return indications, nil
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400647}
648
649// isIndicationAllowedDuringOltAdminDown returns true if the indication is allowed during OLT Admin down, else false
650func isIndicationAllowedDuringOltAdminDown(indication *oop.Indication) bool {
651 switch indication.Data.(type) {
652 case *oop.Indication_OltInd, *oop.Indication_IntfInd, *oop.Indication_IntfOperInd:
653 return true
654
655 default:
656 return false
657 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700658}
659
David K. Bainbridge794735f2020-02-11 21:01:37 -0800660func (dh *DeviceHandler) handleOltIndication(ctx context.Context, oltIndication *oop.OltIndication) error {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700661 raisedTs := time.Now().Unix()
Gamze Abakaa1a50522019-10-03 19:28:27 +0000662 if oltIndication.OperState == "up" && dh.transitionMap.currentDeviceState != deviceStateUp {
npujarec5762e2020-01-01 14:08:48 +0530663 dh.transitionMap.Handle(ctx, DeviceUpInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700664 } else if oltIndication.OperState == "down" {
npujarec5762e2020-01-01 14:08:48 +0530665 dh.transitionMap.Handle(ctx, DeviceDownInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700666 }
Daniele Rossi051466a2019-07-26 13:39:37 +0000667 // Send or clear Alarm
Neha Sharma96b7bf22020-06-15 10:37:32 +0000668 if err := dh.eventMgr.oltUpDownIndication(ctx, oltIndication, dh.device.Id, raisedTs); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +0530669 return olterrors.NewErrAdapter("failed-indication", log.Fields{
divyadesai3af43e12020-08-18 07:10:54 +0000670 "device-id": dh.device.Id,
David K. Bainbridge794735f2020-02-11 21:01:37 -0800671 "indication": oltIndication,
Girish Kumarf26e4882020-03-05 06:49:10 +0000672 "timestamp": raisedTs}, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800673 }
674 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700675}
676
balaji.nagarajan68f56e82025-07-04 15:16:01 +0530677func (dh *DeviceHandler) handleOnuDisableIndication(ctx context.Context, onuIndication *oop.OnuDisabledIndication) error {
678 logger.Infow(ctx, "handleOnuDisableIndication", log.Fields{"device-id": dh.device.Id, "onuInd": onuIndication})
679 sn := dh.stringifySerialNumber(onuIndication.SerialNumber)
680 intfID := onuIndication.GetIntfId()
681 ponPort := plt.IntfIDToPortNo(intfID, voltha.Port_PON_OLT)
682 onuDev := dh.getChildDevice(ctx, sn, ponPort)
683 if onuDev == nil {
684 logger.Warnw(ctx, "handleOnuDisableIndication onu-device-fetch-failed", log.Fields{"device-id": dh.device.Id, "onuInd": onuIndication})
685 onuDev = &OnuDevice{
686 serialNumber: sn,
687 }
688 }
689 dh.discOnus.Delete(sn)
690
691 raisedTs := time.Now().Unix()
692 if err := dh.eventMgr.onuDisableIndication(ctx, onuIndication, dh.device.Id, onuDev, raisedTs); err != nil {
693 return olterrors.NewErrAdapter("failed-indication", log.Fields{
694 "device-id": dh.device.Id,
695 "indication": onuIndication,
696 "timestamp": raisedTs}, err)
697 }
698 OnuIndication := generateOnuIndication(onuDev.intfID, onuDev.onuID, "down", "down")
699 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDev.adapterEndpoint, &ia.OnuIndicationMessage{
700 DeviceId: onuDev.deviceID,
701 OnuIndication: OnuIndication.GetOnuInd(),
702 })
703 if err != nil {
704 return olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
705 "onu-indicator": OnuIndication.GetOnuInd(),
706 "source": dh.openOLT.config.AdapterEndpoint,
707 "device-type": onuDev.deviceType,
708 "device-id": onuDev.deviceID}, err)
709 }
710 return nil
711}
712
713func (dh *DeviceHandler) handleOnuEnableIndication(ctx context.Context, onuIndication *oop.OnuEnabledIndication) error {
714 logger.Infow(ctx, "handleOnuEnableIndication", log.Fields{"device-id": dh.device.Id, "onuInd": onuIndication})
715 sn := dh.stringifySerialNumber(onuIndication.SerialNumber)
716 intfID := onuIndication.GetIntfId()
717 ponPort := plt.IntfIDToPortNo(intfID, voltha.Port_PON_OLT)
718 onuDev := dh.getChildDevice(ctx, sn, ponPort)
719 if onuDev == nil {
720 logger.Warnw(ctx, "handleOnuEnableIndication onu-device-fetch-failed", log.Fields{"device-id": dh.device.Id, "onuInd": onuIndication})
721 onuDev = &OnuDevice{
722 serialNumber: sn,
723 }
724 }
725 raisedTs := time.Now().Unix()
726
727 if err := dh.eventMgr.onuEnableIndication(ctx, onuIndication, dh.device.Id, onuDev, raisedTs); err != nil {
728 return olterrors.NewErrAdapter("failed-indication", log.Fields{
729 "device-id": dh.device.Id,
730 "indication": onuIndication,
731 "timestamp": raisedTs}, err)
732 }
733 return nil
734}
735
Akash Kankanala041a2122024-10-16 15:49:22 +0530736// nolint: gocyclo,govet
npujarec5762e2020-01-01 14:08:48 +0530737func (dh *DeviceHandler) handleIndication(ctx context.Context, indication *oop.Indication) {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700738 raisedTs := time.Now().Unix()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700739 switch indication.Data.(type) {
740 case *oop.Indication_OltInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000741 span, ctx := log.CreateChildSpan(ctx, "olt-indication", log.Fields{"device-id": dh.device.Id})
742 defer span.Finish()
Girish Gowdra852ad912021-05-04 00:05:50 -0700743 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 -0800744 if err := dh.handleOltIndication(ctx, indication.GetOltInd()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400745 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "olt", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800746 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700747 case *oop.Indication_IntfInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000748 span, ctx := log.CreateChildSpan(ctx, "interface-indication", log.Fields{"device-id": dh.device.Id})
749 defer span.Finish()
750
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700751 intfInd := indication.GetIntfInd()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800752 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100753 if err := dh.addPort(ctx, intfInd.GetIntfId(), voltha.Port_PON_OLT, intfInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400754 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800755 }
756 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000757 logger.Infow(ctx, "received-interface-indication", log.Fields{"InterfaceInd": intfInd, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700758 case *oop.Indication_IntfOperInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000759 span, ctx := log.CreateChildSpan(ctx, "interface-oper-indication", log.Fields{"device-id": dh.device.Id})
760 defer span.Finish()
761
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700762 intfOperInd := indication.GetIntfOperInd()
763 if intfOperInd.GetType() == "nni" {
David K. Bainbridge794735f2020-02-11 21:01:37 -0800764 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100765 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_ETHERNET_NNI, intfOperInd.GetOperState(), intfOperInd.GetSpeed()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400766 _ = 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 -0800767 }
768 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700769 } else if intfOperInd.GetType() == "pon" {
770 // TODO: Check what needs to be handled here for When PON PORT down, ONU will be down
771 // Handle pon port update
David K. Bainbridge794735f2020-02-11 21:01:37 -0800772 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100773 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_PON_OLT, intfOperInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400774 _ = 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 -0800775 }
776 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000777 go dh.eventMgr.oltIntfOperIndication(ctx, indication.GetIntfOperInd(), dh.device.Id, raisedTs)
cuilin20187b2a8c32019-03-26 19:52:28 -0700778 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000779 logger.Infow(ctx, "received-interface-oper-indication",
Shrey Baid807a2a02020-04-09 12:52:45 +0530780 log.Fields{"interfaceOperInd": intfOperInd,
Thomas Lee S985938d2020-05-04 11:40:41 +0530781 "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700782 case *oop.Indication_OnuDiscInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000783 span, ctx := log.CreateChildSpan(ctx, "onu-discovery-indication", log.Fields{"device-id": dh.device.Id})
784 defer span.Finish()
785
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700786 onuDiscInd := indication.GetOnuDiscInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000787 logger.Infow(ctx, "received-onu-discovery-indication", log.Fields{"OnuDiscInd": onuDiscInd, "device-id": dh.device.Id})
Akash Kankanala041a2122024-10-16 15:49:22 +0530788 // put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800789 dh.putOnuIndicationToChannel(ctx, indication, onuDiscInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700790 case *oop.Indication_OnuInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000791 span, ctx := log.CreateChildSpan(ctx, "onu-indication", log.Fields{"device-id": dh.device.Id})
792 defer span.Finish()
793
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700794 onuInd := indication.GetOnuInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000795 logger.Infow(ctx, "received-onu-indication", log.Fields{"OnuInd": onuInd, "device-id": dh.device.Id})
Akash Kankanala041a2122024-10-16 15:49:22 +0530796 // put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800797 dh.putOnuIndicationToChannel(ctx, indication, onuInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700798 case *oop.Indication_OmciInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000799 span, ctx := log.CreateChildSpan(ctx, "omci-indication", log.Fields{"device-id": dh.device.Id})
800 defer span.Finish()
801
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700802 omciInd := indication.GetOmciInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000803 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 -0800804 go func() {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000805 if err := dh.omciIndication(ctx, omciInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400806 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "omci", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800807 }
808 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700809 case *oop.Indication_PktInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000810 span, ctx := log.CreateChildSpan(ctx, "packet-indication", log.Fields{"device-id": dh.device.Id})
811 defer span.Finish()
812
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700813 pktInd := indication.GetPktInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000814 logger.Debugw(ctx, "received-packet-indication", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700815 "intf-type": pktInd.IntfId,
816 "intf-id": pktInd.IntfId,
817 "gem-port-id": pktInd.GemportId,
818 "port-no": pktInd.PortNo,
819 "device-id": dh.device.Id,
820 })
821
822 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000823 logger.Debugw(ctx, "received-packet-indication-packet", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700824 "intf-type": pktInd.IntfId,
825 "intf-id": pktInd.IntfId,
826 "gem-port-id": pktInd.GemportId,
827 "port-no": pktInd.PortNo,
828 "packet": hex.EncodeToString(pktInd.Pkt),
829 "device-id": dh.device.Id,
830 })
831 }
832
David K. Bainbridge794735f2020-02-11 21:01:37 -0800833 go func() {
834 if err := dh.handlePacketIndication(ctx, pktInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400835 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "packet", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800836 }
837 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700838 case *oop.Indication_PortStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000839 span, ctx := log.CreateChildSpan(ctx, "port-statistics-indication", log.Fields{"device-id": dh.device.Id})
840 defer span.Finish()
841
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700842 portStats := indication.GetPortStats()
Girish Gowdra9602eb42020-09-09 15:50:39 -0700843 go dh.portStats.PortStatisticsIndication(ctx, portStats, dh.totalPonPorts)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700844 case *oop.Indication_FlowStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000845 span, ctx := log.CreateChildSpan(ctx, "flow-stats-indication", log.Fields{"device-id": dh.device.Id})
846 defer span.Finish()
847
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700848 flowStats := indication.GetFlowStats()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000849 logger.Infow(ctx, "received-flow-stats", log.Fields{"FlowStats": flowStats, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700850 case *oop.Indication_AlarmInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000851 span, ctx := log.CreateChildSpan(ctx, "alarm-indication", log.Fields{"device-id": dh.device.Id})
852 defer span.Finish()
853
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700854 alarmInd := indication.GetAlarmInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000855 logger.Infow(ctx, "received-alarm-indication", log.Fields{"AlarmInd": alarmInd, "device-id": dh.device.Id})
856 go dh.eventMgr.ProcessEvents(ctx, alarmInd, dh.device.Id, raisedTs)
balaji.nagarajan68f56e82025-07-04 15:16:01 +0530857 case *oop.Indication_OnuDisabledInd:
858 span, ctx := log.CreateChildSpan(ctx, "onu-disable-indication", log.Fields{"device-id": dh.device.Id})
859 defer span.Finish()
860 logger.Infow(ctx, "received onu-disable-indication", log.Fields{"device-id": dh.device.Id, "onu-ind": indication.GetOnuInd()})
861 if err := dh.handleOnuDisableIndication(ctx, indication.GetOnuDisabledInd()); err != nil {
862 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "olt", "device-id": dh.device.Id, "onu-ind": indication.GetOnuInd()}, err).Log()
863 }
864 case *oop.Indication_OnuEnabledInd:
865 span, ctx := log.CreateChildSpan(ctx, "onu-enable-indication", log.Fields{"device-id": dh.device.Id})
866 defer span.Finish()
867 logger.Infow(ctx, "received onu-enable-indication", log.Fields{"device-id": dh.device.Id, "onu-ind": indication.GetOnuInd()})
868 if err := dh.handleOnuEnableIndication(ctx, indication.GetOnuEnabledInd()); err != nil {
869 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "olt", "device-id": dh.device.Id, "onu-ind": indication.GetOnuInd()}, err).Log()
870 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700871 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530872}
873
nikesh.krishnanc8473432023-06-14 12:14:54 +0530874func generateOnuIndication(intfID, onuID uint32, operState, adminState string) *oop.Indication {
875 onuInd := &oop.OnuIndication{
876 IntfId: intfID,
877 OnuId: onuID,
878 OperState: operState,
879 AdminState: adminState,
880 }
881 indication := &oop.Indication{
882 Data: &oop.Indication_OnuInd{
883 OnuInd: onuInd,
884 },
885 }
886 return indication
887}
888
889func generateOnuAlarmIndication(intfID uint32, onuID uint32, losStatus string) *oop.AlarmIndication {
890 onuAlarmInd := &oop.OnuAlarmIndication{
891 IntfId: intfID,
892 OnuId: onuID,
893 LosStatus: losStatus,
894 }
895 alarmInd := &oop.AlarmIndication{
896 Data: &oop.AlarmIndication_OnuAlarmInd{
897 OnuAlarmInd: onuAlarmInd,
898 },
899 }
900 return alarmInd
901}
nikesh.krishnanc8473432023-06-14 12:14:54 +0530902
Akash Kankanala041a2122024-10-16 15:49:22 +0530903func generatePonLosAlarmIndication(intfID uint32, losStatus string) *oop.AlarmIndication {
nikesh.krishnanc8473432023-06-14 12:14:54 +0530904 ponlosAlarmInd := &oop.LosIndication{
905 IntfId: intfID,
906 Status: losStatus,
907 }
908 alarmInd := &oop.AlarmIndication{
909 Data: &oop.AlarmIndication_LosInd{
910 LosInd: ponlosAlarmInd,
911 },
912 }
913 return alarmInd
914}
Akash Kankanala041a2122024-10-16 15:49:22 +0530915
nikesh.krishnanc8473432023-06-14 12:14:54 +0530916func (dh *DeviceHandler) updateIntfOperStateAndRaiseIndication(ctx context.Context, operState string, intfID uint32) {
917 go func() {
918 if err := dh.addPort(ctx, intfID, voltha.Port_PON_OLT, operState, defaultPortSpeedMbps); err != nil {
919 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface-oper-pon", "device-id": dh.device.Id}, err).Log()
920 }
921 }()
922
923 raisedTs := time.Now().Unix()
924 go dh.eventMgr.oltIntfOperIndication(ctx, &oop.IntfOperIndication{Type: "pon", IntfId: intfID, OperState: operState}, dh.device.Id, raisedTs)
925}
926
927func (dh *DeviceHandler) reconcileOnus(ctx context.Context) error {
nikesh.krishnanc8473432023-06-14 12:14:54 +0530928 onuDevicesFromCore, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
929 if err != nil {
nikesh.krishnanc8473432023-06-14 12:14:54 +0530930 logger.Error(ctx, "unable to fetch child device", log.Fields{"eeror": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +0530931 return err
932 }
933 for _, onuDeviceFromCore := range onuDevicesFromCore.Items {
nikesh.krishnanc8473432023-06-14 12:14:54 +0530934 onuOperStatusFromCore := onuDeviceFromCore.OperStatus
935 onuConnectStatusFromCore := onuDeviceFromCore.ConnectStatus
936 intfID := plt.PortNoToIntfID(onuDeviceFromCore.ParentPortNo, voltha.Port_PON_OLT)
937
938 onuID := onuDeviceFromCore.ProxyAddress.OnuId
939 onuDeviceFromOlt, err := dh.getOnuInfo(ctx, intfID, &onuID)
940 if err != nil {
941 logger.Error(ctx, "unable to get onu object from olt agent", log.Fields{"eeror": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +0530942 } else {
943 onuOperStatusFromOlt := onuDeviceFromOlt.GetState()
944 onuLosFromOlt := onuDeviceFromOlt.GetLosi()
945 switch {
946 case onuOperStatusFromOlt.String() == "ACTIVE" && onuOperStatusFromCore.String() != "ACTIVE":
947 OnuIndication := generateOnuIndication(intfID, onuID, "up", "up")
948 dh.putOnuIndicationToChannel(ctx, OnuIndication, intfID)
949
950 case onuLosFromOlt.String() == "ON" && onuConnectStatusFromCore.String() == "REACHABLE":
Akash Kankanala041a2122024-10-16 15:49:22 +0530951 OnuIndication := generateOnuIndication(intfID, onuID, "down", "down") // check bal cli login notepad
nikesh.krishnanc8473432023-06-14 12:14:54 +0530952 alarmInd := generateOnuAlarmIndication(intfID, onuID, "on")
953 raisedTs := time.Now().Unix()
954 go dh.eventMgr.ProcessEvents(ctx, alarmInd, dh.device.Id, raisedTs)
955
956 dh.putOnuIndicationToChannel(ctx, OnuIndication, intfID)
balaji.nagarajan7ca68b52026-02-01 11:28:43 +0530957 case onuLosFromOlt.String() == "OFF" && onuConnectStatusFromCore.String() == "REACHABLE":
958 //Nothing to Indicate , just add the onu to the device handler onu cache
959 deviceType := onuDeviceFromCore.Type
960 deviceID := onuDeviceFromCore.Id
961 proxyDeviceID := onuDeviceFromCore.ProxyAddress.DeviceId
962 onuKey := dh.formOnuKey(intfID, onuID)
963 dh.onus.Store(onuKey, NewOnuDevice(deviceID, deviceType, onuDeviceFromCore.SerialNumber, onuID, intfID, proxyDeviceID, false, onuDeviceFromCore.AdapterEndpoint))
nikesh.krishnanc8473432023-06-14 12:14:54 +0530964 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530965 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530966 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530967 return nil
968}
969
970func (dh *DeviceHandler) reconcilePonPorts(ctx context.Context) error { // need onuid and pon id
971 portsFromCore, err := dh.getAllPortsFromCore(ctx, &ca.PortFilter{
972 DeviceId: dh.device.Id,
973 PortType: voltha.Port_PON_OLT,
974 })
975 if err != nil {
976 logger.Error(ctx, "unable to fetch ports from core", log.Fields{"eeror": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +0530977 return err
nikesh.krishnanc8473432023-06-14 12:14:54 +0530978 }
979 for _, portFromCore := range portsFromCore.Items {
980 portNum := portFromCore.GetPortNo()
981 intfID := plt.PortNoToIntfID(portNum, voltha.Port_PON_OLT)
982 portOperStatusFromCore := portFromCore.OperStatus
983 portAdminStateFromCore := portFromCore.AdminState
984 ponPortFromOlt, err := dh.getIntfInfo(ctx, intfID)
985 if err != nil {
986 logger.Error(ctx, "unable to get pon objects from olt agent", log.Fields{"eeror": err})
987 } else {
988 portLosFromOlt := ponPortFromOlt.GetLos()
989 portStateFromOlt := ponPortFromOlt.GetState()
990 if portOperStatusFromCore.String() == "ACTIVE" && portLosFromOlt.String() == "ON" {
991 logger.Debug(ctx, "port is active in core but los is fired from olt", log.Fields{
992 "portStateFromOlt": portStateFromOlt.String(),
993 "portOperStatusFromCore": portOperStatusFromCore.String(),
994 "device-id": dh.device.Id,
995 "port": portNum})
996 ponLosindication := generatePonLosAlarmIndication(intfID, "on")
997 raisedTs := time.Now().Unix()
998 go dh.eventMgr.ProcessEvents(ctx, ponLosindication, dh.device.Id, raisedTs)
nikesh.krishnanc8473432023-06-14 12:14:54 +0530999 }
1000 switch {
1001 case portStateFromOlt.String() == "ACTIVE_WORKING" && portOperStatusFromCore.String() != "ACTIVE":
1002 logger.Debug(ctx, "mismatch between port state in voltha core and raising port up event", log.Fields{
1003 "portStateFromOlt": portStateFromOlt.String(),
1004 "portOperStatusFromCore": portOperStatusFromCore.String(),
1005 "device-id": dh.device.Id,
1006 "port": portNum})
1007 dh.updateIntfOperStateAndRaiseIndication(ctx, "up", intfID)
1008 case (portStateFromOlt.String() == "INACTIVE" || portStateFromOlt.String() == "UNKNOWN") && portOperStatusFromCore.String() == "ACTIVE":
1009 logger.Debug(ctx, "mismatch between port state in voltha core and raising port down event", log.Fields{
1010 "portStateFromOlt": portStateFromOlt.String(),
1011 "portOperStatusFromCore": portOperStatusFromCore.String(),
1012 "device-id": dh.device.Id,
1013 "port": portNum})
1014 dh.updateIntfOperStateAndRaiseIndication(ctx, "down", intfID)
1015 case portStateFromOlt.String() == "DISABLED" && portAdminStateFromCore.String() == "ENABLED":
1016 logger.Error(ctx, "port enabled in device but disabled at votlha core", log.Fields{
1017 "device-id": dh.device.Id,
1018 "port": portNum})
1019 default:
1020 logger.Error(ctx, "mismatch between port state in voltha core and voltha device", log.Fields{
1021 "portStateFromOlt": portStateFromOlt.String(),
1022 "portOperStatusFromCore": portOperStatusFromCore.String(),
1023 "device-id": dh.device.Id,
1024 "port": portNum})
nikesh.krishnanc8473432023-06-14 12:14:54 +05301025 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301026 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301027 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301028 return nil
1029}
1030
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301031// doStateUp handle the olt up indication and update to voltha core
npujarec5762e2020-01-01 14:08:48 +05301032func (dh *DeviceHandler) doStateUp(ctx context.Context) error {
Thomas Lee S85f37312020-04-03 17:06:12 +05301033 //starting the stat collector
Nandita Biradar1b590f12024-09-27 10:56:28 +05301034 // Declare deviceStateFilter to be used later
1035 var deviceStateFilter *ca.DeviceStateFilter
bseenivaaa9165b2025-09-18 17:28:12 +05301036 dh.collectorWaitGroup.Add(1)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001037 go startCollector(ctx, dh)
nikesh.krishnanc8473432023-06-14 12:14:54 +05301038 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301039 if err != nil {
1040 return fmt.Errorf("failed to get device from core: %w", err)
1041 }
1042 logger.Info(ctx, "Device state", log.Fields{
1043 "device-id": device.Id,
1044 "CurrOperStatus": device.OperStatus,
1045 "CurrConnStatus": device.ConnectStatus,
1046 })
1047 // Perform cleanup if the device's operational status is REBOOTED
1048 if device.OperStatus == voltha.OperStatus_RECONCILING && dh.prevOperStatus == voltha.OperStatus_REBOOTED {
1049 // Log the device's operational status if it's REBOOTED
1050 logger.Info(ctx, "Device is transitioning from REBOOTED to RECONCILING", log.Fields{
1051 "device-id": device.Id,
1052 "OperStatus": device.OperStatus,
1053 })
1054 dh.lockDevice.RLock()
1055 // Stop the read indication only if it the routine is active
1056 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
1057 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
1058 // on next execution of the readIndication routine.
1059 if dh.isHeartbeatCheckActive {
1060 dh.stopHeartbeatCheck <- true
1061 }
1062 if dh.isReadIndicationRoutineActive {
1063 dh.stopIndications <- true
1064 }
bseenivaaa9165b2025-09-18 17:28:12 +05301065 if dh.isCollectorActive {
1066 dh.stopCollector <- true
1067 }
Nandita Biradar1b590f12024-09-27 10:56:28 +05301068 dh.lockDevice.RUnlock()
Akash Kankanala041a2122024-10-16 15:49:22 +05301069 if err = dh.cleanupDeviceResources(ctx); err != nil {
Nandita Biradar1b590f12024-09-27 10:56:28 +05301070 logger.Error(ctx, "unable to clean up device resources", log.Fields{"error": err})
1071 return fmt.Errorf("cleanup device resources failed: %w", err)
1072 }
Akash Kankanala041a2122024-10-16 15:49:22 +05301073 if err = dh.initializeDeviceHandlerModules(ctx); err != nil {
Nandita Biradar1b590f12024-09-27 10:56:28 +05301074 return olterrors.NewErrAdapter("device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
1075 }
bseenivaaa9165b2025-09-18 17:28:12 +05301076 dh.collectorWaitGroup.Add(1)
1077 go startCollector(ctx, dh)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301078 go startHeartbeatCheck(ctx, dh)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301079 //dh.lockDevice.RUnlock()
Nandita Biradar1b590f12024-09-27 10:56:28 +05301080 } else if device.OperStatus == voltha.OperStatus_RECONCILING {
1081 // Log the device's operational status if it's RECONCILING
1082 logger.Info(ctx, "Device is being reconciled", log.Fields{
1083 "device-id": device.Id,
1084 "OperStatus": device.OperStatus,
1085 })
1086
1087 // Perform reconciliation steps
1088 err = dh.reconcileOnus(ctx)
1089 if err != nil {
1090 logger.Error(ctx, "unable to reconcile onu", log.Fields{"error": err})
1091 }
1092 err = dh.reconcilePonPorts(ctx)
1093 if err != nil {
1094 logger.Error(ctx, "unable to reconcile pon ports", log.Fields{"error": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +05301095 }
1096 }
Girish Gowdra618fa572021-09-01 17:19:29 -07001097 // instantiate the mcast handler routines.
1098 for i := range dh.incomingMcastFlowOrGroup {
1099 // We land inside the below "if" code path, after the OLT comes back from a reboot, otherwise the routines
1100 // are already active when the DeviceHandler module is first instantiated (as part of Adopt_device RPC invocation).
1101 if !dh.mcastHandlerRoutineActive[i] {
1102 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
1103 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
1104 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
1105 // for incoming mcast flow/group to be processed serially.
1106 dh.mcastHandlerRoutineActive[i] = true
1107 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
1108 }
1109 }
Nandita Biradar1b590f12024-09-27 10:56:28 +05301110 // Create DeviceStateFilter with the desired operational and connection statuses
1111 deviceStateFilter = &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001112 DeviceId: dh.device.Id,
1113 OperStatus: voltha.OperStatus_ACTIVE,
1114 ConnStatus: voltha.ConnectStatus_REACHABLE,
Nandita Biradar1b590f12024-09-27 10:56:28 +05301115 }
1116 // Log DeviceStateFilter for debugging purposes
1117 logger.Info(ctx, "DeviceStateFilter", log.Fields{
1118 "DeviceId": deviceStateFilter.DeviceId,
1119 "OperStatus": deviceStateFilter.OperStatus,
1120 "ConnStatus": deviceStateFilter.ConnStatus,
1121 })
1122 // Synchronous call to update device state - this method is run in its own go routine
balaji6299cb23cbe2025-04-14 17:53:10 +05301123 if err = dh.updateDeviceStateInCore(ctx, deviceStateFilter); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001124 return olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001125 }
Gamze Abaka07868a52020-12-17 14:19:28 +00001126
Akash Kankanala041a2122024-10-16 15:49:22 +05301127 // Clear olt communication failure event
Gamze Abaka07868a52020-12-17 14:19:28 +00001128 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
1129 dh.device.OperStatus = voltha.OperStatus_ACTIVE
balaji6299cb23cbe2025-04-14 17:53:10 +05301130
1131 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
1132 if err != nil {
1133 return olterrors.NewErrAdapter("fetch-ports-failed", log.Fields{"device-id": dh.device.Id}, err)
1134 }
1135 dh.populateActivePorts(ctx, ports.Items)
1136 if err = dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
1137 logger.Error(ctx, "port-status-update-failed", log.Fields{"error": err, "ports": ports})
1138 }
1139
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001140 raisedTs := time.Now().Unix()
Gamze Abaka07868a52020-12-17 14:19:28 +00001141 go dh.eventMgr.oltCommunicationEvent(ctx, dh.device, raisedTs)
1142
Girish Gowdru0c588b22019-04-23 23:24:56 -04001143 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301144}
1145
1146// doStateDown handle the olt down indication
npujarec5762e2020-01-01 14:08:48 +05301147func (dh *DeviceHandler) doStateDown(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001148 logger.Debugw(ctx, "do-state-down-start", log.Fields{"device-id": dh.device.Id})
Girish Gowdrud4245152019-05-10 00:47:31 -04001149
khenaidoo106c61a2021-08-11 18:05:46 -04001150 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Girish Gowdrud4245152019-05-10 00:47:31 -04001151 if err != nil || device == nil {
1152 /*TODO: needs to handle error scenarios */
Girish Kumarf26e4882020-03-05 06:49:10 +00001153 return olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001154 }
1155
1156 cloned := proto.Clone(device).(*voltha.Device)
Girish Gowdrud4245152019-05-10 00:47:31 -04001157
Akash Kankanala041a2122024-10-16 15:49:22 +05301158 // Update the device oper state and connection status
Girish Gowdrud4245152019-05-10 00:47:31 -04001159 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001160 dh.lockDevice.Lock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001161 dh.device = cloned
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001162 dh.lockDevice.Unlock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001163
khenaidoodc2116e2021-10-19 17:33:19 -04001164 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001165 DeviceId: cloned.Id,
1166 OperStatus: cloned.OperStatus,
1167 ConnStatus: cloned.ConnectStatus,
1168 }); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001169 return olterrors.NewErrAdapter("state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001170 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001171
Akash Kankanala041a2122024-10-16 15:49:22 +05301172 // get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04001173 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001174 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001175 return olterrors.NewErrAdapter("child-device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001176 }
1177 for _, onuDevice := range onuDevices.Items {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001178 // Update onu state as down in onu adapter
1179 onuInd := oop.OnuIndication{}
1180 onuInd.OperState = "down"
khenaidoo106c61a2021-08-11 18:05:46 -04001181
1182 ogClient, err := dh.getChildAdapterServiceClient(onuDevice.AdapterEndpoint)
1183 if err != nil {
1184 return err
1185 }
1186 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
khenaidoodc2116e2021-10-19 17:33:19 -04001187 _, err = ogClient.OnuIndication(subCtx, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001188 DeviceId: onuDevice.Id,
1189 OnuIndication: &onuInd,
1190 })
1191 cancel()
David K. Bainbridge794735f2020-02-11 21:01:37 -08001192 if err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001193 _ = olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001194 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001195 "onu-indicator": onuInd,
1196 "device-type": onuDevice.Type,
1197 "device-id": onuDevice.Id}, err).LogAt(log.ErrorLevel)
Akash Kankanala041a2122024-10-16 15:49:22 +05301198 // Do not return here and continue to process other ONUs
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001199 } else {
1200 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 -07001201 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001202 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001203 dh.lockDevice.Lock()
serkant.uluderya245caba2019-09-24 23:15:29 -07001204 /* Discovered ONUs entries need to be cleared , since after OLT
1205 is up, it starts sending discovery indications again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301206 dh.discOnus = sync.Map{}
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001207 dh.lockDevice.Unlock()
1208
Neha Sharma96b7bf22020-06-15 10:37:32 +00001209 logger.Debugw(ctx, "do-state-down-end", log.Fields{"device-id": device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001210 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301211}
1212
1213// doStateInit dial the grpc before going to init state
npujarec5762e2020-01-01 14:08:48 +05301214func (dh *DeviceHandler) doStateInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001215 var err error
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001216 dh.lockDevice.RLock()
1217 hostAndPort := dh.device.GetHostAndPort() //store the IP of OLT , so that when we are blocked on grpc dail with old IP,and IP is updated it wont be updated here.
1218 dh.lockDevice.RUnlock()
Gamze Abaka49c40b32021-05-06 09:30:41 +00001219 // if the connection is already available, close the previous connection (olt reboot case)
1220 if dh.clientCon != nil {
1221 if err = dh.clientCon.Close(); err != nil {
1222 logger.Errorw(ctx, "failed-to-close-previous-connection", log.Fields{"device-id": dh.device.Id})
1223 } else {
1224 logger.Debugw(ctx, "previous-grpc-channel-closed-successfully", log.Fields{"device-id": dh.device.Id})
1225 }
1226 }
1227
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001228 logger.Debugw(ctx, "Dialing grpc", log.Fields{"device-id": dh.device.Id, "host-and-port": hostAndPort})
Abhay Kumard3f18512025-12-09 07:51:12 +00001229 grpc_prometheus.EnableClientHandlingTimeHistogram()
Gamze Abaka49c40b32021-05-06 09:30:41 +00001230 // Use Interceptors to automatically inject and publish Open Tracing Spans by this GRPC client
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001231 dh.clientCon, err = grpc.DialContext(ctx, hostAndPort,
Girish Kumar93e91742020-07-27 16:43:19 +00001232 grpc.WithInsecure(),
1233 grpc.WithBlock(),
1234 grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001235 grpc_opentracing.StreamClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Abhay Kumard3f18512025-12-09 07:51:12 +00001236 grpc_prometheus.StreamClientInterceptor,
Girish Kumar93e91742020-07-27 16:43:19 +00001237 )),
1238 grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001239 grpc_opentracing.UnaryClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Abhay Kumard3f18512025-12-09 07:51:12 +00001240 grpc_prometheus.UnaryClientInterceptor,
Girish Kumar93e91742020-07-27 16:43:19 +00001241 )))
1242
1243 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301244 return olterrors.NewErrCommunication("dial-failure", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05301245 "device-id": dh.device.Id,
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001246 "host-and-port": hostAndPort}, err)
Akash Sonif49299a2024-04-25 12:06:37 +05301247 }
1248
1249 if dh.device.OperStatus == voltha.OperStatus_RECONCILING {
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001250 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
Akash Sonif49299a2024-04-25 12:06:37 +05301251 DeviceId: dh.device.Id,
1252 OperStatus: voltha.OperStatus_RECONCILING,
1253 ConnStatus: voltha.ConnectStatus_REACHABLE,
1254 }); err != nil {
1255 return olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
1256 }
1257 // The OperState and connection state of the device is set to RECONCILING and REACHABLE in the previous section. This also needs to be set on the
1258 // locally cached copy of the device struct.
1259 dh.device.OperStatus = voltha.OperStatus_RECONCILING
1260 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
1261 }
1262
Girish Gowdru0c588b22019-04-23 23:24:56 -04001263 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301264}
1265
1266// postInit create olt client instance to invoke RPC on the olt device
npujarec5762e2020-01-01 14:08:48 +05301267func (dh *DeviceHandler) postInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001268 dh.Client = oop.NewOpenoltClient(dh.clientCon)
bseenivaa20d6c32026-01-11 21:51:19 +05301269 // decoupling it to avoid blocking state machine transition
1270 go dh.transitionMap.Handle(ctx, GrpcConnected)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001271 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301272}
1273
1274// doStateConnected get the device info and update to voltha core
npujarec5762e2020-01-01 14:08:48 +05301275func (dh *DeviceHandler) doStateConnected(ctx context.Context) error {
Thomas Lee S985938d2020-05-04 11:40:41 +05301276 var err error
Neha Sharma96b7bf22020-06-15 10:37:32 +00001277 logger.Debugw(ctx, "olt-device-connected", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001278
1279 // Case where OLT is disabled and then rebooted.
khenaidoo106c61a2021-08-11 18:05:46 -04001280 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Thomas Lee S985938d2020-05-04 11:40:41 +05301281 if err != nil || device == nil {
1282 /*TODO: needs to handle error scenarios */
1283 return olterrors.NewErrAdapter("device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
1284 }
1285 if device.AdminState == voltha.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001286 logger.Debugln(ctx, "do-state-connected--device-admin-state-down")
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001287
1288 cloned := proto.Clone(device).(*voltha.Device)
1289 cloned.ConnectStatus = voltha.ConnectStatus_REACHABLE
1290 cloned.OperStatus = voltha.OperStatus_UNKNOWN
1291 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04001292
khenaidoodc2116e2021-10-19 17:33:19 -04001293 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001294 DeviceId: cloned.Id,
1295 OperStatus: cloned.OperStatus,
1296 ConnStatus: cloned.ConnectStatus,
1297 }); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301298 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 -04001299 }
1300
bseenivaa1622112025-12-11 18:24:02 +05301301 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
Chaitrashree G S44124192019-08-07 20:21:36 -04001302 // Since the device was disabled before the OLT was rebooted, enforce the OLT to be Disabled after re-connection.
bseenivaa1622112025-12-11 18:24:02 +05301303 _, err = dh.Client.DisableOlt(subCtx, new(oop.Empty))
1304 cancel()
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001305 if err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301306 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001307 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001308 // We should still go ahead an initialize various device handler modules so that when OLT is re-enabled, we have
1309 // all the modules initialized and ready to handle incoming ONUs.
1310
Thomas Lee S985938d2020-05-04 11:40:41 +05301311 err = dh.initializeDeviceHandlerModules(ctx)
1312 if err != nil {
1313 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 -04001314 }
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001315
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001316 go startHeartbeatCheck(ctx, dh)
1317
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001318 return nil
1319 }
1320
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001321 if err := dh.initializeDeviceHandlerModules(ctx); err != nil {
bseenivaa20d6c32026-01-11 21:51:19 +05301322 logger.Error(ctx, "device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id, "error": err})
1323 cloned := proto.Clone(device).(*voltha.Device)
1324 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
1325 cloned.OperStatus = voltha.OperStatus_UNKNOWN
1326 dh.device = cloned
1327
1328 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
1329 DeviceId: cloned.Id,
1330 OperStatus: cloned.OperStatus,
1331 ConnStatus: cloned.ConnectStatus,
1332 }); err != nil {
1333 logger.Error(ctx, "device-state-update-failed", log.Fields{"device-id": dh.device.Id, "error": err})
1334 }
1335 // decoupling it to avoid blocking state machine transition
1336 go dh.transitionMap.Handle(ctx, GrpcDisconnected)
1337 return nil
Girish Gowdru0c588b22019-04-23 23:24:56 -04001338 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301339
Neha Sharma96b7bf22020-06-15 10:37:32 +00001340 go dh.updateLocalDevice(ctx)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001341
1342 if device.PmConfigs != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001343 dh.UpdatePmConfig(ctx, device.PmConfigs)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001344 }
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001345
1346 go startHeartbeatCheck(ctx, dh)
1347
cuilin20187b2a8c32019-03-26 19:52:28 -07001348 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301349}
1350
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001351func (dh *DeviceHandler) initializeDeviceHandlerModules(ctx context.Context) error {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001352 var err error
1353 dh.deviceInfo, err = dh.populateDeviceInfo(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001354
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00001355 if dh.flowMgr != nil {
1356 dh.StopAllFlowRoutines(ctx)
1357 }
1358
1359 dh.CloseKVClient(ctx)
1360
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001361 if err != nil {
1362 return olterrors.NewErrAdapter("populate-device-info-failed", log.Fields{"device-id": dh.device.Id}, err)
1363 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001364 dh.totalPonPorts = dh.deviceInfo.GetPonPorts()
1365 dh.agentPreviouslyConnected = dh.deviceInfo.PreviouslyConnected
bseenivaaa9165b2025-09-18 17:28:12 +05301366 // If collector go routine is active, wait for it to stop
1367 dh.lockDevice.RLock()
1368 if dh.isCollectorActive {
1369 dh.lockDevice.RUnlock()
1370 dh.collectorWaitGroup.Wait()
1371 } else {
1372 dh.lockDevice.RUnlock()
1373 }
yasin saplid0566272021-12-21 09:10:30 +00001374 // +1 is for NNI
1375 dh.resourceMgr = make([]*rsrcMgr.OpenOltResourceMgr, dh.totalPonPorts+1)
1376 dh.flowMgr = make([]*OpenOltFlowMgr, dh.totalPonPorts+1)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001377 var i uint32
yasin saplid0566272021-12-21 09:10:30 +00001378 // Index from 0 to until totalPonPorts ( Ex: 0 .. 15 ) -> PonPort Managers
1379 // Index totalPonPorts ( Ex: 16 ) -> NniPort Manager
1380 // There is only one NNI manager since multiple NNI is not supported for now
1381 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001382 // Instantiate resource manager
1383 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 -07001384 return olterrors.ErrResourceManagerInstantiating
1385 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001386 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001387 // GroupManager instance is per OLT. But it needs a reference to any instance of resourceMgr to interface with
1388 // the KV store to manage mcast group data. Provide the first instance (0th index)
1389 if dh.groupMgr = NewGroupManager(ctx, dh, dh.resourceMgr[0]); dh.groupMgr == nil {
1390 return olterrors.ErrGroupManagerInstantiating
1391 }
yasin saplid0566272021-12-21 09:10:30 +00001392 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001393 // Instantiate flow manager
1394 if dh.flowMgr[i] = NewFlowManager(ctx, dh, dh.resourceMgr[i], dh.groupMgr, i); dh.flowMgr[i] == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05301395 // Continue to check the rest of the ports
Mahir Gunyela2e68702022-12-07 00:00:42 -08001396 logger.Errorw(ctx, "error-initializing-flow-manager-for-intf", log.Fields{"intfID": i, "device-id": dh.device.Id})
1397 } else {
1398 dh.resourceMgr[i].TechprofileRef = dh.flowMgr[i].techprofile
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001399 }
1400 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001401 /* TODO: Instantiate Alarm , stats , BW managers */
1402 /* Instantiating Event Manager to handle Alarms and KPIs */
1403 dh.eventMgr = NewEventMgr(dh.EventProxy, dh)
1404
1405 // Stats config for new device
Neha Sharma96b7bf22020-06-15 10:37:32 +00001406 dh.portStats = NewOpenOltStatsMgr(ctx, dh)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001407
1408 return nil
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001409}
1410
Neha Sharma96b7bf22020-06-15 10:37:32 +00001411func (dh *DeviceHandler) populateDeviceInfo(ctx context.Context) (*oop.DeviceInfo, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001412 var err error
1413 var deviceInfo *oop.DeviceInfo
Akash Kankanala041a2122024-10-16 15:49:22 +05301414 var genmac string
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001415
bseenivaa1622112025-12-11 18:24:02 +05301416 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1417 deviceInfo, err = dh.Client.GetDeviceInfo(subCtx, new(oop.Empty))
1418 cancel()
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001419
1420 if err != nil {
bseenivaa20d6c32026-01-11 21:51:19 +05301421 return nil, olterrors.NewErrCommunication("get-device-info-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001422 }
1423 if deviceInfo == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001424 return nil, olterrors.NewErrInvalidValue(log.Fields{"device": nil}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001425 }
1426
Neha Sharma96b7bf22020-06-15 10:37:32 +00001427 logger.Debugw(ctx, "fetched-device-info", log.Fields{"deviceInfo": deviceInfo, "device-id": dh.device.Id})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001428 dh.device.Root = true
1429 dh.device.Vendor = deviceInfo.Vendor
1430 dh.device.Model = deviceInfo.Model
1431 dh.device.SerialNumber = deviceInfo.DeviceSerialNumber
1432 dh.device.HardwareVersion = deviceInfo.HardwareVersion
1433 dh.device.FirmwareVersion = deviceInfo.FirmwareVersion
1434
1435 if deviceInfo.DeviceId == "" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001436 logger.Warnw(ctx, "no-device-id-provided-using-host", log.Fields{"hostport": dh.device.GetHostAndPort()})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001437 host := strings.Split(dh.device.GetHostAndPort(), ":")[0]
Akash Kankanala041a2122024-10-16 15:49:22 +05301438 genmac, err = generateMacFromHost(ctx, host)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001439 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001440 return nil, olterrors.NewErrAdapter("failed-to-generate-mac-host", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001441 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001442 logger.Debugw(ctx, "using-host-for-mac-address", log.Fields{"host": host, "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001443 dh.device.MacAddress = genmac
1444 } else {
1445 dh.device.MacAddress = deviceInfo.DeviceId
1446 }
1447
1448 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -04001449 if err = dh.updateDeviceInCore(ctx, dh.device); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001450 return nil, olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001451 }
1452
1453 return deviceInfo, nil
1454}
1455
Neha Sharma96b7bf22020-06-15 10:37:32 +00001456func startCollector(ctx context.Context, dh *DeviceHandler) {
bseenivaaa9165b2025-09-18 17:28:12 +05301457 logger.Infow(ctx, "starting-collector", log.Fields{"device-id": dh.device.Id})
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001458
1459 defer func() {
1460 dh.lockDevice.Lock()
1461 dh.isCollectorActive = false
1462 dh.lockDevice.Unlock()
bseenivaaa9165b2025-09-18 17:28:12 +05301463 dh.collectorWaitGroup.Done()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001464 }()
1465
1466 dh.lockDevice.Lock()
1467 dh.isCollectorActive = true
1468 dh.lockDevice.Unlock()
1469
Naga Manjunath7615e552019-10-11 22:35:47 +05301470 for {
1471 select {
1472 case <-dh.stopCollector:
bseenivaaa9165b2025-09-18 17:28:12 +05301473 logger.Infow(ctx, "stopping-collector-for-olt", log.Fields{"device-id": dh.device.Id})
Naga Manjunath7615e552019-10-11 22:35:47 +05301474 return
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001475 case <-time.After(time.Duration(dh.metrics.ToPmConfigs().DefaultFreq) * time.Second):
Girish Gowdra34815db2020-05-11 17:18:04 -07001476
khenaidoo106c61a2021-08-11 18:05:46 -04001477 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001478 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001479 logger.Warnw(ctx, "failed-to-list-ports", log.Fields{"device-id": dh.device.Id, "err": err})
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001480 continue
1481 }
khenaidoo106c61a2021-08-11 18:05:46 -04001482 for _, port := range ports.Items {
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301483 // NNI Stats
1484 if port.Type == voltha.Port_ETHERNET_NNI {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001485 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301486 cmnni := dh.portStats.collectNNIMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001487 logger.Debugw(ctx, "collect-nni-metrics", log.Fields{"metrics": cmnni})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001488 go dh.portStats.publishMetrics(ctx, NNIStats, cmnni, port, dh.device.Id, dh.device.Type)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001489 logger.Debugw(ctx, "publish-nni-metrics", log.Fields{"nni-port": port.Label})
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301490 }
1491 // PON Stats
1492 if port.Type == voltha.Port_PON_OLT {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001493 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301494 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
1495 cmpon := dh.portStats.collectPONMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001496 logger.Debugw(ctx, "collect-pon-metrics", log.Fields{"metrics": cmpon})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001497 go dh.portStats.publishMetrics(ctx, PONStats, cmpon, port, dh.device.Id, dh.device.Type)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301498 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001499 logger.Debugw(ctx, "publish-pon-metrics", log.Fields{"pon-port": port.Label})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001500
yasin sapli9e4c5092022-02-01 13:52:33 +00001501 onuGemInfoLst := dh.resourceMgr[intfID].GetOnuGemInfoList(ctx)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001502 if len(onuGemInfoLst) > 0 {
1503 go dh.portStats.collectOnuAndGemStats(ctx, onuGemInfoLst)
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001504 }
Chaitrashree G Sef088112020-02-03 21:39:27 -05001505 }
Naga Manjunath7615e552019-10-11 22:35:47 +05301506 }
1507 }
1508 }
1509}
1510
Mahir Gunyela2e68702022-12-07 00:00:42 -08001511// AdoptDevice adopts the OLT device
npujarec5762e2020-01-01 14:08:48 +05301512func (dh *DeviceHandler) AdoptDevice(ctx context.Context, device *voltha.Device) {
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001513 var dhCtx context.Context
Girish Gowdru0c588b22019-04-23 23:24:56 -04001514 dh.transitionMap = NewTransitionMap(dh)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001515 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id, "Address": device.GetHostAndPort()})
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001516 dhCtx, dh.transitionHandlerCancel = context.WithCancel(context.Background())
1517 dh.transitionMap.Handle(dhCtx, DeviceInit)
Naga Manjunath7615e552019-10-11 22:35:47 +05301518
1519 // Now, set the initial PM configuration for that device
khenaidoo106c61a2021-08-11 18:05:46 -04001520 cgClient, err := dh.coreClient.GetCoreServiceClient()
1521 if err != nil {
1522 logger.Errorw(ctx, "no-core-connection", log.Fields{"device-id": dh.device.Id, "error": err})
1523 return
1524 }
1525
1526 // Now, set the initial PM configuration for that device
1527 if _, err := cgClient.DevicePMConfigUpdate(ctx, dh.metrics.ToPmConfigs()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001528 _ = olterrors.NewErrAdapter("error-updating-performance-metrics", log.Fields{"device-id": device.Id}, err).LogAt(log.ErrorLevel)
Naga Manjunath7615e552019-10-11 22:35:47 +05301529 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301530}
1531
Mahir Gunyela2e68702022-12-07 00:00:42 -08001532// GetOfpDeviceInfo Gets the Ofp information of the given device
khenaidoodc2116e2021-10-19 17:33:19 -04001533func (dh *DeviceHandler) GetOfpDeviceInfo(device *voltha.Device) (*ca.SwitchCapability, error) {
1534 return &ca.SwitchCapability{
cuilin20187b2a8c32019-03-26 19:52:28 -07001535 Desc: &of.OfpDesc{
Devmalya Paul70dd4972019-06-10 15:19:17 +05301536 MfrDesc: "VOLTHA Project",
cuilin20187b2a8c32019-03-26 19:52:28 -07001537 HwDesc: "open_pon",
1538 SwDesc: "open_pon",
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001539 SerialNum: device.SerialNumber,
cuilin20187b2a8c32019-03-26 19:52:28 -07001540 },
1541 SwitchFeatures: &of.OfpSwitchFeatures{
1542 NBuffers: 256,
1543 NTables: 2,
1544 Capabilities: uint32(of.OfpCapabilities_OFPC_FLOW_STATS |
1545 of.OfpCapabilities_OFPC_TABLE_STATS |
1546 of.OfpCapabilities_OFPC_PORT_STATS |
1547 of.OfpCapabilities_OFPC_GROUP_STATS),
1548 },
1549 }, nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301550}
1551
khenaidoo106c61a2021-08-11 18:05:46 -04001552// GetTechProfileDownloadMessage fetches the TechProfileDownloadMessage for the caller.
khenaidoodc2116e2021-10-19 17:33:19 -04001553func (dh *DeviceHandler) GetTechProfileDownloadMessage(ctx context.Context, request *ia.TechProfileInstanceRequestMessage) (*ia.TechProfileDownloadMessage, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001554 ifID, err := plt.IntfIDFromPonPortNum(ctx, request.ParentPonPort)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001555 if err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001556 return nil, err
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001557 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08001558 if dh.flowMgr == nil || dh.flowMgr[ifID] == nil {
1559 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()
1560 }
khenaidoo106c61a2021-08-11 18:05:46 -04001561 return dh.flowMgr[ifID].getTechProfileDownloadMessage(ctx, request.TpInstancePath, request.OnuId, request.DeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001562}
1563
Neha Sharma96b7bf22020-06-15 10:37:32 +00001564func (dh *DeviceHandler) omciIndication(ctx context.Context, omciInd *oop.OmciIndication) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001565 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 -07001566 var deviceType string
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001567 var deviceID string
1568 var proxyDeviceID string
khenaidoo106c61a2021-08-11 18:05:46 -04001569 var childAdapterEndpoint string
cuilin20187b2a8c32019-03-26 19:52:28 -07001570
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001571 transid := extractOmciTransactionID(omciInd.Pkt)
Matteo Scandolo92186242020-06-12 10:54:18 -07001572 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001573 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 -07001574 "omci-transaction-id": transid, "omci-msg": hex.EncodeToString(omciInd.Pkt)})
1575 }
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001576
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001577 onuKey := dh.formOnuKey(omciInd.IntfId, omciInd.OnuId)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301578
1579 if onuInCache, ok := dh.onus.Load(onuKey); !ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001580 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 -07001581 ponPort := plt.IntfIDToPortNo(omciInd.GetIntfId(), voltha.Port_PON_OLT)
cuilin20187b2a8c32019-03-26 19:52:28 -07001582
khenaidoodc2116e2021-10-19 17:33:19 -04001583 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001584 ParentId: dh.device.Id,
1585 OnuId: omciInd.OnuId,
1586 ParentPortNo: ponPort,
1587 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001588 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301589 return olterrors.NewErrNotFound("onu", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001590 "intf-id": omciInd.IntfId,
1591 "onu-id": omciInd.OnuId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001592 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001593 deviceType = onuDevice.Type
1594 deviceID = onuDevice.Id
1595 proxyDeviceID = onuDevice.ProxyAddress.DeviceId
khenaidoo106c61a2021-08-11 18:05:46 -04001596 childAdapterEndpoint = onuDevice.AdapterEndpoint
Akash Kankanala041a2122024-10-16 15:49:22 +05301597 // if not exist in cache, then add to cache.
khenaidoo106c61a2021-08-11 18:05:46 -04001598 dh.onus.Store(onuKey, NewOnuDevice(deviceID, deviceType, onuDevice.SerialNumber, omciInd.OnuId, omciInd.IntfId, proxyDeviceID, false, onuDevice.AdapterEndpoint))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001599 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05301600 // found in cache
Neha Sharma96b7bf22020-06-15 10:37:32 +00001601 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 +05301602 deviceType = onuInCache.(*OnuDevice).deviceType
1603 deviceID = onuInCache.(*OnuDevice).deviceID
1604 proxyDeviceID = onuInCache.(*OnuDevice).proxyDeviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001605 childAdapterEndpoint = onuInCache.(*OnuDevice).adapterEndpoint
cuilin20187b2a8c32019-03-26 19:52:28 -07001606 }
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001607
khenaidoodc2116e2021-10-19 17:33:19 -04001608 if err := dh.sendOmciIndicationToChildAdapter(ctx, childAdapterEndpoint, &ia.OmciMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001609 ParentDeviceId: proxyDeviceID,
1610 ChildDeviceId: deviceID,
1611 Message: omciInd.Pkt,
1612 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301613 return olterrors.NewErrCommunication("omci-request", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001614 "source": dh.openOLT.config.AdapterEndpoint,
1615 "device-type": deviceType,
1616 "destination": childAdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001617 "onu-id": deviceID,
Girish Kumarf26e4882020-03-05 06:49:10 +00001618 "proxy-device-id": proxyDeviceID}, err)
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001619 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001620 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301621}
1622
khenaidoo106c61a2021-08-11 18:05:46 -04001623// //ProcessInterAdapterMessage sends the proxied messages to the target device
1624// // If the proxy address is not found in the unmarshalled message, it first fetches the onu device for which the message
1625// // is meant, and then send the unmarshalled omci message to this onu
khenaidoodc2116e2021-10-19 17:33:19 -04001626// func (dh *DeviceHandler) ProcessInterAdapterMessage(ctx context.Context, msg *ca.InterAdapterMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001627// logger.Debugw(ctx, "process-inter-adapter-message", log.Fields{"msgID": msg.Header.Id})
khenaidoodc2116e2021-10-19 17:33:19 -04001628// if msg.Header.Type == ca.InterAdapterMessageType_OMCI_REQUEST {
khenaidoo106c61a2021-08-11 18:05:46 -04001629// return dh.handleInterAdapterOmciMsg(ctx, msg)
1630// }
1631// return olterrors.NewErrInvalidValue(log.Fields{"inter-adapter-message-type": msg.Header.Type}, nil)
1632// }
cuilin20187b2a8c32019-03-26 19:52:28 -07001633
kesavandb9f54fd2021-11-25 20:08:04 +05301634// ProxyOmciRequests sends the proxied OMCI message to the target device
1635func (dh *DeviceHandler) ProxyOmciRequests(ctx context.Context, omciMsgs *ia.OmciMessages) error {
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301636 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) {
1637 return status.Error(codes.Unavailable, "OLT unreachable")
1638 }
kesavandb9f54fd2021-11-25 20:08:04 +05301639 if omciMsgs.GetProxyAddress() == nil {
1640 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsgs.ChildDeviceId)
1641 if err != nil {
1642 return olterrors.NewErrNotFound("onu", log.Fields{
1643 "parent-device-id": dh.device.Id,
1644 "child-device-id": omciMsgs.ChildDeviceId}, err)
1645 }
1646 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1647 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsgs); err != nil {
1648 return olterrors.NewErrCommunication("send-failed", log.Fields{
1649 "parent-device-id": dh.device.Id,
1650 "child-device-id": omciMsgs.ChildDeviceId}, err)
1651 }
1652 } else {
1653 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsgs.ProxyAddress})
1654 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsgs); err != nil {
1655 return olterrors.NewErrCommunication("send-failed", log.Fields{
1656 "parent-device-id": dh.device.Id,
1657 "child-device-id": omciMsgs.ChildDeviceId}, err)
1658 }
1659 }
1660 return nil
1661}
1662
1663func (dh *DeviceHandler) sendProxyOmciRequests(ctx context.Context, onuDevice *voltha.Device, omciMsgs *ia.OmciMessages) error {
1664 var intfID uint32
1665 var onuID uint32
1666 var connectStatus common.ConnectStatus_Types
1667 if onuDevice != nil {
1668 intfID = onuDevice.ProxyAddress.GetChannelId()
1669 onuID = onuDevice.ProxyAddress.GetOnuId()
1670 connectStatus = onuDevice.ConnectStatus
1671 } else {
1672 intfID = omciMsgs.GetProxyAddress().GetChannelId()
1673 onuID = omciMsgs.GetProxyAddress().GetOnuId()
1674 connectStatus = omciMsgs.GetConnectStatus()
1675 }
1676 if connectStatus != voltha.ConnectStatus_REACHABLE {
1677 logger.Debugw(ctx, "onu-not-reachable--cannot-send-omci", log.Fields{"intf-id": intfID, "onu-id": onuID})
1678
1679 return olterrors.NewErrCommunication("unreachable", log.Fields{
1680 "intf-id": intfID,
1681 "onu-id": onuID}, nil)
1682 }
1683
1684 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1685 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
1686
1687 onuSecOmciMsgList := omciMsgs.GetMessages()
1688
1689 for _, onuSecOmciMsg := range onuSecOmciMsgList {
kesavandb9f54fd2021-11-25 20:08:04 +05301690 var omciMessage *oop.OmciMsg
1691 hexPkt := make([]byte, hex.EncodedLen(len(onuSecOmciMsg)))
1692 hex.Encode(hexPkt, onuSecOmciMsg)
1693 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1694
1695 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1696 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1697 //https://jira.opencord.org/browse/VOL-4604
1698 transid := extractOmciTransactionID(onuSecOmciMsg)
1699 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
1700 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
1701
bseenivaa1622112025-12-11 18:24:02 +05301702 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1703 _, err := dh.Client.OmciMsgOut(subCtx, omciMessage)
1704 cancel()
kesavandb9f54fd2021-11-25 20:08:04 +05301705 if err != nil {
1706 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
1707 "intf-id": intfID,
1708 "onu-id": onuID,
1709 "message": omciMessage}, err)
1710 }
1711 }
1712 return nil
1713}
1714
khenaidoo106c61a2021-08-11 18:05:46 -04001715// ProxyOmciMessage sends the proxied OMCI message to the target device
khenaidoodc2116e2021-10-19 17:33:19 -04001716func (dh *DeviceHandler) ProxyOmciMessage(ctx context.Context, omciMsg *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001717 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 -07001718
Akash Reddy Kankanala7b4d57e2026-01-26 23:18:18 +05301719 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) || DeviceState(dh.device.OperStatus) != DeviceState(voltha.OperStatus_ACTIVE) {
1720 return status.Error(codes.Unavailable, "OLT-is-unreachable-or-not-active")
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301721 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001722 if omciMsg.GetProxyAddress() == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001723 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsg.ChildDeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001724 if err != nil {
1725 return olterrors.NewErrNotFound("onu", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001726 "parent-device-id": dh.device.Id,
1727 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001728 }
khenaidoo106c61a2021-08-11 18:05:46 -04001729 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1730 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001731 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001732 "parent-device-id": dh.device.Id,
1733 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001734 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001735 } else {
khenaidoo106c61a2021-08-11 18:05:46 -04001736 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsg.ProxyAddress})
1737 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001738 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001739 "parent-device-id": dh.device.Id,
1740 "child-device-id": omciMsg.ChildDeviceId}, err)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001741 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001742 }
1743 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301744}
1745
khenaidoodc2116e2021-10-19 17:33:19 -04001746func (dh *DeviceHandler) sendProxiedMessage(ctx context.Context, onuDevice *voltha.Device, omciMsg *ia.OmciMessage) error {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001747 var intfID uint32
1748 var onuID uint32
Esin Karamanccb714b2019-11-29 15:02:06 +00001749 var connectStatus common.ConnectStatus_Types
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001750 if onuDevice != nil {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001751 intfID = onuDevice.ProxyAddress.GetChannelId()
1752 onuID = onuDevice.ProxyAddress.GetOnuId()
1753 connectStatus = onuDevice.ConnectStatus
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001754 } else {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001755 intfID = omciMsg.GetProxyAddress().GetChannelId()
1756 onuID = omciMsg.GetProxyAddress().GetOnuId()
1757 connectStatus = omciMsg.GetConnectStatus()
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001758 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001759 if connectStatus != voltha.ConnectStatus_REACHABLE {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001760 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 -08001761
Thomas Lee S94109f12020-03-03 16:39:29 +05301762 return olterrors.NewErrCommunication("unreachable", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001763 "intf-id": intfID,
1764 "onu-id": onuID}, nil)
cuilin20187b2a8c32019-03-26 19:52:28 -07001765 }
1766
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001767 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1768 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
kesavandb9f54fd2021-11-25 20:08:04 +05301769 // https://jira.opencord.org/browse/VOL-4604
lcuie24ef182019-04-29 22:58:36 -07001770 var omciMessage *oop.OmciMsg
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001771 hexPkt := make([]byte, hex.EncodedLen(len(omciMsg.Message)))
1772 hex.Encode(hexPkt, omciMsg.Message)
1773 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1774
1775 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1776 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1777 transid := extractOmciTransactionID(omciMsg.Message)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001778 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001779 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
cuilin20187b2a8c32019-03-26 19:52:28 -07001780
bseenivaa1622112025-12-11 18:24:02 +05301781 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1782 _, err := dh.Client.OmciMsgOut(subCtx, omciMessage)
1783 cancel()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001784 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301785 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001786 "intf-id": intfID,
1787 "onu-id": onuID,
1788 "message": omciMessage}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001789 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001790 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001791}
1792
David K. Bainbridge794735f2020-02-11 21:01:37 -08001793func (dh *DeviceHandler) activateONU(ctx context.Context, intfID uint32, onuID int64, serialNum *oop.SerialNumber, serialNumber string) error {
kesavand494c2082020-08-31 11:16:12 +05301794 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 +00001795 if err := dh.resourceMgr[intfID].AddNewOnuGemInfoToCacheAndKvStore(ctx, uint32(onuID), serialNumber); err != nil {
Matteo Scandolo92186242020-06-12 10:54:18 -07001796 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": onuID, "intf-id": intfID}, err)
Andrea Campanellab83b39d2020-03-30 11:41:16 +02001797 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001798 var pir uint32 = 1000000
kesavand494c2082020-08-31 11:16:12 +05301799 Onu := oop.Onu{IntfId: intfID, OnuId: uint32(onuID), SerialNumber: serialNum, Pir: pir, OmccEncryption: dh.openOLT.config.OmccEncryption}
bseenivaa1622112025-12-11 18:24:02 +05301800 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1801 defer cancel()
1802 if _, err := dh.Client.ActivateOnu(subCtx, &Onu); err != nil {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001803 st, _ := status.FromError(err)
1804 if st.Code() == codes.AlreadyExists {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001805 logger.Debugw(ctx, "onu-activation-in-progress", log.Fields{"SerialNumber": serialNumber, "onu-id": onuID, "device-id": dh.device.Id})
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001806 } else {
Thomas Lee S985938d2020-05-04 11:40:41 +05301807 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": Onu, "device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001808 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001809 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001810 logger.Infow(ctx, "activated-onu", log.Fields{"SerialNumber": serialNumber, "device-id": dh.device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001811 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001812 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001813}
1814
Mahir Gunyela2e68702022-12-07 00:00:42 -08001815// getChildDevice function can be used in general to get child device, if not found in cache the function will
1816// get from core and update the cache and return the child device.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301817func (dh *DeviceHandler) getChildDevice(ctx context.Context, sn string, parentPortNo uint32) *OnuDevice {
1818 var InCacheOnuDev *OnuDevice
1819 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1820 if onuInCache.(*OnuDevice).serialNumber == sn {
1821 InCacheOnuDev = onuInCache.(*OnuDevice)
1822 return false
1823 }
1824 return true
1825 })
Akash Kankanala041a2122024-10-16 15:49:22 +05301826 // Got the onu device from cache return
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301827 if InCacheOnuDev != nil {
1828 logger.Debugw(ctx, "Got child device from cache", log.Fields{"onudev": InCacheOnuDev.serialNumber})
1829 return InCacheOnuDev
1830 }
1831 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1832 ParentId: dh.device.Id,
1833 SerialNumber: sn,
1834 ParentPortNo: parentPortNo,
1835 })
Akash Kankanala041a2122024-10-16 15:49:22 +05301836 // No device found in core return nil
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301837 if onuDevice == nil {
1838 return nil
1839 }
1840 onuID := onuDevice.ProxyAddress.OnuId
1841 intfID := plt.PortNoToIntfID(parentPortNo, voltha.Port_PON_OLT)
1842 onuKey := dh.formOnuKey(intfID, onuID)
1843
1844 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuDevice.ProxyAddress.OnuId, intfID, onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
1845 dh.onus.Store(onuKey, onuDev)
1846 logger.Debugw(ctx, "got child device from core", log.Fields{"onudev": onuDevice})
1847 return onuDev
1848}
1849
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301850// checkForResourceExistance checks for either device in rw-core or active techprofile in olt-adapter, based on the flag CheckOnuDevExistenceAtOnuDiscovery.
1851// If the ONU device/resource exists in either of these, the ONU discovery will be ignored.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301852func (dh *DeviceHandler) checkForResourceExistance(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) (bool, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001853 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
Akash Kankanala041a2122024-10-16 15:49:22 +05301854 // CheckOnuDevExistenceAtOnuDiscovery if true , a check will be made for the existence of the onu device. If the onu device
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301855 // still exists , the onu discovery will be ignored, else a check for active techprofiles for ONU is checked.
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301856 if dh.openOLT.CheckOnuDevExistenceAtOnuDiscovery {
1857 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1858 ParentId: dh.device.Id,
1859 SerialNumber: sn,
1860 ParentPortNo: parentPortNo,
1861 })
1862 if onuDevice != nil {
1863 logger.Infow(ctx, "Child device still present ignoring discovery indication", log.Fields{"sn": sn})
1864 return true, nil
1865 }
balaji.nagarajan31db4ea2026-01-28 09:13:55 +05301866 logger.Debugw(ctx, "No device present in core , continuing with discovery", log.Fields{"sn": sn})
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301867
1868 return false, nil
1869 } else {
1870 tpInstExists := false
1871 channelID := onuDiscInd.GetIntfId()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301872 onuDev := dh.getChildDevice(ctx, sn, parentPortNo)
1873 if onuDev != nil {
1874 var onuGemInfo *rsrcMgr.OnuGemInfo
1875 var err error
1876 if onuGemInfo, err = dh.resourceMgr[channelID].GetOnuGemInfo(ctx, onuDev.onuID); err != nil {
1877 logger.Warnw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuDev.onuID})
1878 return false, err
1879 }
1880 if onuGemInfo != nil {
1881 for _, uni := range onuGemInfo.UniPorts {
1882 uniID := plt.UniIDFromPortNum(uni)
1883 tpIDs := dh.resourceMgr[channelID].GetTechProfileIDForOnu(ctx, onuDev.onuID, uniID)
1884 if len(tpIDs) != 0 {
1885 logger.Warnw(ctx, "Techprofile present for ONU, ignoring onu discovery", log.Fields{"onuID": onuDev.onuID})
1886 tpInstExists = true
1887 break
1888 }
1889 }
1890 }
1891 }
1892 return tpInstExists, nil
1893 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301894}
1895
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001896// processDiscONULOSClear clears the LOS Alarm if it's needed
1897func (dh *DeviceHandler) processDiscONULOSClear(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) {
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301898 var alarmInd oop.OnuAlarmIndication
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001899 raisedTs := time.Now().Unix()
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301900
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001901 /* When PON cable disconnected and connected back from OLT, it was expected OnuAlarmIndication
1902 with "los_status: off" should be raised but BAL does not raise this Alarm hence manually sending
1903 OnuLosClear event on receiving OnuDiscoveryIndication for the Onu after checking whether
1904 OnuLosRaise event sent for it */
1905 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1906 if onuInCache.(*OnuDevice).serialNumber == sn && onuInCache.(*OnuDevice).losRaised {
1907 if onuDiscInd.GetIntfId() != onuInCache.(*OnuDevice).intfID {
1908 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
1909 "previousIntfId": onuInCache.(*OnuDevice).intfID,
1910 "currentIntfId": onuDiscInd.GetIntfId()})
1911 // TODO:: Should we need to ignore raising OnuLosClear event
1912 // when onu connected to different PON?
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301913 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001914 alarmInd.IntfId = onuInCache.(*OnuDevice).intfID
1915 alarmInd.OnuId = onuInCache.(*OnuDevice).onuID
1916 alarmInd.LosStatus = statusCheckOff
1917 go func() {
1918 if err := dh.eventMgr.onuAlarmIndication(ctx, &alarmInd, onuInCache.(*OnuDevice).deviceID, raisedTs); err != nil {
1919 logger.Errorw(ctx, "indication-failed", log.Fields{"err": err})
1920 }
1921 }()
1922 // stop iterating
1923 return false
1924 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301925 return true
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001926 })
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301927}
1928
bseeniva43b5a912025-06-05 12:48:15 +05301929func (dh *DeviceHandler) handleOnuDiscoveryProcessingError(ctx context.Context, err error, sn string, tpInstExists bool) {
1930 if err != nil || tpInstExists {
1931 logger.Infow(ctx, "onu-processing-errored-out-not-adding-to-discovery-map", log.Fields{"sn": sn})
1932 } else {
1933 // once the function completes set the value to false so that
1934 // we know the processing has inProcess.
1935 // Note that this is done after checking if we are already processing
1936 // to avoid changing the value from a different thread
balaji.nagarajan31db4ea2026-01-28 09:13:55 +05301937 logger.Debugw(ctx, "onu-processing-completed", log.Fields{"sn": sn})
bseeniva43b5a912025-06-05 12:48:15 +05301938 dh.discOnus.Store(sn, false)
1939 }
1940}
1941
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301942func (dh *DeviceHandler) onuDiscIndication(ctx context.Context, onuDiscInd *oop.OnuDiscIndication) error {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301943 var error error
bseeniva43b5a912025-06-05 12:48:15 +05301944 var tpInstExists bool
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301945
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301946 channelID := onuDiscInd.GetIntfId()
1947 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
1948
1949 sn := dh.stringifySerialNumber(onuDiscInd.SerialNumber)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301950 defer func() {
bseeniva43b5a912025-06-05 12:48:15 +05301951 dh.handleOnuDiscoveryProcessingError(ctx, error, sn, tpInstExists)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301952 }()
1953
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301954 logger.Infow(ctx, "new-discovery-indication", log.Fields{"sn": sn})
1955
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301956 // Check for resource existence only if the ForceOnuDiscIndProcessing is disabled.
1957 if !dh.cfg.ForceOnuDiscIndProcessing {
1958 tpInstExists, error = dh.checkForResourceExistance(ctx, onuDiscInd, sn)
1959 if error != nil {
1960 return error
1961 }
1962 if tpInstExists {
1963 // ignore the discovery if tpinstance is present.
1964 logger.Debugw(ctx, "ignoring-onu-indication-as-tp-already-exists", log.Fields{"sn": sn})
1965 return nil
1966 }
Amit Ghoshe5c6a852020-02-10 15:09:46 +00001967 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001968 inProcess, existing := dh.discOnus.LoadOrStore(sn, true)
1969
1970 // if the ONU existed, handle the LOS Alarm
1971 if existing {
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001972 if inProcess.(bool) {
1973 // if we're currently processing the ONU on a different thread, do nothing
1974 logger.Warnw(ctx, "onu-sn-is-being-processed", log.Fields{"sn": sn})
1975 return nil
1976 }
1977 // if we had dealt with this ONU before, but the process didn't complete (this happens in case of errors)
1978 // then continue processing it
1979 logger.Debugw(ctx, "onu-processing-had-completed-but-new-indication", log.Fields{"sn": sn})
1980
1981 dh.processDiscONULOSClear(ctx, onuDiscInd, sn)
serkantule333d152022-10-12 01:44:00 +03001982 return nil
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301983 }
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001984 var onuID uint32
Matteo Scandolo945e4012019-12-12 14:16:11 -08001985
1986 // check the ONU is already know to the OLT
1987 // NOTE the second time the ONU is discovered this should return a device
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301988 onuDevice, error := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001989 ParentId: dh.device.Id,
1990 SerialNumber: sn,
1991 })
Matteo Scandolo945e4012019-12-12 14:16:11 -08001992
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301993 if error != nil {
1994 logger.Debugw(ctx, "core-proxy-get-child-device-failed", log.Fields{"parentDevice": dh.device.Id, "err": error, "sn": sn})
1995 if e, ok := status.FromError(error); ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001996 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 -08001997 switch e.Code() {
1998 case codes.Internal:
1999 // this probably means NOT FOUND, so just create a new device
2000 onuDevice = nil
2001 case codes.DeadlineExceeded:
2002 // if the call times out, cleanup and exit
2003 dh.discOnus.Delete(sn)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302004 error = olterrors.NewErrTimeout("get-child-device", log.Fields{"device-id": dh.device.Id}, error)
2005 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08002006 }
2007 }
2008 }
2009
2010 if onuDevice == nil {
2011 // NOTE this should happen a single time, and only if GetChildDevice returns NotFound
Neha Sharma96b7bf22020-06-15 10:37:32 +00002012 logger.Debugw(ctx, "creating-new-onu", log.Fields{"sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08002013 // we need to create a new ChildDevice
Matt Jeanneret53539512019-07-20 14:47:02 -04002014 ponintfid := onuDiscInd.GetIntfId()
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302015 onuID, error = dh.resourceMgr[ponintfid].GetONUID(ctx)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002016 logger.Infow(ctx, "creating-new-onu-got-onu-id", log.Fields{"sn": sn, "onuId": onuID})
Matteo Scandolo945e4012019-12-12 14:16:11 -08002017
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302018 if error != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08002019 // if we can't create an ID in resource manager,
2020 // cleanup and exit
Matteo Scandolo945e4012019-12-12 14:16:11 -08002021 dh.discOnus.Delete(sn)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302022
2023 error = olterrors.NewErrAdapter("resource-manager-get-onu-id-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002024 "pon-intf-id": ponintfid,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302025 "serial-number": sn}, error)
2026 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08002027 }
2028
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302029 if onuDevice, error = dh.sendChildDeviceDetectedToCore(ctx, &ca.DeviceDiscovery{
khenaidoo106c61a2021-08-11 18:05:46 -04002030 ParentId: dh.device.Id,
2031 ParentPortNo: parentPortNo,
2032 ChannelId: channelID,
2033 VendorId: string(onuDiscInd.SerialNumber.GetVendorId()),
2034 SerialNumber: sn,
2035 OnuId: onuID,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302036 }); error != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08002037 dh.discOnus.Delete(sn)
yasin saplibddc2d72022-02-08 13:10:17 +00002038 dh.resourceMgr[ponintfid].FreeonuID(ctx, []uint32{onuID}) // NOTE I'm not sure this method is actually cleaning up the right thing
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302039
2040 error = olterrors.NewErrAdapter("core-proxy-child-device-detected-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002041 "pon-intf-id": ponintfid,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302042 "serial-number": sn}, error)
2043 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08002044 }
Akash Kankanala041a2122024-10-16 15:49:22 +05302045 if error = dh.eventMgr.OnuDiscoveryIndication(ctx, onuDiscInd, dh.device.Id, onuDevice.Id, onuID, sn, time.Now().Unix()); error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302046 logger.Error(ctx, "discovery-indication-failed", log.Fields{"err": error})
2047 error = olterrors.NewErrAdapter("discovery-indication-failed", log.Fields{
2048 "onu-id": onuID,
2049 "device-id": dh.device.Id,
2050 "serial-number": sn}, error)
2051 return error
Kent Hagermane6ff1012020-07-14 15:07:53 -04002052 }
balaji.nagarajan31db4ea2026-01-28 09:13:55 +05302053 logger.Debugw(ctx, "onu-child-device-added",
Shrey Baid807a2a02020-04-09 12:52:45 +05302054 log.Fields{"onuDevice": onuDevice,
2055 "sn": sn,
Matteo Scandolo92186242020-06-12 10:54:18 -07002056 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05302057 "device-id": dh.device.Id})
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04002058 }
Matteo Scandolo945e4012019-12-12 14:16:11 -08002059
khenaidoo106c61a2021-08-11 18:05:46 -04002060 // Setup the gRPC connection to the adapter responsible for that onuDevice, if not setup yet
2061 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302062 error = dh.setupChildInterAdapterClient(subCtx, onuDevice.AdapterEndpoint)
khenaidoo106c61a2021-08-11 18:05:46 -04002063 cancel()
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302064 if error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302065 error = olterrors.NewErrCommunication("no-connection-to-child-adapter", log.Fields{"device-id": onuDevice.Id}, error)
2066 return error
khenaidoo106c61a2021-08-11 18:05:46 -04002067 }
2068
Matteo Scandolo945e4012019-12-12 14:16:11 -08002069 // we can now use the existing ONU Id
2070 onuID = onuDevice.ProxyAddress.OnuId
Akash Kankanala041a2122024-10-16 15:49:22 +05302071 // Insert the ONU into cache to use in OnuIndication.
Mahir Gunyele77977b2019-06-27 05:36:22 -07002072 //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 +00002073 logger.Debugw(ctx, "onu-discovery-indication-key-create",
Matteo Scandolo92186242020-06-12 10:54:18 -07002074 log.Fields{"onu-id": onuID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302075 "intfId": onuDiscInd.GetIntfId(),
2076 "sn": sn})
Mahir Gunyele77977b2019-06-27 05:36:22 -07002077 onuKey := dh.formOnuKey(onuDiscInd.GetIntfId(), onuID)
Matt Jeanneret53539512019-07-20 14:47:02 -04002078
khenaidoo106c61a2021-08-11 18:05:46 -04002079 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuID, onuDiscInd.GetIntfId(), onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302080 dh.onus.Store(onuKey, onuDev)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002081 logger.Debugw(ctx, "new-onu-device-discovered",
Shrey Baid807a2a02020-04-09 12:52:45 +05302082 log.Fields{"onu": onuDev,
2083 "sn": sn})
Chaitrashree G S35b5d802019-07-08 23:12:03 -04002084
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302085 if error = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002086 DeviceId: onuDevice.Id,
2087 ParentDeviceId: dh.device.Id,
2088 OperStatus: common.OperStatus_DISCOVERED,
2089 ConnStatus: common.ConnectStatus_REACHABLE,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302090 }); error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302091 error = olterrors.NewErrAdapter("failed-to-update-device-state", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002092 "device-id": onuDevice.Id,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302093 "serial-number": sn}, error)
2094 return error
cuilin20187b2a8c32019-03-26 19:52:28 -07002095 }
khenaidoo106c61a2021-08-11 18:05:46 -04002096
Neha Sharma96b7bf22020-06-15 10:37:32 +00002097 logger.Infow(ctx, "onu-discovered-reachable", log.Fields{"device-id": onuDevice.Id, "sn": sn})
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302098 if error = dh.activateONU(ctx, onuDiscInd.IntfId, int64(onuID), onuDiscInd.SerialNumber, sn); error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302099 error = olterrors.NewErrAdapter("onu-activation-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002100 "device-id": onuDevice.Id,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302101 "serial-number": sn}, error)
2102 return error
David K. Bainbridge794735f2020-02-11 21:01:37 -08002103 }
2104 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07002105}
2106
Mahir Gunyelb0046752021-02-26 13:51:05 -08002107func (dh *DeviceHandler) onuIndication(ctx context.Context, onuInd *oop.OnuIndication) error {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002108 ponPort := plt.IntfIDToPortNo(onuInd.GetIntfId(), voltha.Port_PON_OLT)
Mahir Gunyele77977b2019-06-27 05:36:22 -07002109 var onuDevice *voltha.Device
David K. Bainbridge794735f2020-02-11 21:01:37 -08002110 var err error
Mahir Gunyele77977b2019-06-27 05:36:22 -07002111 foundInCache := false
Neha Sharma96b7bf22020-06-15 10:37:32 +00002112 logger.Debugw(ctx, "onu-indication-key-create",
Shrey Baid807a2a02020-04-09 12:52:45 +05302113 log.Fields{"onuId": onuInd.OnuId,
2114 "intfId": onuInd.GetIntfId(),
Thomas Lee S985938d2020-05-04 11:40:41 +05302115 "device-id": dh.device.Id})
Mahir Gunyele77977b2019-06-27 05:36:22 -07002116 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.OnuId)
Mahir Gunyelb0046752021-02-26 13:51:05 -08002117 serialNumber := dh.stringifySerialNumber(onuInd.SerialNumber)
David K. Bainbridge794735f2020-02-11 21:01:37 -08002118 errFields := log.Fields{"device-id": dh.device.Id}
2119
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302120 if onuInCache, ok := dh.onus.Load(onuKey); ok {
Akash Kankanala041a2122024-10-16 15:49:22 +05302121 // If ONU id is discovered before then use GetDevice to get onuDevice because it is cheaper.
Mahir Gunyele77977b2019-06-27 05:36:22 -07002122 foundInCache = true
David K. Bainbridge794735f2020-02-11 21:01:37 -08002123 errFields["onu-id"] = onuInCache.(*OnuDevice).deviceID
khenaidoo106c61a2021-08-11 18:05:46 -04002124 onuDevice, err = dh.getDeviceFromCore(ctx, onuInCache.(*OnuDevice).deviceID)
cuilin20187b2a8c32019-03-26 19:52:28 -07002125 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05302126 // If ONU not found in adapter cache then we have to use GetChildDevice to get onuDevice
Mahir Gunyele77977b2019-06-27 05:36:22 -07002127 if serialNumber != "" {
David K. Bainbridge794735f2020-02-11 21:01:37 -08002128 errFields["serial-number"] = serialNumber
Mahir Gunyele77977b2019-06-27 05:36:22 -07002129 } else {
David K. Bainbridge794735f2020-02-11 21:01:37 -08002130 errFields["onu-id"] = onuInd.OnuId
2131 errFields["parent-port-no"] = ponPort
Mahir Gunyele77977b2019-06-27 05:36:22 -07002132 }
khenaidoodc2116e2021-10-19 17:33:19 -04002133 onuDevice, err = dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002134 ParentId: dh.device.Id,
2135 SerialNumber: serialNumber,
2136 OnuId: onuInd.OnuId,
2137 ParentPortNo: ponPort,
2138 })
cuilin20187b2a8c32019-03-26 19:52:28 -07002139 }
Mahir Gunyele77977b2019-06-27 05:36:22 -07002140
David K. Bainbridge794735f2020-02-11 21:01:37 -08002141 if err != nil || onuDevice == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002142 return olterrors.NewErrNotFound("onu-device", errFields, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07002143 }
2144
David K. Bainbridge794735f2020-02-11 21:01:37 -08002145 if onuDevice.ParentPortNo != ponPort {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002146 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002147 "previousIntfId": onuDevice.ParentPortNo,
2148 "currentIntfId": ponPort})
2149 }
2150
2151 if onuDevice.ProxyAddress.OnuId != onuInd.OnuId {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002152 logger.Warnw(ctx, "onu-id-mismatch-possible-if-voltha-and-olt-rebooted", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302153 "expected-onu-id": onuDevice.ProxyAddress.OnuId,
2154 "received-onu-id": onuInd.OnuId,
Thomas Lee S985938d2020-05-04 11:40:41 +05302155 "device-id": dh.device.Id})
David K. Bainbridge794735f2020-02-11 21:01:37 -08002156 }
2157 if !foundInCache {
2158 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.GetOnuId())
khenaidoo106c61a2021-08-11 18:05:46 -04002159 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 -08002160 }
kesavand7cf3a052020-08-28 12:49:18 +05302161 if onuInd.OperState == "down" && onuInd.FailReason != oop.OnuIndication_ONU_ACTIVATION_FAIL_REASON_NONE {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07002162 if err := dh.eventMgr.onuActivationIndication(ctx, onuActivationFailEvent, onuInd, dh.device.Id, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002163 logger.Warnw(ctx, "onu-activation-indication-reporting-failed", log.Fields{"err": err})
kesavand7cf3a052020-08-28 12:49:18 +05302164 }
2165 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002166 if err := dh.updateOnuStates(ctx, onuDevice, onuInd); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002167 return olterrors.NewErrCommunication("state-update-failed", errFields, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08002168 }
2169 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07002170}
2171
Neha Sharma96b7bf22020-06-15 10:37:32 +00002172func (dh *DeviceHandler) updateOnuStates(ctx context.Context, onuDevice *voltha.Device, onuInd *oop.OnuIndication) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002173 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 -07002174 if onuInd.AdminState == "down" || onuInd.OperState == "down" {
2175 // The ONU has gone admin_state "down" or oper_state "down" - we expect the ONU to send discovery again
2176 // The ONU admin_state is "up" while "oper_state" is down in cases where ONU activation fails. In this case
2177 // the ONU sends Discovery again.
Girish Gowdra429f9502020-05-04 13:22:16 -07002178 dh.discOnus.Delete(onuDevice.SerialNumber)
Amit Ghosh9bbc5652020-02-17 13:37:32 +00002179 // Tests have shown that we sometimes get OperState as NOT down even if AdminState is down, forcing it
2180 if onuInd.OperState != "down" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002181 logger.Warnw(ctx, "onu-admin-state-down", log.Fields{"operState": onuInd.OperState})
Amit Ghosh9bbc5652020-02-17 13:37:32 +00002182 onuInd.OperState = "down"
2183 }
2184 }
2185
David K. Bainbridge794735f2020-02-11 21:01:37 -08002186 switch onuInd.OperState {
khenaidoo106c61a2021-08-11 18:05:46 -04002187 case "up", "down":
Neha Sharma96b7bf22020-06-15 10:37:32 +00002188 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 -04002189
khenaidoodc2116e2021-10-19 17:33:19 -04002190 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002191 DeviceId: onuDevice.Id,
2192 OnuIndication: onuInd,
2193 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002194 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302195 return olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002196 "onu-indicator": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002197 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08002198 "device-type": onuDevice.Type,
Girish Kumarf26e4882020-03-05 06:49:10 +00002199 "device-id": onuDevice.Id}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002200 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002201 default:
Girish Kumarf26e4882020-03-05 06:49:10 +00002202 return olterrors.NewErrInvalidValue(log.Fields{"oper-state": onuInd.OperState}, nil)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002203 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002204 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002205}
2206
cuilin20187b2a8c32019-03-26 19:52:28 -07002207func (dh *DeviceHandler) stringifySerialNumber(serialNum *oop.SerialNumber) string {
2208 if serialNum != nil {
2209 return string(serialNum.VendorId) + dh.stringifyVendorSpecific(serialNum.VendorSpecific)
cuilin20187b2a8c32019-03-26 19:52:28 -07002210 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002211 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07002212}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002213func (dh *DeviceHandler) deStringifySerialNumber(serialNum string) (*oop.SerialNumber, error) {
2214 decodedStr, err := hex.DecodeString(serialNum[4:])
2215 if err != nil {
2216 return nil, err
2217 }
2218 return &oop.SerialNumber{
2219 VendorId: []byte(serialNum[:4]),
Girish Gowdraa09aeab2020-09-14 16:30:52 -07002220 VendorSpecific: decodedStr,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002221 }, nil
2222}
cuilin20187b2a8c32019-03-26 19:52:28 -07002223
2224func (dh *DeviceHandler) stringifyVendorSpecific(vendorSpecific []byte) string {
Mahir Gunyelb0046752021-02-26 13:51:05 -08002225 if len(vendorSpecific) > 3 {
2226 tmp := fmt.Sprintf("%x", (uint32(vendorSpecific[0])>>4)&0x0f) +
2227 fmt.Sprintf("%x", uint32(vendorSpecific[0]&0x0f)) +
2228 fmt.Sprintf("%x", (uint32(vendorSpecific[1])>>4)&0x0f) +
2229 fmt.Sprintf("%x", (uint32(vendorSpecific[1]))&0x0f) +
2230 fmt.Sprintf("%x", (uint32(vendorSpecific[2])>>4)&0x0f) +
2231 fmt.Sprintf("%x", (uint32(vendorSpecific[2]))&0x0f) +
2232 fmt.Sprintf("%x", (uint32(vendorSpecific[3])>>4)&0x0f) +
2233 fmt.Sprintf("%x", (uint32(vendorSpecific[3]))&0x0f)
2234 return tmp
2235 }
2236 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07002237}
2238
Mahir Gunyela2e68702022-12-07 00:00:42 -08002239// UpdateFlowsBulk upates the bulk flow
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002240func (dh *DeviceHandler) UpdateFlowsBulk() error {
Thomas Lee S94109f12020-03-03 16:39:29 +05302241 return olterrors.ErrNotImplemented
cuilin20187b2a8c32019-03-26 19:52:28 -07002242}
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002243
Mahir Gunyela2e68702022-12-07 00:00:42 -08002244// GetChildDevice returns the child device for given parent port and onu id
Neha Sharma96b7bf22020-06-15 10:37:32 +00002245func (dh *DeviceHandler) GetChildDevice(ctx context.Context, parentPort, onuID uint32) (*voltha.Device, error) {
2246 logger.Debugw(ctx, "getchilddevice",
Shrey Baid807a2a02020-04-09 12:52:45 +05302247 log.Fields{"pon-port": parentPort,
Matteo Scandolo92186242020-06-12 10:54:18 -07002248 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05302249 "device-id": dh.device.Id})
khenaidoo106c61a2021-08-11 18:05:46 -04002250
khenaidoodc2116e2021-10-19 17:33:19 -04002251 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002252 ParentId: dh.device.Id,
2253 OnuId: onuID,
2254 ParentPortNo: parentPort,
2255 })
2256
Girish Gowdru0c588b22019-04-23 23:24:56 -04002257 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002258 return nil, olterrors.NewErrNotFound("onu-device", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002259 "intf-id": parentPort,
2260 "onu-id": onuID}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04002261 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002262 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 -08002263 return onuDevice, nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302264}
2265
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002266// SendPacketInToCore sends packet-in to core
2267// For this, it calls SendPacketIn of the core-proxy which uses a device specific topic to send the request.
2268// The adapter handling the device creates a device specific topic
Neha Sharma96b7bf22020-06-15 10:37:32 +00002269func (dh *DeviceHandler) SendPacketInToCore(ctx context.Context, logicalPort uint32, packetPayload []byte) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002270 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002271 logger.Debugw(ctx, "send-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002272 "port": logicalPort,
2273 "packet": hex.EncodeToString(packetPayload),
2274 "device-id": dh.device.Id,
2275 })
2276 }
khenaidoo106c61a2021-08-11 18:05:46 -04002277
khenaidoodc2116e2021-10-19 17:33:19 -04002278 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002279 DeviceId: dh.device.Id,
2280 Port: logicalPort,
2281 Packet: packetPayload,
2282 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302283 return olterrors.NewErrCommunication("packet-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002284 "source": "adapter",
2285 "destination": "core",
2286 "device-id": dh.device.Id,
2287 "logical-port": logicalPort,
Girish Kumarf26e4882020-03-05 06:49:10 +00002288 "packet": hex.EncodeToString(packetPayload)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002289 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002290 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002291 logger.Debugw(ctx, "sent-packet-in-to-core-successfully", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002292 "packet": hex.EncodeToString(packetPayload),
2293 "device-id": dh.device.Id,
2294 })
2295 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002296 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002297}
2298
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002299// UpdatePmConfig updates the pm metrics.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002300func (dh *DeviceHandler) UpdatePmConfig(ctx context.Context, pmConfigs *voltha.PmConfigs) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002301 logger.Infow(ctx, "update-pm-configs", log.Fields{"device-id": dh.device.Id, "pm-configs": pmConfigs})
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002302
2303 if pmConfigs.DefaultFreq != dh.metrics.ToPmConfigs().DefaultFreq {
2304 dh.metrics.UpdateFrequency(pmConfigs.DefaultFreq)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002305 logger.Debugf(ctx, "frequency-updated")
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002306 }
2307
Kent Hagermane6ff1012020-07-14 15:07:53 -04002308 if !pmConfigs.Grouped {
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002309 metrics := dh.metrics.GetSubscriberMetrics()
2310 for _, m := range pmConfigs.Metrics {
2311 metrics[m.Name].Enabled = m.Enabled
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002312 }
2313 }
2314}
2315
khenaidoodc2116e2021-10-19 17:33:19 -04002316func (dh *DeviceHandler) handleFlows(ctx context.Context, device *voltha.Device, flows *of.FlowChanges, flowMetadata *of.FlowMetadata) []error {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002317 var err error
Andrea Campanellac63bba92020-03-10 17:01:04 +01002318 var errorsList []error
2319
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002320 if dh.getDeviceDeletionInProgressFlag() {
2321 // The device itself is going to be reset as part of deletion. So nothing to be done.
2322 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2323 return nil
2324 }
2325
Girish Gowdru0c588b22019-04-23 23:24:56 -04002326 if flows != nil {
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002327 for _, flow := range flows.ToRemove.Items {
Akash Kankanala041a2122024-10-16 15:49:22 +05302328 intfID := dh.getIntfIDFromFlow(flow)
Girish Gowdracefae192020-03-19 18:14:10 -07002329
Neha Sharma96b7bf22020-06-15 10:37:32 +00002330 logger.Debugw(ctx, "removing-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302331 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002332 "intfId": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302333 "flowToRemove": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002334 if flow_utils.HasGroup(flow) {
2335 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupRemove)
2336 } else {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002337 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
2338 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2339 } else {
2340 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, false, nil)
2341 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002342 }
Girish Gowdracefae192020-03-19 18:14:10 -07002343 if err != nil {
Elia Battiston2aaf4342022-02-07 15:16:38 +01002344 if werr, ok := err.(olterrors.WrappedError); ok && status.Code(werr.Unwrap()) == codes.NotFound {
Akash Kankanala041a2122024-10-16 15:49:22 +05302345 // The flow we want to remove is not there, there is no need to throw an error
Elia Battiston2aaf4342022-02-07 15:16:38 +01002346 logger.Warnw(ctx, "flow-to-remove-not-found",
2347 log.Fields{
2348 "ponIf": intfID,
2349 "flowToRemove": flow,
2350 "error": err,
2351 })
2352 } else {
2353 errorsList = append(errorsList, err)
2354 }
Girish Gowdracefae192020-03-19 18:14:10 -07002355 }
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002356 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302357
2358 for _, flow := range flows.ToAdd.Items {
Akash Kankanala041a2122024-10-16 15:49:22 +05302359 intfID := dh.getIntfIDFromFlow(flow)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002360 logger.Debugw(ctx, "adding-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302361 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002362 "ponIf": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302363 "flowToAdd": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002364 if flow_utils.HasGroup(flow) {
2365 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupAdd)
2366 } else {
yasin saplid0566272021-12-21 09:10:30 +00002367 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002368 // The flow manager module could be uninitialized if the flow arrives too soon before the device has reconciled fully
2369 logger.Errorw(ctx, "flow-manager-uninitialized", log.Fields{"device-id": device.Id})
2370 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2371 } else {
yasin saplid0566272021-12-21 09:10:30 +00002372 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, true, flowMetadata)
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002373 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002374 }
Andrea Campanellac63bba92020-03-10 17:01:04 +01002375 if err != nil {
2376 errorsList = append(errorsList, err)
2377 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302378 }
Girish Gowdru0c588b22019-04-23 23:24:56 -04002379 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002380
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002381 return errorsList
2382}
2383
2384func (dh *DeviceHandler) handleGroups(ctx context.Context, groups *of.FlowGroupChanges) []error {
2385 var err error
2386 var errorsList []error
2387
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002388 if dh.getDeviceDeletionInProgressFlag() {
2389 // The device itself is going to be reset as part of deletion. So nothing to be done.
2390 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
2391 return nil
2392 }
2393
Girish Gowdracefae192020-03-19 18:14:10 -07002394 // 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 +00002395 if groups != nil {
2396 for _, group := range groups.ToAdd.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002397 // err = dh.groupMgr.AddGroup(ctx, group)
2398 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupAdd)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002399 if err != nil {
2400 errorsList = append(errorsList, err)
2401 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002402 }
2403 for _, group := range groups.ToUpdate.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002404 // err = dh.groupMgr.ModifyGroup(ctx, group)
2405 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupModify)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002406 if err != nil {
2407 errorsList = append(errorsList, err)
2408 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002409 }
Esin Karamand519bbf2020-07-01 11:16:03 +00002410 for _, group := range groups.ToRemove.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002411 // err = dh.groupMgr.DeleteGroup(ctx, group)
2412 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupRemove)
Esin Karamand519bbf2020-07-01 11:16:03 +00002413 if err != nil {
2414 errorsList = append(errorsList, err)
2415 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002416 }
2417 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002418
2419 return errorsList
2420}
2421
Mahir Gunyela2e68702022-12-07 00:00:42 -08002422// UpdateFlowsIncrementally updates the device flow
khenaidoodc2116e2021-10-19 17:33:19 -04002423func (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 -07002424 var errorsList []error
Girish Gowdra950326e2021-11-05 12:43:24 -07002425
2426 if dh.getDeviceDeletionInProgressFlag() {
2427 // The device itself is going to be reset as part of deletion. So nothing to be done.
2428 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2429 return nil
2430 }
nikesh.krishnan0897d472023-09-05 18:35:08 +05302431 if dh.transitionMap.currentDeviceState != deviceStateUp {
2432 logger.Error(ctx, "device-is-not-up--not-handling-flows-or-groups", log.Fields{"device-id": device.Id, "current-device-state": dh.transitionMap.currentDeviceState})
2433 return fmt.Errorf("device-is-not-up--not-handling-flows-or-groups")
2434 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002435 logger.Debugw(ctx, "received-incremental-flowupdate-in-device-handler", log.Fields{"device-id": device.Id, "flows": flows, "groups": groups, "flowMetadata": flowMetadata})
2436 errorsList = append(errorsList, dh.handleFlows(ctx, device, flows, flowMetadata)...)
2437 errorsList = append(errorsList, dh.handleGroups(ctx, groups)...)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002438 if len(errorsList) > 0 {
2439 return fmt.Errorf("errors-installing-flows-groups, errors:%v", errorsList)
2440 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002441 logger.Debugw(ctx, "updated-flows-incrementally-successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0c588b22019-04-23 23:24:56 -04002442 return nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302443}
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002444
Mahir Gunyela2e68702022-12-07 00:00:42 -08002445// DisableDevice disables the given device
2446// It marks the following for the given device:
2447// Device-Handler Admin-State : down
2448// Device Port-State: UNKNOWN
2449// Device Oper-State: UNKNOWN
Neha Sharma96b7bf22020-06-15 10:37:32 +00002450func (dh *DeviceHandler) DisableDevice(ctx context.Context, device *voltha.Device) error {
Chaitrashree G S44124192019-08-07 20:21:36 -04002451 /* On device disable ,admin state update has to be done prior sending request to agent since
2452 the indication thread may processes invalid indications of ONU and OLT*/
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002453 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302454 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2455 if _, err := dh.Client.DisableOlt(subCtx, new(oop.Empty)); err != nil {
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002456 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
bseenivaa1622112025-12-11 18:24:02 +05302457 cancel()
Girish Kumarf26e4882020-03-05 06:49:10 +00002458 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": device.Id}, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002459 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002460 }
bseenivaa1622112025-12-11 18:24:02 +05302461 cancel()
Chaitrashree G S44124192019-08-07 20:21:36 -04002462 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002463 logger.Debugw(ctx, "olt-disabled", log.Fields{"device-id": device.Id})
Chaitrashree G S44124192019-08-07 20:21:36 -04002464 /* Discovered ONUs entries need to be cleared , since on device disable the child devices goes to
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002465 UNREACHABLE state which needs to be configured again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302466
2467 dh.discOnus = sync.Map{}
2468 dh.onus = sync.Map{}
2469
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002470 dh.lockDevice.RLock()
Akash Kankanala041a2122024-10-16 15:49:22 +05302471 // stopping the stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002472 if dh.isCollectorActive {
2473 dh.stopCollector <- true
2474 }
2475 dh.lockDevice.RUnlock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302476
Neha Sharma96b7bf22020-06-15 10:37:32 +00002477 go dh.notifyChildDevices(ctx, "unreachable")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002478 cloned := proto.Clone(device).(*voltha.Device)
Akash Kankanala041a2122024-10-16 15:49:22 +05302479 // Update device Admin state
Thomas Lee S985938d2020-05-04 11:40:41 +05302480 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04002481
kdarapu1afeceb2020-02-12 01:38:09 -05002482 // 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 -04002483 if err := dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002484 DeviceId: cloned.Id,
2485 PortTypeFilter: ^uint32(1 << voltha.Port_PON_OLT),
2486 OperStatus: voltha.OperStatus_UNKNOWN,
2487 }); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002488 return olterrors.NewErrAdapter("ports-state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002489 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002490 logger.Debugw(ctx, "disable-device-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002491 return nil
2492}
2493
Neha Sharma96b7bf22020-06-15 10:37:32 +00002494func (dh *DeviceHandler) notifyChildDevices(ctx context.Context, state string) {
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002495 // Update onu state as unreachable in onu adapter
2496 onuInd := oop.OnuIndication{}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302497 onuInd.OperState = state
khenaidoo106c61a2021-08-11 18:05:46 -04002498
Akash Kankanala041a2122024-10-16 15:49:22 +05302499 // get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04002500 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002501 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002502 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 -04002503 }
2504 if onuDevices != nil {
2505 for _, onuDevice := range onuDevices.Items {
khenaidoodc2116e2021-10-19 17:33:19 -04002506 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002507 DeviceId: onuDevice.Id,
2508 OnuIndication: &onuInd,
2509 })
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002510 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002511 logger.Errorw(ctx, "failed-to-send-inter-adapter-message", log.Fields{"OnuInd": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002512 "From Adapter": dh.openOLT.config.AdapterEndpoint, "DeviceType": onuDevice.Type, "device-id": onuDevice.Id})
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002513 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002514 }
2515 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002516}
2517
Mahir Gunyela2e68702022-12-07 00:00:42 -08002518// ReenableDevice re-enables the olt device after disable
2519// It marks the following for the given device:
2520// Device-Handler Admin-State : up
2521// Device Port-State: ACTIVE
2522// Device Oper-State: ACTIVE
Neha Sharma96b7bf22020-06-15 10:37:32 +00002523func (dh *DeviceHandler) ReenableDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302524 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302525 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2526 if _, err := dh.Client.ReenableOlt(subCtx, new(oop.Empty)); err != nil {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302527 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
bseenivaa1622112025-12-11 18:24:02 +05302528 cancel()
nikesh.krishnane363ace2023-02-28 03:12:38 +05302529 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, err)
2530 }
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302531 }
bseenivaa1622112025-12-11 18:24:02 +05302532 cancel()
nikesh.krishnane363ace2023-02-28 03:12:38 +05302533 } else {
2534 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, errors.New("nil device client"))
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302535 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002536 logger.Debug(ctx, "olt-reenabled")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002537
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002538 // Update the all ports state on that device to enable
khenaidoo106c61a2021-08-11 18:05:46 -04002539 ports, err := dh.listDevicePortsFromCore(ctx, device.Id)
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002540 var retError error
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002541 if err != nil {
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002542 retError = olterrors.NewErrAdapter("list-ports-failed", log.Fields{"device-id": device.Id}, err)
2543 } else {
2544 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
2545 retError = olterrors.NewErrAdapter("port-status-update-failed-after-olt-reenable", log.Fields{"device": device}, err)
2546 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002547 }
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002548 if retError == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05302549 // Update the device oper status as ACTIVE
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002550 device.OperStatus = voltha.OperStatus_ACTIVE
2551 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05302552 // Update the device oper status as FAILED
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002553 device.OperStatus = voltha.OperStatus_FAILED
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002554 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002555 dh.device = device
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002556
khenaidoodc2116e2021-10-19 17:33:19 -04002557 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002558 DeviceId: device.Id,
2559 OperStatus: device.OperStatus,
2560 ConnStatus: device.ConnectStatus,
2561 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302562 return olterrors.NewErrAdapter("state-update-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002563 "device-id": device.Id,
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002564 "connect-status": device.ConnectStatus,
2565 "oper-status": device.OperStatus}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002566 }
kesavand39e0aa32020-01-28 20:58:50 -05002567
Neha Sharma96b7bf22020-06-15 10:37:32 +00002568 logger.Debugw(ctx, "reenabledevice-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002569
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002570 return retError
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002571}
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002572
npujarec5762e2020-01-01 14:08:48 +05302573func (dh *DeviceHandler) clearUNIData(ctx context.Context, onu *rsrcMgr.OnuGemInfo) error {
Devmalya Paul495b94a2019-08-27 19:42:00 -04002574 var uniID uint32
2575 var err error
Gustavo Silva41af9122022-10-11 11:05:13 -03002576 var errs []error
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302577 for _, port := range onu.UniPorts {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002578 uniID = plt.UniIDFromPortNum(port)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002579 logger.Debugw(ctx, "clearing-resource-data-for-uni-port", log.Fields{"port": port, "uni-id": uniID})
A R Karthick1f85b802019-10-11 05:06:05 +00002580 /* Delete tech-profile instance from the KV store */
Mahir Gunyela2e68702022-12-07 00:00:42 -08002581 if dh.flowMgr == nil || dh.flowMgr[onu.IntfID] == nil {
2582 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu-no-flowmng", log.Fields{"onu-id": onu.OnuID})
2583 } else {
2584 if err = dh.flowMgr[onu.IntfID].DeleteTechProfileInstances(ctx, onu.IntfID, onu.OnuID, uniID); err != nil {
2585 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002586 errs = append(errs, err)
Mahir Gunyela2e68702022-12-07 00:00:42 -08002587 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002588 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002589 logger.Debugw(ctx, "deleted-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002590 tpIDList := dh.resourceMgr[onu.IntfID].GetTechProfileIDForOnu(ctx, onu.OnuID, uniID)
Gamze Abakafee36392019-10-03 11:17:24 +00002591 for _, tpID := range tpIDList {
yasin saplibddc2d72022-02-08 13:10:17 +00002592 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "upstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002593 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002594 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002595 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002596 logger.Debugw(ctx, "removed-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002597 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "downstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002598 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002599 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002600 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002601 logger.Debugw(ctx, "removed-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302602 }
yasin saplibddc2d72022-02-08 13:10:17 +00002603 dh.resourceMgr[onu.IntfID].FreePONResourcesForONU(ctx, onu.OnuID, uniID)
2604 if err = dh.resourceMgr[onu.IntfID].RemoveTechProfileIDsForOnu(ctx, onu.OnuID, uniID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002605 logger.Debugw(ctx, "failed-to-remove-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002606 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302607 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002608 logger.Debugw(ctx, "removed-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002609 if err = dh.resourceMgr[onu.IntfID].DeletePacketInGemPortForOnu(ctx, onu.OnuID, port); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002610 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 -03002611 errs = append(errs, err)
A R Karthick1f85b802019-10-11 05:06:05 +00002612 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002613 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002614 if len(errs) > 0 {
2615 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-clear-uni-data, errors:%v",
2616 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2617 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002618 return nil
2619}
2620
Devmalya Paul495b94a2019-08-27 19:42:00 -04002621// 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 +05302622func (dh *DeviceHandler) DeleteDevice(ctx context.Context, device *voltha.Device) error {
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002623 logger.Debugw(ctx, "function-entry-delete-device", log.Fields{"device-id": dh.device.Id})
Devmalya Paul495b94a2019-08-27 19:42:00 -04002624 /* Clear the KV store data associated with the all the UNI ports
2625 This clears up flow data and also resource map data for various
2626 other pon resources like alloc_id and gemport_id
2627 */
Girish Gowdra950326e2021-11-05 12:43:24 -07002628
Abhay Kumarb87ac882025-10-30 09:55:07 +00002629 if dh.getDeviceDeletionInProgressFlag() {
2630 logger.Errorw(ctx, "cannot complete operation as device deletion is in progress", log.Fields{"device-id": dh.device.Id})
2631 return olterrors.NewErrAdapter(fmt.Errorf("cannot complete operation as device deletion is in progress").Error(), log.Fields{"device-id": dh.device.Id}, nil)
2632 }
2633
Girish Gowdra950326e2021-11-05 12:43:24 -07002634 dh.setDeviceDeletionInProgressFlag(true)
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002635 dh.StopAllFlowRoutines(ctx)
Girish Gowdra950326e2021-11-05 12:43:24 -07002636
Himani Chawla49a5d562020-11-25 11:53:44 +05302637 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002638 // Stop the Stats collector
2639 if dh.isCollectorActive {
2640 dh.stopCollector <- true
2641 }
2642 // stop the heartbeat check routine
2643 if dh.isHeartbeatCheckActive {
2644 dh.stopHeartbeatCheck <- true
2645 }
Himani Chawla49a5d562020-11-25 11:53:44 +05302646 // Stop the read indication only if it the routine is active
2647 if dh.isReadIndicationRoutineActive {
2648 dh.stopIndications <- true
2649 }
2650 dh.lockDevice.RUnlock()
Akash Soni5c76e272024-01-15 04:09:24 +05302651
2652 err := dh.cleanupDeviceResources(ctx)
2653 if err != nil {
2654 logger.Errorw(ctx, "could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id, "err": err})
balaji.nagarajan2e572c42026-01-27 15:09:39 +05302655 dh.setDeviceDeletionInProgressFlag(false)
2656 return status.Error(codes.Internal, olterrors.NewErrAdapter("could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id}, err).Error())
Akash Soni5c76e272024-01-15 04:09:24 +05302657 } else {
2658 logger.Debugw(ctx, "successfully-removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
2659 }
2660
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002661 dh.removeOnuIndicationChannels(ctx)
Akash Kankanala041a2122024-10-16 15:49:22 +05302662 // Reset the state
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002663 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302664 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2665 if _, err = dh.Client.Reboot(subCtx, new(oop.Empty)); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002666 go func() {
2667 failureReason := fmt.Sprintf("Failed to reboot during device delete request with error: %s", err.Error())
Akash Kankanala041a2122024-10-16 15:49:22 +05302668 if err1 := dh.eventMgr.oltRebootFailedEvent(ctx, dh.device.Id, failureReason, time.Now().Unix()); err1 != nil {
2669 logger.Errorw(ctx, "on-olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err1})
Gustavo Silva41af9122022-10-11 11:05:13 -03002670 }
2671 }()
2672 logger.Errorw(ctx, "olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002673 }
bseenivaa1622112025-12-11 18:24:02 +05302674 cancel()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002675 }
Girish Gowdrab1caa442020-10-19 12:24:39 -07002676 // There is no need to update the core about operation status and connection status of the OLT.
2677 // The OLT is getting deleted anyway and the core might have already cleared the OLT device from its DB.
2678 // So any attempt to update the operation status and connection status of the OLT will result in core throwing an error back,
2679 // because the device does not exist in DB.
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002680
khenaidoo7eb2d672021-10-22 19:08:50 -04002681 // Stop the adapter grpc clients for that parent device
2682 dh.deleteAdapterClients(ctx)
Gustavo Silva41af9122022-10-11 11:05:13 -03002683 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002684}
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002685
2686// StopAllFlowRoutines stops all flow routines
2687func (dh *DeviceHandler) StopAllFlowRoutines(ctx context.Context) {
2688 var wg sync.WaitGroup
2689 wg.Add(1) // for the mcast routine below to finish
2690 go dh.StopAllMcastHandlerRoutines(ctx, &wg)
2691 for _, flMgr := range dh.flowMgr {
2692 if flMgr != nil {
2693 wg.Add(1) // for the flow handler routine below to finish
2694 go flMgr.StopAllFlowHandlerRoutines(ctx, &wg)
2695 }
2696 }
2697 if !dh.waitForTimeoutOrCompletion(&wg, time.Second*30) {
2698 logger.Warnw(ctx, "timed out waiting for stopping flow and group handlers", log.Fields{"deviceID": dh.device.Id})
2699 } else {
2700 logger.Infow(ctx, "all flow and group handlers shutdown gracefully", log.Fields{"deviceID": dh.device.Id})
2701 }
2702}
2703
Gustavo Silva41af9122022-10-11 11:05:13 -03002704func (dh *DeviceHandler) cleanupDeviceResources(ctx context.Context) error {
2705 var errs []error
Abhay Kumarb87ac882025-10-30 09:55:07 +00002706 if dh.resourceMgr != nil && dh.totalPonPorts > 0 {
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302707 var ponPort uint32
Girish Gowdra9602eb42020-09-09 15:50:39 -07002708 for ponPort = 0; ponPort < dh.totalPonPorts; ponPort++ {
yasin sapli9e4c5092022-02-01 13:52:33 +00002709 onuGemData := dh.resourceMgr[ponPort].GetOnuGemInfoList(ctx)
Andrey Pozolotin32b36562021-06-02 10:23:26 +03002710 for i, onu := range onuGemData {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002711 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
Gustavo Silva41af9122022-10-11 11:05:13 -03002712 if err := dh.clearUNIData(ctx, &onuGemData[i]); err != nil {
2713 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302714 }
2715 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002716 if err := dh.resourceMgr[ponPort].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2717 errs = append(errs, err)
2718 }
2719 if err := dh.resourceMgr[ponPort].DeleteAllOnuGemInfoForIntf(ctx); err != nil {
2720 errs = append(errs, err)
2721 }
2722 if err := dh.resourceMgr[ponPort].DeleteMcastQueueForIntf(ctx); err != nil {
2723 errs = append(errs, err)
2724 }
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002725 if err := dh.resourceMgr[ponPort].Delete(ctx, ponPort); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002726 errs = append(errs, err)
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002727 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002728 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002729 }
2730 // Clean up NNI manager's data
2731 if err := dh.resourceMgr[dh.totalPonPorts].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2732 errs = append(errs, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002733 }
A R Karthick1f85b802019-10-11 05:06:05 +00002734
balaji.nagarajan2e572c42026-01-27 15:09:39 +05302735 if len(errs) == 0 {
2736 // Take one final sweep at cleaning up KV store for the OLT device
2737 // Clean everything at <base-path-prefix>/openolt/<device-id>
2738 if err := dh.kvStore.DeleteWithPrefix(ctx, ""); err != nil {
2739 errs = append(errs, err)
2740 }
2741 logger.Debugw(ctx, "lockDevice for KVStore close client", log.Fields{"deviceID": dh.device.Id})
2742 dh.CloseKVClient(ctx)
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002743 }
2744
Devmalya Paul495b94a2019-08-27 19:42:00 -04002745 /*Delete ONU map for the device*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302746 dh.onus.Range(func(key interface{}, value interface{}) bool {
2747 dh.onus.Delete(key)
2748 return true
2749 })
2750
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002751 /*Delete discovered ONU map for the device*/
2752 dh.discOnus.Range(func(key interface{}, value interface{}) bool {
2753 dh.discOnus.Delete(key)
2754 return true
2755 })
Gustavo Silva41af9122022-10-11 11:05:13 -03002756 if len(errs) > 0 {
2757 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-device-delete, errors:%v",
2758 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2759 }
2760 return nil
Devmalya Paul495b94a2019-08-27 19:42:00 -04002761}
2762
Mahir Gunyela2e68702022-12-07 00:00:42 -08002763// RebootDevice reboots the given device
Neha Sharma96b7bf22020-06-15 10:37:32 +00002764func (dh *DeviceHandler) RebootDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302765 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302766 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2767 defer cancel()
2768 if _, err := dh.Client.Reboot(subCtx, new(oop.Empty)); err != nil {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302769 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, err)
2770 }
2771 } else {
2772 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, errors.New("nil device client"))
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002773 }
nikesh.krishnane363ace2023-02-28 03:12:38 +05302774
Neha Sharma96b7bf22020-06-15 10:37:32 +00002775 logger.Debugw(ctx, "rebooted-device-successfully", log.Fields{"device-id": device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002776 return nil
2777}
2778
David K. Bainbridge794735f2020-02-11 21:01:37 -08002779func (dh *DeviceHandler) handlePacketIndication(ctx context.Context, packetIn *oop.PacketIndication) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002780 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002781 logger.Debugw(ctx, "received-packet-in", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002782 "packet-indication": *packetIn,
2783 "device-id": dh.device.Id,
2784 "packet": hex.EncodeToString(packetIn.Pkt),
2785 })
2786 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002787 if dh.flowMgr == nil || dh.flowMgr[packetIn.IntfId] == nil {
2788 return olterrors.NewErrNotFound("flow-manager", log.Fields{"intf-id": packetIn.IntfId, "packet": hex.EncodeToString(packetIn.Pkt)}, nil)
2789 }
Girish Gowdra9602eb42020-09-09 15:50:39 -07002790 logicalPortNum, err := dh.flowMgr[packetIn.IntfId].GetLogicalPortFromPacketIn(ctx, packetIn)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002791 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002792 return olterrors.NewErrNotFound("logical-port", log.Fields{"packet": hex.EncodeToString(packetIn.Pkt)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002793 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002794 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002795 logger.Debugw(ctx, "sending-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002796 "logical-port-num": logicalPortNum,
2797 "device-id": dh.device.Id,
2798 "packet": hex.EncodeToString(packetIn.Pkt),
2799 })
2800 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002801
khenaidoodc2116e2021-10-19 17:33:19 -04002802 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002803 DeviceId: dh.device.Id,
2804 Port: logicalPortNum,
2805 Packet: packetIn.Pkt,
2806 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302807 return olterrors.NewErrCommunication("send-packet-in", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002808 "destination": "core",
Thomas Lee S985938d2020-05-04 11:40:41 +05302809 "source": dh.device.Type,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002810 "device-id": dh.device.Id,
2811 "packet": hex.EncodeToString(packetIn.Pkt),
2812 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002813 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002814
Matteo Scandolo92186242020-06-12 10:54:18 -07002815 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002816 logger.Debugw(ctx, "success-sending-packet-in-to-core!", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002817 "packet": hex.EncodeToString(packetIn.Pkt),
2818 "device-id": dh.device.Id,
2819 })
2820 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002821 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002822}
2823
Mahir Gunyela2e68702022-12-07 00:00:42 -08002824// PacketOutNNI sends packet-out from VOLTHA to OLT on the NNI provided
2825func (dh *DeviceHandler) PacketOutNNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2826 nniIntfID, err := plt.IntfIDFromNniPortNum(ctx, uint32(egressPortNo))
2827 if err != nil {
2828 return olterrors.NewErrInvalidValue(log.Fields{
2829 "egress-nni-port": egressPortNo,
2830 "device-id": dh.device.Id,
2831 }, err)
2832 }
2833 uplinkPkt := oop.UplinkPacket{IntfId: nniIntfID, Pkt: packet.Data}
2834
2835 if logger.V(log.DebugLevel) {
2836 logger.Debugw(ctx, "sending-packet-to-nni", log.Fields{
2837 "uplink-pkt": uplinkPkt,
2838 "packet": hex.EncodeToString(packet.Data),
2839 "device-id": dh.device.Id,
2840 })
2841 }
2842
bseenivaa1622112025-12-11 18:24:02 +05302843 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2844 defer cancel()
2845 if _, err := dh.Client.UplinkPacketOut(subCtx, &uplinkPkt); err != nil {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002846 return olterrors.NewErrCommunication("packet-out-to-nni", log.Fields{
2847 "packet": hex.EncodeToString(packet.Data),
2848 "device-id": dh.device.Id,
2849 }, err)
2850 }
2851 return nil
2852}
2853
2854// PacketOutUNI sends packet-out from VOLTHA to OLT on the UNI provided
2855func (dh *DeviceHandler) PacketOutUNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2856 outerEthType := (uint16(packet.Data[12]) << 8) | uint16(packet.Data[13])
2857 innerEthType := (uint16(packet.Data[16]) << 8) | uint16(packet.Data[17])
2858 if outerEthType == 0x8942 || outerEthType == 0x88cc {
2859 // Do not packet-out lldp packets on uni port.
2860 // ONOS has no clue about uni/nni ports, it just packets out on all
2861 // available ports on the Logical Switch. It should not be interested
2862 // in the UNI links.
2863 logger.Debugw(ctx, "dropping-lldp-packet-out-on-uni", log.Fields{
2864 "device-id": dh.device.Id,
2865 })
2866 return nil
2867 }
2868 if outerEthType == 0x88a8 || outerEthType == 0x8100 {
2869 if innerEthType == 0x8100 {
2870 // q-in-q 802.1ad or 802.1q double tagged packet.
2871 // slice out the outer tag.
2872 packet.Data = append(packet.Data[:12], packet.Data[16:]...)
2873 if logger.V(log.DebugLevel) {
2874 logger.Debugw(ctx, "packet-now-single-tagged", log.Fields{
2875 "packet-data": hex.EncodeToString(packet.Data),
2876 "device-id": dh.device.Id,
2877 })
2878 }
2879 }
2880 }
2881 intfID := plt.IntfIDFromUniPortNum(uint32(egressPortNo))
2882 onuID := plt.OnuIDFromPortNum(uint32(egressPortNo))
2883 uniID := plt.UniIDFromPortNum(uint32(egressPortNo))
2884 var gemPortID uint32
2885 err := olterrors.NewErrNotFound("no-flow-manager-found-for-packet-out", log.Fields{"device-id": dh.device.Id}, nil).(error)
2886 if dh.flowMgr != nil && dh.flowMgr[intfID] != nil {
2887 gemPortID, err = dh.flowMgr[intfID].GetPacketOutGemPortID(ctx, intfID, onuID, uint32(egressPortNo), packet.Data)
2888 }
2889 if err != nil {
2890 // In this case the openolt agent will receive the gemPortID as 0.
2891 // The agent tries to retrieve the gemPortID in this case.
2892 // This may not always succeed at the agent and packetOut may fail.
2893 logger.Errorw(ctx, "failed-to-retrieve-gemport-id-for-packet-out", log.Fields{
2894 "intf-id": intfID,
2895 "onu-id": onuID,
2896 "uni-id": uniID,
2897 "packet": hex.EncodeToString(packet.Data),
2898 "device-id": dh.device.Id,
2899 "error": err,
2900 })
2901 }
2902
2903 onuPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, PortNo: uint32(egressPortNo), GemportId: gemPortID, Pkt: packet.Data}
2904 if logger.V(log.DebugLevel) {
2905 logger.Debugw(ctx, "sending-packet-to-onu", log.Fields{
2906 "egress-port-no": egressPortNo,
2907 "intf-id": intfID,
2908 "onu-id": onuID,
2909 "uni-id": uniID,
2910 "gem-port-id": gemPortID,
2911 "packet": hex.EncodeToString(packet.Data),
2912 "device-id": dh.device.Id,
2913 })
2914 }
2915
bseenivaa1622112025-12-11 18:24:02 +05302916 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2917 defer cancel()
2918 if _, err := dh.Client.OnuPacketOut(subCtx, &onuPkt); err != nil {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002919 return olterrors.NewErrCommunication("packet-out-send", log.Fields{
2920 "source": "adapter",
2921 "destination": "onu",
2922 "egress-port-number": egressPortNo,
2923 "intf-id": intfID,
2924 "oni-id": onuID,
2925 "uni-id": uniID,
2926 "gem-port-id": gemPortID,
2927 "packet": hex.EncodeToString(packet.Data),
2928 "device-id": dh.device.Id,
2929 }, err)
2930 }
2931 return nil
2932}
2933
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002934// PacketOut sends packet-out from VOLTHA to OLT on the egress port provided
khenaidoo106c61a2021-08-11 18:05:46 -04002935func (dh *DeviceHandler) PacketOut(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002936 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002937 logger.Debugw(ctx, "incoming-packet-out", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002938 "device-id": dh.device.Id,
2939 "egress-port-no": egressPortNo,
2940 "pkt-length": len(packet.Data),
2941 "packet": hex.EncodeToString(packet.Data),
2942 })
2943 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002944
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002945 egressPortType := plt.IntfIDToPortTypeName(uint32(egressPortNo))
Mahir Gunyela2e68702022-12-07 00:00:42 -08002946 var err error
mgouda86543582025-10-29 20:58:16 +05302947 switch egressPortType {
2948 case voltha.Port_ETHERNET_UNI:
Mahir Gunyela2e68702022-12-07 00:00:42 -08002949 err = dh.PacketOutUNI(ctx, egressPortNo, packet)
mgouda86543582025-10-29 20:58:16 +05302950 case voltha.Port_ETHERNET_NNI:
Mahir Gunyela2e68702022-12-07 00:00:42 -08002951 err = dh.PacketOutNNI(ctx, egressPortNo, packet)
mgouda86543582025-10-29 20:58:16 +05302952 default:
Neha Sharma96b7bf22020-06-15 10:37:32 +00002953 logger.Warnw(ctx, "packet-out-to-this-interface-type-not-implemented", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302954 "egress-port-no": egressPortNo,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002955 "egressPortType": egressPortType,
2956 "packet": hex.EncodeToString(packet.Data),
Thomas Lee S985938d2020-05-04 11:40:41 +05302957 "device-id": dh.device.Id,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002958 })
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002959 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002960 return err
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002961}
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002962
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002963func (dh *DeviceHandler) formOnuKey(intfID, onuID uint32) string {
2964 return "" + strconv.Itoa(int(intfID)) + "." + strconv.Itoa(int(onuID))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002965}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302966
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002967func startHeartbeatCheck(ctx context.Context, dh *DeviceHandler) {
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002968 defer func() {
2969 dh.lockDevice.Lock()
2970 dh.isHeartbeatCheckActive = false
2971 dh.lockDevice.Unlock()
2972 }()
2973
2974 dh.lockDevice.Lock()
2975 dh.isHeartbeatCheckActive = true
2976 dh.lockDevice.Unlock()
2977
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302978 // start the heartbeat check towards the OLT.
2979 var timerCheck *time.Timer
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302980 dh.heartbeatSignature = dh.getHeartbeatSignature(ctx)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302981
2982 for {
2983 heartbeatTimer := time.NewTimer(dh.openOLT.HeartbeatCheckInterval)
2984 select {
2985 case <-heartbeatTimer.C:
Neha Sharma8f4e4322020-08-06 10:51:53 +00002986 ctxWithTimeout, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.openOLT.GrpcTimeoutInterval)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002987 if heartBeat, err := dh.Client.HeartbeatCheck(ctxWithTimeout, new(oop.Empty)); err != nil {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002988 logger.Warnw(ctx, "heartbeat-failed", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302989 if timerCheck == nil {
2990 // start a after func, when expired will update the state to the core
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002991 timerCheck = time.AfterFunc(dh.openOLT.HeartbeatFailReportInterval, func() { dh.updateStateUnreachable(ctx) })
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302992 }
2993 } else {
2994 if timerCheck != nil {
2995 if timerCheck.Stop() {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002996 logger.Debugw(ctx, "got-heartbeat-within-timeout", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302997 }
2998 timerCheck = nil
2999 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303000 if dh.heartbeatSignature == 0 || dh.heartbeatSignature == heartBeat.HeartbeatSignature {
3001 if dh.heartbeatSignature == 0 {
3002 // First time the signature will be 0, update the signture to DB when not found.
3003 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
3004 dh.heartbeatSignature = heartBeat.HeartbeatSignature
3005 }
3006 logger.Infow(ctx, "heartbeat signature", log.Fields{"sign": dh.heartbeatSignature})
3007
3008 dh.lockDevice.RLock()
3009 // Stop the read indication only if it the routine is active
3010 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3011 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3012 // on next execution of the readIndication routine.
3013 if !dh.isReadIndicationRoutineActive {
3014 // Start reading indications
3015 go func() {
3016 if err = dh.readIndications(ctx); err != nil {
3017 _ = olterrors.NewErrAdapter("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
3018 }
3019 }()
3020 }
3021 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303022 } else {
3023 logger.Warn(ctx, "Heartbeat signature changed, OLT is rebooted. Cleaningup resources.")
balaji.nagarajan2e572c42026-01-27 15:09:39 +05303024 dh.updateStateRebooted(ctx)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303025 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
3026 dh.heartbeatSignature = heartBeat.HeartbeatSignature
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303027 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303028 }
3029 cancel()
3030 case <-dh.stopHeartbeatCheck:
Matteo Scandolo861e06e2021-05-26 11:51:46 -07003031 logger.Debugw(ctx, "stopping-heartbeat-check", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303032 return
3033 }
3034 }
3035}
3036
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003037func (dh *DeviceHandler) updateStateUnreachable(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -04003038 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003039 if err != nil || device == nil {
Girish Gowdrab1caa442020-10-19 12:24:39 -07003040 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
3041 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
3042 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
3043 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
3044 // cleanup in the adapter was already done during DeleteDevice API handler routine.
Kent Hagermane6ff1012020-07-14 15:07:53 -04003045 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
Girish Gowdrab1caa442020-10-19 12:24:39 -07003046 // Immediately return, otherwise accessing a null 'device' struct would cause panic
3047 return
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003048 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303049
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303050 logger.Warnw(ctx, "update-state-unreachable", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
Matteo Scandolo861e06e2021-05-26 11:51:46 -07003051 "admin-state": device.AdminState, "oper-status": device.OperStatus})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003052 if device.ConnectStatus == voltha.ConnectStatus_REACHABLE {
khenaidoodc2116e2021-10-19 17:33:19 -04003053 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04003054 DeviceId: dh.device.Id,
3055 OperStatus: voltha.OperStatus_UNKNOWN,
3056 ConnStatus: voltha.ConnectStatus_UNREACHABLE,
3057 }); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04003058 _ = 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 -04003059 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303060 /*
3061 if err = dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
3062 DeviceId: dh.device.Id,
3063 PortTypeFilter: 0,
3064 OperStatus: voltha.OperStatus_UNKNOWN,
3065 }); err != nil {
3066 _ = olterrors.NewErrAdapter("port-update-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
3067 }
3068 */
Gamze Abaka07868a52020-12-17 14:19:28 +00003069
Akash Kankanala041a2122024-10-16 15:49:22 +05303070 // raise olt communication failure event
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07003071 raisedTs := time.Now().Unix()
khenaidoo106c61a2021-08-11 18:05:46 -04003072 cloned := proto.Clone(device).(*voltha.Device)
3073 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
3074 cloned.OperStatus = voltha.OperStatus_UNKNOWN
3075 dh.device = cloned // update local copy of the device
3076 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
Gamze Abaka07868a52020-12-17 14:19:28 +00003077
Girish Gowdra3ab6d212020-03-24 17:33:15 -07003078 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003079 // Stop the Stats collector
3080 if dh.isCollectorActive {
3081 dh.stopCollector <- true
3082 }
3083 // stop the heartbeat check routine
3084 if dh.isHeartbeatCheckActive {
3085 dh.stopHeartbeatCheck <- true
3086 }
Girish Gowdra3ab6d212020-03-24 17:33:15 -07003087 // Stop the read indication only if it the routine is active
3088 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3089 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3090 // on next execution of the readIndication routine.
3091 if dh.isReadIndicationRoutineActive {
3092 dh.stopIndications <- true
3093 }
3094 dh.lockDevice.RUnlock()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003095 dh.transitionMap.Handle(ctx, DeviceInit)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303096 }
3097}
kesavand39e0aa32020-01-28 20:58:50 -05003098
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303099func (dh *DeviceHandler) updateStateRebooted(ctx context.Context) {
3100 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
3101 if err != nil || device == nil {
3102 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
3103 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
3104 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
3105 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
3106 // cleanup in the adapter was already done during DeleteDevice API handler routine.
3107 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
3108 // Immediately return, otherwise accessing a null 'device' struct would cause panic
3109 return
3110 }
Akash Kankanala041a2122024-10-16 15:49:22 +05303111 // Starting the cleanup process
Mahir Gunyel701df862023-09-07 16:16:04 -07003112 dh.setDeviceDeletionInProgressFlag(true)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303113
3114 logger.Warnw(ctx, "update-state-rebooted", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
3115 "admin-state": device.AdminState, "oper-status": device.OperStatus, "conn-status": voltha.ConnectStatus_UNREACHABLE})
bseenivad1c984b2025-01-09 12:54:44 +05303116 // First, stop the read indication and heartbeat check routines to prevent any delay
3117 // in cleanup, which could cause the heartbeat routine to restart the read indication.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303118 dh.lockDevice.RLock()
3119 // Stop the read indication only if it the routine is active
3120 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3121 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3122 // on next execution of the readIndication routine.
3123 if dh.isReadIndicationRoutineActive {
3124 dh.stopIndications <- true
3125 }
3126 dh.lockDevice.RUnlock()
3127
bseenivad1c984b2025-01-09 12:54:44 +05303128 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
3129 DeviceId: dh.device.Id,
3130 OperStatus: voltha.OperStatus_REBOOTED,
3131 ConnStatus: voltha.ConnectStatus_REACHABLE,
3132 }); err != nil {
3133 _ = olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
3134 }
3135
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303136 //raise olt communication failure event
3137 raisedTs := time.Now().Unix()
3138 cloned := proto.Clone(device).(*voltha.Device)
3139 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
3140 cloned.OperStatus = voltha.OperStatus_UNKNOWN
3141 dh.device = cloned // update local copy of the device
3142 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
3143
Gustavo Silva41af9122022-10-11 11:05:13 -03003144 if err := dh.cleanupDeviceResources(ctx); err != nil {
3145 logger.Errorw(ctx, "failure-in-cleanup-device-resources", log.Fields{"device-id": dh.device.Id, "err": err})
3146 } else {
3147 logger.Debugw(ctx, "removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
3148 }
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003149
3150 dh.lockDevice.RLock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303151 // Stop the Stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003152 if dh.isCollectorActive {
3153 dh.stopCollector <- true
3154 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303155 // stop the heartbeat check routine
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003156 if dh.isHeartbeatCheckActive {
3157 dh.stopHeartbeatCheck <- true
3158 }
3159 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303160
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00003161 dh.StopAllFlowRoutines(ctx)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303162
Akash Kankanala041a2122024-10-16 15:49:22 +05303163 // reset adapter reconcile flag
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303164 dh.adapterPreviouslyConnected = false
3165 for {
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303166 childDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
3167 if err != nil || childDevices == nil {
3168 logger.Errorw(ctx, "Failed to get child devices from core", log.Fields{"deviceID": dh.device.Id})
3169 continue
3170 }
3171 if len(childDevices.Items) == 0 {
3172 logger.Infow(ctx, "All childDevices cleared from core, proceed with device init", log.Fields{"deviceID": dh.device.Id})
3173 break
3174 } else {
3175 logger.Warn(ctx, "Not all child devices are cleared, continuing to wait")
3176 time.Sleep(5 * time.Second)
3177 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303178 }
Akash Kankanala041a2122024-10-16 15:49:22 +05303179 // Cleanup completed , reset the flag
Mahir Gunyel701df862023-09-07 16:16:04 -07003180 dh.setDeviceDeletionInProgressFlag(false)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303181 logger.Infow(ctx, "cleanup complete after reboot , moving to init", log.Fields{"deviceID": device.Id})
3182 dh.transitionMap.Handle(ctx, DeviceInit)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303183}
3184
balaji.nagarajan68f56e82025-07-04 15:16:01 +05303185// EnableOnuSerialNumber to enable onu serial number
3186func (dh *DeviceHandler) EnableOnuSerialNumber(ctx context.Context, device *voltha.OnuSerialNumberOnOLTPon) error {
3187 logger.Debugw(ctx, "enable-onu-serial-number", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber, "port": device.Port.PortNo})
3188 onuSerialNumber := device.SerialNumber
3189
3190 // fetch interfaceid from PortNo
3191 ponID := plt.PortNoToIntfID(device.Port.GetPortNo(), voltha.Port_PON_OLT)
3192
3193 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3194 if err != nil {
3195 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3196 log.Fields{
3197 "devicer-id": dh.device.Id,
3198 "serial-number": onuSerialNumber}, err).Log()
3199 }
3200
3201 onuIntf := &oop.InterfaceOnuSerialNumber{
3202 IntfId: ponID,
3203 OnuSerialNumber: sn,
3204 }
3205 _, err = dh.Client.EnableOnuSerialNumber(ctx, onuIntf)
3206
3207 if err != nil {
3208 logger.Errorw(ctx, "failed to enable onu serial number", log.Fields{"onudev": onuSerialNumber, "error": err})
3209 return olterrors.NewErrAdapter("onu-serial-number-enable-failed", log.Fields{
3210 "device-id": dh.device.Id,
3211 "onu-serial-number": onuSerialNumber}, err)
3212 }
3213 return nil
3214}
3215
3216// DisableOnuSerialNumber to disable onu serial number
3217func (dh *DeviceHandler) DisableOnuSerialNumber(ctx context.Context, device *voltha.OnuSerialNumberOnOLTPon) error {
3218 logger.Debugw(ctx, "disable-onu-serial-number", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber, "port": device.Port.PortNo})
3219 onuSerialNumber := device.SerialNumber
3220 ponID := plt.PortNoToIntfID(device.Port.GetPortNo(), voltha.Port_PON_OLT)
3221 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3222 if err != nil {
3223 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3224 log.Fields{
3225 "devicer-id": dh.device.Id,
3226 "serial-number": onuSerialNumber}, err).Log()
3227 }
3228
3229 onuIntf := &oop.InterfaceOnuSerialNumber{
3230 OnuSerialNumber: sn,
3231 IntfId: ponID,
3232 }
3233 _, err = dh.Client.DisableOnuSerialNumber(ctx, onuIntf)
3234
3235 if err != nil {
3236 logger.Errorw(ctx, "failed to disable onu serial number", log.Fields{"onudev": onuSerialNumber, "error": err})
3237 return olterrors.NewErrAdapter("onu-serial-number-disable-failed", log.Fields{
3238 "device-id": dh.device.Id,
3239 "onu-serial-number": onuSerialNumber}, err)
3240 }
3241 return nil
3242}
3243
3244// EnableOnu to enable onu
3245func (dh *DeviceHandler) EnableOnu(ctx context.Context, device *voltha.Device) error {
3246 logger.Debugw(ctx, "enable-onu", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber})
3247 onuSerialNumber := device.SerialNumber
3248 InCacheOnuDev := dh.getChildDevice(ctx, onuSerialNumber, dh.device.ParentPortNo)
3249 if InCacheOnuDev == nil {
3250 logger.Errorw(ctx, "failed to get child device from cache", log.Fields{"onudev": onuSerialNumber})
3251 return olterrors.NewErrAdapter("failed to get child device from cache", log.Fields{
3252 "device-id": dh.device.Id,
3253 "onu-serial-number": onuSerialNumber}, nil)
3254 }
3255 logger.Debugw(ctx, "successfully-received-child-device-from-cache", log.Fields{"child-device-intfid": InCacheOnuDev.intfID, "child-device-sn": InCacheOnuDev.serialNumber, "child-onuid": InCacheOnuDev.onuID})
3256
3257 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3258 if err != nil {
3259 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3260 log.Fields{
3261 "device-id": dh.device.Id,
3262 "serial-number": onuSerialNumber}, err).Log()
3263 }
3264
3265 onuIntf := &oop.InterfaceOnuSerialNumber{
3266 OnuSerialNumber: sn,
3267 IntfId: InCacheOnuDev.intfID,
3268 }
3269 onuIntfReq := &oop.InterfaceOnuSerialNumberOnuId{
3270 OnuId: InCacheOnuDev.onuID,
3271 IntfIdSerialNum: onuIntf,
3272 }
3273 _, err = dh.Client.EnableOnu(ctx, onuIntfReq)
3274
3275 if err != nil {
3276 logger.Errorw(ctx, "failed to enable onu ", log.Fields{"onudev": onuSerialNumber, "error": err})
3277 return olterrors.NewErrAdapter("onu-enable-failed", log.Fields{
3278 "olt-device-id": dh.device.Id,
3279 "onu-serial-number": onuSerialNumber}, err)
3280 }
3281 return nil
3282}
3283
3284// DisableOnu to disable onu
3285func (dh *DeviceHandler) DisableOnu(ctx context.Context, device *voltha.Device) error {
3286 logger.Debugw(ctx, "disable-onu", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber})
3287 onuSerialNumber := device.SerialNumber
3288 InCacheOnuDev := dh.getChildDevice(ctx, onuSerialNumber, dh.device.ParentPortNo)
3289 if InCacheOnuDev == nil {
3290 logger.Errorw(ctx, "failed to get child device from cache", log.Fields{"onudev": onuSerialNumber})
3291 return olterrors.NewErrAdapter("failed to get child device from cache", log.Fields{
3292 "device-id": dh.device.Id,
3293 "onu-serial-number": onuSerialNumber}, nil)
3294 }
3295 logger.Debugw(ctx, "successfully-received-child-device-from-cache", log.Fields{"child-device-intfid": InCacheOnuDev.intfID, "child-device-sn": InCacheOnuDev.serialNumber, "child-onuid": InCacheOnuDev.onuID})
3296
3297 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3298 if err != nil {
3299 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3300 log.Fields{
3301 "device-id": dh.device.Id,
3302 "serial-number": onuSerialNumber}, err).Log()
3303 }
3304
3305 onuIntf := &oop.InterfaceOnuSerialNumber{
3306 OnuSerialNumber: sn,
3307 IntfId: InCacheOnuDev.intfID,
3308 }
3309 onuIntfReq := &oop.InterfaceOnuSerialNumberOnuId{
3310 OnuId: InCacheOnuDev.onuID,
3311 IntfIdSerialNum: onuIntf,
3312 }
3313 _, err = dh.Client.DisableOnu(ctx, onuIntfReq)
3314
3315 if err != nil {
3316 logger.Errorw(ctx, "failed to disable onu ", log.Fields{"onudev": onuSerialNumber, "error": err})
3317 return olterrors.NewErrAdapter("onu-disable-failed", log.Fields{
3318 "olt-device-id": dh.device.Id,
3319 "onu-serial-number": onuSerialNumber}, err)
3320 }
3321 return nil
3322}
3323
kesavand39e0aa32020-01-28 20:58:50 -05003324// EnablePort to enable Pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00003325func (dh *DeviceHandler) EnablePort(ctx context.Context, port *voltha.Port) error {
3326 logger.Debugw(ctx, "enable-port", log.Fields{"Device": dh.device, "port": port})
3327 return dh.modifyPhyPort(ctx, port, true)
kesavand39e0aa32020-01-28 20:58:50 -05003328}
3329
3330// DisablePort to disable pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00003331func (dh *DeviceHandler) DisablePort(ctx context.Context, port *voltha.Port) error {
3332 logger.Debugw(ctx, "disable-port", log.Fields{"Device": dh.device, "port": port})
3333 return dh.modifyPhyPort(ctx, port, false)
kesavand39e0aa32020-01-28 20:58:50 -05003334}
3335
Mahir Gunyela2e68702022-12-07 00:00:42 -08003336// 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 +00003337func (dh *DeviceHandler) modifyPhyPort(ctx context.Context, port *voltha.Port, enablePort bool) error {
3338 logger.Infow(ctx, "modifyPhyPort", log.Fields{"port": port, "Enable": enablePort, "device-id": dh.device.Id})
kesavand39e0aa32020-01-28 20:58:50 -05003339 if port.GetType() == voltha.Port_ETHERNET_NNI {
3340 // Bug is opened for VOL-2505 to support NNI disable feature.
Neha Sharma96b7bf22020-06-15 10:37:32 +00003341 logger.Infow(ctx, "voltha-supports-single-nni-hence-disable-of-nni-not-allowed",
Shrey Baid807a2a02020-04-09 12:52:45 +05303342 log.Fields{"device": dh.device, "port": port})
Thomas Lee S94109f12020-03-03 16:39:29 +05303343 return olterrors.NewErrAdapter("illegal-port-request", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003344 "port-type": port.GetType,
Girish Kumarf26e4882020-03-05 06:49:10 +00003345 "enable-state": enablePort}, nil)
kesavand39e0aa32020-01-28 20:58:50 -05003346 }
3347 // fetch interfaceid from PortNo
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003348 ponID := plt.PortNoToIntfID(port.GetPortNo(), voltha.Port_PON_OLT)
kesavand39e0aa32020-01-28 20:58:50 -05003349 ponIntf := &oop.Interface{IntfId: ponID}
3350 var operStatus voltha.OperStatus_Types
bseenivaa1622112025-12-11 18:24:02 +05303351 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
kesavand39e0aa32020-01-28 20:58:50 -05003352 if enablePort {
3353 operStatus = voltha.OperStatus_ACTIVE
bseenivaa1622112025-12-11 18:24:02 +05303354 out, err := dh.Client.EnablePonIf(subCtx, ponIntf)
3355 cancel()
kesavand39e0aa32020-01-28 20:58:50 -05003356 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303357 return olterrors.NewErrAdapter("pon-port-enable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003358 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003359 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003360 }
3361 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05003362 dh.activePorts.Store(ponID, true)
Neha Sharma96b7bf22020-06-15 10:37:32 +00003363 logger.Infow(ctx, "enabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05003364 } else {
3365 operStatus = voltha.OperStatus_UNKNOWN
bseenivaa1622112025-12-11 18:24:02 +05303366 out, err := dh.Client.DisablePonIf(subCtx, ponIntf)
3367 cancel()
kesavand39e0aa32020-01-28 20:58:50 -05003368 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303369 return olterrors.NewErrAdapter("pon-port-disable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003370 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003371 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003372 }
3373 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05003374 dh.activePorts.Store(ponID, false)
Neha Sharma96b7bf22020-06-15 10:37:32 +00003375 logger.Infow(ctx, "disabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05003376 }
khenaidoodc2116e2021-10-19 17:33:19 -04003377 if err := dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -04003378 DeviceId: dh.device.Id,
3379 PortType: voltha.Port_PON_OLT,
3380 PortNo: port.PortNo,
3381 OperStatus: operStatus,
3382 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303383 return olterrors.NewErrAdapter("port-state-update-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303384 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003385 "port": port.PortNo}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003386 }
3387 return nil
3388}
3389
Mahir Gunyela2e68702022-12-07 00:00:42 -08003390// disableAdminDownPorts disables the ports, if the corresponding port Adminstate is disabled on reboot and Renable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003391func (dh *DeviceHandler) disableAdminDownPorts(ctx context.Context, ports []*voltha.Port) error {
kesavand39e0aa32020-01-28 20:58:50 -05003392 // Disable the port and update the oper_port_status to core
3393 // if the Admin state of the port is disabled on reboot and re-enable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003394 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003395 if port.AdminState == common.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00003396 if err := dh.DisablePort(ctx, port); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303397 return olterrors.NewErrAdapter("port-disable-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303398 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003399 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003400 }
3401 }
3402 }
3403 return nil
3404}
3405
Mahir Gunyela2e68702022-12-07 00:00:42 -08003406// populateActivePorts to populate activePorts map
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003407func (dh *DeviceHandler) populateActivePorts(ctx context.Context, ports []*voltha.Port) {
3408 logger.Infow(ctx, "populateActivePorts", log.Fields{"device-id": dh.device.Id})
3409 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003410 if port.Type == voltha.Port_ETHERNET_NNI {
3411 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003412 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), true)
kesavand39e0aa32020-01-28 20:58:50 -05003413 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003414 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), false)
kesavand39e0aa32020-01-28 20:58:50 -05003415 }
3416 }
3417 if port.Type == voltha.Port_PON_OLT {
3418 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003419 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), true)
kesavand39e0aa32020-01-28 20:58:50 -05003420 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003421 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), false)
kesavand39e0aa32020-01-28 20:58:50 -05003422 }
3423 }
3424 }
3425}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003426
3427// ChildDeviceLost deletes ONU and clears pon resources related to it.
Girish Gowdraa0870562021-03-11 14:30:14 -08003428func (dh *DeviceHandler) ChildDeviceLost(ctx context.Context, pPortNo uint32, onuID uint32, onuSn string) error {
divyadesai3af43e12020-08-18 07:10:54 +00003429 logger.Debugw(ctx, "child-device-lost", log.Fields{"parent-device-id": dh.device.Id})
Girish Gowdrab4c33302022-03-18 15:07:38 -07003430 if dh.getDeviceDeletionInProgressFlag() {
3431 // Given that the OLT device itself is getting deleted, everything will be cleaned up in the DB and the OLT
3432 // will reboot, so everything will be reset on the pOLT too.
3433 logger.Infow(ctx, "olt-device-delete-in-progress-not-handling-child-device-lost",
3434 log.Fields{"parent-device-id": dh.device.Id, "pon-port": pPortNo, "onuID": onuID, "onuSN": onuSn})
3435 return nil
3436 }
Sridhar Ravindra92c9b0d2025-01-16 00:15:54 +05303437
3438 if dh.transitionMap.currentDeviceState != deviceStateUp {
3439 logger.Warnw(ctx, "device-is-not-up--not-handling-child-device-lost", log.Fields{"device-id": dh.device.Id, "current-device-state": dh.transitionMap.currentDeviceState})
3440 return fmt.Errorf("device-is-not-up--not-handling-child-device-lost")
3441 }
3442
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003443 intfID := plt.PortNoToIntfID(pPortNo, voltha.Port_PON_OLT)
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003444 onuKey := dh.formOnuKey(intfID, onuID)
Girish Gowdraa0870562021-03-11 14:30:14 -08003445
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003446 var sn *oop.SerialNumber
3447 var err error
Girish Gowdraa0870562021-03-11 14:30:14 -08003448 if sn, err = dh.deStringifySerialNumber(onuSn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303449 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003450 log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303451 "devicer-id": dh.device.Id,
Girish Gowdraa0870562021-03-11 14:30:14 -08003452 "serial-number": onuSn}, err).Log()
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003453 }
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003454
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003455 onu := &oop.Onu{IntfId: intfID, OnuId: onuID, SerialNumber: sn}
Akash Kankanala041a2122024-10-16 15:49:22 +05303456 // clear PON resources associated with ONU
yasin saplibddc2d72022-02-08 13:10:17 +00003457 onuGem, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003458 if err != nil || onuGem == nil || onuGem.OnuID != onuID {
3459 logger.Warnw(ctx, "failed-to-get-onu-info-for-pon-port", log.Fields{
3460 "device-id": dh.device.Id,
3461 "intf-id": intfID,
3462 "onuID": onuID,
3463 "err": err})
3464 } else {
3465 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
yasin saplie87d4bd2021-12-06 09:04:03 +00003466 // Delete flows from device before schedulers and queue
3467 // Clear flowids for gem cache.
3468 removedFlows := []uint64{}
3469 for _, gem := range onuGem.GemPorts {
3470 if flowIDs, err := dh.resourceMgr[intfID].GetFlowIDsForGem(ctx, gem); err == nil {
3471 for _, flowID := range flowIDs {
Akash Kankanala041a2122024-10-16 15:49:22 +05303472 // multiple gem port can have the same flow id
3473 // it is better to send only one flowRemove request to the agent
yasin saplie87d4bd2021-12-06 09:04:03 +00003474 var alreadyRemoved bool
3475 for _, removedFlowID := range removedFlows {
3476 if removedFlowID == flowID {
3477 logger.Debugw(ctx, "flow-is-already-removed-due-to-another-gem", log.Fields{"flowID": flowID})
3478 alreadyRemoved = true
3479 break
3480 }
3481 }
3482 if !alreadyRemoved {
Mahir Gunyela2e68702022-12-07 00:00:42 -08003483 dh.removeFlowFromDevice(ctx, flowID, intfID)
yasin saplie87d4bd2021-12-06 09:04:03 +00003484 removedFlows = appendUnique64bit(removedFlows, flowID)
3485 }
3486 }
3487 }
3488 _ = dh.resourceMgr[intfID].DeleteFlowIDsForGem(ctx, gem)
3489 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003490 if err := dh.clearUNIData(ctx, onuGem); err != nil {
3491 logger.Warnw(ctx, "failed-to-clear-uni-data-for-onu", log.Fields{
3492 "device-id": dh.device.Id,
3493 "onu-device": onu,
3494 "err": err})
3495 }
yasin saplibddc2d72022-02-08 13:10:17 +00003496 if err := dh.resourceMgr[intfID].DelOnuGemInfo(ctx, onuID); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003497 logger.Warnw(ctx, "persistence-update-onu-gem-info-failed", log.Fields{
3498 "intf-id": intfID,
3499 "onu-device": onu,
3500 "onu-gem": onuGem,
3501 "err": err})
Akash Kankanala041a2122024-10-16 15:49:22 +05303502 // Not returning error on cleanup.
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003503 }
3504 logger.Debugw(ctx, "removed-onu-gem-info", log.Fields{"intf": intfID, "onu-device": onu, "onugem": onuGem})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003505 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003506
bseenivaa1622112025-12-11 18:24:02 +05303507 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003508 // Now clear the ONU on the OLT
bseenivaa1622112025-12-11 18:24:02 +05303509 if _, err := dh.Client.DeleteOnu(subCtx, onu); err != nil {
3510 cancel()
Thomas Lee S94109f12020-03-03 16:39:29 +05303511 return olterrors.NewErrAdapter("failed-to-delete-onu", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303512 "device-id": dh.device.Id,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003513 "onu-id": onuID}, err).Log()
3514 }
bseenivaa1622112025-12-11 18:24:02 +05303515 cancel()
balaji.nagarajanbf44ce82026-01-27 08:59:36 +05303516
3517 //free resources only if the deleteonu is successful
3518 dh.resourceMgr[intfID].FreeonuID(ctx, []uint32{onuID})
3519 dh.onus.Delete(onuKey)
3520 dh.discOnus.Delete(onuSn)
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003521 return nil
3522}
Mahir Gunyela2e68702022-12-07 00:00:42 -08003523func (dh *DeviceHandler) removeFlowFromDevice(ctx context.Context, flowID uint64, intfID uint32) {
3524 flow := &oop.Flow{FlowId: flowID}
3525 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
3526 logger.Warnw(ctx, "failed-to-get-flow-mgr-to-remove-flow-from-device", log.Fields{
3527 "device-id": dh.device.Id})
3528 } else {
3529 if err := dh.flowMgr[intfID].removeFlowFromDevice(ctx, flow, flowID); err != nil {
3530 logger.Warnw(ctx, "failed-to-remove-flow-from-device", log.Fields{
3531 "device-id": dh.device.Id,
3532 "err": err})
3533 }
3534 }
3535}
Girish Gowdracefae192020-03-19 18:14:10 -07003536
3537func getInPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003538 for _, field := range flow_utils.GetOfbFields(flow) {
3539 if field.Type == flow_utils.IN_PORT {
Girish Gowdracefae192020-03-19 18:14:10 -07003540 return field.GetPort()
3541 }
3542 }
3543 return InvalidPort
3544}
3545
3546func getOutPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003547 for _, action := range flow_utils.GetActions(flow) {
3548 if action.Type == flow_utils.OUTPUT {
Girish Gowdracefae192020-03-19 18:14:10 -07003549 if out := action.GetOutput(); out != nil {
3550 return out.GetPort()
3551 }
3552 }
3553 }
3554 return InvalidPort
3555}
3556
Girish Gowdracefae192020-03-19 18:14:10 -07003557func getPorts(flow *of.OfpFlowStats) (uint32, uint32) {
3558 inPort := getInPortFromFlow(flow)
3559 outPort := getOutPortFromFlow(flow)
3560
3561 if inPort == InvalidPort || outPort == InvalidPort {
3562 return inPort, outPort
3563 }
3564
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003565 if isControllerFlow := plt.IsControllerBoundFlow(outPort); isControllerFlow {
Girish Gowdracefae192020-03-19 18:14:10 -07003566 /* Get UNI port/ IN Port from tunnel ID field for upstream controller bound flows */
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003567 if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003568 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003569 return uniPort, outPort
3570 }
3571 }
3572 } else {
3573 // Downstream flow from NNI to PON port , Use tunnel ID as new OUT port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003574 if portType := plt.IntfIDToPortTypeName(outPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003575 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003576 return inPort, uniPort
3577 }
3578 // Upstream flow from PON to NNI port , Use tunnel ID as new IN port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003579 } else if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003580 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003581 return uniPort, outPort
3582 }
3583 }
3584 }
3585
3586 return InvalidPort, InvalidPort
3587}
Matt Jeanneretceea2e02020-03-27 14:19:57 -04003588
3589func extractOmciTransactionID(omciPkt []byte) uint16 {
3590 if len(omciPkt) > 3 {
3591 d := omciPkt[0:2]
3592 transid := binary.BigEndian.Uint16(d)
3593 return transid
3594 }
3595 return 0
3596}
Mahir Gunyel0f89fd22020-04-11 18:24:42 -07003597
3598// StoreOnuDevice stores the onu parameters to the local cache.
3599func (dh *DeviceHandler) StoreOnuDevice(onuDevice *OnuDevice) {
3600 onuKey := dh.formOnuKey(onuDevice.intfID, onuDevice.onuID)
3601 dh.onus.Store(onuKey, onuDevice)
3602}
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003603
khenaidoodc2116e2021-10-19 17:33:19 -04003604func (dh *DeviceHandler) getExtValue(ctx context.Context, device *voltha.Device, value extension.ValueType_Type) (*extension.ReturnValues, error) {
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003605 var err error
Andrea Campanella9931ad62020-04-28 15:11:06 +02003606 var sn *oop.SerialNumber
Gamze Abaka78a1d2a2020-04-27 10:17:27 +00003607 var ID uint32
khenaidoodc2116e2021-10-19 17:33:19 -04003608 resp := new(extension.ReturnValues)
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003609 valueparam := new(oop.ValueParam)
Neha Sharma8f4e4322020-08-06 10:51:53 +00003610 ctx = log.WithSpanFromContext(context.Background(), ctx)
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003611 logger.Infow(ctx, "getExtValue", log.Fields{"onu-id": device.Id, "pon-intf": device.ParentPortNo})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003612 if sn, err = dh.deStringifySerialNumber(device.SerialNumber); err != nil {
3613 return nil, err
3614 }
3615 ID = device.ProxyAddress.GetOnuId()
3616 Onu := oop.Onu{IntfId: device.ParentPortNo, OnuId: ID, SerialNumber: sn}
3617 valueparam.Onu = &Onu
3618 valueparam.Value = value
3619
3620 // This API is unsupported until agent patch is added
3621 resp.Unsupported = uint32(value)
3622 _ = ctx
3623
3624 // Uncomment this code once agent changes are complete and tests
3625 /*
3626 resp, err = dh.Client.GetValue(ctx, valueparam)
3627 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003628 logger.Errorw("error-while-getValue", log.Fields{"DeviceID": dh.device, "onu-id": onuid, "err": err})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003629 return nil, err
3630 }
3631 */
3632
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003633 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 -08003634 return resp, nil
3635}
Girish Gowdra9602eb42020-09-09 15:50:39 -07003636
Akash Kankanala041a2122024-10-16 15:49:22 +05303637func (dh *DeviceHandler) getIntfIDFromFlow(flow *of.OfpFlowStats) uint32 {
yasin saplid0566272021-12-21 09:10:30 +00003638 // Default to NNI
3639 var intfID = dh.totalPonPorts
Girish Gowdra9602eb42020-09-09 15:50:39 -07003640 inPort, outPort := getPorts(flow)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003641 if inPort != InvalidPort && outPort != InvalidPort {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003642 _, intfID, _, _ = plt.ExtractAccessFromFlow(inPort, outPort)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003643 }
3644 return intfID
3645}
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003646
Akash Kankanala041a2122024-10-16 15:49:22 +05303647func (dh *DeviceHandler) getOnuIndicationChannel(intfID uint32) chan onuIndicationMsg {
Mahir Gunyelb0046752021-02-26 13:51:05 -08003648 dh.perPonOnuIndicationChannelLock.Lock()
3649 if ch, ok := dh.perPonOnuIndicationChannel[intfID]; ok {
3650 dh.perPonOnuIndicationChannelLock.Unlock()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003651 return ch.indicationChannel
3652 }
3653 channels := onuIndicationChannels{
Akash Kankanala041a2122024-10-16 15:49:22 +05303654 // We create a buffered channel here to avoid calling function to be blocked
3655 // in case of multiple indications from the ONUs,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003656 //especially in the case where indications are buffered in OLT.
Mahir Gunyelb0046752021-02-26 13:51:05 -08003657 indicationChannel: make(chan onuIndicationMsg, 500),
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003658 stopChannel: make(chan struct{}),
3659 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003660 dh.perPonOnuIndicationChannel[intfID] = channels
3661 dh.perPonOnuIndicationChannelLock.Unlock()
3662 go dh.onuIndicationsRoutine(&channels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003663 return channels.indicationChannel
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003664}
3665
Mahir Gunyelb0046752021-02-26 13:51:05 -08003666func (dh *DeviceHandler) removeOnuIndicationChannels(ctx context.Context) {
3667 logger.Debug(ctx, "remove-onu-indication-channels", log.Fields{"device-id": dh.device.Id})
3668 dh.perPonOnuIndicationChannelLock.Lock()
3669 defer dh.perPonOnuIndicationChannelLock.Unlock()
3670 for _, v := range dh.perPonOnuIndicationChannel {
3671 close(v.stopChannel)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003672 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003673 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003674}
3675
Mahir Gunyelb0046752021-02-26 13:51:05 -08003676func (dh *DeviceHandler) putOnuIndicationToChannel(ctx context.Context, indication *oop.Indication, intfID uint32) {
3677 ind := onuIndicationMsg{
3678 ctx: ctx,
3679 indication: indication,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003680 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003681 logger.Debugw(ctx, "put-onu-indication-to-channel", log.Fields{"indication": indication, "intfID": intfID})
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003682 // Send the onuIndication on the ONU channel
Akash Kankanala041a2122024-10-16 15:49:22 +05303683 dh.getOnuIndicationChannel(intfID) <- ind
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003684}
3685
Mahir Gunyelb0046752021-02-26 13:51:05 -08003686func (dh *DeviceHandler) onuIndicationsRoutine(onuChannels *onuIndicationChannels) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003687 for {
3688 select {
3689 // process one indication per onu, before proceeding to the next one
3690 case onuInd := <-onuChannels.indicationChannel:
Andrea Campanella46b01402021-11-15 16:58:05 -08003691 indication := *(proto.Clone(onuInd.indication)).(*oop.Indication)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003692 logger.Debugw(onuInd.ctx, "calling-indication", log.Fields{"device-id": dh.device.Id,
Andrea Campanella46b01402021-11-15 16:58:05 -08003693 "ind": indication})
3694 switch indication.Data.(type) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003695 case *oop.Indication_OnuInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003696 if err := dh.onuIndication(onuInd.ctx, indication.GetOnuInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003697 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3698 "type": "onu-indication",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003699 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003700 }
3701 case *oop.Indication_OnuDiscInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003702 if err := dh.onuDiscIndication(onuInd.ctx, indication.GetOnuDiscInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003703 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3704 "type": "onu-discovery",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003705 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003706 }
3707 }
3708 case <-onuChannels.stopChannel:
3709 logger.Debugw(context.Background(), "stop-signal-received-for-onu-channel", log.Fields{"device-id": dh.device.Id})
3710 close(onuChannels.indicationChannel)
3711 return
3712 }
3713 }
3714}
Girish Gowdra491a9c62021-01-06 16:43:07 -08003715
3716// RouteMcastFlowOrGroupMsgToChannel routes incoming mcast flow or group to a channel to be handled by the a specific
3717// instance of mcastFlowOrGroupChannelHandlerRoutine meant to handle messages for that group.
khenaidoodc2116e2021-10-19 17:33:19 -04003718func (dh *DeviceHandler) RouteMcastFlowOrGroupMsgToChannel(ctx context.Context, flow *of.OfpFlowStats, group *of.OfpGroupEntry, action string) error {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003719 if dh.getDeviceDeletionInProgressFlag() {
3720 // The device itself is going to be reset as part of deletion. So nothing to be done.
3721 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
3722 return nil
3723 }
3724
Girish Gowdra491a9c62021-01-06 16:43:07 -08003725 // Step1 : Fill McastFlowOrGroupControlBlock
3726 // Step2 : Push the McastFlowOrGroupControlBlock to appropriate channel
3727 // Step3 : Wait on response channel for response
3728 // Step4 : Return error value
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003729 startTime := time.Now()
Girish Gowdra491a9c62021-01-06 16:43:07 -08003730 logger.Debugw(ctx, "process-flow-or-group", log.Fields{"flow": flow, "group": group, "action": action})
3731 errChan := make(chan error)
3732 var groupID uint32
3733 mcastFlowOrGroupCb := McastFlowOrGroupControlBlock{
3734 ctx: ctx,
3735 flowOrGroupAction: action,
3736 flow: flow,
3737 group: group,
3738 errChan: &errChan,
3739 }
3740 if flow != nil {
3741 groupID = flow_utils.GetGroup(flow)
3742 } else if group != nil {
3743 groupID = group.Desc.GroupId
3744 } else {
3745 return errors.New("flow-and-group-both-nil")
3746 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003747 mcastRoutineIdx := groupID % MaxNumOfGroupHandlerChannels
3748 if dh.mcastHandlerRoutineActive[mcastRoutineIdx] {
3749 // Derive the appropriate go routine to handle the request by a simple module operation.
3750 // There are only MaxNumOfGroupHandlerChannels number of channels to handle the mcast flow or group
3751 dh.incomingMcastFlowOrGroup[groupID%MaxNumOfGroupHandlerChannels] <- mcastFlowOrGroupCb
3752 // Wait for handler to return error value
3753 err := <-errChan
3754 logger.Debugw(ctx, "process-flow-or-group--received-resp", log.Fields{"err": err, "totalTimeInSeconds": time.Since(startTime).Milliseconds()})
3755 return err
3756 }
3757 logger.Errorw(ctx, "mcast handler routine not active for onu", log.Fields{"mcastRoutineIdx": mcastRoutineIdx})
3758 return fmt.Errorf("mcast-handler-routine-not-active-for-index-%v", mcastRoutineIdx)
Girish Gowdra491a9c62021-01-06 16:43:07 -08003759}
3760
3761// mcastFlowOrGroupChannelHandlerRoutine routine to handle incoming mcast flow/group message
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003762func (dh *DeviceHandler) mcastFlowOrGroupChannelHandlerRoutine(routineIndex int, mcastFlowOrGroupChannel chan McastFlowOrGroupControlBlock, stopHandler chan bool) {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003763 for {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003764 select {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003765 // block on the channel to receive an incoming mcast flow/group
3766 // process the flow completely before proceeding to handle the next flow
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003767 case mcastFlowOrGroupCb := <-mcastFlowOrGroupChannel:
3768 if mcastFlowOrGroupCb.flow != nil {
3769 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3770 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-flow",
3771 log.Fields{"device-id": dh.device.Id,
3772 "flowToAdd": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003773 err := olterrors.NewErrNotFound("no-flow-manager-found-to-add-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3774 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3775 for _, flMgr := range dh.flowMgr {
3776 if flMgr != nil {
3777 err = flMgr.AddFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow, nil)
3778 break
3779 }
3780 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003781 // Pass the return value over the return channel
3782 *mcastFlowOrGroupCb.errChan <- err
3783 } else { // flow remove
3784 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-flow",
3785 log.Fields{"device-id": dh.device.Id,
3786 "flowToRemove": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003787 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3788 err := olterrors.NewErrNotFound("no-flow-manager-found-to-remove-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3789 for _, flMgr := range dh.flowMgr {
3790 if flMgr != nil {
3791 err = flMgr.RemoveFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow)
3792 break
3793 }
3794 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003795 // Pass the return value over the return channel
3796 *mcastFlowOrGroupCb.errChan <- err
3797 }
3798 } else { // mcast group
mgouda86543582025-10-29 20:58:16 +05303799 switch mcastFlowOrGroupCb.flowOrGroupAction {
3800 case McastFlowOrGroupAdd:
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003801 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-group",
3802 log.Fields{"device-id": dh.device.Id,
3803 "groupToAdd": mcastFlowOrGroupCb.group})
3804 err := dh.groupMgr.AddGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3805 // Pass the return value over the return channel
3806 *mcastFlowOrGroupCb.errChan <- err
mgouda86543582025-10-29 20:58:16 +05303807 case McastFlowOrGroupModify: // group modify
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003808 logger.Debugw(mcastFlowOrGroupCb.ctx, "modifying-mcast-group",
3809 log.Fields{"device-id": dh.device.Id,
3810 "groupToModify": mcastFlowOrGroupCb.group})
3811 err := dh.groupMgr.ModifyGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3812 // Pass the return value over the return channel
3813 *mcastFlowOrGroupCb.errChan <- err
mgouda86543582025-10-29 20:58:16 +05303814 default: // group remove
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003815 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-group",
3816 log.Fields{"device-id": dh.device.Id,
3817 "groupToRemove": mcastFlowOrGroupCb.group})
3818 err := dh.groupMgr.DeleteGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3819 // Pass the return value over the return channel
3820 *mcastFlowOrGroupCb.errChan <- err
3821 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08003822 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003823 case <-stopHandler:
3824 dh.mcastHandlerRoutineActive[routineIndex] = false
3825 return
Girish Gowdra491a9c62021-01-06 16:43:07 -08003826 }
3827 }
3828}
kesavand62126212021-01-12 04:56:06 -05003829
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003830// StopAllMcastHandlerRoutines stops all flow handler routines. Call this when device is being rebooted or deleted
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003831func (dh *DeviceHandler) StopAllMcastHandlerRoutines(ctx context.Context, wg *sync.WaitGroup) {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003832 for i, v := range dh.stopMcastHandlerRoutine {
3833 if dh.mcastHandlerRoutineActive[i] {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003834 select {
3835 case v <- true:
3836 case <-time.After(time.Second * 5):
3837 logger.Warnw(ctx, "timeout stopping mcast handler routine", log.Fields{"idx": i, "deviceID": dh.device.Id})
3838 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003839 }
3840 }
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00003841
3842 if dh.incomingMcastFlowOrGroup != nil {
3843 for k := range dh.incomingMcastFlowOrGroup {
3844 if dh.incomingMcastFlowOrGroup[k] != nil {
3845 dh.incomingMcastFlowOrGroup[k] = nil
3846 }
3847 }
3848 dh.incomingMcastFlowOrGroup = nil
3849 }
3850
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003851 wg.Done()
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003852 logger.Debug(ctx, "stopped all mcast handler routines")
3853}
3854
Akash Kankanala041a2122024-10-16 15:49:22 +05303855// nolint: unparam
kesavand62126212021-01-12 04:56:06 -05003856func (dh *DeviceHandler) getOltPortCounters(ctx context.Context, oltPortInfo *extension.GetOltPortCounters) *extension.SingleGetValueResponse {
kesavand62126212021-01-12 04:56:06 -05003857 singleValResp := extension.SingleGetValueResponse{
3858 Response: &extension.GetValueResponse{
3859 Response: &extension.GetValueResponse_PortCoutners{
3860 PortCoutners: &extension.GetOltPortCountersResponse{},
3861 },
3862 },
3863 }
3864
Akash Kankanala041a2122024-10-16 15:49:22 +05303865 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
kesavand62126212021-01-12 04:56:06 -05003866 return &extension.SingleGetValueResponse{
3867 Response: &extension.GetValueResponse{
3868 Status: status,
3869 ErrReason: reason,
3870 },
3871 }
3872 }
3873
3874 if oltPortInfo.PortType != extension.GetOltPortCounters_Port_ETHERNET_NNI &&
3875 oltPortInfo.PortType != extension.GetOltPortCounters_Port_PON_OLT {
Akash Kankanala041a2122024-10-16 15:49:22 +05303876 // send error response
kesavand62126212021-01-12 04:56:06 -05003877 logger.Debugw(ctx, "getOltPortCounters invalid portType", log.Fields{"oltPortInfo": oltPortInfo.PortType})
3878 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
3879 }
3880 statIndChn := make(chan bool, 1)
3881 dh.portStats.RegisterForStatIndication(ctx, portStatsType, statIndChn, oltPortInfo.PortNo, oltPortInfo.PortType)
3882 defer dh.portStats.DeRegisterFromStatIndication(ctx, portStatsType, statIndChn)
Akash Kankanala041a2122024-10-16 15:49:22 +05303883 // request openOlt agent to send the the port statistics indication
kesavand62126212021-01-12 04:56:06 -05003884
3885 go func() {
bseenivaa1622112025-12-11 18:24:02 +05303886 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3887 _, err := dh.Client.CollectStatistics(subCtx, new(oop.Empty))
kesavand62126212021-01-12 04:56:06 -05003888 if err != nil {
3889 logger.Errorw(ctx, "getOltPortCounters CollectStatistics failed ", log.Fields{"err": err})
3890 }
bseenivaa1622112025-12-11 18:24:02 +05303891 cancel()
kesavand62126212021-01-12 04:56:06 -05003892 }()
3893 select {
3894 case <-statIndChn:
Akash Kankanala041a2122024-10-16 15:49:22 +05303895 // indication received for ports stats
kesavand62126212021-01-12 04:56:06 -05003896 logger.Debugw(ctx, "getOltPortCounters recvd statIndChn", log.Fields{"oltPortInfo": oltPortInfo})
3897 case <-time.After(oltPortInfoTimeout * time.Second):
3898 logger.Debugw(ctx, "getOltPortCounters timeout happened", log.Fields{"oltPortInfo": oltPortInfo})
3899 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3900 case <-ctx.Done():
3901 logger.Debugw(ctx, "getOltPortCounters ctx Done ", log.Fields{"oltPortInfo": oltPortInfo})
3902 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3903 }
mgouda86543582025-10-29 20:58:16 +05303904 switch oltPortInfo.PortType {
3905 case extension.GetOltPortCounters_Port_ETHERNET_NNI:
Akash Kankanala041a2122024-10-16 15:49:22 +05303906 // get nni stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003907 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_ETHERNET_NNI)
kesavand62126212021-01-12 04:56:06 -05003908 logger.Debugw(ctx, "getOltPortCounters intfID ", log.Fields{"intfID": intfID})
3909 cmnni := dh.portStats.collectNNIMetrics(intfID)
3910 if cmnni == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05303911 // TODO define the error reason
kesavand62126212021-01-12 04:56:06 -05003912 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3913 }
3914 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmnni)
3915 return &singleValResp
mgouda86543582025-10-29 20:58:16 +05303916 case extension.GetOltPortCounters_Port_PON_OLT:
kesavand62126212021-01-12 04:56:06 -05003917 // get pon stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003918 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_PON_OLT)
kesavand62126212021-01-12 04:56:06 -05003919 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
3920 cmpon := dh.portStats.collectPONMetrics(intfID)
3921 if cmpon == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05303922 // TODO define the error reason
kesavand62126212021-01-12 04:56:06 -05003923 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3924 }
3925 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmpon)
3926 return &singleValResp
3927 }
3928 }
3929 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3930}
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303931
Akash Kankanala041a2122024-10-16 15:49:22 +05303932//nolint:unparam
Akash Soni3bcf5e02024-12-03 08:01:48 +05303933func (dh *DeviceHandler) getOltOffloadStats(ctx context.Context, oltPortInfo *extension.GetOffloadedAppsStatisticsRequest) *extension.SingleGetValueResponse {
Akash Soni3bcf5e02024-12-03 08:01:48 +05303934 singleValResp := extension.SingleGetValueResponse{
3935 Response: &extension.GetValueResponse{
3936 Status: extension.GetValueResponse_OK,
3937 Response: &extension.GetValueResponse_OffloadedAppsStats{
3938 OffloadedAppsStats: &extension.GetOffloadedAppsStatisticsResponse{},
3939 },
3940 },
3941 }
3942
3943 return &singleValResp
3944}
3945
Akash Kankanala041a2122024-10-16 15:49:22 +05303946//nolint:unparam
Akash Soni3c75ad72024-12-23 12:09:48 +05303947func (dh *DeviceHandler) setOltOffload(ctx context.Context, congig *extension.AppOffloadConfig) *extension.SingleSetValueResponse {
Akash Soni3c75ad72024-12-23 12:09:48 +05303948 singleValResp := extension.SingleSetValueResponse{
3949 Response: &extension.SetValueResponse{
3950 Status: extension.SetValueResponse_OK,
3951 },
3952 }
3953
3954 return &singleValResp
3955}
3956
Akash Kankanala041a2122024-10-16 15:49:22 +05303957//nolint:unparam
Akash Soni3c75ad72024-12-23 12:09:48 +05303958func (dh *DeviceHandler) setOnuOffload(ctx context.Context, config *extension.AppOffloadOnuConfig) *extension.SingleSetValueResponse {
Akash Soni3bcf5e02024-12-03 08:01:48 +05303959 singleValResp := extension.SingleSetValueResponse{
3960 Response: &extension.SetValueResponse{
3961 Status: extension.SetValueResponse_OK,
3962 },
3963 }
3964
3965 return &singleValResp
3966}
3967
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303968func (dh *DeviceHandler) getOnuPonCounters(ctx context.Context, onuPonInfo *extension.GetOnuCountersRequest) *extension.SingleGetValueResponse {
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303969 singleValResp := extension.SingleGetValueResponse{
3970 Response: &extension.GetValueResponse{
3971 Response: &extension.GetValueResponse_OnuPonCounters{
3972 OnuPonCounters: &extension.GetOnuCountersResponse{},
3973 },
3974 },
3975 }
3976
Akash Kankanala041a2122024-10-16 15:49:22 +05303977 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303978 return &extension.SingleGetValueResponse{
3979 Response: &extension.GetValueResponse{
3980 Status: status,
3981 ErrReason: reason,
3982 },
3983 }
3984 }
3985 intfID := onuPonInfo.IntfId
3986 onuID := onuPonInfo.OnuId
3987 onuKey := dh.formOnuKey(intfID, onuID)
3988
3989 if _, ok := dh.onus.Load(onuKey); !ok {
3990 logger.Errorw(ctx, "get-onui-pon-counters-request-invalid-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3991 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3992 }
3993 logger.Debugw(ctx, "get-onui-pon-counters-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3994 cmnni := dh.portStats.collectOnDemandOnuStats(ctx, intfID, onuID)
3995 if cmnni == nil {
3996 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3997 }
3998 dh.portStats.updateGetOnuPonCountersResponse(ctx, &singleValResp, cmnni)
3999 return &singleValResp
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05304000}
Gamze Abaka85e9a142021-05-26 13:41:39 +00004001
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05304002func (dh *DeviceHandler) CheckOnuGemInfo(ctx context.Context, intfID uint32, onuID uint32) (*rsrcMgr.OnuGemInfo, error) {
4003 onuGemInfo, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
4004 if err != nil {
4005 logger.Errorw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuID})
4006 return nil, err
4007 }
4008 if onuGemInfo != nil {
4009 if len(onuGemInfo.UniPorts) == 0 {
4010 logger.Errorw(ctx, "No uniports present for the ONU", log.Fields{"onuID": onuID})
4011 return nil, err
4012 }
4013 logger.Debugw(ctx, "Received onuGemInfo", log.Fields{"onuID": onuID, "onuGemInfo": onuGemInfo})
4014 return onuGemInfo, nil
4015 }
4016 logger.Errorw(ctx, "Received nil onuGemInfo", log.Fields{"onuID": onuID})
4017 return nil, fmt.Errorf("onuGemInfo received as null, onuID : %d", onuID)
4018}
4019
4020func (dh *DeviceHandler) getAllocGemStats(ctx context.Context, intfID uint32, onuID uint32, onuGemInfo *rsrcMgr.OnuGemInfo, singleValResp *extension.SingleGetValueResponse) error {
4021 var err error
4022 var allocStats *oop.OnuAllocIdStatistics
4023 var onuGemStats *oop.GemPortStatistics
4024 for _, uni := range onuGemInfo.UniPorts {
4025 uniID := plt.UniIDFromPortNum(uni)
4026 uniPath := getUniPortPath(dh.device.Id, intfID, int32(onuID), int32(uniID))
4027 tpIDs := dh.resourceMgr[intfID].GetTechProfileIDForOnu(ctx, onuID, uniID)
4028 if len(tpIDs) == 0 {
4029 logger.Errorw(ctx, "No TPIDs present for the Uni", log.Fields{"onuID": onuID, "uniPort": uni})
4030 continue
4031 }
4032 for _, tpId := range tpIDs {
4033 tpPath := dh.flowMgr[intfID].getTPpath(ctx, uniPath, uint32(tpId))
4034 techProfileInstance, _ := dh.flowMgr[intfID].techprofile.GetTPInstance(ctx, tpPath)
4035 onuStatsFromOlt := extension.OnuAllocGemStatsFromOltResponse{}
4036 if techProfileInstance != nil {
4037 switch tpInst := techProfileInstance.(type) {
4038 case *tp_pb.TechProfileInstance:
4039 allocId := tpInst.UsScheduler.AllocId
4040 onuAllocPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, AllocId: allocId}
bseenivaa1622112025-12-11 18:24:02 +05304041 allocCtx, allocCtxcancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4042 allocStats, err = dh.Client.GetAllocIdStatistics(allocCtx, &onuAllocPkt)
4043 allocCtxcancel()
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05304044 if err != nil {
4045 logger.Errorw(ctx, "Error received from openolt for GetAllocIdStatistics", log.Fields{"onuID": onuID, "AllodId": allocId, "Error": err})
4046 return err
4047 }
4048 allocIdInfo := extension.OnuAllocIdInfoFromOlt{}
4049 allocIdInfo.AllocId = allocStats.AllocId
4050 allocIdInfo.RxBytes = allocStats.RxBytes
4051
4052 onuStatsFromOlt.AllocIdInfo = &allocIdInfo
4053
4054 gemPorts := tpInst.UpstreamGemPortAttributeList
4055 for _, gem := range gemPorts {
4056 onuGemPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, GemportId: gem.GemportId}
bseenivaa1622112025-12-11 18:24:02 +05304057 gemCtx, gemCtxcancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4058 onuGemStats, err = dh.Client.GetGemPortStatistics(gemCtx, &onuGemPkt)
4059 gemCtxcancel()
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05304060 if err != nil {
4061 logger.Errorw(ctx, "Error received from openolt for GetGemPortStatistics", log.Fields{"onuID": onuID, "GemPortId": gem.GemportId, "Error": err})
4062 return err
4063 }
4064 gemStatsInfo := extension.OnuGemPortInfoFromOlt{}
4065 gemStatsInfo.GemId = onuGemStats.GemportId
4066 gemStatsInfo.RxBytes = onuGemStats.RxBytes
4067 gemStatsInfo.RxPackets = onuGemStats.RxPackets
4068 gemStatsInfo.TxBytes = onuGemStats.TxBytes
4069 gemStatsInfo.TxPackets = onuGemStats.TxPackets
4070
4071 onuStatsFromOlt.GemPortInfo = append(onuStatsFromOlt.GemPortInfo, &gemStatsInfo)
4072 }
4073 singleValResp.Response.GetOnuStatsFromOltResponse().AllocGemStatsInfo = append(singleValResp.Response.GetOnuStatsFromOltResponse().AllocGemStatsInfo, &onuStatsFromOlt)
4074
4075 default:
4076 logger.Errorw(ctx, "Invalid Techprofile type received", log.Fields{"onuID": onuID, "TpId": tpId})
4077 return err
4078 }
4079 } else {
4080 logger.Errorw(ctx, "No TpInstance found for the TpID", log.Fields{"onuID": onuID, "TpId": tpId})
4081 continue
4082 }
4083 }
4084 }
4085 return err
4086}
4087
4088//nolint:unparam
4089func (dh *DeviceHandler) getOnuStatsFromOlt(ctx context.Context, onuInfo *extension.GetOnuStatsFromOltRequest, onuDevice *voltha.Device) *extension.SingleGetValueResponse {
4090 singleValResp := extension.SingleGetValueResponse{
4091 Response: &extension.GetValueResponse{
4092 Status: extension.GetValueResponse_OK,
4093 Response: &extension.GetValueResponse_OnuStatsFromOltResponse{
4094 OnuStatsFromOltResponse: &extension.GetOnuStatsFromOltResponse{},
4095 },
4096 },
4097 }
4098 errResp := func(status extension.GetValueResponse_Status,
4099 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4100 return &extension.SingleGetValueResponse{
4101 Response: &extension.GetValueResponse{
4102 Status: status,
4103 ErrReason: reason,
4104 },
4105 }
4106 }
4107
4108 var intfID, onuID uint32
4109 if onuDevice != nil {
4110 onuID = onuDevice.ProxyAddress.OnuId
4111 intfID = plt.PortNoToIntfID(onuDevice.ParentPortNo, voltha.Port_PON_OLT)
4112 }
4113
4114 onuKey := dh.formOnuKey(intfID, onuID)
4115 if _, ok := dh.onus.Load(onuKey); !ok {
4116 logger.Errorw(ctx, "getOnuStatsFromOlt request received for invalid device", log.Fields{"deviceId": onuDevice.Id, "intfID": intfID, "onuID": onuID})
4117 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4118 }
4119 logger.Debugw(ctx, "getOnuStatsFromOlt request received", log.Fields{"intfID": intfID, "onuID": onuID})
4120
4121 onuGemInfo, err := dh.CheckOnuGemInfo(ctx, intfID, onuID)
4122 if err == nil {
4123 err = dh.getAllocGemStats(ctx, intfID, onuID, onuGemInfo, &singleValResp)
4124 if err != nil {
4125 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
4126 }
4127 } else {
4128 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4129 }
4130 return &singleValResp
4131}
4132
nikesh.krishnanc8473432023-06-14 12:14:54 +05304133func (dh *DeviceHandler) getOnuInfo(ctx context.Context, intfID uint32, onuID *uint32) (*oop.OnuInfo, error) {
nikesh.krishnanc8473432023-06-14 12:14:54 +05304134 Onu := oop.Onu{IntfId: intfID, OnuId: *onuID}
bseenivaa1622112025-12-11 18:24:02 +05304135 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4136 OnuInfo, err := dh.Client.GetOnuInfo(subCtx, &Onu)
4137 cancel()
nikesh.krishnanc8473432023-06-14 12:14:54 +05304138 if err != nil {
4139 return nil, err
4140 }
4141 return OnuInfo, nil
nikesh.krishnanc8473432023-06-14 12:14:54 +05304142}
4143
4144func (dh *DeviceHandler) getIntfInfo(ctx context.Context, intfID uint32) (*oop.PonIntfInfo, error) {
nikesh.krishnanc8473432023-06-14 12:14:54 +05304145 Intf := oop.Interface{IntfId: intfID}
bseenivaa1622112025-12-11 18:24:02 +05304146 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4147 IntfInfo, err := dh.Client.GetPonInterfaceInfo(subCtx, &Intf)
4148 cancel()
nikesh.krishnanc8473432023-06-14 12:14:54 +05304149 if err != nil {
4150 return nil, err
4151 }
4152 return IntfInfo, nil
nikesh.krishnanc8473432023-06-14 12:14:54 +05304153}
4154
Gamze Abaka85e9a142021-05-26 13:41:39 +00004155func (dh *DeviceHandler) getRxPower(ctx context.Context, rxPowerRequest *extension.GetRxPowerRequest) *extension.SingleGetValueResponse {
Gamze Abaka85e9a142021-05-26 13:41:39 +00004156 Onu := oop.Onu{IntfId: rxPowerRequest.IntfId, OnuId: rxPowerRequest.OnuId}
bseenivaa1622112025-12-11 18:24:02 +05304157 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4158 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4159 cancel()
Gamze Abaka85e9a142021-05-26 13:41:39 +00004160 if err != nil {
4161 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
4162 return generateSingleGetValueErrorResponse(err)
4163 }
4164 return &extension.SingleGetValueResponse{
4165 Response: &extension.GetValueResponse{
4166 Status: extension.GetValueResponse_OK,
4167 Response: &extension.GetValueResponse_RxPower{
4168 RxPower: &extension.GetRxPowerResponse{
4169 IntfId: rxPowerRequest.IntfId,
4170 OnuId: rxPowerRequest.OnuId,
4171 Status: rxPower.Status,
4172 FailReason: rxPower.FailReason.String(),
4173 RxPower: rxPower.RxPowerMeanDbm,
4174 },
4175 },
4176 },
4177 }
4178}
4179
praneeth nalmas55616d62023-02-06 09:19:18 +05304180func (dh *DeviceHandler) getPONRxPower(ctx context.Context, OltRxPowerRequest *extension.GetOltRxPowerRequest) *extension.SingleGetValueResponse {
Akash Kankanala041a2122024-10-16 15:49:22 +05304181 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
praneeth nalmas55616d62023-02-06 09:19:18 +05304182 return &extension.SingleGetValueResponse{
4183 Response: &extension.GetValueResponse{
4184 Status: status,
4185 ErrReason: reason,
4186 },
4187 }
4188 }
4189
4190 resp := extension.SingleGetValueResponse{
4191 Response: &extension.GetValueResponse{
4192 Status: extension.GetValueResponse_OK,
4193 Response: &extension.GetValueResponse_OltRxPower{
4194 OltRxPower: &extension.GetOltRxPowerResponse{},
4195 },
4196 },
4197 }
4198
4199 logger.Debugw(ctx, "getPONRxPower", log.Fields{"portLabel": OltRxPowerRequest.PortLabel, "OnuSerialNumber": OltRxPowerRequest.OnuSn, "device-id": dh.device.Id})
4200 portLabel := OltRxPowerRequest.PortLabel
4201 serialNumber := OltRxPowerRequest.OnuSn
4202
4203 portInfo := strings.Split(portLabel, "-")
4204 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4205
4206 if err != nil {
4207 logger.Errorw(ctx, "getPONRxPower invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4208 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4209 }
4210
4211 if portInfo[0] != "pon" {
4212 logger.Errorw(ctx, "getPONRxPower invalid portType", log.Fields{"oltPortType": portInfo[0]})
4213 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4214 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304215
4216 if serialNumber != "" {
praneeth nalmas55616d62023-02-06 09:19:18 +05304217 onuDev := dh.getChildDevice(ctx, serialNumber, (uint32)(portNumber))
4218 if onuDev != nil {
bseenivaa1622112025-12-11 18:24:02 +05304219 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
praneeth nalmas55616d62023-02-06 09:19:18 +05304220 Onu := oop.Onu{IntfId: uint32(portNumber), OnuId: onuDev.onuID}
bseenivaa1622112025-12-11 18:24:02 +05304221 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4222 cancel()
praneeth nalmas55616d62023-02-06 09:19:18 +05304223 if err != nil {
praneeth nalmas55616d62023-02-06 09:19:18 +05304224 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
4225 return generateSingleGetValueErrorResponse(err)
praneeth nalmas55616d62023-02-06 09:19:18 +05304226 }
4227
4228 rxPowerValue := extension.RxPower{}
4229 rxPowerValue.OnuSn = onuDev.serialNumber
4230 rxPowerValue.Status = rxPower.GetStatus()
4231 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
4232 rxPowerValue.FailReason = rxPower.GetFailReason().String()
4233
4234 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
praneeth nalmas55616d62023-02-06 09:19:18 +05304235 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304236 logger.Errorw(ctx, "getPONRxPower invalid Device", log.Fields{"portLabel": portLabel, "serialNumber": serialNumber})
4237 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4238 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304239 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304240 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
praneeth kumar nalmasb234f232023-11-29 12:50:46 +05304241 if onuInCache.(*OnuDevice).intfID == (uint32)(portNumber) {
praneeth kumar nalmasb234f232023-11-29 12:50:46 +05304242 Onu := oop.Onu{IntfId: (uint32)(portNumber), OnuId: onuInCache.(*OnuDevice).onuID}
bseenivaa1622112025-12-11 18:24:02 +05304243 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4244 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4245 cancel()
praneeth nalmas55616d62023-02-06 09:19:18 +05304246 if err != nil {
4247 logger.Errorw(ctx, "error-while-getting-rx-power, however considering to proceed further with other ONUs on PON", log.Fields{"Onu": Onu, "err": err})
4248 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304249 rxPowerValue := extension.RxPower{}
4250 rxPowerValue.OnuSn = onuInCache.(*OnuDevice).serialNumber
4251 rxPowerValue.Status = rxPower.GetStatus()
4252 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
4253 rxPowerValue.FailReason = rxPower.GetFailReason().String()
4254
4255 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
4256 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304257 }
4258 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
4259 return true
4260 })
4261 }
4262 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
4263 return &resp
4264}
4265
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304266func (dh *DeviceHandler) getPonPortStats(ctx context.Context, ponStatsRequest *extension.GetPonStatsRequest) *extension.SingleGetValueResponse {
4267 errResp := func(status extension.GetValueResponse_Status,
4268 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4269 return &extension.SingleGetValueResponse{
4270 Response: &extension.GetValueResponse{
4271 Status: status,
4272 ErrReason: reason,
4273 },
4274 }
4275 }
4276
4277 resp := extension.SingleGetValueResponse{
4278 Response: &extension.GetValueResponse{
4279 Status: extension.GetValueResponse_OK,
4280 Response: &extension.GetValueResponse_OltPonStatsResponse{
4281 OltPonStatsResponse: &extension.GetPonStatsResponse{},
4282 },
4283 },
4284 }
4285
4286 portLabel := ponStatsRequest.GetPortLabel()
4287 logger.Debugw(ctx, "getPonPortStats", log.Fields{"portLabel": portLabel, "device-id": dh.device.Id})
4288
4289 portInfo := strings.Split(portLabel, "-")
4290 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4291
4292 if err != nil {
4293 logger.Errorw(ctx, "getPonPortStats invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4294 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4295 }
4296
4297 if portInfo[0] != "pon" {
4298 logger.Errorw(ctx, "getPonPortStats invalid portType", log.Fields{"oltPortType": portInfo[0]})
4299 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4300 }
4301
4302 Interface := oop.Interface{IntfId: uint32(portNumber)}
bseenivaa1622112025-12-11 18:24:02 +05304303 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4304 ponStats, err := dh.Client.GetPonPortStatistics(subCtx, &Interface)
4305 cancel()
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304306 if err != nil {
4307 logger.Errorw(ctx, "error-while-getting-pon-port-stats", log.Fields{"IntfId": portNumber, "err": err})
4308 return generateSingleGetValueErrorResponse(err)
4309 }
4310
4311 ponPortStats := resp.Response.GetOltPonStatsResponse()
4312 ponPortStats.PonPort = uint32(portNumber)
4313 ponPortStats.PortStatistics = ponStats
4314
4315 logger.Infow(ctx, "getPonPortStats response ", log.Fields{"Response": resp})
4316 return &resp
4317}
4318
4319func (dh *DeviceHandler) getNniPortStats(ctx context.Context, nniStatsRequest *extension.GetNNIStatsRequest) *extension.SingleGetValueResponse {
4320 errResp := func(status extension.GetValueResponse_Status,
4321 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4322 return &extension.SingleGetValueResponse{
4323 Response: &extension.GetValueResponse{
4324 Status: status,
4325 ErrReason: reason,
4326 },
4327 }
4328 }
4329
4330 resp := extension.SingleGetValueResponse{
4331 Response: &extension.GetValueResponse{
4332 Status: extension.GetValueResponse_OK,
4333 Response: &extension.GetValueResponse_OltNniStatsResponse{
4334 OltNniStatsResponse: &extension.GetNNIStatsResponse{},
4335 },
4336 },
4337 }
4338
4339 portLabel := nniStatsRequest.GetPortLabel()
4340 logger.Debugw(ctx, "getNniPortStats", log.Fields{"portLabel": portLabel, "device-id": dh.device.Id})
4341
4342 portInfo := strings.Split(portLabel, "-")
4343 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4344
4345 if err != nil {
4346 logger.Errorw(ctx, "getNniPortStats invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4347 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4348 }
4349
4350 if portInfo[0] != "nni" {
4351 logger.Errorw(ctx, "getNniPortStats invalid portType", log.Fields{"oltPortType": portInfo[0]})
4352 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4353 }
4354
4355 Interface := oop.Interface{IntfId: uint32(portNumber)}
bseenivaa1622112025-12-11 18:24:02 +05304356 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4357 nniStats, err := dh.Client.GetNniPortStatistics(subCtx, &Interface)
4358 cancel()
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304359 if err != nil {
4360 logger.Errorw(ctx, "error-while-getting-nni-port-stats", log.Fields{"PortNo": portNumber, "err": err})
4361 return generateSingleGetValueErrorResponse(err)
4362 }
4363
4364 nniPortStats := resp.Response.GetOltNniStatsResponse()
4365 nniPortStats.NniPort = uint32(portNumber)
4366 nniPortStats.PortStatistics = nniStats
4367
4368 logger.Infow(ctx, "getNniPortStats response ", log.Fields{"Response": resp})
4369 return &resp
4370}
4371
Akash Kankanala041a2122024-10-16 15:49:22 +05304372// nolint: unparam
Gamze Abaka85e9a142021-05-26 13:41:39 +00004373func generateSingleGetValueErrorResponse(err error) *extension.SingleGetValueResponse {
Akash Kankanala041a2122024-10-16 15:49:22 +05304374 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
Gamze Abaka85e9a142021-05-26 13:41:39 +00004375 return &extension.SingleGetValueResponse{
4376 Response: &extension.GetValueResponse{
4377 Status: status,
4378 ErrReason: reason,
4379 },
4380 }
4381 }
4382
4383 if err != nil {
4384 if e, ok := status.FromError(err); ok {
4385 switch e.Code() {
4386 case codes.Internal:
4387 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
4388 case codes.DeadlineExceeded:
4389 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
4390 case codes.Unimplemented:
4391 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_UNSUPPORTED)
4392 case codes.NotFound:
4393 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4394 }
4395 }
4396 }
4397
4398 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_REASON_UNDEFINED)
4399}
khenaidoo106c61a2021-08-11 18:05:46 -04004400
4401/*
4402Helper functions to communicate with Core
4403*/
4404
4405func (dh *DeviceHandler) getDeviceFromCore(ctx context.Context, deviceID string) (*voltha.Device, error) {
4406 cClient, err := dh.coreClient.GetCoreServiceClient()
4407 if err != nil || cClient == nil {
4408 return nil, err
4409 }
4410 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4411 defer cancel()
4412 return cClient.GetDevice(subCtx, &common.ID{Id: deviceID})
4413}
4414
khenaidoodc2116e2021-10-19 17:33:19 -04004415func (dh *DeviceHandler) getChildDeviceFromCore(ctx context.Context, childDeviceFilter *ca.ChildDeviceFilter) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004416 cClient, err := dh.coreClient.GetCoreServiceClient()
4417 if err != nil || cClient == nil {
4418 return nil, err
4419 }
4420 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4421 defer cancel()
4422 return cClient.GetChildDevice(subCtx, childDeviceFilter)
4423}
4424
khenaidoodc2116e2021-10-19 17:33:19 -04004425func (dh *DeviceHandler) updateDeviceStateInCore(ctx context.Context, deviceStateFilter *ca.DeviceStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004426 cClient, err := dh.coreClient.GetCoreServiceClient()
4427 if err != nil || cClient == nil {
4428 return err
4429 }
4430 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4431 defer cancel()
4432 _, err = cClient.DeviceStateUpdate(subCtx, deviceStateFilter)
4433 return err
4434}
4435
4436func (dh *DeviceHandler) getChildDevicesFromCore(ctx context.Context, deviceID string) (*voltha.Devices, error) {
4437 cClient, err := dh.coreClient.GetCoreServiceClient()
4438 if err != nil || cClient == nil {
4439 return nil, err
4440 }
4441 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4442 defer cancel()
4443 return cClient.GetChildDevices(subCtx, &common.ID{Id: deviceID})
4444}
4445
4446func (dh *DeviceHandler) listDevicePortsFromCore(ctx context.Context, deviceID string) (*voltha.Ports, error) {
4447 cClient, err := dh.coreClient.GetCoreServiceClient()
4448 if err != nil || cClient == nil {
4449 return nil, err
4450 }
4451 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4452 defer cancel()
4453 return cClient.ListDevicePorts(subCtx, &common.ID{Id: deviceID})
4454}
4455
4456func (dh *DeviceHandler) updateDeviceInCore(ctx context.Context, device *voltha.Device) error {
4457 cClient, err := dh.coreClient.GetCoreServiceClient()
4458 if err != nil || cClient == nil {
4459 return err
4460 }
4461 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4462 defer cancel()
4463 _, err = cClient.DeviceUpdate(subCtx, device)
4464 return err
4465}
4466
khenaidoodc2116e2021-10-19 17:33:19 -04004467func (dh *DeviceHandler) sendChildDeviceDetectedToCore(ctx context.Context, deviceDiscoveryInfo *ca.DeviceDiscovery) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004468 cClient, err := dh.coreClient.GetCoreServiceClient()
4469 if err != nil || cClient == nil {
4470 return nil, err
4471 }
4472 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4473 defer cancel()
4474 return cClient.ChildDeviceDetected(subCtx, deviceDiscoveryInfo)
4475}
4476
khenaidoodc2116e2021-10-19 17:33:19 -04004477func (dh *DeviceHandler) sendPacketToCore(ctx context.Context, pkt *ca.PacketIn) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004478 cClient, err := dh.coreClient.GetCoreServiceClient()
4479 if err != nil || cClient == nil {
4480 return err
4481 }
4482 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4483 defer cancel()
4484 _, err = cClient.SendPacketIn(subCtx, pkt)
4485 return err
4486}
4487
4488func (dh *DeviceHandler) createPortInCore(ctx context.Context, port *voltha.Port) error {
4489 cClient, err := dh.coreClient.GetCoreServiceClient()
4490 if err != nil || cClient == nil {
4491 return err
4492 }
4493 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4494 defer cancel()
4495 _, err = cClient.PortCreated(subCtx, port)
4496 return err
4497}
4498
khenaidoodc2116e2021-10-19 17:33:19 -04004499func (dh *DeviceHandler) updatePortsStateInCore(ctx context.Context, portFilter *ca.PortStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004500 cClient, err := dh.coreClient.GetCoreServiceClient()
4501 if err != nil || cClient == nil {
4502 return err
4503 }
4504 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4505 defer cancel()
4506 _, err = cClient.PortsStateUpdate(subCtx, portFilter)
4507 return err
4508}
4509
khenaidoodc2116e2021-10-19 17:33:19 -04004510func (dh *DeviceHandler) updatePortStateInCore(ctx context.Context, portState *ca.PortState) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004511 cClient, err := dh.coreClient.GetCoreServiceClient()
4512 if err != nil || cClient == nil {
4513 return err
4514 }
4515 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4516 defer cancel()
4517 _, err = cClient.PortStateUpdate(subCtx, portState)
4518 return err
4519}
4520
khenaidoodc2116e2021-10-19 17:33:19 -04004521func (dh *DeviceHandler) getPortFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Port, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004522 cClient, err := dh.coreClient.GetCoreServiceClient()
4523 if err != nil || cClient == nil {
4524 return nil, err
4525 }
4526 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4527 defer cancel()
4528 return cClient.GetDevicePort(subCtx, portFilter)
4529}
4530
nikesh.krishnanc8473432023-06-14 12:14:54 +05304531func (dh *DeviceHandler) getAllPortsFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Ports, error) {
4532 cClient, err := dh.coreClient.GetCoreServiceClient()
4533 if err != nil || cClient == nil {
4534 return nil, err
4535 }
4536 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4537 defer cancel()
4538 return cClient.GetPorts(subCtx, portFilter)
4539}
4540
khenaidoo106c61a2021-08-11 18:05:46 -04004541/*
4542Helper functions to communicate with child adapter
4543*/
4544
khenaidoodc2116e2021-10-19 17:33:19 -04004545func (dh *DeviceHandler) sendOmciIndicationToChildAdapter(ctx context.Context, childEndpoint string, response *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004546 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4547 if err != nil || aClient == nil {
4548 return err
4549 }
4550 logger.Debugw(ctx, "sending-omci-response", log.Fields{"response": response, "child-endpoint": childEndpoint})
4551 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4552 defer cancel()
4553 _, err = aClient.OmciIndication(subCtx, response)
4554 return err
4555}
4556
khenaidoodc2116e2021-10-19 17:33:19 -04004557func (dh *DeviceHandler) sendOnuIndicationToChildAdapter(ctx context.Context, childEndpoint string, onuInd *ia.OnuIndicationMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004558 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4559 if err != nil || aClient == nil {
4560 return err
4561 }
4562 logger.Debugw(ctx, "sending-onu-indication", log.Fields{"onu-indication": onuInd, "child-endpoint": childEndpoint})
4563 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4564 defer cancel()
4565 _, err = aClient.OnuIndication(subCtx, onuInd)
4566 return err
4567}
4568
khenaidoodc2116e2021-10-19 17:33:19 -04004569func (dh *DeviceHandler) sendDeleteTContToChildAdapter(ctx context.Context, childEndpoint string, tContInfo *ia.DeleteTcontMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004570 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4571 if err != nil || aClient == nil {
4572 return err
4573 }
4574 logger.Debugw(ctx, "sending-delete-tcont", log.Fields{"tcont": tContInfo, "child-endpoint": childEndpoint})
4575 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4576 defer cancel()
4577 _, err = aClient.DeleteTCont(subCtx, tContInfo)
4578 return err
4579}
4580
khenaidoodc2116e2021-10-19 17:33:19 -04004581func (dh *DeviceHandler) sendDeleteGemPortToChildAdapter(ctx context.Context, childEndpoint string, gemPortInfo *ia.DeleteGemPortMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004582 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4583 if err != nil || aClient == nil {
4584 return err
4585 }
4586 logger.Debugw(ctx, "sending-delete-gem-port", log.Fields{"gem-port-info": gemPortInfo, "child-endpoint": childEndpoint})
4587 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4588 defer cancel()
4589 _, err = aClient.DeleteGemPort(subCtx, gemPortInfo)
4590 return err
4591}
4592
khenaidoodc2116e2021-10-19 17:33:19 -04004593func (dh *DeviceHandler) sendDownloadTechProfileToChildAdapter(ctx context.Context, childEndpoint string, tpDownloadInfo *ia.TechProfileDownloadMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004594 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4595 if err != nil || aClient == nil {
4596 return err
4597 }
4598 logger.Debugw(ctx, "sending-tech-profile-download", log.Fields{"tp-download-info": tpDownloadInfo, "child-endpoint": childEndpoint})
4599 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4600 defer cancel()
4601 _, err = aClient.DownloadTechProfile(subCtx, tpDownloadInfo)
4602 return err
4603}
4604
4605/*
4606Helper functions for remote communication
4607*/
4608
4609// TODO: Use a connection tracker such that the adapter connection is stopped when the last device that adapter
4610// supports is deleted
4611func (dh *DeviceHandler) setupChildInterAdapterClient(ctx context.Context, endpoint string) error {
balaji.nagarajan31db4ea2026-01-28 09:13:55 +05304612 logger.Debugw(ctx, "setting-child-adapter-connection", log.Fields{"child-endpoint": endpoint})
khenaidoo106c61a2021-08-11 18:05:46 -04004613
4614 dh.lockChildAdapterClients.Lock()
4615 defer dh.lockChildAdapterClients.Unlock()
4616 if _, ok := dh.childAdapterClients[endpoint]; ok {
4617 // Already set
4618 return nil
4619 }
4620
4621 // Setup child's adapter grpc connection
4622 var err error
khenaidoo27e7ac92021-12-08 14:43:09 -05004623 if dh.childAdapterClients[endpoint], err = vgrpc.NewClient(
4624 dh.cfg.AdapterEndpoint,
4625 endpoint,
khenaidooefff76e2021-12-15 16:51:30 -05004626 "onu_inter_adapter_service.OnuInterAdapterService",
4627 dh.onuInterAdapterRestarted,
4628 vgrpc.ClientContextData(dh.device.Id)); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04004629 logger.Errorw(ctx, "grpc-client-not-created", log.Fields{"error": err, "endpoint": endpoint})
4630 return err
4631 }
nikesh.krishnand9812542023-08-01 18:31:39 +05304632 retryCodes := []codes.Code{
4633 codes.Unavailable, // server is currently unavailable
4634 codes.DeadlineExceeded, // deadline for the operation was exceeded
4635 }
4636 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(dh.cfg.PerRPCRetryTimeout, 0.2))
4637 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 -04004638
nikesh.krishnand9812542023-08-01 18:31:39 +05304639 go dh.childAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), dh.getOnuInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo106c61a2021-08-11 18:05:46 -04004640 // Wait until we have a connection to the child adapter.
4641 // Unlimited retries or until context expires
4642 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
4643 backoff := vgrpc.NewBackoff(dh.cfg.MinBackoffRetryDelay, dh.cfg.MaxBackoffRetryDelay, 0)
4644 for {
4645 client, err := dh.childAdapterClients[endpoint].GetOnuInterAdapterServiceClient()
4646 if err == nil && client != nil {
4647 logger.Infow(subCtx, "connected-to-child-adapter", log.Fields{"child-endpoint": endpoint})
4648 break
4649 }
4650 logger.Warnw(subCtx, "connection-to-child-adapter-not-ready", log.Fields{"error": err, "child-endpoint": endpoint})
4651 // Backoff
4652 if err = backoff.Backoff(subCtx); err != nil {
4653 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "child-endpoint": endpoint})
4654 break
4655 }
4656 }
4657 return nil
4658}
4659
khenaidoodc2116e2021-10-19 17:33:19 -04004660func (dh *DeviceHandler) getChildAdapterServiceClient(endpoint string) (onu_inter_adapter_service.OnuInterAdapterServiceClient, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004661 // First check from cache
4662 dh.lockChildAdapterClients.RLock()
4663 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4664 dh.lockChildAdapterClients.RUnlock()
4665 return cgClient.GetOnuInterAdapterServiceClient()
4666 }
4667 dh.lockChildAdapterClients.RUnlock()
4668
4669 // Set the child connection - can occur on restarts
4670 ctx, cancel := context.WithTimeout(context.Background(), dh.cfg.RPCTimeout)
4671 err := dh.setupChildInterAdapterClient(ctx, endpoint)
4672 cancel()
4673 if err != nil {
4674 return nil, err
4675 }
4676
4677 // Get the child client now
4678 dh.lockChildAdapterClients.RLock()
4679 defer dh.lockChildAdapterClients.RUnlock()
4680 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4681 return cgClient.GetOnuInterAdapterServiceClient()
4682 }
4683 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
4684}
4685
4686func (dh *DeviceHandler) deleteAdapterClients(ctx context.Context) {
4687 dh.lockChildAdapterClients.Lock()
4688 defer dh.lockChildAdapterClients.Unlock()
4689 for key, client := range dh.childAdapterClients {
4690 client.Stop(ctx)
4691 delete(dh.childAdapterClients, key)
4692 }
4693}
4694
khenaidooefff76e2021-12-15 16:51:30 -05004695// TODO: Any action the adapter needs to do following a onu adapter inter adapter service restart?
4696func (dh *DeviceHandler) onuInterAdapterRestarted(ctx context.Context, endPoint string) error {
4697 logger.Warnw(ctx, "onu-inter-adapter-service-reconnected", log.Fields{"endpoint": endPoint})
khenaidoo106c61a2021-08-11 18:05:46 -04004698 return nil
4699}
4700
khenaidooefff76e2021-12-15 16:51:30 -05004701// getOnuInterAdapterServiceClientHandler is used to setup the remote gRPC service
4702func (dh *DeviceHandler) getOnuInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
4703 if conn == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04004704 return nil
4705 }
khenaidooefff76e2021-12-15 16:51:30 -05004706 return onu_inter_adapter_service.NewOnuInterAdapterServiceClient(conn)
khenaidoo106c61a2021-08-11 18:05:46 -04004707}
Girish Gowdra950326e2021-11-05 12:43:24 -07004708
4709func (dh *DeviceHandler) setDeviceDeletionInProgressFlag(flag bool) {
4710 dh.lockDevice.Lock()
4711 defer dh.lockDevice.Unlock()
4712 dh.isDeviceDeletionInProgress = flag
4713}
4714
4715func (dh *DeviceHandler) getDeviceDeletionInProgressFlag() bool {
4716 dh.lockDevice.RLock()
4717 defer dh.lockDevice.RUnlock()
4718 return dh.isDeviceDeletionInProgress
4719}
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08004720
4721// waitForTimeoutOrCompletion waits for the waitgroup for the specified max timeout.
4722// Returns false if waiting timed out.
4723func (dh *DeviceHandler) waitForTimeoutOrCompletion(wg *sync.WaitGroup, timeout time.Duration) bool {
4724 c := make(chan struct{})
4725 go func() {
4726 defer close(c)
4727 wg.Wait()
4728 }()
4729 select {
4730 case <-c:
4731 return true // completed normally
4732 case <-time.After(timeout):
4733 return false // timed out
4734 }
4735}
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05304736
4737func (dh *DeviceHandler) updateHeartbeatSignature(ctx context.Context, signature uint32) {
4738 val, err := json.Marshal(signature)
4739 if err != nil {
4740 logger.Error(ctx, "failed-to-marshal")
4741 return
4742 }
4743 if err = dh.kvStore.Put(ctx, heartbeatPath, val); err != nil {
4744 logger.Error(ctx, "failed-to-store-hearbeat-signature")
4745 }
4746}
4747
4748func (dh *DeviceHandler) getHeartbeatSignature(ctx context.Context) uint32 {
4749 var signature uint32
4750
4751 Value, er := dh.kvStore.Get(ctx, heartbeatPath)
4752 if er == nil {
4753 if Value != nil {
4754 Val, er := kvstore.ToByte(Value.Value)
4755 if er != nil {
4756 logger.Errorw(ctx, "Failed to convert into byte array", log.Fields{"err": er})
4757 return signature
4758 }
4759 if er = json.Unmarshal(Val, &signature); er != nil {
4760 logger.Error(ctx, "Failed to unmarshal signature", log.Fields{"err": er})
4761 return signature
4762 }
4763 }
4764 }
4765 return signature
4766}
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00004767
4768func (dh *DeviceHandler) UpdateDevice(ctx context.Context, updateDevice *voltha.UpdateDevice) {
4769 var dhCtx context.Context
4770 logger.Debug(ctx, "UpdateDevice called", log.Fields{"deviceConfig": updateDevice})
4771 dh.lockDevice.Lock()
4772 if dh.transitionHandlerCancel != nil {
4773 dh.transitionHandlerCancel() //if the previous device transition was grpc blocked on old IP,this make that handler return/exit.
4774 dh.transitionHandlerCancel = nil
4775 }
4776 err := updateDeviceAddress(dh.device, updateDevice) //update the device handler with the new device which would have newIP
4777 if err != nil {
4778 dh.lockDevice.Unlock()
4779 logger.Errorw(ctx, "failed-to-update-device-address", log.Fields{"error": err})
4780 return
4781 }
4782 connectStatus := dh.device.ConnectStatus
4783 dhCtx, dh.transitionHandlerCancel = context.WithCancel(context.Background())
4784 dh.lockDevice.Unlock()
4785 if connectStatus == voltha.ConnectStatus_REACHABLE {
4786 dh.updateStateUnreachable(dhCtx)
4787 } else {
4788 dh.transitionMap.Handle(dhCtx, DeviceInit)
4789 }
4790}
4791
4792func updateDeviceAddress(device *voltha.Device, deviceConfig *voltha.UpdateDevice) error {
4793 switch addr := deviceConfig.Address.(type) {
4794 case *voltha.UpdateDevice_Ipv4Address:
4795 if current, ok := device.Address.(*voltha.Device_Ipv4Address); ok {
4796 if current.Ipv4Address == addr.Ipv4Address {
4797 return fmt.Errorf("no-change-in-IPV4-device-address")
4798 }
4799 device.Address = &voltha.Device_Ipv4Address{Ipv4Address: addr.Ipv4Address}
4800 }
4801 case *voltha.UpdateDevice_Ipv6Address:
4802 if current, ok := device.Address.(*voltha.Device_Ipv6Address); ok {
4803 if current.Ipv6Address == addr.Ipv6Address {
4804 return fmt.Errorf("no-change-in-IPV6-device-address")
4805 }
4806 device.Address = &voltha.Device_Ipv6Address{Ipv6Address: addr.Ipv6Address}
4807 }
4808 case *voltha.UpdateDevice_HostAndPort:
4809 if current, ok := device.Address.(*voltha.Device_HostAndPort); ok {
4810 if current.HostAndPort == addr.HostAndPort {
4811 return fmt.Errorf("no-change-in-HostAndPort-device-address")
4812 }
4813 device.Address = &voltha.Device_HostAndPort{HostAndPort: addr.HostAndPort}
4814 }
4815 default:
4816 return fmt.Errorf("invalid-device-config-address-type")
4817 }
4818 return nil
4819}