blob: 429178be92e111920ea9c9a5f6ac8ee26b0e98f2 [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)
957 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530958 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530959 }
nikesh.krishnanc8473432023-06-14 12:14:54 +0530960 return nil
961}
962
963func (dh *DeviceHandler) reconcilePonPorts(ctx context.Context) error { // need onuid and pon id
964 portsFromCore, err := dh.getAllPortsFromCore(ctx, &ca.PortFilter{
965 DeviceId: dh.device.Id,
966 PortType: voltha.Port_PON_OLT,
967 })
968 if err != nil {
969 logger.Error(ctx, "unable to fetch ports from core", log.Fields{"eeror": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +0530970 return err
nikesh.krishnanc8473432023-06-14 12:14:54 +0530971 }
972 for _, portFromCore := range portsFromCore.Items {
973 portNum := portFromCore.GetPortNo()
974 intfID := plt.PortNoToIntfID(portNum, voltha.Port_PON_OLT)
975 portOperStatusFromCore := portFromCore.OperStatus
976 portAdminStateFromCore := portFromCore.AdminState
977 ponPortFromOlt, err := dh.getIntfInfo(ctx, intfID)
978 if err != nil {
979 logger.Error(ctx, "unable to get pon objects from olt agent", log.Fields{"eeror": err})
980 } else {
981 portLosFromOlt := ponPortFromOlt.GetLos()
982 portStateFromOlt := ponPortFromOlt.GetState()
983 if portOperStatusFromCore.String() == "ACTIVE" && portLosFromOlt.String() == "ON" {
984 logger.Debug(ctx, "port is active in core but los is fired from olt", log.Fields{
985 "portStateFromOlt": portStateFromOlt.String(),
986 "portOperStatusFromCore": portOperStatusFromCore.String(),
987 "device-id": dh.device.Id,
988 "port": portNum})
989 ponLosindication := generatePonLosAlarmIndication(intfID, "on")
990 raisedTs := time.Now().Unix()
991 go dh.eventMgr.ProcessEvents(ctx, ponLosindication, dh.device.Id, raisedTs)
nikesh.krishnanc8473432023-06-14 12:14:54 +0530992 }
993 switch {
994 case portStateFromOlt.String() == "ACTIVE_WORKING" && portOperStatusFromCore.String() != "ACTIVE":
995 logger.Debug(ctx, "mismatch between port state in voltha core and raising port up event", log.Fields{
996 "portStateFromOlt": portStateFromOlt.String(),
997 "portOperStatusFromCore": portOperStatusFromCore.String(),
998 "device-id": dh.device.Id,
999 "port": portNum})
1000 dh.updateIntfOperStateAndRaiseIndication(ctx, "up", intfID)
1001 case (portStateFromOlt.String() == "INACTIVE" || portStateFromOlt.String() == "UNKNOWN") && portOperStatusFromCore.String() == "ACTIVE":
1002 logger.Debug(ctx, "mismatch between port state in voltha core and raising port down event", log.Fields{
1003 "portStateFromOlt": portStateFromOlt.String(),
1004 "portOperStatusFromCore": portOperStatusFromCore.String(),
1005 "device-id": dh.device.Id,
1006 "port": portNum})
1007 dh.updateIntfOperStateAndRaiseIndication(ctx, "down", intfID)
1008 case portStateFromOlt.String() == "DISABLED" && portAdminStateFromCore.String() == "ENABLED":
1009 logger.Error(ctx, "port enabled in device but disabled at votlha core", log.Fields{
1010 "device-id": dh.device.Id,
1011 "port": portNum})
1012 default:
1013 logger.Error(ctx, "mismatch between port state in voltha core and voltha device", log.Fields{
1014 "portStateFromOlt": portStateFromOlt.String(),
1015 "portOperStatusFromCore": portOperStatusFromCore.String(),
1016 "device-id": dh.device.Id,
1017 "port": portNum})
nikesh.krishnanc8473432023-06-14 12:14:54 +05301018 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301019 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301020 }
nikesh.krishnanc8473432023-06-14 12:14:54 +05301021 return nil
1022}
1023
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301024// doStateUp handle the olt up indication and update to voltha core
npujarec5762e2020-01-01 14:08:48 +05301025func (dh *DeviceHandler) doStateUp(ctx context.Context) error {
Thomas Lee S85f37312020-04-03 17:06:12 +05301026 //starting the stat collector
Nandita Biradar1b590f12024-09-27 10:56:28 +05301027 // Declare deviceStateFilter to be used later
1028 var deviceStateFilter *ca.DeviceStateFilter
bseenivaaa9165b2025-09-18 17:28:12 +05301029 dh.collectorWaitGroup.Add(1)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001030 go startCollector(ctx, dh)
nikesh.krishnanc8473432023-06-14 12:14:54 +05301031 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301032 if err != nil {
1033 return fmt.Errorf("failed to get device from core: %w", err)
1034 }
1035 logger.Info(ctx, "Device state", log.Fields{
1036 "device-id": device.Id,
1037 "CurrOperStatus": device.OperStatus,
1038 "CurrConnStatus": device.ConnectStatus,
1039 })
1040 // Perform cleanup if the device's operational status is REBOOTED
1041 if device.OperStatus == voltha.OperStatus_RECONCILING && dh.prevOperStatus == voltha.OperStatus_REBOOTED {
1042 // Log the device's operational status if it's REBOOTED
1043 logger.Info(ctx, "Device is transitioning from REBOOTED to RECONCILING", log.Fields{
1044 "device-id": device.Id,
1045 "OperStatus": device.OperStatus,
1046 })
1047 dh.lockDevice.RLock()
1048 // Stop the read indication only if it the routine is active
1049 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
1050 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
1051 // on next execution of the readIndication routine.
1052 if dh.isHeartbeatCheckActive {
1053 dh.stopHeartbeatCheck <- true
1054 }
1055 if dh.isReadIndicationRoutineActive {
1056 dh.stopIndications <- true
1057 }
bseenivaaa9165b2025-09-18 17:28:12 +05301058 if dh.isCollectorActive {
1059 dh.stopCollector <- true
1060 }
Nandita Biradar1b590f12024-09-27 10:56:28 +05301061 dh.lockDevice.RUnlock()
Akash Kankanala041a2122024-10-16 15:49:22 +05301062 if err = dh.cleanupDeviceResources(ctx); err != nil {
Nandita Biradar1b590f12024-09-27 10:56:28 +05301063 logger.Error(ctx, "unable to clean up device resources", log.Fields{"error": err})
1064 return fmt.Errorf("cleanup device resources failed: %w", err)
1065 }
Akash Kankanala041a2122024-10-16 15:49:22 +05301066 if err = dh.initializeDeviceHandlerModules(ctx); err != nil {
Nandita Biradar1b590f12024-09-27 10:56:28 +05301067 return olterrors.NewErrAdapter("device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
1068 }
bseenivaaa9165b2025-09-18 17:28:12 +05301069 dh.collectorWaitGroup.Add(1)
1070 go startCollector(ctx, dh)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301071 go startHeartbeatCheck(ctx, dh)
Nandita Biradar1b590f12024-09-27 10:56:28 +05301072 //dh.lockDevice.RUnlock()
Nandita Biradar1b590f12024-09-27 10:56:28 +05301073 } else if device.OperStatus == voltha.OperStatus_RECONCILING {
1074 // Log the device's operational status if it's RECONCILING
1075 logger.Info(ctx, "Device is being reconciled", log.Fields{
1076 "device-id": device.Id,
1077 "OperStatus": device.OperStatus,
1078 })
1079
1080 // Perform reconciliation steps
1081 err = dh.reconcileOnus(ctx)
1082 if err != nil {
1083 logger.Error(ctx, "unable to reconcile onu", log.Fields{"error": err})
1084 }
1085 err = dh.reconcilePonPorts(ctx)
1086 if err != nil {
1087 logger.Error(ctx, "unable to reconcile pon ports", log.Fields{"error": err})
nikesh.krishnanc8473432023-06-14 12:14:54 +05301088 }
1089 }
Girish Gowdra618fa572021-09-01 17:19:29 -07001090 // instantiate the mcast handler routines.
1091 for i := range dh.incomingMcastFlowOrGroup {
1092 // We land inside the below "if" code path, after the OLT comes back from a reboot, otherwise the routines
1093 // are already active when the DeviceHandler module is first instantiated (as part of Adopt_device RPC invocation).
1094 if !dh.mcastHandlerRoutineActive[i] {
1095 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
1096 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
1097 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
1098 // for incoming mcast flow/group to be processed serially.
1099 dh.mcastHandlerRoutineActive[i] = true
1100 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
1101 }
1102 }
Nandita Biradar1b590f12024-09-27 10:56:28 +05301103 // Create DeviceStateFilter with the desired operational and connection statuses
1104 deviceStateFilter = &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001105 DeviceId: dh.device.Id,
1106 OperStatus: voltha.OperStatus_ACTIVE,
1107 ConnStatus: voltha.ConnectStatus_REACHABLE,
Nandita Biradar1b590f12024-09-27 10:56:28 +05301108 }
1109 // Log DeviceStateFilter for debugging purposes
1110 logger.Info(ctx, "DeviceStateFilter", log.Fields{
1111 "DeviceId": deviceStateFilter.DeviceId,
1112 "OperStatus": deviceStateFilter.OperStatus,
1113 "ConnStatus": deviceStateFilter.ConnStatus,
1114 })
1115 // Synchronous call to update device state - this method is run in its own go routine
balaji6299cb23cbe2025-04-14 17:53:10 +05301116 if err = dh.updateDeviceStateInCore(ctx, deviceStateFilter); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001117 return olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001118 }
Gamze Abaka07868a52020-12-17 14:19:28 +00001119
Akash Kankanala041a2122024-10-16 15:49:22 +05301120 // Clear olt communication failure event
Gamze Abaka07868a52020-12-17 14:19:28 +00001121 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
1122 dh.device.OperStatus = voltha.OperStatus_ACTIVE
balaji6299cb23cbe2025-04-14 17:53:10 +05301123
1124 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
1125 if err != nil {
1126 return olterrors.NewErrAdapter("fetch-ports-failed", log.Fields{"device-id": dh.device.Id}, err)
1127 }
1128 dh.populateActivePorts(ctx, ports.Items)
1129 if err = dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
1130 logger.Error(ctx, "port-status-update-failed", log.Fields{"error": err, "ports": ports})
1131 }
1132
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001133 raisedTs := time.Now().Unix()
Gamze Abaka07868a52020-12-17 14:19:28 +00001134 go dh.eventMgr.oltCommunicationEvent(ctx, dh.device, raisedTs)
1135
Girish Gowdru0c588b22019-04-23 23:24:56 -04001136 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301137}
1138
1139// doStateDown handle the olt down indication
npujarec5762e2020-01-01 14:08:48 +05301140func (dh *DeviceHandler) doStateDown(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001141 logger.Debugw(ctx, "do-state-down-start", log.Fields{"device-id": dh.device.Id})
Girish Gowdrud4245152019-05-10 00:47:31 -04001142
khenaidoo106c61a2021-08-11 18:05:46 -04001143 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Girish Gowdrud4245152019-05-10 00:47:31 -04001144 if err != nil || device == nil {
1145 /*TODO: needs to handle error scenarios */
Girish Kumarf26e4882020-03-05 06:49:10 +00001146 return olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001147 }
1148
1149 cloned := proto.Clone(device).(*voltha.Device)
Girish Gowdrud4245152019-05-10 00:47:31 -04001150
Akash Kankanala041a2122024-10-16 15:49:22 +05301151 // Update the device oper state and connection status
Girish Gowdrud4245152019-05-10 00:47:31 -04001152 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001153 dh.lockDevice.Lock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001154 dh.device = cloned
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001155 dh.lockDevice.Unlock()
Girish Gowdrud4245152019-05-10 00:47:31 -04001156
khenaidoodc2116e2021-10-19 17:33:19 -04001157 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001158 DeviceId: cloned.Id,
1159 OperStatus: cloned.OperStatus,
1160 ConnStatus: cloned.ConnectStatus,
1161 }); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001162 return olterrors.NewErrAdapter("state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -04001163 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001164
Akash Kankanala041a2122024-10-16 15:49:22 +05301165 // get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04001166 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001167 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001168 return olterrors.NewErrAdapter("child-device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001169 }
1170 for _, onuDevice := range onuDevices.Items {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001171 // Update onu state as down in onu adapter
1172 onuInd := oop.OnuIndication{}
1173 onuInd.OperState = "down"
khenaidoo106c61a2021-08-11 18:05:46 -04001174
1175 ogClient, err := dh.getChildAdapterServiceClient(onuDevice.AdapterEndpoint)
1176 if err != nil {
1177 return err
1178 }
1179 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
khenaidoodc2116e2021-10-19 17:33:19 -04001180 _, err = ogClient.OnuIndication(subCtx, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001181 DeviceId: onuDevice.Id,
1182 OnuIndication: &onuInd,
1183 })
1184 cancel()
David K. Bainbridge794735f2020-02-11 21:01:37 -08001185 if err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001186 _ = olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001187 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001188 "onu-indicator": onuInd,
1189 "device-type": onuDevice.Type,
1190 "device-id": onuDevice.Id}, err).LogAt(log.ErrorLevel)
Akash Kankanala041a2122024-10-16 15:49:22 +05301191 // Do not return here and continue to process other ONUs
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001192 } else {
1193 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 -07001194 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001195 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001196 dh.lockDevice.Lock()
serkant.uluderya245caba2019-09-24 23:15:29 -07001197 /* Discovered ONUs entries need to be cleared , since after OLT
1198 is up, it starts sending discovery indications again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301199 dh.discOnus = sync.Map{}
Girish Gowdrabe811ff2021-01-26 17:12:12 -08001200 dh.lockDevice.Unlock()
1201
Neha Sharma96b7bf22020-06-15 10:37:32 +00001202 logger.Debugw(ctx, "do-state-down-end", log.Fields{"device-id": device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001203 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301204}
1205
1206// doStateInit dial the grpc before going to init state
npujarec5762e2020-01-01 14:08:48 +05301207func (dh *DeviceHandler) doStateInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001208 var err error
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001209 dh.lockDevice.RLock()
1210 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.
1211 dh.lockDevice.RUnlock()
Gamze Abaka49c40b32021-05-06 09:30:41 +00001212 // if the connection is already available, close the previous connection (olt reboot case)
1213 if dh.clientCon != nil {
1214 if err = dh.clientCon.Close(); err != nil {
1215 logger.Errorw(ctx, "failed-to-close-previous-connection", log.Fields{"device-id": dh.device.Id})
1216 } else {
1217 logger.Debugw(ctx, "previous-grpc-channel-closed-successfully", log.Fields{"device-id": dh.device.Id})
1218 }
1219 }
1220
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001221 logger.Debugw(ctx, "Dialing grpc", log.Fields{"device-id": dh.device.Id, "host-and-port": hostAndPort})
Abhay Kumard3f18512025-12-09 07:51:12 +00001222 grpc_prometheus.EnableClientHandlingTimeHistogram()
Gamze Abaka49c40b32021-05-06 09:30:41 +00001223 // Use Interceptors to automatically inject and publish Open Tracing Spans by this GRPC client
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001224 dh.clientCon, err = grpc.DialContext(ctx, hostAndPort,
Girish Kumar93e91742020-07-27 16:43:19 +00001225 grpc.WithInsecure(),
1226 grpc.WithBlock(),
1227 grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001228 grpc_opentracing.StreamClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Abhay Kumard3f18512025-12-09 07:51:12 +00001229 grpc_prometheus.StreamClientInterceptor,
Girish Kumar93e91742020-07-27 16:43:19 +00001230 )),
1231 grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
Girish Kumar935f7af2020-08-18 11:59:42 +00001232 grpc_opentracing.UnaryClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Abhay Kumard3f18512025-12-09 07:51:12 +00001233 grpc_prometheus.UnaryClientInterceptor,
Girish Kumar93e91742020-07-27 16:43:19 +00001234 )))
1235
1236 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301237 return olterrors.NewErrCommunication("dial-failure", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05301238 "device-id": dh.device.Id,
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001239 "host-and-port": hostAndPort}, err)
Akash Sonif49299a2024-04-25 12:06:37 +05301240 }
1241
1242 if dh.device.OperStatus == voltha.OperStatus_RECONCILING {
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001243 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
Akash Sonif49299a2024-04-25 12:06:37 +05301244 DeviceId: dh.device.Id,
1245 OperStatus: voltha.OperStatus_RECONCILING,
1246 ConnStatus: voltha.ConnectStatus_REACHABLE,
1247 }); err != nil {
1248 return olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
1249 }
1250 // 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
1251 // locally cached copy of the device struct.
1252 dh.device.OperStatus = voltha.OperStatus_RECONCILING
1253 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
1254 }
1255
Girish Gowdru0c588b22019-04-23 23:24:56 -04001256 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301257}
1258
1259// postInit create olt client instance to invoke RPC on the olt device
npujarec5762e2020-01-01 14:08:48 +05301260func (dh *DeviceHandler) postInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001261 dh.Client = oop.NewOpenoltClient(dh.clientCon)
bseenivaa20d6c32026-01-11 21:51:19 +05301262 // decoupling it to avoid blocking state machine transition
1263 go dh.transitionMap.Handle(ctx, GrpcConnected)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001264 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301265}
1266
1267// doStateConnected get the device info and update to voltha core
npujarec5762e2020-01-01 14:08:48 +05301268func (dh *DeviceHandler) doStateConnected(ctx context.Context) error {
Thomas Lee S985938d2020-05-04 11:40:41 +05301269 var err error
Neha Sharma96b7bf22020-06-15 10:37:32 +00001270 logger.Debugw(ctx, "olt-device-connected", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001271
1272 // Case where OLT is disabled and then rebooted.
khenaidoo106c61a2021-08-11 18:05:46 -04001273 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Thomas Lee S985938d2020-05-04 11:40:41 +05301274 if err != nil || device == nil {
1275 /*TODO: needs to handle error scenarios */
1276 return olterrors.NewErrAdapter("device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
1277 }
1278 if device.AdminState == voltha.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001279 logger.Debugln(ctx, "do-state-connected--device-admin-state-down")
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001280
1281 cloned := proto.Clone(device).(*voltha.Device)
1282 cloned.ConnectStatus = voltha.ConnectStatus_REACHABLE
1283 cloned.OperStatus = voltha.OperStatus_UNKNOWN
1284 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04001285
khenaidoodc2116e2021-10-19 17:33:19 -04001286 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001287 DeviceId: cloned.Id,
1288 OperStatus: cloned.OperStatus,
1289 ConnStatus: cloned.ConnectStatus,
1290 }); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301291 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 -04001292 }
1293
bseenivaa1622112025-12-11 18:24:02 +05301294 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
Chaitrashree G S44124192019-08-07 20:21:36 -04001295 // 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 +05301296 _, err = dh.Client.DisableOlt(subCtx, new(oop.Empty))
1297 cancel()
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001298 if err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05301299 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001300 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001301 // We should still go ahead an initialize various device handler modules so that when OLT is re-enabled, we have
1302 // all the modules initialized and ready to handle incoming ONUs.
1303
Thomas Lee S985938d2020-05-04 11:40:41 +05301304 err = dh.initializeDeviceHandlerModules(ctx)
1305 if err != nil {
1306 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 -04001307 }
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001308
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001309 go startHeartbeatCheck(ctx, dh)
1310
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04001311 return nil
1312 }
1313
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001314 if err := dh.initializeDeviceHandlerModules(ctx); err != nil {
bseenivaa20d6c32026-01-11 21:51:19 +05301315 logger.Error(ctx, "device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id, "error": err})
1316 cloned := proto.Clone(device).(*voltha.Device)
1317 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
1318 cloned.OperStatus = voltha.OperStatus_UNKNOWN
1319 dh.device = cloned
1320
1321 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
1322 DeviceId: cloned.Id,
1323 OperStatus: cloned.OperStatus,
1324 ConnStatus: cloned.ConnectStatus,
1325 }); err != nil {
1326 logger.Error(ctx, "device-state-update-failed", log.Fields{"device-id": dh.device.Id, "error": err})
1327 }
1328 // decoupling it to avoid blocking state machine transition
1329 go dh.transitionMap.Handle(ctx, GrpcDisconnected)
1330 return nil
Girish Gowdru0c588b22019-04-23 23:24:56 -04001331 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301332
Neha Sharma96b7bf22020-06-15 10:37:32 +00001333 go dh.updateLocalDevice(ctx)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001334
1335 if device.PmConfigs != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001336 dh.UpdatePmConfig(ctx, device.PmConfigs)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001337 }
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001338
1339 go startHeartbeatCheck(ctx, dh)
1340
cuilin20187b2a8c32019-03-26 19:52:28 -07001341 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301342}
1343
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001344func (dh *DeviceHandler) initializeDeviceHandlerModules(ctx context.Context) error {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001345 var err error
1346 dh.deviceInfo, err = dh.populateDeviceInfo(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001347
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00001348 if dh.flowMgr != nil {
1349 dh.StopAllFlowRoutines(ctx)
1350 }
1351
1352 dh.CloseKVClient(ctx)
1353
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001354 if err != nil {
1355 return olterrors.NewErrAdapter("populate-device-info-failed", log.Fields{"device-id": dh.device.Id}, err)
1356 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001357 dh.totalPonPorts = dh.deviceInfo.GetPonPorts()
1358 dh.agentPreviouslyConnected = dh.deviceInfo.PreviouslyConnected
bseenivaaa9165b2025-09-18 17:28:12 +05301359 // If collector go routine is active, wait for it to stop
1360 dh.lockDevice.RLock()
1361 if dh.isCollectorActive {
1362 dh.lockDevice.RUnlock()
1363 dh.collectorWaitGroup.Wait()
1364 } else {
1365 dh.lockDevice.RUnlock()
1366 }
yasin saplid0566272021-12-21 09:10:30 +00001367 // +1 is for NNI
1368 dh.resourceMgr = make([]*rsrcMgr.OpenOltResourceMgr, dh.totalPonPorts+1)
1369 dh.flowMgr = make([]*OpenOltFlowMgr, dh.totalPonPorts+1)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001370 var i uint32
yasin saplid0566272021-12-21 09:10:30 +00001371 // Index from 0 to until totalPonPorts ( Ex: 0 .. 15 ) -> PonPort Managers
1372 // Index totalPonPorts ( Ex: 16 ) -> NniPort Manager
1373 // There is only one NNI manager since multiple NNI is not supported for now
1374 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001375 // Instantiate resource manager
1376 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 -07001377 return olterrors.ErrResourceManagerInstantiating
1378 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001379 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001380 // GroupManager instance is per OLT. But it needs a reference to any instance of resourceMgr to interface with
1381 // the KV store to manage mcast group data. Provide the first instance (0th index)
1382 if dh.groupMgr = NewGroupManager(ctx, dh, dh.resourceMgr[0]); dh.groupMgr == nil {
1383 return olterrors.ErrGroupManagerInstantiating
1384 }
yasin saplid0566272021-12-21 09:10:30 +00001385 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001386 // Instantiate flow manager
1387 if dh.flowMgr[i] = NewFlowManager(ctx, dh, dh.resourceMgr[i], dh.groupMgr, i); dh.flowMgr[i] == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05301388 // Continue to check the rest of the ports
Mahir Gunyela2e68702022-12-07 00:00:42 -08001389 logger.Errorw(ctx, "error-initializing-flow-manager-for-intf", log.Fields{"intfID": i, "device-id": dh.device.Id})
1390 } else {
1391 dh.resourceMgr[i].TechprofileRef = dh.flowMgr[i].techprofile
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001392 }
1393 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001394 /* TODO: Instantiate Alarm , stats , BW managers */
1395 /* Instantiating Event Manager to handle Alarms and KPIs */
1396 dh.eventMgr = NewEventMgr(dh.EventProxy, dh)
1397
1398 // Stats config for new device
Neha Sharma96b7bf22020-06-15 10:37:32 +00001399 dh.portStats = NewOpenOltStatsMgr(ctx, dh)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001400
1401 return nil
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001402}
1403
Neha Sharma96b7bf22020-06-15 10:37:32 +00001404func (dh *DeviceHandler) populateDeviceInfo(ctx context.Context) (*oop.DeviceInfo, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001405 var err error
1406 var deviceInfo *oop.DeviceInfo
Akash Kankanala041a2122024-10-16 15:49:22 +05301407 var genmac string
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001408
bseenivaa1622112025-12-11 18:24:02 +05301409 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1410 deviceInfo, err = dh.Client.GetDeviceInfo(subCtx, new(oop.Empty))
1411 cancel()
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001412
1413 if err != nil {
bseenivaa20d6c32026-01-11 21:51:19 +05301414 return nil, olterrors.NewErrCommunication("get-device-info-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001415 }
1416 if deviceInfo == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001417 return nil, olterrors.NewErrInvalidValue(log.Fields{"device": nil}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001418 }
1419
Neha Sharma96b7bf22020-06-15 10:37:32 +00001420 logger.Debugw(ctx, "fetched-device-info", log.Fields{"deviceInfo": deviceInfo, "device-id": dh.device.Id})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001421 dh.device.Root = true
1422 dh.device.Vendor = deviceInfo.Vendor
1423 dh.device.Model = deviceInfo.Model
1424 dh.device.SerialNumber = deviceInfo.DeviceSerialNumber
1425 dh.device.HardwareVersion = deviceInfo.HardwareVersion
1426 dh.device.FirmwareVersion = deviceInfo.FirmwareVersion
1427
1428 if deviceInfo.DeviceId == "" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001429 logger.Warnw(ctx, "no-device-id-provided-using-host", log.Fields{"hostport": dh.device.GetHostAndPort()})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001430 host := strings.Split(dh.device.GetHostAndPort(), ":")[0]
Akash Kankanala041a2122024-10-16 15:49:22 +05301431 genmac, err = generateMacFromHost(ctx, host)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001432 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001433 return nil, olterrors.NewErrAdapter("failed-to-generate-mac-host", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001434 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001435 logger.Debugw(ctx, "using-host-for-mac-address", log.Fields{"host": host, "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001436 dh.device.MacAddress = genmac
1437 } else {
1438 dh.device.MacAddress = deviceInfo.DeviceId
1439 }
1440
1441 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -04001442 if err = dh.updateDeviceInCore(ctx, dh.device); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001443 return nil, olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001444 }
1445
1446 return deviceInfo, nil
1447}
1448
Neha Sharma96b7bf22020-06-15 10:37:32 +00001449func startCollector(ctx context.Context, dh *DeviceHandler) {
bseenivaaa9165b2025-09-18 17:28:12 +05301450 logger.Infow(ctx, "starting-collector", log.Fields{"device-id": dh.device.Id})
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001451
1452 defer func() {
1453 dh.lockDevice.Lock()
1454 dh.isCollectorActive = false
1455 dh.lockDevice.Unlock()
bseenivaaa9165b2025-09-18 17:28:12 +05301456 dh.collectorWaitGroup.Done()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001457 }()
1458
1459 dh.lockDevice.Lock()
1460 dh.isCollectorActive = true
1461 dh.lockDevice.Unlock()
1462
Naga Manjunath7615e552019-10-11 22:35:47 +05301463 for {
1464 select {
1465 case <-dh.stopCollector:
bseenivaaa9165b2025-09-18 17:28:12 +05301466 logger.Infow(ctx, "stopping-collector-for-olt", log.Fields{"device-id": dh.device.Id})
Naga Manjunath7615e552019-10-11 22:35:47 +05301467 return
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001468 case <-time.After(time.Duration(dh.metrics.ToPmConfigs().DefaultFreq) * time.Second):
Girish Gowdra34815db2020-05-11 17:18:04 -07001469
khenaidoo106c61a2021-08-11 18:05:46 -04001470 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001471 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001472 logger.Warnw(ctx, "failed-to-list-ports", log.Fields{"device-id": dh.device.Id, "err": err})
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001473 continue
1474 }
khenaidoo106c61a2021-08-11 18:05:46 -04001475 for _, port := range ports.Items {
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301476 // NNI Stats
1477 if port.Type == voltha.Port_ETHERNET_NNI {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001478 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301479 cmnni := dh.portStats.collectNNIMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001480 logger.Debugw(ctx, "collect-nni-metrics", log.Fields{"metrics": cmnni})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001481 go dh.portStats.publishMetrics(ctx, NNIStats, cmnni, port, dh.device.Id, dh.device.Type)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001482 logger.Debugw(ctx, "publish-nni-metrics", log.Fields{"nni-port": port.Label})
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301483 }
1484 // PON Stats
1485 if port.Type == voltha.Port_PON_OLT {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001486 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301487 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
1488 cmpon := dh.portStats.collectPONMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001489 logger.Debugw(ctx, "collect-pon-metrics", log.Fields{"metrics": cmpon})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001490 go dh.portStats.publishMetrics(ctx, PONStats, cmpon, port, dh.device.Id, dh.device.Type)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301491 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001492 logger.Debugw(ctx, "publish-pon-metrics", log.Fields{"pon-port": port.Label})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001493
yasin sapli9e4c5092022-02-01 13:52:33 +00001494 onuGemInfoLst := dh.resourceMgr[intfID].GetOnuGemInfoList(ctx)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001495 if len(onuGemInfoLst) > 0 {
1496 go dh.portStats.collectOnuAndGemStats(ctx, onuGemInfoLst)
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001497 }
Chaitrashree G Sef088112020-02-03 21:39:27 -05001498 }
Naga Manjunath7615e552019-10-11 22:35:47 +05301499 }
1500 }
1501 }
1502}
1503
Mahir Gunyela2e68702022-12-07 00:00:42 -08001504// AdoptDevice adopts the OLT device
npujarec5762e2020-01-01 14:08:48 +05301505func (dh *DeviceHandler) AdoptDevice(ctx context.Context, device *voltha.Device) {
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001506 var dhCtx context.Context
Girish Gowdru0c588b22019-04-23 23:24:56 -04001507 dh.transitionMap = NewTransitionMap(dh)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001508 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id, "Address": device.GetHostAndPort()})
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00001509 dhCtx, dh.transitionHandlerCancel = context.WithCancel(context.Background())
1510 dh.transitionMap.Handle(dhCtx, DeviceInit)
Naga Manjunath7615e552019-10-11 22:35:47 +05301511
1512 // Now, set the initial PM configuration for that device
khenaidoo106c61a2021-08-11 18:05:46 -04001513 cgClient, err := dh.coreClient.GetCoreServiceClient()
1514 if err != nil {
1515 logger.Errorw(ctx, "no-core-connection", log.Fields{"device-id": dh.device.Id, "error": err})
1516 return
1517 }
1518
1519 // Now, set the initial PM configuration for that device
1520 if _, err := cgClient.DevicePMConfigUpdate(ctx, dh.metrics.ToPmConfigs()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001521 _ = olterrors.NewErrAdapter("error-updating-performance-metrics", log.Fields{"device-id": device.Id}, err).LogAt(log.ErrorLevel)
Naga Manjunath7615e552019-10-11 22:35:47 +05301522 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301523}
1524
Mahir Gunyela2e68702022-12-07 00:00:42 -08001525// GetOfpDeviceInfo Gets the Ofp information of the given device
khenaidoodc2116e2021-10-19 17:33:19 -04001526func (dh *DeviceHandler) GetOfpDeviceInfo(device *voltha.Device) (*ca.SwitchCapability, error) {
1527 return &ca.SwitchCapability{
cuilin20187b2a8c32019-03-26 19:52:28 -07001528 Desc: &of.OfpDesc{
Devmalya Paul70dd4972019-06-10 15:19:17 +05301529 MfrDesc: "VOLTHA Project",
cuilin20187b2a8c32019-03-26 19:52:28 -07001530 HwDesc: "open_pon",
1531 SwDesc: "open_pon",
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001532 SerialNum: device.SerialNumber,
cuilin20187b2a8c32019-03-26 19:52:28 -07001533 },
1534 SwitchFeatures: &of.OfpSwitchFeatures{
1535 NBuffers: 256,
1536 NTables: 2,
1537 Capabilities: uint32(of.OfpCapabilities_OFPC_FLOW_STATS |
1538 of.OfpCapabilities_OFPC_TABLE_STATS |
1539 of.OfpCapabilities_OFPC_PORT_STATS |
1540 of.OfpCapabilities_OFPC_GROUP_STATS),
1541 },
1542 }, nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301543}
1544
khenaidoo106c61a2021-08-11 18:05:46 -04001545// GetTechProfileDownloadMessage fetches the TechProfileDownloadMessage for the caller.
khenaidoodc2116e2021-10-19 17:33:19 -04001546func (dh *DeviceHandler) GetTechProfileDownloadMessage(ctx context.Context, request *ia.TechProfileInstanceRequestMessage) (*ia.TechProfileDownloadMessage, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001547 ifID, err := plt.IntfIDFromPonPortNum(ctx, request.ParentPonPort)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001548 if err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001549 return nil, err
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001550 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08001551 if dh.flowMgr == nil || dh.flowMgr[ifID] == nil {
1552 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()
1553 }
khenaidoo106c61a2021-08-11 18:05:46 -04001554 return dh.flowMgr[ifID].getTechProfileDownloadMessage(ctx, request.TpInstancePath, request.OnuId, request.DeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001555}
1556
Neha Sharma96b7bf22020-06-15 10:37:32 +00001557func (dh *DeviceHandler) omciIndication(ctx context.Context, omciInd *oop.OmciIndication) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001558 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 -07001559 var deviceType string
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001560 var deviceID string
1561 var proxyDeviceID string
khenaidoo106c61a2021-08-11 18:05:46 -04001562 var childAdapterEndpoint string
cuilin20187b2a8c32019-03-26 19:52:28 -07001563
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001564 transid := extractOmciTransactionID(omciInd.Pkt)
Matteo Scandolo92186242020-06-12 10:54:18 -07001565 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001566 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 -07001567 "omci-transaction-id": transid, "omci-msg": hex.EncodeToString(omciInd.Pkt)})
1568 }
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001569
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001570 onuKey := dh.formOnuKey(omciInd.IntfId, omciInd.OnuId)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301571
1572 if onuInCache, ok := dh.onus.Load(onuKey); !ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001573 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 -07001574 ponPort := plt.IntfIDToPortNo(omciInd.GetIntfId(), voltha.Port_PON_OLT)
cuilin20187b2a8c32019-03-26 19:52:28 -07001575
khenaidoodc2116e2021-10-19 17:33:19 -04001576 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001577 ParentId: dh.device.Id,
1578 OnuId: omciInd.OnuId,
1579 ParentPortNo: ponPort,
1580 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001581 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301582 return olterrors.NewErrNotFound("onu", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001583 "intf-id": omciInd.IntfId,
1584 "onu-id": omciInd.OnuId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001585 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001586 deviceType = onuDevice.Type
1587 deviceID = onuDevice.Id
1588 proxyDeviceID = onuDevice.ProxyAddress.DeviceId
khenaidoo106c61a2021-08-11 18:05:46 -04001589 childAdapterEndpoint = onuDevice.AdapterEndpoint
Akash Kankanala041a2122024-10-16 15:49:22 +05301590 // if not exist in cache, then add to cache.
khenaidoo106c61a2021-08-11 18:05:46 -04001591 dh.onus.Store(onuKey, NewOnuDevice(deviceID, deviceType, onuDevice.SerialNumber, omciInd.OnuId, omciInd.IntfId, proxyDeviceID, false, onuDevice.AdapterEndpoint))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001592 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05301593 // found in cache
Neha Sharma96b7bf22020-06-15 10:37:32 +00001594 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 +05301595 deviceType = onuInCache.(*OnuDevice).deviceType
1596 deviceID = onuInCache.(*OnuDevice).deviceID
1597 proxyDeviceID = onuInCache.(*OnuDevice).proxyDeviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001598 childAdapterEndpoint = onuInCache.(*OnuDevice).adapterEndpoint
cuilin20187b2a8c32019-03-26 19:52:28 -07001599 }
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001600
khenaidoodc2116e2021-10-19 17:33:19 -04001601 if err := dh.sendOmciIndicationToChildAdapter(ctx, childAdapterEndpoint, &ia.OmciMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001602 ParentDeviceId: proxyDeviceID,
1603 ChildDeviceId: deviceID,
1604 Message: omciInd.Pkt,
1605 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301606 return olterrors.NewErrCommunication("omci-request", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001607 "source": dh.openOLT.config.AdapterEndpoint,
1608 "device-type": deviceType,
1609 "destination": childAdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001610 "onu-id": deviceID,
Girish Kumarf26e4882020-03-05 06:49:10 +00001611 "proxy-device-id": proxyDeviceID}, err)
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001612 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001613 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301614}
1615
khenaidoo106c61a2021-08-11 18:05:46 -04001616// //ProcessInterAdapterMessage sends the proxied messages to the target device
1617// // If the proxy address is not found in the unmarshalled message, it first fetches the onu device for which the message
1618// // is meant, and then send the unmarshalled omci message to this onu
khenaidoodc2116e2021-10-19 17:33:19 -04001619// func (dh *DeviceHandler) ProcessInterAdapterMessage(ctx context.Context, msg *ca.InterAdapterMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001620// logger.Debugw(ctx, "process-inter-adapter-message", log.Fields{"msgID": msg.Header.Id})
khenaidoodc2116e2021-10-19 17:33:19 -04001621// if msg.Header.Type == ca.InterAdapterMessageType_OMCI_REQUEST {
khenaidoo106c61a2021-08-11 18:05:46 -04001622// return dh.handleInterAdapterOmciMsg(ctx, msg)
1623// }
1624// return olterrors.NewErrInvalidValue(log.Fields{"inter-adapter-message-type": msg.Header.Type}, nil)
1625// }
cuilin20187b2a8c32019-03-26 19:52:28 -07001626
kesavandb9f54fd2021-11-25 20:08:04 +05301627// ProxyOmciRequests sends the proxied OMCI message to the target device
1628func (dh *DeviceHandler) ProxyOmciRequests(ctx context.Context, omciMsgs *ia.OmciMessages) error {
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301629 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) {
1630 return status.Error(codes.Unavailable, "OLT unreachable")
1631 }
kesavandb9f54fd2021-11-25 20:08:04 +05301632 if omciMsgs.GetProxyAddress() == nil {
1633 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsgs.ChildDeviceId)
1634 if err != nil {
1635 return olterrors.NewErrNotFound("onu", log.Fields{
1636 "parent-device-id": dh.device.Id,
1637 "child-device-id": omciMsgs.ChildDeviceId}, err)
1638 }
1639 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1640 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsgs); err != nil {
1641 return olterrors.NewErrCommunication("send-failed", log.Fields{
1642 "parent-device-id": dh.device.Id,
1643 "child-device-id": omciMsgs.ChildDeviceId}, err)
1644 }
1645 } else {
1646 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsgs.ProxyAddress})
1647 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), nil, 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 }
1653 return nil
1654}
1655
1656func (dh *DeviceHandler) sendProxyOmciRequests(ctx context.Context, onuDevice *voltha.Device, omciMsgs *ia.OmciMessages) error {
1657 var intfID uint32
1658 var onuID uint32
1659 var connectStatus common.ConnectStatus_Types
1660 if onuDevice != nil {
1661 intfID = onuDevice.ProxyAddress.GetChannelId()
1662 onuID = onuDevice.ProxyAddress.GetOnuId()
1663 connectStatus = onuDevice.ConnectStatus
1664 } else {
1665 intfID = omciMsgs.GetProxyAddress().GetChannelId()
1666 onuID = omciMsgs.GetProxyAddress().GetOnuId()
1667 connectStatus = omciMsgs.GetConnectStatus()
1668 }
1669 if connectStatus != voltha.ConnectStatus_REACHABLE {
1670 logger.Debugw(ctx, "onu-not-reachable--cannot-send-omci", log.Fields{"intf-id": intfID, "onu-id": onuID})
1671
1672 return olterrors.NewErrCommunication("unreachable", log.Fields{
1673 "intf-id": intfID,
1674 "onu-id": onuID}, nil)
1675 }
1676
1677 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1678 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
1679
1680 onuSecOmciMsgList := omciMsgs.GetMessages()
1681
1682 for _, onuSecOmciMsg := range onuSecOmciMsgList {
kesavandb9f54fd2021-11-25 20:08:04 +05301683 var omciMessage *oop.OmciMsg
1684 hexPkt := make([]byte, hex.EncodedLen(len(onuSecOmciMsg)))
1685 hex.Encode(hexPkt, onuSecOmciMsg)
1686 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1687
1688 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1689 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1690 //https://jira.opencord.org/browse/VOL-4604
1691 transid := extractOmciTransactionID(onuSecOmciMsg)
1692 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
1693 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
1694
bseenivaa1622112025-12-11 18:24:02 +05301695 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1696 _, err := dh.Client.OmciMsgOut(subCtx, omciMessage)
1697 cancel()
kesavandb9f54fd2021-11-25 20:08:04 +05301698 if err != nil {
1699 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
1700 "intf-id": intfID,
1701 "onu-id": onuID,
1702 "message": omciMessage}, err)
1703 }
1704 }
1705 return nil
1706}
1707
khenaidoo106c61a2021-08-11 18:05:46 -04001708// ProxyOmciMessage sends the proxied OMCI message to the target device
khenaidoodc2116e2021-10-19 17:33:19 -04001709func (dh *DeviceHandler) ProxyOmciMessage(ctx context.Context, omciMsg *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001710 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 -07001711
Abhilash Laxmeshwar092e6ca2022-12-08 19:51:27 +05301712 if DeviceState(dh.device.ConnectStatus) != DeviceState(voltha.ConnectStatus_REACHABLE) {
1713 return status.Error(codes.Unavailable, "OLT unreachable")
1714 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001715 if omciMsg.GetProxyAddress() == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001716 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsg.ChildDeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001717 if err != nil {
1718 return olterrors.NewErrNotFound("onu", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001719 "parent-device-id": dh.device.Id,
1720 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001721 }
khenaidoo106c61a2021-08-11 18:05:46 -04001722 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1723 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001724 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001725 "parent-device-id": dh.device.Id,
1726 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001727 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001728 } else {
khenaidoo106c61a2021-08-11 18:05:46 -04001729 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsg.ProxyAddress})
1730 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), nil, 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)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001734 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001735 }
1736 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301737}
1738
khenaidoodc2116e2021-10-19 17:33:19 -04001739func (dh *DeviceHandler) sendProxiedMessage(ctx context.Context, onuDevice *voltha.Device, omciMsg *ia.OmciMessage) error {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001740 var intfID uint32
1741 var onuID uint32
Esin Karamanccb714b2019-11-29 15:02:06 +00001742 var connectStatus common.ConnectStatus_Types
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001743 if onuDevice != nil {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001744 intfID = onuDevice.ProxyAddress.GetChannelId()
1745 onuID = onuDevice.ProxyAddress.GetOnuId()
1746 connectStatus = onuDevice.ConnectStatus
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001747 } else {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001748 intfID = omciMsg.GetProxyAddress().GetChannelId()
1749 onuID = omciMsg.GetProxyAddress().GetOnuId()
1750 connectStatus = omciMsg.GetConnectStatus()
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001751 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001752 if connectStatus != voltha.ConnectStatus_REACHABLE {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001753 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 -08001754
Thomas Lee S94109f12020-03-03 16:39:29 +05301755 return olterrors.NewErrCommunication("unreachable", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001756 "intf-id": intfID,
1757 "onu-id": onuID}, nil)
cuilin20187b2a8c32019-03-26 19:52:28 -07001758 }
1759
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001760 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1761 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
kesavandb9f54fd2021-11-25 20:08:04 +05301762 // https://jira.opencord.org/browse/VOL-4604
lcuie24ef182019-04-29 22:58:36 -07001763 var omciMessage *oop.OmciMsg
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001764 hexPkt := make([]byte, hex.EncodedLen(len(omciMsg.Message)))
1765 hex.Encode(hexPkt, omciMsg.Message)
1766 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1767
1768 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1769 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1770 transid := extractOmciTransactionID(omciMsg.Message)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001771 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001772 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
cuilin20187b2a8c32019-03-26 19:52:28 -07001773
bseenivaa1622112025-12-11 18:24:02 +05301774 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1775 _, err := dh.Client.OmciMsgOut(subCtx, omciMessage)
1776 cancel()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001777 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301778 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001779 "intf-id": intfID,
1780 "onu-id": onuID,
1781 "message": omciMessage}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001782 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001783 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001784}
1785
David K. Bainbridge794735f2020-02-11 21:01:37 -08001786func (dh *DeviceHandler) activateONU(ctx context.Context, intfID uint32, onuID int64, serialNum *oop.SerialNumber, serialNumber string) error {
kesavand494c2082020-08-31 11:16:12 +05301787 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 +00001788 if err := dh.resourceMgr[intfID].AddNewOnuGemInfoToCacheAndKvStore(ctx, uint32(onuID), serialNumber); err != nil {
Matteo Scandolo92186242020-06-12 10:54:18 -07001789 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": onuID, "intf-id": intfID}, err)
Andrea Campanellab83b39d2020-03-30 11:41:16 +02001790 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001791 var pir uint32 = 1000000
kesavand494c2082020-08-31 11:16:12 +05301792 Onu := oop.Onu{IntfId: intfID, OnuId: uint32(onuID), SerialNumber: serialNum, Pir: pir, OmccEncryption: dh.openOLT.config.OmccEncryption}
bseenivaa1622112025-12-11 18:24:02 +05301793 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1794 defer cancel()
1795 if _, err := dh.Client.ActivateOnu(subCtx, &Onu); err != nil {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001796 st, _ := status.FromError(err)
1797 if st.Code() == codes.AlreadyExists {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001798 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 -04001799 } else {
Thomas Lee S985938d2020-05-04 11:40:41 +05301800 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": Onu, "device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001801 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001802 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001803 logger.Infow(ctx, "activated-onu", log.Fields{"SerialNumber": serialNumber, "device-id": dh.device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001804 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001805 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001806}
1807
Mahir Gunyela2e68702022-12-07 00:00:42 -08001808// getChildDevice function can be used in general to get child device, if not found in cache the function will
1809// get from core and update the cache and return the child device.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301810func (dh *DeviceHandler) getChildDevice(ctx context.Context, sn string, parentPortNo uint32) *OnuDevice {
1811 var InCacheOnuDev *OnuDevice
1812 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1813 if onuInCache.(*OnuDevice).serialNumber == sn {
1814 InCacheOnuDev = onuInCache.(*OnuDevice)
1815 return false
1816 }
1817 return true
1818 })
Akash Kankanala041a2122024-10-16 15:49:22 +05301819 // Got the onu device from cache return
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301820 if InCacheOnuDev != nil {
1821 logger.Debugw(ctx, "Got child device from cache", log.Fields{"onudev": InCacheOnuDev.serialNumber})
1822 return InCacheOnuDev
1823 }
1824 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1825 ParentId: dh.device.Id,
1826 SerialNumber: sn,
1827 ParentPortNo: parentPortNo,
1828 })
Akash Kankanala041a2122024-10-16 15:49:22 +05301829 // No device found in core return nil
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301830 if onuDevice == nil {
1831 return nil
1832 }
1833 onuID := onuDevice.ProxyAddress.OnuId
1834 intfID := plt.PortNoToIntfID(parentPortNo, voltha.Port_PON_OLT)
1835 onuKey := dh.formOnuKey(intfID, onuID)
1836
1837 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuDevice.ProxyAddress.OnuId, intfID, onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
1838 dh.onus.Store(onuKey, onuDev)
1839 logger.Debugw(ctx, "got child device from core", log.Fields{"onudev": onuDevice})
1840 return onuDev
1841}
1842
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301843// checkForResourceExistance checks for either device in rw-core or active techprofile in olt-adapter, based on the flag CheckOnuDevExistenceAtOnuDiscovery.
1844// If the ONU device/resource exists in either of these, the ONU discovery will be ignored.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301845func (dh *DeviceHandler) checkForResourceExistance(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) (bool, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001846 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
Akash Kankanala041a2122024-10-16 15:49:22 +05301847 // 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 +05301848 // 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 +05301849 if dh.openOLT.CheckOnuDevExistenceAtOnuDiscovery {
1850 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1851 ParentId: dh.device.Id,
1852 SerialNumber: sn,
1853 ParentPortNo: parentPortNo,
1854 })
1855 if onuDevice != nil {
1856 logger.Infow(ctx, "Child device still present ignoring discovery indication", log.Fields{"sn": sn})
1857 return true, nil
1858 }
1859 logger.Infow(ctx, "No device present in core , continuing with discovery", log.Fields{"sn": sn})
1860
1861 return false, nil
1862 } else {
1863 tpInstExists := false
1864 channelID := onuDiscInd.GetIntfId()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301865 onuDev := dh.getChildDevice(ctx, sn, parentPortNo)
1866 if onuDev != nil {
1867 var onuGemInfo *rsrcMgr.OnuGemInfo
1868 var err error
1869 if onuGemInfo, err = dh.resourceMgr[channelID].GetOnuGemInfo(ctx, onuDev.onuID); err != nil {
1870 logger.Warnw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuDev.onuID})
1871 return false, err
1872 }
1873 if onuGemInfo != nil {
1874 for _, uni := range onuGemInfo.UniPorts {
1875 uniID := plt.UniIDFromPortNum(uni)
1876 tpIDs := dh.resourceMgr[channelID].GetTechProfileIDForOnu(ctx, onuDev.onuID, uniID)
1877 if len(tpIDs) != 0 {
1878 logger.Warnw(ctx, "Techprofile present for ONU, ignoring onu discovery", log.Fields{"onuID": onuDev.onuID})
1879 tpInstExists = true
1880 break
1881 }
1882 }
1883 }
1884 }
1885 return tpInstExists, nil
1886 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301887}
1888
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001889// processDiscONULOSClear clears the LOS Alarm if it's needed
1890func (dh *DeviceHandler) processDiscONULOSClear(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) {
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301891 var alarmInd oop.OnuAlarmIndication
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001892 raisedTs := time.Now().Unix()
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301893
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001894 /* When PON cable disconnected and connected back from OLT, it was expected OnuAlarmIndication
1895 with "los_status: off" should be raised but BAL does not raise this Alarm hence manually sending
1896 OnuLosClear event on receiving OnuDiscoveryIndication for the Onu after checking whether
1897 OnuLosRaise event sent for it */
1898 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1899 if onuInCache.(*OnuDevice).serialNumber == sn && onuInCache.(*OnuDevice).losRaised {
1900 if onuDiscInd.GetIntfId() != onuInCache.(*OnuDevice).intfID {
1901 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
1902 "previousIntfId": onuInCache.(*OnuDevice).intfID,
1903 "currentIntfId": onuDiscInd.GetIntfId()})
1904 // TODO:: Should we need to ignore raising OnuLosClear event
1905 // when onu connected to different PON?
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301906 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001907 alarmInd.IntfId = onuInCache.(*OnuDevice).intfID
1908 alarmInd.OnuId = onuInCache.(*OnuDevice).onuID
1909 alarmInd.LosStatus = statusCheckOff
1910 go func() {
1911 if err := dh.eventMgr.onuAlarmIndication(ctx, &alarmInd, onuInCache.(*OnuDevice).deviceID, raisedTs); err != nil {
1912 logger.Errorw(ctx, "indication-failed", log.Fields{"err": err})
1913 }
1914 }()
1915 // stop iterating
1916 return false
1917 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301918 return true
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001919 })
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301920}
1921
bseeniva43b5a912025-06-05 12:48:15 +05301922func (dh *DeviceHandler) handleOnuDiscoveryProcessingError(ctx context.Context, err error, sn string, tpInstExists bool) {
1923 if err != nil || tpInstExists {
1924 logger.Infow(ctx, "onu-processing-errored-out-not-adding-to-discovery-map", log.Fields{"sn": sn})
1925 } else {
1926 // once the function completes set the value to false so that
1927 // we know the processing has inProcess.
1928 // Note that this is done after checking if we are already processing
1929 // to avoid changing the value from a different thread
1930 logger.Infow(ctx, "onu-processing-completed", log.Fields{"sn": sn})
1931 dh.discOnus.Store(sn, false)
1932 }
1933}
1934
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301935func (dh *DeviceHandler) onuDiscIndication(ctx context.Context, onuDiscInd *oop.OnuDiscIndication) error {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301936 var error error
bseeniva43b5a912025-06-05 12:48:15 +05301937 var tpInstExists bool
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301938
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301939 channelID := onuDiscInd.GetIntfId()
1940 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
1941
1942 sn := dh.stringifySerialNumber(onuDiscInd.SerialNumber)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301943 defer func() {
bseeniva43b5a912025-06-05 12:48:15 +05301944 dh.handleOnuDiscoveryProcessingError(ctx, error, sn, tpInstExists)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301945 }()
1946
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301947 logger.Infow(ctx, "new-discovery-indication", log.Fields{"sn": sn})
1948
Sridhar Ravindraab785f22025-07-21 17:20:55 +05301949 // Check for resource existence only if the ForceOnuDiscIndProcessing is disabled.
1950 if !dh.cfg.ForceOnuDiscIndProcessing {
1951 tpInstExists, error = dh.checkForResourceExistance(ctx, onuDiscInd, sn)
1952 if error != nil {
1953 return error
1954 }
1955 if tpInstExists {
1956 // ignore the discovery if tpinstance is present.
1957 logger.Debugw(ctx, "ignoring-onu-indication-as-tp-already-exists", log.Fields{"sn": sn})
1958 return nil
1959 }
Amit Ghoshe5c6a852020-02-10 15:09:46 +00001960 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001961 inProcess, existing := dh.discOnus.LoadOrStore(sn, true)
1962
1963 // if the ONU existed, handle the LOS Alarm
1964 if existing {
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001965 if inProcess.(bool) {
1966 // if we're currently processing the ONU on a different thread, do nothing
1967 logger.Warnw(ctx, "onu-sn-is-being-processed", log.Fields{"sn": sn})
1968 return nil
1969 }
1970 // if we had dealt with this ONU before, but the process didn't complete (this happens in case of errors)
1971 // then continue processing it
1972 logger.Debugw(ctx, "onu-processing-had-completed-but-new-indication", log.Fields{"sn": sn})
1973
1974 dh.processDiscONULOSClear(ctx, onuDiscInd, sn)
serkantule333d152022-10-12 01:44:00 +03001975 return nil
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301976 }
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001977 var onuID uint32
Matteo Scandolo945e4012019-12-12 14:16:11 -08001978
1979 // check the ONU is already know to the OLT
1980 // NOTE the second time the ONU is discovered this should return a device
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301981 onuDevice, error := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001982 ParentId: dh.device.Id,
1983 SerialNumber: sn,
1984 })
Matteo Scandolo945e4012019-12-12 14:16:11 -08001985
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301986 if error != nil {
1987 logger.Debugw(ctx, "core-proxy-get-child-device-failed", log.Fields{"parentDevice": dh.device.Id, "err": error, "sn": sn})
1988 if e, ok := status.FromError(error); ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001989 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 -08001990 switch e.Code() {
1991 case codes.Internal:
1992 // this probably means NOT FOUND, so just create a new device
1993 onuDevice = nil
1994 case codes.DeadlineExceeded:
1995 // if the call times out, cleanup and exit
1996 dh.discOnus.Delete(sn)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05301997 error = olterrors.NewErrTimeout("get-child-device", log.Fields{"device-id": dh.device.Id}, error)
1998 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08001999 }
2000 }
2001 }
2002
2003 if onuDevice == nil {
2004 // NOTE this should happen a single time, and only if GetChildDevice returns NotFound
Neha Sharma96b7bf22020-06-15 10:37:32 +00002005 logger.Debugw(ctx, "creating-new-onu", log.Fields{"sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08002006 // we need to create a new ChildDevice
Matt Jeanneret53539512019-07-20 14:47:02 -04002007 ponintfid := onuDiscInd.GetIntfId()
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302008 onuID, error = dh.resourceMgr[ponintfid].GetONUID(ctx)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002009 logger.Infow(ctx, "creating-new-onu-got-onu-id", log.Fields{"sn": sn, "onuId": onuID})
Matteo Scandolo945e4012019-12-12 14:16:11 -08002010
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302011 if error != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08002012 // if we can't create an ID in resource manager,
2013 // cleanup and exit
Matteo Scandolo945e4012019-12-12 14:16:11 -08002014 dh.discOnus.Delete(sn)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302015
2016 error = olterrors.NewErrAdapter("resource-manager-get-onu-id-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002017 "pon-intf-id": ponintfid,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302018 "serial-number": sn}, error)
2019 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08002020 }
2021
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302022 if onuDevice, error = dh.sendChildDeviceDetectedToCore(ctx, &ca.DeviceDiscovery{
khenaidoo106c61a2021-08-11 18:05:46 -04002023 ParentId: dh.device.Id,
2024 ParentPortNo: parentPortNo,
2025 ChannelId: channelID,
2026 VendorId: string(onuDiscInd.SerialNumber.GetVendorId()),
2027 SerialNumber: sn,
2028 OnuId: onuID,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302029 }); error != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08002030 dh.discOnus.Delete(sn)
yasin saplibddc2d72022-02-08 13:10:17 +00002031 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 +05302032
2033 error = olterrors.NewErrAdapter("core-proxy-child-device-detected-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002034 "pon-intf-id": ponintfid,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302035 "serial-number": sn}, error)
2036 return error
Matteo Scandolo945e4012019-12-12 14:16:11 -08002037 }
Akash Kankanala041a2122024-10-16 15:49:22 +05302038 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 +05302039 logger.Error(ctx, "discovery-indication-failed", log.Fields{"err": error})
2040 error = olterrors.NewErrAdapter("discovery-indication-failed", log.Fields{
2041 "onu-id": onuID,
2042 "device-id": dh.device.Id,
2043 "serial-number": sn}, error)
2044 return error
Kent Hagermane6ff1012020-07-14 15:07:53 -04002045 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002046 logger.Infow(ctx, "onu-child-device-added",
Shrey Baid807a2a02020-04-09 12:52:45 +05302047 log.Fields{"onuDevice": onuDevice,
2048 "sn": sn,
Matteo Scandolo92186242020-06-12 10:54:18 -07002049 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05302050 "device-id": dh.device.Id})
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04002051 }
Matteo Scandolo945e4012019-12-12 14:16:11 -08002052
khenaidoo106c61a2021-08-11 18:05:46 -04002053 // Setup the gRPC connection to the adapter responsible for that onuDevice, if not setup yet
2054 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302055 error = dh.setupChildInterAdapterClient(subCtx, onuDevice.AdapterEndpoint)
khenaidoo106c61a2021-08-11 18:05:46 -04002056 cancel()
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302057 if error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302058 error = olterrors.NewErrCommunication("no-connection-to-child-adapter", log.Fields{"device-id": onuDevice.Id}, error)
2059 return error
khenaidoo106c61a2021-08-11 18:05:46 -04002060 }
2061
Matteo Scandolo945e4012019-12-12 14:16:11 -08002062 // we can now use the existing ONU Id
2063 onuID = onuDevice.ProxyAddress.OnuId
Akash Kankanala041a2122024-10-16 15:49:22 +05302064 // Insert the ONU into cache to use in OnuIndication.
Mahir Gunyele77977b2019-06-27 05:36:22 -07002065 //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 +00002066 logger.Debugw(ctx, "onu-discovery-indication-key-create",
Matteo Scandolo92186242020-06-12 10:54:18 -07002067 log.Fields{"onu-id": onuID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302068 "intfId": onuDiscInd.GetIntfId(),
2069 "sn": sn})
Mahir Gunyele77977b2019-06-27 05:36:22 -07002070 onuKey := dh.formOnuKey(onuDiscInd.GetIntfId(), onuID)
Matt Jeanneret53539512019-07-20 14:47:02 -04002071
khenaidoo106c61a2021-08-11 18:05:46 -04002072 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuID, onuDiscInd.GetIntfId(), onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302073 dh.onus.Store(onuKey, onuDev)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002074 logger.Debugw(ctx, "new-onu-device-discovered",
Shrey Baid807a2a02020-04-09 12:52:45 +05302075 log.Fields{"onu": onuDev,
2076 "sn": sn})
Chaitrashree G S35b5d802019-07-08 23:12:03 -04002077
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302078 if error = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002079 DeviceId: onuDevice.Id,
2080 ParentDeviceId: dh.device.Id,
2081 OperStatus: common.OperStatus_DISCOVERED,
2082 ConnStatus: common.ConnectStatus_REACHABLE,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302083 }); error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302084 error = olterrors.NewErrAdapter("failed-to-update-device-state", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002085 "device-id": onuDevice.Id,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302086 "serial-number": sn}, error)
2087 return error
cuilin20187b2a8c32019-03-26 19:52:28 -07002088 }
khenaidoo106c61a2021-08-11 18:05:46 -04002089
Neha Sharma96b7bf22020-06-15 10:37:32 +00002090 logger.Infow(ctx, "onu-discovered-reachable", log.Fields{"device-id": onuDevice.Id, "sn": sn})
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302091 if error = dh.activateONU(ctx, onuDiscInd.IntfId, int64(onuID), onuDiscInd.SerialNumber, sn); error != nil {
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302092 error = olterrors.NewErrAdapter("onu-activation-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002093 "device-id": onuDevice.Id,
nikesh.krishnan3099ac12023-10-06 14:37:21 +05302094 "serial-number": sn}, error)
2095 return error
David K. Bainbridge794735f2020-02-11 21:01:37 -08002096 }
2097 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07002098}
2099
Mahir Gunyelb0046752021-02-26 13:51:05 -08002100func (dh *DeviceHandler) onuIndication(ctx context.Context, onuInd *oop.OnuIndication) error {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002101 ponPort := plt.IntfIDToPortNo(onuInd.GetIntfId(), voltha.Port_PON_OLT)
Mahir Gunyele77977b2019-06-27 05:36:22 -07002102 var onuDevice *voltha.Device
David K. Bainbridge794735f2020-02-11 21:01:37 -08002103 var err error
Mahir Gunyele77977b2019-06-27 05:36:22 -07002104 foundInCache := false
Neha Sharma96b7bf22020-06-15 10:37:32 +00002105 logger.Debugw(ctx, "onu-indication-key-create",
Shrey Baid807a2a02020-04-09 12:52:45 +05302106 log.Fields{"onuId": onuInd.OnuId,
2107 "intfId": onuInd.GetIntfId(),
Thomas Lee S985938d2020-05-04 11:40:41 +05302108 "device-id": dh.device.Id})
Mahir Gunyele77977b2019-06-27 05:36:22 -07002109 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.OnuId)
Mahir Gunyelb0046752021-02-26 13:51:05 -08002110 serialNumber := dh.stringifySerialNumber(onuInd.SerialNumber)
David K. Bainbridge794735f2020-02-11 21:01:37 -08002111 errFields := log.Fields{"device-id": dh.device.Id}
2112
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302113 if onuInCache, ok := dh.onus.Load(onuKey); ok {
Akash Kankanala041a2122024-10-16 15:49:22 +05302114 // If ONU id is discovered before then use GetDevice to get onuDevice because it is cheaper.
Mahir Gunyele77977b2019-06-27 05:36:22 -07002115 foundInCache = true
David K. Bainbridge794735f2020-02-11 21:01:37 -08002116 errFields["onu-id"] = onuInCache.(*OnuDevice).deviceID
khenaidoo106c61a2021-08-11 18:05:46 -04002117 onuDevice, err = dh.getDeviceFromCore(ctx, onuInCache.(*OnuDevice).deviceID)
cuilin20187b2a8c32019-03-26 19:52:28 -07002118 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05302119 // If ONU not found in adapter cache then we have to use GetChildDevice to get onuDevice
Mahir Gunyele77977b2019-06-27 05:36:22 -07002120 if serialNumber != "" {
David K. Bainbridge794735f2020-02-11 21:01:37 -08002121 errFields["serial-number"] = serialNumber
Mahir Gunyele77977b2019-06-27 05:36:22 -07002122 } else {
David K. Bainbridge794735f2020-02-11 21:01:37 -08002123 errFields["onu-id"] = onuInd.OnuId
2124 errFields["parent-port-no"] = ponPort
Mahir Gunyele77977b2019-06-27 05:36:22 -07002125 }
khenaidoodc2116e2021-10-19 17:33:19 -04002126 onuDevice, err = dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002127 ParentId: dh.device.Id,
2128 SerialNumber: serialNumber,
2129 OnuId: onuInd.OnuId,
2130 ParentPortNo: ponPort,
2131 })
cuilin20187b2a8c32019-03-26 19:52:28 -07002132 }
Mahir Gunyele77977b2019-06-27 05:36:22 -07002133
David K. Bainbridge794735f2020-02-11 21:01:37 -08002134 if err != nil || onuDevice == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002135 return olterrors.NewErrNotFound("onu-device", errFields, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07002136 }
2137
David K. Bainbridge794735f2020-02-11 21:01:37 -08002138 if onuDevice.ParentPortNo != ponPort {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002139 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002140 "previousIntfId": onuDevice.ParentPortNo,
2141 "currentIntfId": ponPort})
2142 }
2143
2144 if onuDevice.ProxyAddress.OnuId != onuInd.OnuId {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002145 logger.Warnw(ctx, "onu-id-mismatch-possible-if-voltha-and-olt-rebooted", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302146 "expected-onu-id": onuDevice.ProxyAddress.OnuId,
2147 "received-onu-id": onuInd.OnuId,
Thomas Lee S985938d2020-05-04 11:40:41 +05302148 "device-id": dh.device.Id})
David K. Bainbridge794735f2020-02-11 21:01:37 -08002149 }
2150 if !foundInCache {
2151 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.GetOnuId())
khenaidoo106c61a2021-08-11 18:05:46 -04002152 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 -08002153 }
kesavand7cf3a052020-08-28 12:49:18 +05302154 if onuInd.OperState == "down" && onuInd.FailReason != oop.OnuIndication_ONU_ACTIVATION_FAIL_REASON_NONE {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07002155 if err := dh.eventMgr.onuActivationIndication(ctx, onuActivationFailEvent, onuInd, dh.device.Id, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002156 logger.Warnw(ctx, "onu-activation-indication-reporting-failed", log.Fields{"err": err})
kesavand7cf3a052020-08-28 12:49:18 +05302157 }
2158 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002159 if err := dh.updateOnuStates(ctx, onuDevice, onuInd); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002160 return olterrors.NewErrCommunication("state-update-failed", errFields, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08002161 }
2162 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07002163}
2164
Neha Sharma96b7bf22020-06-15 10:37:32 +00002165func (dh *DeviceHandler) updateOnuStates(ctx context.Context, onuDevice *voltha.Device, onuInd *oop.OnuIndication) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002166 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 -07002167 if onuInd.AdminState == "down" || onuInd.OperState == "down" {
2168 // The ONU has gone admin_state "down" or oper_state "down" - we expect the ONU to send discovery again
2169 // The ONU admin_state is "up" while "oper_state" is down in cases where ONU activation fails. In this case
2170 // the ONU sends Discovery again.
Girish Gowdra429f9502020-05-04 13:22:16 -07002171 dh.discOnus.Delete(onuDevice.SerialNumber)
Amit Ghosh9bbc5652020-02-17 13:37:32 +00002172 // Tests have shown that we sometimes get OperState as NOT down even if AdminState is down, forcing it
2173 if onuInd.OperState != "down" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002174 logger.Warnw(ctx, "onu-admin-state-down", log.Fields{"operState": onuInd.OperState})
Amit Ghosh9bbc5652020-02-17 13:37:32 +00002175 onuInd.OperState = "down"
2176 }
2177 }
2178
David K. Bainbridge794735f2020-02-11 21:01:37 -08002179 switch onuInd.OperState {
khenaidoo106c61a2021-08-11 18:05:46 -04002180 case "up", "down":
Neha Sharma96b7bf22020-06-15 10:37:32 +00002181 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 -04002182
khenaidoodc2116e2021-10-19 17:33:19 -04002183 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002184 DeviceId: onuDevice.Id,
2185 OnuIndication: onuInd,
2186 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002187 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302188 return olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002189 "onu-indicator": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002190 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08002191 "device-type": onuDevice.Type,
Girish Kumarf26e4882020-03-05 06:49:10 +00002192 "device-id": onuDevice.Id}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002193 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002194 default:
Girish Kumarf26e4882020-03-05 06:49:10 +00002195 return olterrors.NewErrInvalidValue(log.Fields{"oper-state": onuInd.OperState}, nil)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002196 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002197 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002198}
2199
cuilin20187b2a8c32019-03-26 19:52:28 -07002200func (dh *DeviceHandler) stringifySerialNumber(serialNum *oop.SerialNumber) string {
2201 if serialNum != nil {
2202 return string(serialNum.VendorId) + dh.stringifyVendorSpecific(serialNum.VendorSpecific)
cuilin20187b2a8c32019-03-26 19:52:28 -07002203 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002204 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07002205}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002206func (dh *DeviceHandler) deStringifySerialNumber(serialNum string) (*oop.SerialNumber, error) {
2207 decodedStr, err := hex.DecodeString(serialNum[4:])
2208 if err != nil {
2209 return nil, err
2210 }
2211 return &oop.SerialNumber{
2212 VendorId: []byte(serialNum[:4]),
Girish Gowdraa09aeab2020-09-14 16:30:52 -07002213 VendorSpecific: decodedStr,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002214 }, nil
2215}
cuilin20187b2a8c32019-03-26 19:52:28 -07002216
2217func (dh *DeviceHandler) stringifyVendorSpecific(vendorSpecific []byte) string {
Mahir Gunyelb0046752021-02-26 13:51:05 -08002218 if len(vendorSpecific) > 3 {
2219 tmp := fmt.Sprintf("%x", (uint32(vendorSpecific[0])>>4)&0x0f) +
2220 fmt.Sprintf("%x", uint32(vendorSpecific[0]&0x0f)) +
2221 fmt.Sprintf("%x", (uint32(vendorSpecific[1])>>4)&0x0f) +
2222 fmt.Sprintf("%x", (uint32(vendorSpecific[1]))&0x0f) +
2223 fmt.Sprintf("%x", (uint32(vendorSpecific[2])>>4)&0x0f) +
2224 fmt.Sprintf("%x", (uint32(vendorSpecific[2]))&0x0f) +
2225 fmt.Sprintf("%x", (uint32(vendorSpecific[3])>>4)&0x0f) +
2226 fmt.Sprintf("%x", (uint32(vendorSpecific[3]))&0x0f)
2227 return tmp
2228 }
2229 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07002230}
2231
Mahir Gunyela2e68702022-12-07 00:00:42 -08002232// UpdateFlowsBulk upates the bulk flow
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002233func (dh *DeviceHandler) UpdateFlowsBulk() error {
Thomas Lee S94109f12020-03-03 16:39:29 +05302234 return olterrors.ErrNotImplemented
cuilin20187b2a8c32019-03-26 19:52:28 -07002235}
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002236
Mahir Gunyela2e68702022-12-07 00:00:42 -08002237// GetChildDevice returns the child device for given parent port and onu id
Neha Sharma96b7bf22020-06-15 10:37:32 +00002238func (dh *DeviceHandler) GetChildDevice(ctx context.Context, parentPort, onuID uint32) (*voltha.Device, error) {
2239 logger.Debugw(ctx, "getchilddevice",
Shrey Baid807a2a02020-04-09 12:52:45 +05302240 log.Fields{"pon-port": parentPort,
Matteo Scandolo92186242020-06-12 10:54:18 -07002241 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05302242 "device-id": dh.device.Id})
khenaidoo106c61a2021-08-11 18:05:46 -04002243
khenaidoodc2116e2021-10-19 17:33:19 -04002244 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002245 ParentId: dh.device.Id,
2246 OnuId: onuID,
2247 ParentPortNo: parentPort,
2248 })
2249
Girish Gowdru0c588b22019-04-23 23:24:56 -04002250 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002251 return nil, olterrors.NewErrNotFound("onu-device", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002252 "intf-id": parentPort,
2253 "onu-id": onuID}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04002254 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002255 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 -08002256 return onuDevice, nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302257}
2258
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002259// SendPacketInToCore sends packet-in to core
2260// For this, it calls SendPacketIn of the core-proxy which uses a device specific topic to send the request.
2261// The adapter handling the device creates a device specific topic
Neha Sharma96b7bf22020-06-15 10:37:32 +00002262func (dh *DeviceHandler) SendPacketInToCore(ctx context.Context, logicalPort uint32, packetPayload []byte) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002263 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002264 logger.Debugw(ctx, "send-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002265 "port": logicalPort,
2266 "packet": hex.EncodeToString(packetPayload),
2267 "device-id": dh.device.Id,
2268 })
2269 }
khenaidoo106c61a2021-08-11 18:05:46 -04002270
khenaidoodc2116e2021-10-19 17:33:19 -04002271 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002272 DeviceId: dh.device.Id,
2273 Port: logicalPort,
2274 Packet: packetPayload,
2275 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302276 return olterrors.NewErrCommunication("packet-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002277 "source": "adapter",
2278 "destination": "core",
2279 "device-id": dh.device.Id,
2280 "logical-port": logicalPort,
Girish Kumarf26e4882020-03-05 06:49:10 +00002281 "packet": hex.EncodeToString(packetPayload)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002282 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002283 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002284 logger.Debugw(ctx, "sent-packet-in-to-core-successfully", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002285 "packet": hex.EncodeToString(packetPayload),
2286 "device-id": dh.device.Id,
2287 })
2288 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002289 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002290}
2291
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002292// UpdatePmConfig updates the pm metrics.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002293func (dh *DeviceHandler) UpdatePmConfig(ctx context.Context, pmConfigs *voltha.PmConfigs) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002294 logger.Infow(ctx, "update-pm-configs", log.Fields{"device-id": dh.device.Id, "pm-configs": pmConfigs})
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002295
2296 if pmConfigs.DefaultFreq != dh.metrics.ToPmConfigs().DefaultFreq {
2297 dh.metrics.UpdateFrequency(pmConfigs.DefaultFreq)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002298 logger.Debugf(ctx, "frequency-updated")
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002299 }
2300
Kent Hagermane6ff1012020-07-14 15:07:53 -04002301 if !pmConfigs.Grouped {
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002302 metrics := dh.metrics.GetSubscriberMetrics()
2303 for _, m := range pmConfigs.Metrics {
2304 metrics[m.Name].Enabled = m.Enabled
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00002305 }
2306 }
2307}
2308
khenaidoodc2116e2021-10-19 17:33:19 -04002309func (dh *DeviceHandler) handleFlows(ctx context.Context, device *voltha.Device, flows *of.FlowChanges, flowMetadata *of.FlowMetadata) []error {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002310 var err error
Andrea Campanellac63bba92020-03-10 17:01:04 +01002311 var errorsList []error
2312
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002313 if dh.getDeviceDeletionInProgressFlag() {
2314 // The device itself is going to be reset as part of deletion. So nothing to be done.
2315 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2316 return nil
2317 }
2318
Girish Gowdru0c588b22019-04-23 23:24:56 -04002319 if flows != nil {
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002320 for _, flow := range flows.ToRemove.Items {
Akash Kankanala041a2122024-10-16 15:49:22 +05302321 intfID := dh.getIntfIDFromFlow(flow)
Girish Gowdracefae192020-03-19 18:14:10 -07002322
Neha Sharma96b7bf22020-06-15 10:37:32 +00002323 logger.Debugw(ctx, "removing-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302324 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002325 "intfId": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302326 "flowToRemove": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002327 if flow_utils.HasGroup(flow) {
2328 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupRemove)
2329 } else {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002330 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
2331 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2332 } else {
2333 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, false, nil)
2334 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002335 }
Girish Gowdracefae192020-03-19 18:14:10 -07002336 if err != nil {
Elia Battiston2aaf4342022-02-07 15:16:38 +01002337 if werr, ok := err.(olterrors.WrappedError); ok && status.Code(werr.Unwrap()) == codes.NotFound {
Akash Kankanala041a2122024-10-16 15:49:22 +05302338 // The flow we want to remove is not there, there is no need to throw an error
Elia Battiston2aaf4342022-02-07 15:16:38 +01002339 logger.Warnw(ctx, "flow-to-remove-not-found",
2340 log.Fields{
2341 "ponIf": intfID,
2342 "flowToRemove": flow,
2343 "error": err,
2344 })
2345 } else {
2346 errorsList = append(errorsList, err)
2347 }
Girish Gowdracefae192020-03-19 18:14:10 -07002348 }
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04002349 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302350
2351 for _, flow := range flows.ToAdd.Items {
Akash Kankanala041a2122024-10-16 15:49:22 +05302352 intfID := dh.getIntfIDFromFlow(flow)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002353 logger.Debugw(ctx, "adding-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05302354 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00002355 "ponIf": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05302356 "flowToAdd": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08002357 if flow_utils.HasGroup(flow) {
2358 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupAdd)
2359 } else {
yasin saplid0566272021-12-21 09:10:30 +00002360 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002361 // The flow manager module could be uninitialized if the flow arrives too soon before the device has reconciled fully
2362 logger.Errorw(ctx, "flow-manager-uninitialized", log.Fields{"device-id": device.Id})
2363 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
2364 } else {
yasin saplid0566272021-12-21 09:10:30 +00002365 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, true, flowMetadata)
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002366 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08002367 }
Andrea Campanellac63bba92020-03-10 17:01:04 +01002368 if err != nil {
2369 errorsList = append(errorsList, err)
2370 }
Girish Gowdra3d633032019-12-10 16:37:05 +05302371 }
Girish Gowdru0c588b22019-04-23 23:24:56 -04002372 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002373
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002374 return errorsList
2375}
2376
2377func (dh *DeviceHandler) handleGroups(ctx context.Context, groups *of.FlowGroupChanges) []error {
2378 var err error
2379 var errorsList []error
2380
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002381 if dh.getDeviceDeletionInProgressFlag() {
2382 // The device itself is going to be reset as part of deletion. So nothing to be done.
2383 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
2384 return nil
2385 }
2386
Girish Gowdracefae192020-03-19 18:14:10 -07002387 // 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 +00002388 if groups != nil {
2389 for _, group := range groups.ToAdd.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002390 // err = dh.groupMgr.AddGroup(ctx, group)
2391 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupAdd)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002392 if err != nil {
2393 errorsList = append(errorsList, err)
2394 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002395 }
2396 for _, group := range groups.ToUpdate.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002397 // err = dh.groupMgr.ModifyGroup(ctx, group)
2398 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupModify)
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 }
Esin Karamand519bbf2020-07-01 11:16:03 +00002403 for _, group := range groups.ToRemove.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002404 // err = dh.groupMgr.DeleteGroup(ctx, group)
2405 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupRemove)
Esin Karamand519bbf2020-07-01 11:16:03 +00002406 if err != nil {
2407 errorsList = append(errorsList, err)
2408 }
Esin Karamanccb714b2019-11-29 15:02:06 +00002409 }
2410 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002411
2412 return errorsList
2413}
2414
Mahir Gunyela2e68702022-12-07 00:00:42 -08002415// UpdateFlowsIncrementally updates the device flow
khenaidoodc2116e2021-10-19 17:33:19 -04002416func (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 -07002417 var errorsList []error
Girish Gowdra950326e2021-11-05 12:43:24 -07002418
2419 if dh.getDeviceDeletionInProgressFlag() {
2420 // The device itself is going to be reset as part of deletion. So nothing to be done.
2421 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
2422 return nil
2423 }
nikesh.krishnan0897d472023-09-05 18:35:08 +05302424 if dh.transitionMap.currentDeviceState != deviceStateUp {
2425 logger.Error(ctx, "device-is-not-up--not-handling-flows-or-groups", log.Fields{"device-id": device.Id, "current-device-state": dh.transitionMap.currentDeviceState})
2426 return fmt.Errorf("device-is-not-up--not-handling-flows-or-groups")
2427 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07002428 logger.Debugw(ctx, "received-incremental-flowupdate-in-device-handler", log.Fields{"device-id": device.Id, "flows": flows, "groups": groups, "flowMetadata": flowMetadata})
2429 errorsList = append(errorsList, dh.handleFlows(ctx, device, flows, flowMetadata)...)
2430 errorsList = append(errorsList, dh.handleGroups(ctx, groups)...)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002431 if len(errorsList) > 0 {
2432 return fmt.Errorf("errors-installing-flows-groups, errors:%v", errorsList)
2433 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002434 logger.Debugw(ctx, "updated-flows-incrementally-successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0c588b22019-04-23 23:24:56 -04002435 return nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302436}
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002437
Mahir Gunyela2e68702022-12-07 00:00:42 -08002438// DisableDevice disables the given device
2439// It marks the following for the given device:
2440// Device-Handler Admin-State : down
2441// Device Port-State: UNKNOWN
2442// Device Oper-State: UNKNOWN
Neha Sharma96b7bf22020-06-15 10:37:32 +00002443func (dh *DeviceHandler) DisableDevice(ctx context.Context, device *voltha.Device) error {
Chaitrashree G S44124192019-08-07 20:21:36 -04002444 /* On device disable ,admin state update has to be done prior sending request to agent since
2445 the indication thread may processes invalid indications of ONU and OLT*/
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002446 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302447 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2448 if _, err := dh.Client.DisableOlt(subCtx, new(oop.Empty)); err != nil {
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002449 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
bseenivaa1622112025-12-11 18:24:02 +05302450 cancel()
Girish Kumarf26e4882020-03-05 06:49:10 +00002451 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": device.Id}, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002452 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002453 }
bseenivaa1622112025-12-11 18:24:02 +05302454 cancel()
Chaitrashree G S44124192019-08-07 20:21:36 -04002455 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002456 logger.Debugw(ctx, "olt-disabled", log.Fields{"device-id": device.Id})
Chaitrashree G S44124192019-08-07 20:21:36 -04002457 /* Discovered ONUs entries need to be cleared , since on device disable the child devices goes to
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002458 UNREACHABLE state which needs to be configured again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302459
2460 dh.discOnus = sync.Map{}
2461 dh.onus = sync.Map{}
2462
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002463 dh.lockDevice.RLock()
Akash Kankanala041a2122024-10-16 15:49:22 +05302464 // stopping the stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002465 if dh.isCollectorActive {
2466 dh.stopCollector <- true
2467 }
2468 dh.lockDevice.RUnlock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302469
Neha Sharma96b7bf22020-06-15 10:37:32 +00002470 go dh.notifyChildDevices(ctx, "unreachable")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002471 cloned := proto.Clone(device).(*voltha.Device)
Akash Kankanala041a2122024-10-16 15:49:22 +05302472 // Update device Admin state
Thomas Lee S985938d2020-05-04 11:40:41 +05302473 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04002474
kdarapu1afeceb2020-02-12 01:38:09 -05002475 // 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 -04002476 if err := dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002477 DeviceId: cloned.Id,
2478 PortTypeFilter: ^uint32(1 << voltha.Port_PON_OLT),
2479 OperStatus: voltha.OperStatus_UNKNOWN,
2480 }); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002481 return olterrors.NewErrAdapter("ports-state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002482 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002483 logger.Debugw(ctx, "disable-device-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002484 return nil
2485}
2486
Neha Sharma96b7bf22020-06-15 10:37:32 +00002487func (dh *DeviceHandler) notifyChildDevices(ctx context.Context, state string) {
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002488 // Update onu state as unreachable in onu adapter
2489 onuInd := oop.OnuIndication{}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302490 onuInd.OperState = state
khenaidoo106c61a2021-08-11 18:05:46 -04002491
Akash Kankanala041a2122024-10-16 15:49:22 +05302492 // get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04002493 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002494 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002495 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 -04002496 }
2497 if onuDevices != nil {
2498 for _, onuDevice := range onuDevices.Items {
khenaidoodc2116e2021-10-19 17:33:19 -04002499 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002500 DeviceId: onuDevice.Id,
2501 OnuIndication: &onuInd,
2502 })
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002503 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002504 logger.Errorw(ctx, "failed-to-send-inter-adapter-message", log.Fields{"OnuInd": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002505 "From Adapter": dh.openOLT.config.AdapterEndpoint, "DeviceType": onuDevice.Type, "device-id": onuDevice.Id})
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002506 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002507 }
2508 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002509}
2510
Mahir Gunyela2e68702022-12-07 00:00:42 -08002511// ReenableDevice re-enables the olt device after disable
2512// It marks the following for the given device:
2513// Device-Handler Admin-State : up
2514// Device Port-State: ACTIVE
2515// Device Oper-State: ACTIVE
Neha Sharma96b7bf22020-06-15 10:37:32 +00002516func (dh *DeviceHandler) ReenableDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302517 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302518 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2519 if _, err := dh.Client.ReenableOlt(subCtx, new(oop.Empty)); err != nil {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302520 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
bseenivaa1622112025-12-11 18:24:02 +05302521 cancel()
nikesh.krishnane363ace2023-02-28 03:12:38 +05302522 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, err)
2523 }
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302524 }
bseenivaa1622112025-12-11 18:24:02 +05302525 cancel()
nikesh.krishnane363ace2023-02-28 03:12:38 +05302526 } else {
2527 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 +05302528 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002529 logger.Debug(ctx, "olt-reenabled")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002530
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002531 // Update the all ports state on that device to enable
khenaidoo106c61a2021-08-11 18:05:46 -04002532 ports, err := dh.listDevicePortsFromCore(ctx, device.Id)
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002533 var retError error
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002534 if err != nil {
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002535 retError = olterrors.NewErrAdapter("list-ports-failed", log.Fields{"device-id": device.Id}, err)
2536 } else {
2537 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
2538 retError = olterrors.NewErrAdapter("port-status-update-failed-after-olt-reenable", log.Fields{"device": device}, err)
2539 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002540 }
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002541 if retError == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05302542 // Update the device oper status as ACTIVE
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002543 device.OperStatus = voltha.OperStatus_ACTIVE
2544 } else {
Akash Kankanala041a2122024-10-16 15:49:22 +05302545 // Update the device oper status as FAILED
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002546 device.OperStatus = voltha.OperStatus_FAILED
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002547 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002548 dh.device = device
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002549
khenaidoodc2116e2021-10-19 17:33:19 -04002550 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002551 DeviceId: device.Id,
2552 OperStatus: device.OperStatus,
2553 ConnStatus: device.ConnectStatus,
2554 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302555 return olterrors.NewErrAdapter("state-update-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002556 "device-id": device.Id,
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002557 "connect-status": device.ConnectStatus,
2558 "oper-status": device.OperStatus}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002559 }
kesavand39e0aa32020-01-28 20:58:50 -05002560
Neha Sharma96b7bf22020-06-15 10:37:32 +00002561 logger.Debugw(ctx, "reenabledevice-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002562
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002563 return retError
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002564}
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002565
npujarec5762e2020-01-01 14:08:48 +05302566func (dh *DeviceHandler) clearUNIData(ctx context.Context, onu *rsrcMgr.OnuGemInfo) error {
Devmalya Paul495b94a2019-08-27 19:42:00 -04002567 var uniID uint32
2568 var err error
Gustavo Silva41af9122022-10-11 11:05:13 -03002569 var errs []error
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302570 for _, port := range onu.UniPorts {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002571 uniID = plt.UniIDFromPortNum(port)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002572 logger.Debugw(ctx, "clearing-resource-data-for-uni-port", log.Fields{"port": port, "uni-id": uniID})
A R Karthick1f85b802019-10-11 05:06:05 +00002573 /* Delete tech-profile instance from the KV store */
Mahir Gunyela2e68702022-12-07 00:00:42 -08002574 if dh.flowMgr == nil || dh.flowMgr[onu.IntfID] == nil {
2575 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu-no-flowmng", log.Fields{"onu-id": onu.OnuID})
2576 } else {
2577 if err = dh.flowMgr[onu.IntfID].DeleteTechProfileInstances(ctx, onu.IntfID, onu.OnuID, uniID); err != nil {
2578 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002579 errs = append(errs, err)
Mahir Gunyela2e68702022-12-07 00:00:42 -08002580 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002581 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002582 logger.Debugw(ctx, "deleted-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002583 tpIDList := dh.resourceMgr[onu.IntfID].GetTechProfileIDForOnu(ctx, onu.OnuID, uniID)
Gamze Abakafee36392019-10-03 11:17:24 +00002584 for _, tpID := range tpIDList {
yasin saplibddc2d72022-02-08 13:10:17 +00002585 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "upstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002586 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002587 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002588 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002589 logger.Debugw(ctx, "removed-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002590 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "downstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002591 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002592 errs = append(errs, err)
Gamze Abakafee36392019-10-03 11:17:24 +00002593 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002594 logger.Debugw(ctx, "removed-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302595 }
yasin saplibddc2d72022-02-08 13:10:17 +00002596 dh.resourceMgr[onu.IntfID].FreePONResourcesForONU(ctx, onu.OnuID, uniID)
2597 if err = dh.resourceMgr[onu.IntfID].RemoveTechProfileIDsForOnu(ctx, onu.OnuID, uniID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002598 logger.Debugw(ctx, "failed-to-remove-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
Gustavo Silva41af9122022-10-11 11:05:13 -03002599 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302600 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002601 logger.Debugw(ctx, "removed-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002602 if err = dh.resourceMgr[onu.IntfID].DeletePacketInGemPortForOnu(ctx, onu.OnuID, port); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002603 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 -03002604 errs = append(errs, err)
A R Karthick1f85b802019-10-11 05:06:05 +00002605 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002606 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002607 if len(errs) > 0 {
2608 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-clear-uni-data, errors:%v",
2609 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2610 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002611 return nil
2612}
2613
Devmalya Paul495b94a2019-08-27 19:42:00 -04002614// 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 +05302615func (dh *DeviceHandler) DeleteDevice(ctx context.Context, device *voltha.Device) error {
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002616 logger.Debugw(ctx, "function-entry-delete-device", log.Fields{"device-id": dh.device.Id})
Devmalya Paul495b94a2019-08-27 19:42:00 -04002617 /* Clear the KV store data associated with the all the UNI ports
2618 This clears up flow data and also resource map data for various
2619 other pon resources like alloc_id and gemport_id
2620 */
Girish Gowdra950326e2021-11-05 12:43:24 -07002621
Abhay Kumarb87ac882025-10-30 09:55:07 +00002622 if dh.getDeviceDeletionInProgressFlag() {
2623 logger.Errorw(ctx, "cannot complete operation as device deletion is in progress", log.Fields{"device-id": dh.device.Id})
2624 return olterrors.NewErrAdapter(fmt.Errorf("cannot complete operation as device deletion is in progress").Error(), log.Fields{"device-id": dh.device.Id}, nil)
2625 }
2626
Girish Gowdra950326e2021-11-05 12:43:24 -07002627 dh.setDeviceDeletionInProgressFlag(true)
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002628 dh.StopAllFlowRoutines(ctx)
Girish Gowdra950326e2021-11-05 12:43:24 -07002629
Himani Chawla49a5d562020-11-25 11:53:44 +05302630 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002631 // Stop the Stats collector
2632 if dh.isCollectorActive {
2633 dh.stopCollector <- true
2634 }
2635 // stop the heartbeat check routine
2636 if dh.isHeartbeatCheckActive {
2637 dh.stopHeartbeatCheck <- true
2638 }
Himani Chawla49a5d562020-11-25 11:53:44 +05302639 // Stop the read indication only if it the routine is active
2640 if dh.isReadIndicationRoutineActive {
2641 dh.stopIndications <- true
2642 }
2643 dh.lockDevice.RUnlock()
Akash Soni5c76e272024-01-15 04:09:24 +05302644
2645 err := dh.cleanupDeviceResources(ctx)
2646 if err != nil {
2647 logger.Errorw(ctx, "could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id, "err": err})
2648 } else {
2649 logger.Debugw(ctx, "successfully-removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
2650 }
2651
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002652 dh.removeOnuIndicationChannels(ctx)
Akash Kankanala041a2122024-10-16 15:49:22 +05302653 // Reset the state
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002654 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302655 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2656 if _, err = dh.Client.Reboot(subCtx, new(oop.Empty)); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002657 go func() {
2658 failureReason := fmt.Sprintf("Failed to reboot during device delete request with error: %s", err.Error())
Akash Kankanala041a2122024-10-16 15:49:22 +05302659 if err1 := dh.eventMgr.oltRebootFailedEvent(ctx, dh.device.Id, failureReason, time.Now().Unix()); err1 != nil {
2660 logger.Errorw(ctx, "on-olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err1})
Gustavo Silva41af9122022-10-11 11:05:13 -03002661 }
2662 }()
2663 logger.Errorw(ctx, "olt-reboot-failed", log.Fields{"device-id": dh.device.Id, "err": err})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002664 }
bseenivaa1622112025-12-11 18:24:02 +05302665 cancel()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002666 }
Girish Gowdrab1caa442020-10-19 12:24:39 -07002667 // There is no need to update the core about operation status and connection status of the OLT.
2668 // The OLT is getting deleted anyway and the core might have already cleared the OLT device from its DB.
2669 // So any attempt to update the operation status and connection status of the OLT will result in core throwing an error back,
2670 // because the device does not exist in DB.
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002671
khenaidoo7eb2d672021-10-22 19:08:50 -04002672 // Stop the adapter grpc clients for that parent device
2673 dh.deleteAdapterClients(ctx)
Gustavo Silva41af9122022-10-11 11:05:13 -03002674 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002675}
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002676
2677// StopAllFlowRoutines stops all flow routines
2678func (dh *DeviceHandler) StopAllFlowRoutines(ctx context.Context) {
2679 var wg sync.WaitGroup
2680 wg.Add(1) // for the mcast routine below to finish
2681 go dh.StopAllMcastHandlerRoutines(ctx, &wg)
2682 for _, flMgr := range dh.flowMgr {
2683 if flMgr != nil {
2684 wg.Add(1) // for the flow handler routine below to finish
2685 go flMgr.StopAllFlowHandlerRoutines(ctx, &wg)
2686 }
2687 }
2688 if !dh.waitForTimeoutOrCompletion(&wg, time.Second*30) {
2689 logger.Warnw(ctx, "timed out waiting for stopping flow and group handlers", log.Fields{"deviceID": dh.device.Id})
2690 } else {
2691 logger.Infow(ctx, "all flow and group handlers shutdown gracefully", log.Fields{"deviceID": dh.device.Id})
2692 }
2693}
2694
Gustavo Silva41af9122022-10-11 11:05:13 -03002695func (dh *DeviceHandler) cleanupDeviceResources(ctx context.Context) error {
2696 var errs []error
Abhay Kumarb87ac882025-10-30 09:55:07 +00002697 if dh.resourceMgr != nil && dh.totalPonPorts > 0 {
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302698 var ponPort uint32
Girish Gowdra9602eb42020-09-09 15:50:39 -07002699 for ponPort = 0; ponPort < dh.totalPonPorts; ponPort++ {
yasin sapli9e4c5092022-02-01 13:52:33 +00002700 onuGemData := dh.resourceMgr[ponPort].GetOnuGemInfoList(ctx)
Andrey Pozolotin32b36562021-06-02 10:23:26 +03002701 for i, onu := range onuGemData {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002702 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
Gustavo Silva41af9122022-10-11 11:05:13 -03002703 if err := dh.clearUNIData(ctx, &onuGemData[i]); err != nil {
2704 errs = append(errs, err)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302705 }
2706 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002707 if err := dh.resourceMgr[ponPort].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2708 errs = append(errs, err)
2709 }
2710 if err := dh.resourceMgr[ponPort].DeleteAllOnuGemInfoForIntf(ctx); err != nil {
2711 errs = append(errs, err)
2712 }
2713 if err := dh.resourceMgr[ponPort].DeleteMcastQueueForIntf(ctx); err != nil {
2714 errs = append(errs, err)
2715 }
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002716 if err := dh.resourceMgr[ponPort].Delete(ctx, ponPort); err != nil {
Gustavo Silva41af9122022-10-11 11:05:13 -03002717 errs = append(errs, err)
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002718 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002719 }
Gustavo Silva41af9122022-10-11 11:05:13 -03002720 }
2721 // Clean up NNI manager's data
2722 if err := dh.resourceMgr[dh.totalPonPorts].DeleteAllFlowIDsForGemForIntf(ctx); err != nil {
2723 errs = append(errs, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002724 }
A R Karthick1f85b802019-10-11 05:06:05 +00002725
Abhay Kumarb87ac882025-10-30 09:55:07 +00002726 logger.Debugw(ctx, "lockDevice for KVStore close client", log.Fields{"deviceID": dh.device.Id})
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00002727 dh.CloseKVClient(ctx)
2728
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002729 // Take one final sweep at cleaning up KV store for the OLT device
2730 // Clean everything at <base-path-prefix>/openolt/<device-id>
Gustavo Silva41af9122022-10-11 11:05:13 -03002731 if err := dh.kvStore.DeleteWithPrefix(ctx, ""); err != nil {
2732 errs = append(errs, err)
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002733 }
2734
Devmalya Paul495b94a2019-08-27 19:42:00 -04002735 /*Delete ONU map for the device*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302736 dh.onus.Range(func(key interface{}, value interface{}) bool {
2737 dh.onus.Delete(key)
2738 return true
2739 })
2740
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002741 /*Delete discovered ONU map for the device*/
2742 dh.discOnus.Range(func(key interface{}, value interface{}) bool {
2743 dh.discOnus.Delete(key)
2744 return true
2745 })
Gustavo Silva41af9122022-10-11 11:05:13 -03002746 if len(errs) > 0 {
2747 return olterrors.NewErrAdapter(fmt.Errorf("one-or-more-error-during-device-delete, errors:%v",
2748 errs).Error(), log.Fields{"device-id": dh.device.Id}, nil)
2749 }
2750 return nil
Devmalya Paul495b94a2019-08-27 19:42:00 -04002751}
2752
Mahir Gunyela2e68702022-12-07 00:00:42 -08002753// RebootDevice reboots the given device
Neha Sharma96b7bf22020-06-15 10:37:32 +00002754func (dh *DeviceHandler) RebootDevice(ctx context.Context, device *voltha.Device) error {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302755 if dh.Client != nil {
bseenivaa1622112025-12-11 18:24:02 +05302756 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2757 defer cancel()
2758 if _, err := dh.Client.Reboot(subCtx, new(oop.Empty)); err != nil {
nikesh.krishnane363ace2023-02-28 03:12:38 +05302759 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, err)
2760 }
2761 } else {
2762 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 -04002763 }
nikesh.krishnane363ace2023-02-28 03:12:38 +05302764
Neha Sharma96b7bf22020-06-15 10:37:32 +00002765 logger.Debugw(ctx, "rebooted-device-successfully", log.Fields{"device-id": device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002766 return nil
2767}
2768
David K. Bainbridge794735f2020-02-11 21:01:37 -08002769func (dh *DeviceHandler) handlePacketIndication(ctx context.Context, packetIn *oop.PacketIndication) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002770 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002771 logger.Debugw(ctx, "received-packet-in", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002772 "packet-indication": *packetIn,
2773 "device-id": dh.device.Id,
2774 "packet": hex.EncodeToString(packetIn.Pkt),
2775 })
2776 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002777 if dh.flowMgr == nil || dh.flowMgr[packetIn.IntfId] == nil {
2778 return olterrors.NewErrNotFound("flow-manager", log.Fields{"intf-id": packetIn.IntfId, "packet": hex.EncodeToString(packetIn.Pkt)}, nil)
2779 }
Girish Gowdra9602eb42020-09-09 15:50:39 -07002780 logicalPortNum, err := dh.flowMgr[packetIn.IntfId].GetLogicalPortFromPacketIn(ctx, packetIn)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002781 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002782 return olterrors.NewErrNotFound("logical-port", log.Fields{"packet": hex.EncodeToString(packetIn.Pkt)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002783 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002784 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002785 logger.Debugw(ctx, "sending-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002786 "logical-port-num": logicalPortNum,
2787 "device-id": dh.device.Id,
2788 "packet": hex.EncodeToString(packetIn.Pkt),
2789 })
2790 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002791
khenaidoodc2116e2021-10-19 17:33:19 -04002792 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002793 DeviceId: dh.device.Id,
2794 Port: logicalPortNum,
2795 Packet: packetIn.Pkt,
2796 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302797 return olterrors.NewErrCommunication("send-packet-in", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002798 "destination": "core",
Thomas Lee S985938d2020-05-04 11:40:41 +05302799 "source": dh.device.Type,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002800 "device-id": dh.device.Id,
2801 "packet": hex.EncodeToString(packetIn.Pkt),
2802 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002803 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002804
Matteo Scandolo92186242020-06-12 10:54:18 -07002805 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002806 logger.Debugw(ctx, "success-sending-packet-in-to-core!", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002807 "packet": hex.EncodeToString(packetIn.Pkt),
2808 "device-id": dh.device.Id,
2809 })
2810 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002811 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002812}
2813
Mahir Gunyela2e68702022-12-07 00:00:42 -08002814// PacketOutNNI sends packet-out from VOLTHA to OLT on the NNI provided
2815func (dh *DeviceHandler) PacketOutNNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2816 nniIntfID, err := plt.IntfIDFromNniPortNum(ctx, uint32(egressPortNo))
2817 if err != nil {
2818 return olterrors.NewErrInvalidValue(log.Fields{
2819 "egress-nni-port": egressPortNo,
2820 "device-id": dh.device.Id,
2821 }, err)
2822 }
2823 uplinkPkt := oop.UplinkPacket{IntfId: nniIntfID, Pkt: packet.Data}
2824
2825 if logger.V(log.DebugLevel) {
2826 logger.Debugw(ctx, "sending-packet-to-nni", log.Fields{
2827 "uplink-pkt": uplinkPkt,
2828 "packet": hex.EncodeToString(packet.Data),
2829 "device-id": dh.device.Id,
2830 })
2831 }
2832
bseenivaa1622112025-12-11 18:24:02 +05302833 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2834 defer cancel()
2835 if _, err := dh.Client.UplinkPacketOut(subCtx, &uplinkPkt); err != nil {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002836 return olterrors.NewErrCommunication("packet-out-to-nni", log.Fields{
2837 "packet": hex.EncodeToString(packet.Data),
2838 "device-id": dh.device.Id,
2839 }, err)
2840 }
2841 return nil
2842}
2843
2844// PacketOutUNI sends packet-out from VOLTHA to OLT on the UNI provided
2845func (dh *DeviceHandler) PacketOutUNI(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
2846 outerEthType := (uint16(packet.Data[12]) << 8) | uint16(packet.Data[13])
2847 innerEthType := (uint16(packet.Data[16]) << 8) | uint16(packet.Data[17])
2848 if outerEthType == 0x8942 || outerEthType == 0x88cc {
2849 // Do not packet-out lldp packets on uni port.
2850 // ONOS has no clue about uni/nni ports, it just packets out on all
2851 // available ports on the Logical Switch. It should not be interested
2852 // in the UNI links.
2853 logger.Debugw(ctx, "dropping-lldp-packet-out-on-uni", log.Fields{
2854 "device-id": dh.device.Id,
2855 })
2856 return nil
2857 }
2858 if outerEthType == 0x88a8 || outerEthType == 0x8100 {
2859 if innerEthType == 0x8100 {
2860 // q-in-q 802.1ad or 802.1q double tagged packet.
2861 // slice out the outer tag.
2862 packet.Data = append(packet.Data[:12], packet.Data[16:]...)
2863 if logger.V(log.DebugLevel) {
2864 logger.Debugw(ctx, "packet-now-single-tagged", log.Fields{
2865 "packet-data": hex.EncodeToString(packet.Data),
2866 "device-id": dh.device.Id,
2867 })
2868 }
2869 }
2870 }
2871 intfID := plt.IntfIDFromUniPortNum(uint32(egressPortNo))
2872 onuID := plt.OnuIDFromPortNum(uint32(egressPortNo))
2873 uniID := plt.UniIDFromPortNum(uint32(egressPortNo))
2874 var gemPortID uint32
2875 err := olterrors.NewErrNotFound("no-flow-manager-found-for-packet-out", log.Fields{"device-id": dh.device.Id}, nil).(error)
2876 if dh.flowMgr != nil && dh.flowMgr[intfID] != nil {
2877 gemPortID, err = dh.flowMgr[intfID].GetPacketOutGemPortID(ctx, intfID, onuID, uint32(egressPortNo), packet.Data)
2878 }
2879 if err != nil {
2880 // In this case the openolt agent will receive the gemPortID as 0.
2881 // The agent tries to retrieve the gemPortID in this case.
2882 // This may not always succeed at the agent and packetOut may fail.
2883 logger.Errorw(ctx, "failed-to-retrieve-gemport-id-for-packet-out", log.Fields{
2884 "intf-id": intfID,
2885 "onu-id": onuID,
2886 "uni-id": uniID,
2887 "packet": hex.EncodeToString(packet.Data),
2888 "device-id": dh.device.Id,
2889 "error": err,
2890 })
2891 }
2892
2893 onuPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, PortNo: uint32(egressPortNo), GemportId: gemPortID, Pkt: packet.Data}
2894 if logger.V(log.DebugLevel) {
2895 logger.Debugw(ctx, "sending-packet-to-onu", log.Fields{
2896 "egress-port-no": egressPortNo,
2897 "intf-id": intfID,
2898 "onu-id": onuID,
2899 "uni-id": uniID,
2900 "gem-port-id": gemPortID,
2901 "packet": hex.EncodeToString(packet.Data),
2902 "device-id": dh.device.Id,
2903 })
2904 }
2905
bseenivaa1622112025-12-11 18:24:02 +05302906 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
2907 defer cancel()
2908 if _, err := dh.Client.OnuPacketOut(subCtx, &onuPkt); err != nil {
Mahir Gunyela2e68702022-12-07 00:00:42 -08002909 return olterrors.NewErrCommunication("packet-out-send", log.Fields{
2910 "source": "adapter",
2911 "destination": "onu",
2912 "egress-port-number": egressPortNo,
2913 "intf-id": intfID,
2914 "oni-id": onuID,
2915 "uni-id": uniID,
2916 "gem-port-id": gemPortID,
2917 "packet": hex.EncodeToString(packet.Data),
2918 "device-id": dh.device.Id,
2919 }, err)
2920 }
2921 return nil
2922}
2923
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002924// PacketOut sends packet-out from VOLTHA to OLT on the egress port provided
khenaidoo106c61a2021-08-11 18:05:46 -04002925func (dh *DeviceHandler) PacketOut(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002926 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002927 logger.Debugw(ctx, "incoming-packet-out", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002928 "device-id": dh.device.Id,
2929 "egress-port-no": egressPortNo,
2930 "pkt-length": len(packet.Data),
2931 "packet": hex.EncodeToString(packet.Data),
2932 })
2933 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002934
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002935 egressPortType := plt.IntfIDToPortTypeName(uint32(egressPortNo))
Mahir Gunyela2e68702022-12-07 00:00:42 -08002936 var err error
mgouda86543582025-10-29 20:58:16 +05302937 switch egressPortType {
2938 case voltha.Port_ETHERNET_UNI:
Mahir Gunyela2e68702022-12-07 00:00:42 -08002939 err = dh.PacketOutUNI(ctx, egressPortNo, packet)
mgouda86543582025-10-29 20:58:16 +05302940 case voltha.Port_ETHERNET_NNI:
Mahir Gunyela2e68702022-12-07 00:00:42 -08002941 err = dh.PacketOutNNI(ctx, egressPortNo, packet)
mgouda86543582025-10-29 20:58:16 +05302942 default:
Neha Sharma96b7bf22020-06-15 10:37:32 +00002943 logger.Warnw(ctx, "packet-out-to-this-interface-type-not-implemented", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302944 "egress-port-no": egressPortNo,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002945 "egressPortType": egressPortType,
2946 "packet": hex.EncodeToString(packet.Data),
Thomas Lee S985938d2020-05-04 11:40:41 +05302947 "device-id": dh.device.Id,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002948 })
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002949 }
Mahir Gunyela2e68702022-12-07 00:00:42 -08002950 return err
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002951}
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002952
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002953func (dh *DeviceHandler) formOnuKey(intfID, onuID uint32) string {
2954 return "" + strconv.Itoa(int(intfID)) + "." + strconv.Itoa(int(onuID))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002955}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302956
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002957func startHeartbeatCheck(ctx context.Context, dh *DeviceHandler) {
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002958 defer func() {
2959 dh.lockDevice.Lock()
2960 dh.isHeartbeatCheckActive = false
2961 dh.lockDevice.Unlock()
2962 }()
2963
2964 dh.lockDevice.Lock()
2965 dh.isHeartbeatCheckActive = true
2966 dh.lockDevice.Unlock()
2967
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302968 // start the heartbeat check towards the OLT.
2969 var timerCheck *time.Timer
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302970 dh.heartbeatSignature = dh.getHeartbeatSignature(ctx)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302971
2972 for {
2973 heartbeatTimer := time.NewTimer(dh.openOLT.HeartbeatCheckInterval)
2974 select {
2975 case <-heartbeatTimer.C:
Neha Sharma8f4e4322020-08-06 10:51:53 +00002976 ctxWithTimeout, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.openOLT.GrpcTimeoutInterval)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002977 if heartBeat, err := dh.Client.HeartbeatCheck(ctxWithTimeout, new(oop.Empty)); err != nil {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002978 logger.Warnw(ctx, "heartbeat-failed", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302979 if timerCheck == nil {
2980 // start a after func, when expired will update the state to the core
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002981 timerCheck = time.AfterFunc(dh.openOLT.HeartbeatFailReportInterval, func() { dh.updateStateUnreachable(ctx) })
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302982 }
2983 } else {
2984 if timerCheck != nil {
2985 if timerCheck.Stop() {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002986 logger.Debugw(ctx, "got-heartbeat-within-timeout", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302987 }
2988 timerCheck = nil
2989 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302990 if dh.heartbeatSignature == 0 || dh.heartbeatSignature == heartBeat.HeartbeatSignature {
2991 if dh.heartbeatSignature == 0 {
2992 // First time the signature will be 0, update the signture to DB when not found.
2993 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
2994 dh.heartbeatSignature = heartBeat.HeartbeatSignature
2995 }
2996 logger.Infow(ctx, "heartbeat signature", log.Fields{"sign": dh.heartbeatSignature})
2997
2998 dh.lockDevice.RLock()
2999 // Stop the read indication only if it the routine is active
3000 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3001 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3002 // on next execution of the readIndication routine.
3003 if !dh.isReadIndicationRoutineActive {
3004 // Start reading indications
3005 go func() {
3006 if err = dh.readIndications(ctx); err != nil {
3007 _ = olterrors.NewErrAdapter("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
3008 }
3009 }()
3010 }
3011 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303012 } else {
3013 logger.Warn(ctx, "Heartbeat signature changed, OLT is rebooted. Cleaningup resources.")
3014 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
3015 dh.heartbeatSignature = heartBeat.HeartbeatSignature
3016 go dh.updateStateRebooted(ctx)
3017 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303018 }
3019 cancel()
3020 case <-dh.stopHeartbeatCheck:
Matteo Scandolo861e06e2021-05-26 11:51:46 -07003021 logger.Debugw(ctx, "stopping-heartbeat-check", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303022 return
3023 }
3024 }
3025}
3026
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003027func (dh *DeviceHandler) updateStateUnreachable(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -04003028 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003029 if err != nil || device == nil {
Girish Gowdrab1caa442020-10-19 12:24:39 -07003030 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
3031 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
3032 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
3033 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
3034 // cleanup in the adapter was already done during DeleteDevice API handler routine.
Kent Hagermane6ff1012020-07-14 15:07:53 -04003035 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
Girish Gowdrab1caa442020-10-19 12:24:39 -07003036 // Immediately return, otherwise accessing a null 'device' struct would cause panic
3037 return
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003038 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303039
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303040 logger.Warnw(ctx, "update-state-unreachable", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
Matteo Scandolo861e06e2021-05-26 11:51:46 -07003041 "admin-state": device.AdminState, "oper-status": device.OperStatus})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003042 if device.ConnectStatus == voltha.ConnectStatus_REACHABLE {
khenaidoodc2116e2021-10-19 17:33:19 -04003043 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04003044 DeviceId: dh.device.Id,
3045 OperStatus: voltha.OperStatus_UNKNOWN,
3046 ConnStatus: voltha.ConnectStatus_UNREACHABLE,
3047 }); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04003048 _ = 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 -04003049 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303050 /*
3051 if err = dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
3052 DeviceId: dh.device.Id,
3053 PortTypeFilter: 0,
3054 OperStatus: voltha.OperStatus_UNKNOWN,
3055 }); err != nil {
3056 _ = olterrors.NewErrAdapter("port-update-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
3057 }
3058 */
Gamze Abaka07868a52020-12-17 14:19:28 +00003059
Akash Kankanala041a2122024-10-16 15:49:22 +05303060 // raise olt communication failure event
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07003061 raisedTs := time.Now().Unix()
khenaidoo106c61a2021-08-11 18:05:46 -04003062 cloned := proto.Clone(device).(*voltha.Device)
3063 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
3064 cloned.OperStatus = voltha.OperStatus_UNKNOWN
3065 dh.device = cloned // update local copy of the device
3066 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
Gamze Abaka07868a52020-12-17 14:19:28 +00003067
Girish Gowdra3ab6d212020-03-24 17:33:15 -07003068 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003069 // Stop the Stats collector
3070 if dh.isCollectorActive {
3071 dh.stopCollector <- true
3072 }
3073 // stop the heartbeat check routine
3074 if dh.isHeartbeatCheckActive {
3075 dh.stopHeartbeatCheck <- true
3076 }
Girish Gowdra3ab6d212020-03-24 17:33:15 -07003077 // Stop the read indication only if it the routine is active
3078 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3079 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3080 // on next execution of the readIndication routine.
3081 if dh.isReadIndicationRoutineActive {
3082 dh.stopIndications <- true
3083 }
3084 dh.lockDevice.RUnlock()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04003085 dh.transitionMap.Handle(ctx, DeviceInit)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05303086 }
3087}
kesavand39e0aa32020-01-28 20:58:50 -05003088
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303089func (dh *DeviceHandler) updateStateRebooted(ctx context.Context) {
3090 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
3091 if err != nil || device == nil {
3092 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
3093 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
3094 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
3095 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
3096 // cleanup in the adapter was already done during DeleteDevice API handler routine.
3097 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
3098 // Immediately return, otherwise accessing a null 'device' struct would cause panic
3099 return
3100 }
Akash Kankanala041a2122024-10-16 15:49:22 +05303101 // Starting the cleanup process
Mahir Gunyel701df862023-09-07 16:16:04 -07003102 dh.setDeviceDeletionInProgressFlag(true)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303103
3104 logger.Warnw(ctx, "update-state-rebooted", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
3105 "admin-state": device.AdminState, "oper-status": device.OperStatus, "conn-status": voltha.ConnectStatus_UNREACHABLE})
bseenivad1c984b2025-01-09 12:54:44 +05303106 // First, stop the read indication and heartbeat check routines to prevent any delay
3107 // in cleanup, which could cause the heartbeat routine to restart the read indication.
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303108 dh.lockDevice.RLock()
3109 // Stop the read indication only if it the routine is active
3110 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
3111 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
3112 // on next execution of the readIndication routine.
3113 if dh.isReadIndicationRoutineActive {
3114 dh.stopIndications <- true
3115 }
3116 dh.lockDevice.RUnlock()
3117
bseenivad1c984b2025-01-09 12:54:44 +05303118 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
3119 DeviceId: dh.device.Id,
3120 OperStatus: voltha.OperStatus_REBOOTED,
3121 ConnStatus: voltha.ConnectStatus_REACHABLE,
3122 }); err != nil {
3123 _ = olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
3124 }
3125
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303126 //raise olt communication failure event
3127 raisedTs := time.Now().Unix()
3128 cloned := proto.Clone(device).(*voltha.Device)
3129 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
3130 cloned.OperStatus = voltha.OperStatus_UNKNOWN
3131 dh.device = cloned // update local copy of the device
3132 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
3133
Gustavo Silva41af9122022-10-11 11:05:13 -03003134 if err := dh.cleanupDeviceResources(ctx); err != nil {
3135 logger.Errorw(ctx, "failure-in-cleanup-device-resources", log.Fields{"device-id": dh.device.Id, "err": err})
3136 } else {
3137 logger.Debugw(ctx, "removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
3138 }
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003139
3140 dh.lockDevice.RLock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303141 // Stop the Stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003142 if dh.isCollectorActive {
3143 dh.stopCollector <- true
3144 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303145 // stop the heartbeat check routine
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00003146 if dh.isHeartbeatCheckActive {
3147 dh.stopHeartbeatCheck <- true
3148 }
3149 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303150
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00003151 dh.StopAllFlowRoutines(ctx)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303152
Akash Kankanala041a2122024-10-16 15:49:22 +05303153 // reset adapter reconcile flag
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303154 dh.adapterPreviouslyConnected = false
3155 for {
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303156 childDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
3157 if err != nil || childDevices == nil {
3158 logger.Errorw(ctx, "Failed to get child devices from core", log.Fields{"deviceID": dh.device.Id})
3159 continue
3160 }
3161 if len(childDevices.Items) == 0 {
3162 logger.Infow(ctx, "All childDevices cleared from core, proceed with device init", log.Fields{"deviceID": dh.device.Id})
3163 break
3164 } else {
3165 logger.Warn(ctx, "Not all child devices are cleared, continuing to wait")
3166 time.Sleep(5 * time.Second)
3167 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303168 }
Akash Kankanala041a2122024-10-16 15:49:22 +05303169 // Cleanup completed , reset the flag
Mahir Gunyel701df862023-09-07 16:16:04 -07003170 dh.setDeviceDeletionInProgressFlag(false)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303171 logger.Infow(ctx, "cleanup complete after reboot , moving to init", log.Fields{"deviceID": device.Id})
3172 dh.transitionMap.Handle(ctx, DeviceInit)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303173}
3174
balaji.nagarajan68f56e82025-07-04 15:16:01 +05303175// EnableOnuSerialNumber to enable onu serial number
3176func (dh *DeviceHandler) EnableOnuSerialNumber(ctx context.Context, device *voltha.OnuSerialNumberOnOLTPon) error {
3177 logger.Debugw(ctx, "enable-onu-serial-number", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber, "port": device.Port.PortNo})
3178 onuSerialNumber := device.SerialNumber
3179
3180 // fetch interfaceid from PortNo
3181 ponID := plt.PortNoToIntfID(device.Port.GetPortNo(), voltha.Port_PON_OLT)
3182
3183 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3184 if err != nil {
3185 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3186 log.Fields{
3187 "devicer-id": dh.device.Id,
3188 "serial-number": onuSerialNumber}, err).Log()
3189 }
3190
3191 onuIntf := &oop.InterfaceOnuSerialNumber{
3192 IntfId: ponID,
3193 OnuSerialNumber: sn,
3194 }
3195 _, err = dh.Client.EnableOnuSerialNumber(ctx, onuIntf)
3196
3197 if err != nil {
3198 logger.Errorw(ctx, "failed to enable onu serial number", log.Fields{"onudev": onuSerialNumber, "error": err})
3199 return olterrors.NewErrAdapter("onu-serial-number-enable-failed", log.Fields{
3200 "device-id": dh.device.Id,
3201 "onu-serial-number": onuSerialNumber}, err)
3202 }
3203 return nil
3204}
3205
3206// DisableOnuSerialNumber to disable onu serial number
3207func (dh *DeviceHandler) DisableOnuSerialNumber(ctx context.Context, device *voltha.OnuSerialNumberOnOLTPon) error {
3208 logger.Debugw(ctx, "disable-onu-serial-number", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber, "port": device.Port.PortNo})
3209 onuSerialNumber := device.SerialNumber
3210 ponID := plt.PortNoToIntfID(device.Port.GetPortNo(), voltha.Port_PON_OLT)
3211 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3212 if err != nil {
3213 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3214 log.Fields{
3215 "devicer-id": dh.device.Id,
3216 "serial-number": onuSerialNumber}, err).Log()
3217 }
3218
3219 onuIntf := &oop.InterfaceOnuSerialNumber{
3220 OnuSerialNumber: sn,
3221 IntfId: ponID,
3222 }
3223 _, err = dh.Client.DisableOnuSerialNumber(ctx, onuIntf)
3224
3225 if err != nil {
3226 logger.Errorw(ctx, "failed to disable onu serial number", log.Fields{"onudev": onuSerialNumber, "error": err})
3227 return olterrors.NewErrAdapter("onu-serial-number-disable-failed", log.Fields{
3228 "device-id": dh.device.Id,
3229 "onu-serial-number": onuSerialNumber}, err)
3230 }
3231 return nil
3232}
3233
3234// EnableOnu to enable onu
3235func (dh *DeviceHandler) EnableOnu(ctx context.Context, device *voltha.Device) error {
3236 logger.Debugw(ctx, "enable-onu", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber})
3237 onuSerialNumber := device.SerialNumber
3238 InCacheOnuDev := dh.getChildDevice(ctx, onuSerialNumber, dh.device.ParentPortNo)
3239 if InCacheOnuDev == nil {
3240 logger.Errorw(ctx, "failed to get child device from cache", log.Fields{"onudev": onuSerialNumber})
3241 return olterrors.NewErrAdapter("failed to get child device from cache", log.Fields{
3242 "device-id": dh.device.Id,
3243 "onu-serial-number": onuSerialNumber}, nil)
3244 }
3245 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})
3246
3247 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3248 if err != nil {
3249 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3250 log.Fields{
3251 "device-id": dh.device.Id,
3252 "serial-number": onuSerialNumber}, err).Log()
3253 }
3254
3255 onuIntf := &oop.InterfaceOnuSerialNumber{
3256 OnuSerialNumber: sn,
3257 IntfId: InCacheOnuDev.intfID,
3258 }
3259 onuIntfReq := &oop.InterfaceOnuSerialNumberOnuId{
3260 OnuId: InCacheOnuDev.onuID,
3261 IntfIdSerialNum: onuIntf,
3262 }
3263 _, err = dh.Client.EnableOnu(ctx, onuIntfReq)
3264
3265 if err != nil {
3266 logger.Errorw(ctx, "failed to enable onu ", log.Fields{"onudev": onuSerialNumber, "error": err})
3267 return olterrors.NewErrAdapter("onu-enable-failed", log.Fields{
3268 "olt-device-id": dh.device.Id,
3269 "onu-serial-number": onuSerialNumber}, err)
3270 }
3271 return nil
3272}
3273
3274// DisableOnu to disable onu
3275func (dh *DeviceHandler) DisableOnu(ctx context.Context, device *voltha.Device) error {
3276 logger.Debugw(ctx, "disable-onu", log.Fields{"Device": dh.device, "onu-serial-number": device.SerialNumber})
3277 onuSerialNumber := device.SerialNumber
3278 InCacheOnuDev := dh.getChildDevice(ctx, onuSerialNumber, dh.device.ParentPortNo)
3279 if InCacheOnuDev == nil {
3280 logger.Errorw(ctx, "failed to get child device from cache", log.Fields{"onudev": onuSerialNumber})
3281 return olterrors.NewErrAdapter("failed to get child device from cache", log.Fields{
3282 "device-id": dh.device.Id,
3283 "onu-serial-number": onuSerialNumber}, nil)
3284 }
3285 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})
3286
3287 sn, err := dh.deStringifySerialNumber(onuSerialNumber)
3288 if err != nil {
3289 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
3290 log.Fields{
3291 "device-id": dh.device.Id,
3292 "serial-number": onuSerialNumber}, err).Log()
3293 }
3294
3295 onuIntf := &oop.InterfaceOnuSerialNumber{
3296 OnuSerialNumber: sn,
3297 IntfId: InCacheOnuDev.intfID,
3298 }
3299 onuIntfReq := &oop.InterfaceOnuSerialNumberOnuId{
3300 OnuId: InCacheOnuDev.onuID,
3301 IntfIdSerialNum: onuIntf,
3302 }
3303 _, err = dh.Client.DisableOnu(ctx, onuIntfReq)
3304
3305 if err != nil {
3306 logger.Errorw(ctx, "failed to disable onu ", log.Fields{"onudev": onuSerialNumber, "error": err})
3307 return olterrors.NewErrAdapter("onu-disable-failed", log.Fields{
3308 "olt-device-id": dh.device.Id,
3309 "onu-serial-number": onuSerialNumber}, err)
3310 }
3311 return nil
3312}
3313
kesavand39e0aa32020-01-28 20:58:50 -05003314// EnablePort to enable Pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00003315func (dh *DeviceHandler) EnablePort(ctx context.Context, port *voltha.Port) error {
3316 logger.Debugw(ctx, "enable-port", log.Fields{"Device": dh.device, "port": port})
3317 return dh.modifyPhyPort(ctx, port, true)
kesavand39e0aa32020-01-28 20:58:50 -05003318}
3319
3320// DisablePort to disable pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00003321func (dh *DeviceHandler) DisablePort(ctx context.Context, port *voltha.Port) error {
3322 logger.Debugw(ctx, "disable-port", log.Fields{"Device": dh.device, "port": port})
3323 return dh.modifyPhyPort(ctx, port, false)
kesavand39e0aa32020-01-28 20:58:50 -05003324}
3325
Mahir Gunyela2e68702022-12-07 00:00:42 -08003326// 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 +00003327func (dh *DeviceHandler) modifyPhyPort(ctx context.Context, port *voltha.Port, enablePort bool) error {
3328 logger.Infow(ctx, "modifyPhyPort", log.Fields{"port": port, "Enable": enablePort, "device-id": dh.device.Id})
kesavand39e0aa32020-01-28 20:58:50 -05003329 if port.GetType() == voltha.Port_ETHERNET_NNI {
3330 // Bug is opened for VOL-2505 to support NNI disable feature.
Neha Sharma96b7bf22020-06-15 10:37:32 +00003331 logger.Infow(ctx, "voltha-supports-single-nni-hence-disable-of-nni-not-allowed",
Shrey Baid807a2a02020-04-09 12:52:45 +05303332 log.Fields{"device": dh.device, "port": port})
Thomas Lee S94109f12020-03-03 16:39:29 +05303333 return olterrors.NewErrAdapter("illegal-port-request", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003334 "port-type": port.GetType,
Girish Kumarf26e4882020-03-05 06:49:10 +00003335 "enable-state": enablePort}, nil)
kesavand39e0aa32020-01-28 20:58:50 -05003336 }
3337 // fetch interfaceid from PortNo
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003338 ponID := plt.PortNoToIntfID(port.GetPortNo(), voltha.Port_PON_OLT)
kesavand39e0aa32020-01-28 20:58:50 -05003339 ponIntf := &oop.Interface{IntfId: ponID}
3340 var operStatus voltha.OperStatus_Types
bseenivaa1622112025-12-11 18:24:02 +05303341 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
kesavand39e0aa32020-01-28 20:58:50 -05003342 if enablePort {
3343 operStatus = voltha.OperStatus_ACTIVE
bseenivaa1622112025-12-11 18:24:02 +05303344 out, err := dh.Client.EnablePonIf(subCtx, ponIntf)
3345 cancel()
kesavand39e0aa32020-01-28 20:58:50 -05003346 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303347 return olterrors.NewErrAdapter("pon-port-enable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003348 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003349 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003350 }
3351 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05003352 dh.activePorts.Store(ponID, true)
Neha Sharma96b7bf22020-06-15 10:37:32 +00003353 logger.Infow(ctx, "enabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05003354 } else {
3355 operStatus = voltha.OperStatus_UNKNOWN
bseenivaa1622112025-12-11 18:24:02 +05303356 out, err := dh.Client.DisablePonIf(subCtx, ponIntf)
3357 cancel()
kesavand39e0aa32020-01-28 20:58:50 -05003358 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303359 return olterrors.NewErrAdapter("pon-port-disable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08003360 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003361 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003362 }
3363 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05003364 dh.activePorts.Store(ponID, false)
Neha Sharma96b7bf22020-06-15 10:37:32 +00003365 logger.Infow(ctx, "disabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05003366 }
khenaidoodc2116e2021-10-19 17:33:19 -04003367 if err := dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -04003368 DeviceId: dh.device.Id,
3369 PortType: voltha.Port_PON_OLT,
3370 PortNo: port.PortNo,
3371 OperStatus: operStatus,
3372 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303373 return olterrors.NewErrAdapter("port-state-update-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303374 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003375 "port": port.PortNo}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003376 }
3377 return nil
3378}
3379
Mahir Gunyela2e68702022-12-07 00:00:42 -08003380// disableAdminDownPorts disables the ports, if the corresponding port Adminstate is disabled on reboot and Renable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003381func (dh *DeviceHandler) disableAdminDownPorts(ctx context.Context, ports []*voltha.Port) error {
kesavand39e0aa32020-01-28 20:58:50 -05003382 // Disable the port and update the oper_port_status to core
3383 // if the Admin state of the port is disabled on reboot and re-enable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003384 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003385 if port.AdminState == common.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00003386 if err := dh.DisablePort(ctx, port); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303387 return olterrors.NewErrAdapter("port-disable-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303388 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00003389 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05003390 }
3391 }
3392 }
3393 return nil
3394}
3395
Mahir Gunyela2e68702022-12-07 00:00:42 -08003396// populateActivePorts to populate activePorts map
Kent Hagermanf1db18b2020-07-08 13:38:15 -04003397func (dh *DeviceHandler) populateActivePorts(ctx context.Context, ports []*voltha.Port) {
3398 logger.Infow(ctx, "populateActivePorts", log.Fields{"device-id": dh.device.Id})
3399 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05003400 if port.Type == voltha.Port_ETHERNET_NNI {
3401 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003402 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), true)
kesavand39e0aa32020-01-28 20:58:50 -05003403 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003404 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), false)
kesavand39e0aa32020-01-28 20:58:50 -05003405 }
3406 }
3407 if port.Type == voltha.Port_PON_OLT {
3408 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003409 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), true)
kesavand39e0aa32020-01-28 20:58:50 -05003410 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003411 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), false)
kesavand39e0aa32020-01-28 20:58:50 -05003412 }
3413 }
3414 }
3415}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003416
3417// ChildDeviceLost deletes ONU and clears pon resources related to it.
Girish Gowdraa0870562021-03-11 14:30:14 -08003418func (dh *DeviceHandler) ChildDeviceLost(ctx context.Context, pPortNo uint32, onuID uint32, onuSn string) error {
divyadesai3af43e12020-08-18 07:10:54 +00003419 logger.Debugw(ctx, "child-device-lost", log.Fields{"parent-device-id": dh.device.Id})
Girish Gowdrab4c33302022-03-18 15:07:38 -07003420 if dh.getDeviceDeletionInProgressFlag() {
3421 // Given that the OLT device itself is getting deleted, everything will be cleaned up in the DB and the OLT
3422 // will reboot, so everything will be reset on the pOLT too.
3423 logger.Infow(ctx, "olt-device-delete-in-progress-not-handling-child-device-lost",
3424 log.Fields{"parent-device-id": dh.device.Id, "pon-port": pPortNo, "onuID": onuID, "onuSN": onuSn})
3425 return nil
3426 }
Sridhar Ravindra92c9b0d2025-01-16 00:15:54 +05303427
3428 if dh.transitionMap.currentDeviceState != deviceStateUp {
3429 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})
3430 return fmt.Errorf("device-is-not-up--not-handling-child-device-lost")
3431 }
3432
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003433 intfID := plt.PortNoToIntfID(pPortNo, voltha.Port_PON_OLT)
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003434 onuKey := dh.formOnuKey(intfID, onuID)
Girish Gowdraa0870562021-03-11 14:30:14 -08003435
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003436 var sn *oop.SerialNumber
3437 var err error
Girish Gowdraa0870562021-03-11 14:30:14 -08003438 if sn, err = dh.deStringifySerialNumber(onuSn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05303439 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003440 log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303441 "devicer-id": dh.device.Id,
Girish Gowdraa0870562021-03-11 14:30:14 -08003442 "serial-number": onuSn}, err).Log()
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003443 }
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003444
Girish Gowdra89ae6d82020-05-28 23:40:53 -07003445 onu := &oop.Onu{IntfId: intfID, OnuId: onuID, SerialNumber: sn}
Akash Kankanala041a2122024-10-16 15:49:22 +05303446 // clear PON resources associated with ONU
yasin saplibddc2d72022-02-08 13:10:17 +00003447 onuGem, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003448 if err != nil || onuGem == nil || onuGem.OnuID != onuID {
3449 logger.Warnw(ctx, "failed-to-get-onu-info-for-pon-port", log.Fields{
3450 "device-id": dh.device.Id,
3451 "intf-id": intfID,
3452 "onuID": onuID,
3453 "err": err})
3454 } else {
3455 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
yasin saplie87d4bd2021-12-06 09:04:03 +00003456 // Delete flows from device before schedulers and queue
3457 // Clear flowids for gem cache.
3458 removedFlows := []uint64{}
3459 for _, gem := range onuGem.GemPorts {
3460 if flowIDs, err := dh.resourceMgr[intfID].GetFlowIDsForGem(ctx, gem); err == nil {
3461 for _, flowID := range flowIDs {
Akash Kankanala041a2122024-10-16 15:49:22 +05303462 // multiple gem port can have the same flow id
3463 // it is better to send only one flowRemove request to the agent
yasin saplie87d4bd2021-12-06 09:04:03 +00003464 var alreadyRemoved bool
3465 for _, removedFlowID := range removedFlows {
3466 if removedFlowID == flowID {
3467 logger.Debugw(ctx, "flow-is-already-removed-due-to-another-gem", log.Fields{"flowID": flowID})
3468 alreadyRemoved = true
3469 break
3470 }
3471 }
3472 if !alreadyRemoved {
Mahir Gunyela2e68702022-12-07 00:00:42 -08003473 dh.removeFlowFromDevice(ctx, flowID, intfID)
yasin saplie87d4bd2021-12-06 09:04:03 +00003474 removedFlows = appendUnique64bit(removedFlows, flowID)
3475 }
3476 }
3477 }
3478 _ = dh.resourceMgr[intfID].DeleteFlowIDsForGem(ctx, gem)
3479 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003480 if err := dh.clearUNIData(ctx, onuGem); err != nil {
3481 logger.Warnw(ctx, "failed-to-clear-uni-data-for-onu", log.Fields{
3482 "device-id": dh.device.Id,
3483 "onu-device": onu,
3484 "err": err})
3485 }
yasin saplibddc2d72022-02-08 13:10:17 +00003486 if err := dh.resourceMgr[intfID].DelOnuGemInfo(ctx, onuID); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003487 logger.Warnw(ctx, "persistence-update-onu-gem-info-failed", log.Fields{
3488 "intf-id": intfID,
3489 "onu-device": onu,
3490 "onu-gem": onuGem,
3491 "err": err})
Akash Kankanala041a2122024-10-16 15:49:22 +05303492 // Not returning error on cleanup.
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003493 }
3494 logger.Debugw(ctx, "removed-onu-gem-info", log.Fields{"intf": intfID, "onu-device": onu, "onugem": onuGem})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003495 }
yasin saplibddc2d72022-02-08 13:10:17 +00003496 dh.resourceMgr[intfID].FreeonuID(ctx, []uint32{onuID})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003497 dh.onus.Delete(onuKey)
3498 dh.discOnus.Delete(onuSn)
3499
bseenivaa1622112025-12-11 18:24:02 +05303500 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003501 // Now clear the ONU on the OLT
bseenivaa1622112025-12-11 18:24:02 +05303502 if _, err := dh.Client.DeleteOnu(subCtx, onu); err != nil {
3503 cancel()
Thomas Lee S94109f12020-03-03 16:39:29 +05303504 return olterrors.NewErrAdapter("failed-to-delete-onu", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05303505 "device-id": dh.device.Id,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003506 "onu-id": onuID}, err).Log()
3507 }
bseenivaa1622112025-12-11 18:24:02 +05303508 cancel()
Chaitrashree G S1a55b882020-02-04 17:35:35 -05003509 return nil
3510}
Mahir Gunyela2e68702022-12-07 00:00:42 -08003511func (dh *DeviceHandler) removeFlowFromDevice(ctx context.Context, flowID uint64, intfID uint32) {
3512 flow := &oop.Flow{FlowId: flowID}
3513 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
3514 logger.Warnw(ctx, "failed-to-get-flow-mgr-to-remove-flow-from-device", log.Fields{
3515 "device-id": dh.device.Id})
3516 } else {
3517 if err := dh.flowMgr[intfID].removeFlowFromDevice(ctx, flow, flowID); err != nil {
3518 logger.Warnw(ctx, "failed-to-remove-flow-from-device", log.Fields{
3519 "device-id": dh.device.Id,
3520 "err": err})
3521 }
3522 }
3523}
Girish Gowdracefae192020-03-19 18:14:10 -07003524
3525func getInPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003526 for _, field := range flow_utils.GetOfbFields(flow) {
3527 if field.Type == flow_utils.IN_PORT {
Girish Gowdracefae192020-03-19 18:14:10 -07003528 return field.GetPort()
3529 }
3530 }
3531 return InvalidPort
3532}
3533
3534func getOutPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003535 for _, action := range flow_utils.GetActions(flow) {
3536 if action.Type == flow_utils.OUTPUT {
Girish Gowdracefae192020-03-19 18:14:10 -07003537 if out := action.GetOutput(); out != nil {
3538 return out.GetPort()
3539 }
3540 }
3541 }
3542 return InvalidPort
3543}
3544
Girish Gowdracefae192020-03-19 18:14:10 -07003545func getPorts(flow *of.OfpFlowStats) (uint32, uint32) {
3546 inPort := getInPortFromFlow(flow)
3547 outPort := getOutPortFromFlow(flow)
3548
3549 if inPort == InvalidPort || outPort == InvalidPort {
3550 return inPort, outPort
3551 }
3552
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003553 if isControllerFlow := plt.IsControllerBoundFlow(outPort); isControllerFlow {
Girish Gowdracefae192020-03-19 18:14:10 -07003554 /* Get UNI port/ IN Port from tunnel ID field for upstream controller bound flows */
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003555 if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003556 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003557 return uniPort, outPort
3558 }
3559 }
3560 } else {
3561 // Downstream flow from NNI to PON port , Use tunnel ID as new OUT port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003562 if portType := plt.IntfIDToPortTypeName(outPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003563 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07003564 return inPort, uniPort
3565 }
3566 // Upstream flow from PON to NNI port , Use tunnel ID as new IN port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003567 } else 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 }
3573
3574 return InvalidPort, InvalidPort
3575}
Matt Jeanneretceea2e02020-03-27 14:19:57 -04003576
3577func extractOmciTransactionID(omciPkt []byte) uint16 {
3578 if len(omciPkt) > 3 {
3579 d := omciPkt[0:2]
3580 transid := binary.BigEndian.Uint16(d)
3581 return transid
3582 }
3583 return 0
3584}
Mahir Gunyel0f89fd22020-04-11 18:24:42 -07003585
3586// StoreOnuDevice stores the onu parameters to the local cache.
3587func (dh *DeviceHandler) StoreOnuDevice(onuDevice *OnuDevice) {
3588 onuKey := dh.formOnuKey(onuDevice.intfID, onuDevice.onuID)
3589 dh.onus.Store(onuKey, onuDevice)
3590}
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003591
khenaidoodc2116e2021-10-19 17:33:19 -04003592func (dh *DeviceHandler) getExtValue(ctx context.Context, device *voltha.Device, value extension.ValueType_Type) (*extension.ReturnValues, error) {
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003593 var err error
Andrea Campanella9931ad62020-04-28 15:11:06 +02003594 var sn *oop.SerialNumber
Gamze Abaka78a1d2a2020-04-27 10:17:27 +00003595 var ID uint32
khenaidoodc2116e2021-10-19 17:33:19 -04003596 resp := new(extension.ReturnValues)
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003597 valueparam := new(oop.ValueParam)
Neha Sharma8f4e4322020-08-06 10:51:53 +00003598 ctx = log.WithSpanFromContext(context.Background(), ctx)
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003599 logger.Infow(ctx, "getExtValue", log.Fields{"onu-id": device.Id, "pon-intf": device.ParentPortNo})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003600 if sn, err = dh.deStringifySerialNumber(device.SerialNumber); err != nil {
3601 return nil, err
3602 }
3603 ID = device.ProxyAddress.GetOnuId()
3604 Onu := oop.Onu{IntfId: device.ParentPortNo, OnuId: ID, SerialNumber: sn}
3605 valueparam.Onu = &Onu
3606 valueparam.Value = value
3607
3608 // This API is unsupported until agent patch is added
3609 resp.Unsupported = uint32(value)
3610 _ = ctx
3611
3612 // Uncomment this code once agent changes are complete and tests
3613 /*
3614 resp, err = dh.Client.GetValue(ctx, valueparam)
3615 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003616 logger.Errorw("error-while-getValue", log.Fields{"DeviceID": dh.device, "onu-id": onuid, "err": err})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08003617 return nil, err
3618 }
3619 */
3620
Girish Kumara1ea2aa2020-08-19 18:14:22 +00003621 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 -08003622 return resp, nil
3623}
Girish Gowdra9602eb42020-09-09 15:50:39 -07003624
Akash Kankanala041a2122024-10-16 15:49:22 +05303625func (dh *DeviceHandler) getIntfIDFromFlow(flow *of.OfpFlowStats) uint32 {
yasin saplid0566272021-12-21 09:10:30 +00003626 // Default to NNI
3627 var intfID = dh.totalPonPorts
Girish Gowdra9602eb42020-09-09 15:50:39 -07003628 inPort, outPort := getPorts(flow)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003629 if inPort != InvalidPort && outPort != InvalidPort {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003630 _, intfID, _, _ = plt.ExtractAccessFromFlow(inPort, outPort)
Girish Gowdra9602eb42020-09-09 15:50:39 -07003631 }
3632 return intfID
3633}
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003634
Akash Kankanala041a2122024-10-16 15:49:22 +05303635func (dh *DeviceHandler) getOnuIndicationChannel(intfID uint32) chan onuIndicationMsg {
Mahir Gunyelb0046752021-02-26 13:51:05 -08003636 dh.perPonOnuIndicationChannelLock.Lock()
3637 if ch, ok := dh.perPonOnuIndicationChannel[intfID]; ok {
3638 dh.perPonOnuIndicationChannelLock.Unlock()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003639 return ch.indicationChannel
3640 }
3641 channels := onuIndicationChannels{
Akash Kankanala041a2122024-10-16 15:49:22 +05303642 // We create a buffered channel here to avoid calling function to be blocked
3643 // in case of multiple indications from the ONUs,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003644 //especially in the case where indications are buffered in OLT.
Mahir Gunyelb0046752021-02-26 13:51:05 -08003645 indicationChannel: make(chan onuIndicationMsg, 500),
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003646 stopChannel: make(chan struct{}),
3647 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003648 dh.perPonOnuIndicationChannel[intfID] = channels
3649 dh.perPonOnuIndicationChannelLock.Unlock()
3650 go dh.onuIndicationsRoutine(&channels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003651 return channels.indicationChannel
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003652}
3653
Mahir Gunyelb0046752021-02-26 13:51:05 -08003654func (dh *DeviceHandler) removeOnuIndicationChannels(ctx context.Context) {
3655 logger.Debug(ctx, "remove-onu-indication-channels", log.Fields{"device-id": dh.device.Id})
3656 dh.perPonOnuIndicationChannelLock.Lock()
3657 defer dh.perPonOnuIndicationChannelLock.Unlock()
3658 for _, v := range dh.perPonOnuIndicationChannel {
3659 close(v.stopChannel)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003660 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003661 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003662}
3663
Mahir Gunyelb0046752021-02-26 13:51:05 -08003664func (dh *DeviceHandler) putOnuIndicationToChannel(ctx context.Context, indication *oop.Indication, intfID uint32) {
3665 ind := onuIndicationMsg{
3666 ctx: ctx,
3667 indication: indication,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003668 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003669 logger.Debugw(ctx, "put-onu-indication-to-channel", log.Fields{"indication": indication, "intfID": intfID})
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003670 // Send the onuIndication on the ONU channel
Akash Kankanala041a2122024-10-16 15:49:22 +05303671 dh.getOnuIndicationChannel(intfID) <- ind
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003672}
3673
Mahir Gunyelb0046752021-02-26 13:51:05 -08003674func (dh *DeviceHandler) onuIndicationsRoutine(onuChannels *onuIndicationChannels) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003675 for {
3676 select {
3677 // process one indication per onu, before proceeding to the next one
3678 case onuInd := <-onuChannels.indicationChannel:
Andrea Campanella46b01402021-11-15 16:58:05 -08003679 indication := *(proto.Clone(onuInd.indication)).(*oop.Indication)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003680 logger.Debugw(onuInd.ctx, "calling-indication", log.Fields{"device-id": dh.device.Id,
Andrea Campanella46b01402021-11-15 16:58:05 -08003681 "ind": indication})
3682 switch indication.Data.(type) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003683 case *oop.Indication_OnuInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003684 if err := dh.onuIndication(onuInd.ctx, indication.GetOnuInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003685 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3686 "type": "onu-indication",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003687 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003688 }
3689 case *oop.Indication_OnuDiscInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003690 if err := dh.onuDiscIndication(onuInd.ctx, indication.GetOnuDiscInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003691 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3692 "type": "onu-discovery",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003693 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003694 }
3695 }
3696 case <-onuChannels.stopChannel:
3697 logger.Debugw(context.Background(), "stop-signal-received-for-onu-channel", log.Fields{"device-id": dh.device.Id})
3698 close(onuChannels.indicationChannel)
3699 return
3700 }
3701 }
3702}
Girish Gowdra491a9c62021-01-06 16:43:07 -08003703
3704// RouteMcastFlowOrGroupMsgToChannel routes incoming mcast flow or group to a channel to be handled by the a specific
3705// instance of mcastFlowOrGroupChannelHandlerRoutine meant to handle messages for that group.
khenaidoodc2116e2021-10-19 17:33:19 -04003706func (dh *DeviceHandler) RouteMcastFlowOrGroupMsgToChannel(ctx context.Context, flow *of.OfpFlowStats, group *of.OfpGroupEntry, action string) error {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003707 if dh.getDeviceDeletionInProgressFlag() {
3708 // The device itself is going to be reset as part of deletion. So nothing to be done.
3709 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
3710 return nil
3711 }
3712
Girish Gowdra491a9c62021-01-06 16:43:07 -08003713 // Step1 : Fill McastFlowOrGroupControlBlock
3714 // Step2 : Push the McastFlowOrGroupControlBlock to appropriate channel
3715 // Step3 : Wait on response channel for response
3716 // Step4 : Return error value
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003717 startTime := time.Now()
Girish Gowdra491a9c62021-01-06 16:43:07 -08003718 logger.Debugw(ctx, "process-flow-or-group", log.Fields{"flow": flow, "group": group, "action": action})
3719 errChan := make(chan error)
3720 var groupID uint32
3721 mcastFlowOrGroupCb := McastFlowOrGroupControlBlock{
3722 ctx: ctx,
3723 flowOrGroupAction: action,
3724 flow: flow,
3725 group: group,
3726 errChan: &errChan,
3727 }
3728 if flow != nil {
3729 groupID = flow_utils.GetGroup(flow)
3730 } else if group != nil {
3731 groupID = group.Desc.GroupId
3732 } else {
3733 return errors.New("flow-and-group-both-nil")
3734 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003735 mcastRoutineIdx := groupID % MaxNumOfGroupHandlerChannels
3736 if dh.mcastHandlerRoutineActive[mcastRoutineIdx] {
3737 // Derive the appropriate go routine to handle the request by a simple module operation.
3738 // There are only MaxNumOfGroupHandlerChannels number of channels to handle the mcast flow or group
3739 dh.incomingMcastFlowOrGroup[groupID%MaxNumOfGroupHandlerChannels] <- mcastFlowOrGroupCb
3740 // Wait for handler to return error value
3741 err := <-errChan
3742 logger.Debugw(ctx, "process-flow-or-group--received-resp", log.Fields{"err": err, "totalTimeInSeconds": time.Since(startTime).Milliseconds()})
3743 return err
3744 }
3745 logger.Errorw(ctx, "mcast handler routine not active for onu", log.Fields{"mcastRoutineIdx": mcastRoutineIdx})
3746 return fmt.Errorf("mcast-handler-routine-not-active-for-index-%v", mcastRoutineIdx)
Girish Gowdra491a9c62021-01-06 16:43:07 -08003747}
3748
3749// mcastFlowOrGroupChannelHandlerRoutine routine to handle incoming mcast flow/group message
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003750func (dh *DeviceHandler) mcastFlowOrGroupChannelHandlerRoutine(routineIndex int, mcastFlowOrGroupChannel chan McastFlowOrGroupControlBlock, stopHandler chan bool) {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003751 for {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003752 select {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003753 // block on the channel to receive an incoming mcast flow/group
3754 // process the flow completely before proceeding to handle the next flow
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003755 case mcastFlowOrGroupCb := <-mcastFlowOrGroupChannel:
3756 if mcastFlowOrGroupCb.flow != nil {
3757 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3758 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-flow",
3759 log.Fields{"device-id": dh.device.Id,
3760 "flowToAdd": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003761 err := olterrors.NewErrNotFound("no-flow-manager-found-to-add-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3762 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3763 for _, flMgr := range dh.flowMgr {
3764 if flMgr != nil {
3765 err = flMgr.AddFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow, nil)
3766 break
3767 }
3768 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003769 // Pass the return value over the return channel
3770 *mcastFlowOrGroupCb.errChan <- err
3771 } else { // flow remove
3772 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-flow",
3773 log.Fields{"device-id": dh.device.Id,
3774 "flowToRemove": mcastFlowOrGroupCb.flow})
Mahir Gunyela2e68702022-12-07 00:00:42 -08003775 // The mcast flow is not unique to any particular PON port, so it is OK to default to first non nil PON
3776 err := olterrors.NewErrNotFound("no-flow-manager-found-to-remove-mcast-flow", log.Fields{"device-id": dh.device.Id}, nil).(error)
3777 for _, flMgr := range dh.flowMgr {
3778 if flMgr != nil {
3779 err = flMgr.RemoveFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow)
3780 break
3781 }
3782 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003783 // Pass the return value over the return channel
3784 *mcastFlowOrGroupCb.errChan <- err
3785 }
3786 } else { // mcast group
mgouda86543582025-10-29 20:58:16 +05303787 switch mcastFlowOrGroupCb.flowOrGroupAction {
3788 case McastFlowOrGroupAdd:
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003789 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-group",
3790 log.Fields{"device-id": dh.device.Id,
3791 "groupToAdd": mcastFlowOrGroupCb.group})
3792 err := dh.groupMgr.AddGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3793 // Pass the return value over the return channel
3794 *mcastFlowOrGroupCb.errChan <- err
mgouda86543582025-10-29 20:58:16 +05303795 case McastFlowOrGroupModify: // group modify
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003796 logger.Debugw(mcastFlowOrGroupCb.ctx, "modifying-mcast-group",
3797 log.Fields{"device-id": dh.device.Id,
3798 "groupToModify": mcastFlowOrGroupCb.group})
3799 err := dh.groupMgr.ModifyGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3800 // Pass the return value over the return channel
3801 *mcastFlowOrGroupCb.errChan <- err
mgouda86543582025-10-29 20:58:16 +05303802 default: // group remove
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003803 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-group",
3804 log.Fields{"device-id": dh.device.Id,
3805 "groupToRemove": mcastFlowOrGroupCb.group})
3806 err := dh.groupMgr.DeleteGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3807 // Pass the return value over the return channel
3808 *mcastFlowOrGroupCb.errChan <- err
3809 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08003810 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003811 case <-stopHandler:
3812 dh.mcastHandlerRoutineActive[routineIndex] = false
3813 return
Girish Gowdra491a9c62021-01-06 16:43:07 -08003814 }
3815 }
3816}
kesavand62126212021-01-12 04:56:06 -05003817
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003818// StopAllMcastHandlerRoutines stops all flow handler routines. Call this when device is being rebooted or deleted
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003819func (dh *DeviceHandler) StopAllMcastHandlerRoutines(ctx context.Context, wg *sync.WaitGroup) {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003820 for i, v := range dh.stopMcastHandlerRoutine {
3821 if dh.mcastHandlerRoutineActive[i] {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003822 select {
3823 case v <- true:
3824 case <-time.After(time.Second * 5):
3825 logger.Warnw(ctx, "timeout stopping mcast handler routine", log.Fields{"idx": i, "deviceID": dh.device.Id})
3826 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003827 }
3828 }
Holger Hildebrandt143b5be2023-02-10 08:28:15 +00003829
3830 if dh.incomingMcastFlowOrGroup != nil {
3831 for k := range dh.incomingMcastFlowOrGroup {
3832 if dh.incomingMcastFlowOrGroup[k] != nil {
3833 dh.incomingMcastFlowOrGroup[k] = nil
3834 }
3835 }
3836 dh.incomingMcastFlowOrGroup = nil
3837 }
3838
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003839 wg.Done()
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003840 logger.Debug(ctx, "stopped all mcast handler routines")
3841}
3842
Akash Kankanala041a2122024-10-16 15:49:22 +05303843// nolint: unparam
kesavand62126212021-01-12 04:56:06 -05003844func (dh *DeviceHandler) getOltPortCounters(ctx context.Context, oltPortInfo *extension.GetOltPortCounters) *extension.SingleGetValueResponse {
kesavand62126212021-01-12 04:56:06 -05003845 singleValResp := extension.SingleGetValueResponse{
3846 Response: &extension.GetValueResponse{
3847 Response: &extension.GetValueResponse_PortCoutners{
3848 PortCoutners: &extension.GetOltPortCountersResponse{},
3849 },
3850 },
3851 }
3852
Akash Kankanala041a2122024-10-16 15:49:22 +05303853 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
kesavand62126212021-01-12 04:56:06 -05003854 return &extension.SingleGetValueResponse{
3855 Response: &extension.GetValueResponse{
3856 Status: status,
3857 ErrReason: reason,
3858 },
3859 }
3860 }
3861
3862 if oltPortInfo.PortType != extension.GetOltPortCounters_Port_ETHERNET_NNI &&
3863 oltPortInfo.PortType != extension.GetOltPortCounters_Port_PON_OLT {
Akash Kankanala041a2122024-10-16 15:49:22 +05303864 // send error response
kesavand62126212021-01-12 04:56:06 -05003865 logger.Debugw(ctx, "getOltPortCounters invalid portType", log.Fields{"oltPortInfo": oltPortInfo.PortType})
3866 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
3867 }
3868 statIndChn := make(chan bool, 1)
3869 dh.portStats.RegisterForStatIndication(ctx, portStatsType, statIndChn, oltPortInfo.PortNo, oltPortInfo.PortType)
3870 defer dh.portStats.DeRegisterFromStatIndication(ctx, portStatsType, statIndChn)
Akash Kankanala041a2122024-10-16 15:49:22 +05303871 // request openOlt agent to send the the port statistics indication
kesavand62126212021-01-12 04:56:06 -05003872
3873 go func() {
bseenivaa1622112025-12-11 18:24:02 +05303874 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3875 _, err := dh.Client.CollectStatistics(subCtx, new(oop.Empty))
kesavand62126212021-01-12 04:56:06 -05003876 if err != nil {
3877 logger.Errorw(ctx, "getOltPortCounters CollectStatistics failed ", log.Fields{"err": err})
3878 }
bseenivaa1622112025-12-11 18:24:02 +05303879 cancel()
kesavand62126212021-01-12 04:56:06 -05003880 }()
3881 select {
3882 case <-statIndChn:
Akash Kankanala041a2122024-10-16 15:49:22 +05303883 // indication received for ports stats
kesavand62126212021-01-12 04:56:06 -05003884 logger.Debugw(ctx, "getOltPortCounters recvd statIndChn", log.Fields{"oltPortInfo": oltPortInfo})
3885 case <-time.After(oltPortInfoTimeout * time.Second):
3886 logger.Debugw(ctx, "getOltPortCounters timeout happened", log.Fields{"oltPortInfo": oltPortInfo})
3887 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3888 case <-ctx.Done():
3889 logger.Debugw(ctx, "getOltPortCounters ctx Done ", log.Fields{"oltPortInfo": oltPortInfo})
3890 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3891 }
mgouda86543582025-10-29 20:58:16 +05303892 switch oltPortInfo.PortType {
3893 case extension.GetOltPortCounters_Port_ETHERNET_NNI:
Akash Kankanala041a2122024-10-16 15:49:22 +05303894 // get nni stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003895 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_ETHERNET_NNI)
kesavand62126212021-01-12 04:56:06 -05003896 logger.Debugw(ctx, "getOltPortCounters intfID ", log.Fields{"intfID": intfID})
3897 cmnni := dh.portStats.collectNNIMetrics(intfID)
3898 if cmnni == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05303899 // TODO define the error reason
kesavand62126212021-01-12 04:56:06 -05003900 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3901 }
3902 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmnni)
3903 return &singleValResp
mgouda86543582025-10-29 20:58:16 +05303904 case extension.GetOltPortCounters_Port_PON_OLT:
kesavand62126212021-01-12 04:56:06 -05003905 // get pon stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003906 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_PON_OLT)
kesavand62126212021-01-12 04:56:06 -05003907 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
3908 cmpon := dh.portStats.collectPONMetrics(intfID)
3909 if cmpon == nil {
Akash Kankanala041a2122024-10-16 15:49:22 +05303910 // TODO define the error reason
kesavand62126212021-01-12 04:56:06 -05003911 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3912 }
3913 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmpon)
3914 return &singleValResp
3915 }
3916 }
3917 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3918}
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303919
Akash Kankanala041a2122024-10-16 15:49:22 +05303920//nolint:unparam
Akash Soni3bcf5e02024-12-03 08:01:48 +05303921func (dh *DeviceHandler) getOltOffloadStats(ctx context.Context, oltPortInfo *extension.GetOffloadedAppsStatisticsRequest) *extension.SingleGetValueResponse {
Akash Soni3bcf5e02024-12-03 08:01:48 +05303922 singleValResp := extension.SingleGetValueResponse{
3923 Response: &extension.GetValueResponse{
3924 Status: extension.GetValueResponse_OK,
3925 Response: &extension.GetValueResponse_OffloadedAppsStats{
3926 OffloadedAppsStats: &extension.GetOffloadedAppsStatisticsResponse{},
3927 },
3928 },
3929 }
3930
3931 return &singleValResp
3932}
3933
Akash Kankanala041a2122024-10-16 15:49:22 +05303934//nolint:unparam
Akash Soni3c75ad72024-12-23 12:09:48 +05303935func (dh *DeviceHandler) setOltOffload(ctx context.Context, congig *extension.AppOffloadConfig) *extension.SingleSetValueResponse {
Akash Soni3c75ad72024-12-23 12:09:48 +05303936 singleValResp := extension.SingleSetValueResponse{
3937 Response: &extension.SetValueResponse{
3938 Status: extension.SetValueResponse_OK,
3939 },
3940 }
3941
3942 return &singleValResp
3943}
3944
Akash Kankanala041a2122024-10-16 15:49:22 +05303945//nolint:unparam
Akash Soni3c75ad72024-12-23 12:09:48 +05303946func (dh *DeviceHandler) setOnuOffload(ctx context.Context, config *extension.AppOffloadOnuConfig) *extension.SingleSetValueResponse {
Akash Soni3bcf5e02024-12-03 08:01:48 +05303947 singleValResp := extension.SingleSetValueResponse{
3948 Response: &extension.SetValueResponse{
3949 Status: extension.SetValueResponse_OK,
3950 },
3951 }
3952
3953 return &singleValResp
3954}
3955
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303956func (dh *DeviceHandler) getOnuPonCounters(ctx context.Context, onuPonInfo *extension.GetOnuCountersRequest) *extension.SingleGetValueResponse {
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303957 singleValResp := extension.SingleGetValueResponse{
3958 Response: &extension.GetValueResponse{
3959 Response: &extension.GetValueResponse_OnuPonCounters{
3960 OnuPonCounters: &extension.GetOnuCountersResponse{},
3961 },
3962 },
3963 }
3964
Akash Kankanala041a2122024-10-16 15:49:22 +05303965 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303966 return &extension.SingleGetValueResponse{
3967 Response: &extension.GetValueResponse{
3968 Status: status,
3969 ErrReason: reason,
3970 },
3971 }
3972 }
3973 intfID := onuPonInfo.IntfId
3974 onuID := onuPonInfo.OnuId
3975 onuKey := dh.formOnuKey(intfID, onuID)
3976
3977 if _, ok := dh.onus.Load(onuKey); !ok {
3978 logger.Errorw(ctx, "get-onui-pon-counters-request-invalid-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3979 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3980 }
3981 logger.Debugw(ctx, "get-onui-pon-counters-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3982 cmnni := dh.portStats.collectOnDemandOnuStats(ctx, intfID, onuID)
3983 if cmnni == nil {
3984 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3985 }
3986 dh.portStats.updateGetOnuPonCountersResponse(ctx, &singleValResp, cmnni)
3987 return &singleValResp
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303988}
Gamze Abaka85e9a142021-05-26 13:41:39 +00003989
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05303990func (dh *DeviceHandler) CheckOnuGemInfo(ctx context.Context, intfID uint32, onuID uint32) (*rsrcMgr.OnuGemInfo, error) {
3991 onuGemInfo, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
3992 if err != nil {
3993 logger.Errorw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuID})
3994 return nil, err
3995 }
3996 if onuGemInfo != nil {
3997 if len(onuGemInfo.UniPorts) == 0 {
3998 logger.Errorw(ctx, "No uniports present for the ONU", log.Fields{"onuID": onuID})
3999 return nil, err
4000 }
4001 logger.Debugw(ctx, "Received onuGemInfo", log.Fields{"onuID": onuID, "onuGemInfo": onuGemInfo})
4002 return onuGemInfo, nil
4003 }
4004 logger.Errorw(ctx, "Received nil onuGemInfo", log.Fields{"onuID": onuID})
4005 return nil, fmt.Errorf("onuGemInfo received as null, onuID : %d", onuID)
4006}
4007
4008func (dh *DeviceHandler) getAllocGemStats(ctx context.Context, intfID uint32, onuID uint32, onuGemInfo *rsrcMgr.OnuGemInfo, singleValResp *extension.SingleGetValueResponse) error {
4009 var err error
4010 var allocStats *oop.OnuAllocIdStatistics
4011 var onuGemStats *oop.GemPortStatistics
4012 for _, uni := range onuGemInfo.UniPorts {
4013 uniID := plt.UniIDFromPortNum(uni)
4014 uniPath := getUniPortPath(dh.device.Id, intfID, int32(onuID), int32(uniID))
4015 tpIDs := dh.resourceMgr[intfID].GetTechProfileIDForOnu(ctx, onuID, uniID)
4016 if len(tpIDs) == 0 {
4017 logger.Errorw(ctx, "No TPIDs present for the Uni", log.Fields{"onuID": onuID, "uniPort": uni})
4018 continue
4019 }
4020 for _, tpId := range tpIDs {
4021 tpPath := dh.flowMgr[intfID].getTPpath(ctx, uniPath, uint32(tpId))
4022 techProfileInstance, _ := dh.flowMgr[intfID].techprofile.GetTPInstance(ctx, tpPath)
4023 onuStatsFromOlt := extension.OnuAllocGemStatsFromOltResponse{}
4024 if techProfileInstance != nil {
4025 switch tpInst := techProfileInstance.(type) {
4026 case *tp_pb.TechProfileInstance:
4027 allocId := tpInst.UsScheduler.AllocId
4028 onuAllocPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, AllocId: allocId}
bseenivaa1622112025-12-11 18:24:02 +05304029 allocCtx, allocCtxcancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4030 allocStats, err = dh.Client.GetAllocIdStatistics(allocCtx, &onuAllocPkt)
4031 allocCtxcancel()
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05304032 if err != nil {
4033 logger.Errorw(ctx, "Error received from openolt for GetAllocIdStatistics", log.Fields{"onuID": onuID, "AllodId": allocId, "Error": err})
4034 return err
4035 }
4036 allocIdInfo := extension.OnuAllocIdInfoFromOlt{}
4037 allocIdInfo.AllocId = allocStats.AllocId
4038 allocIdInfo.RxBytes = allocStats.RxBytes
4039
4040 onuStatsFromOlt.AllocIdInfo = &allocIdInfo
4041
4042 gemPorts := tpInst.UpstreamGemPortAttributeList
4043 for _, gem := range gemPorts {
4044 onuGemPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, GemportId: gem.GemportId}
bseenivaa1622112025-12-11 18:24:02 +05304045 gemCtx, gemCtxcancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4046 onuGemStats, err = dh.Client.GetGemPortStatistics(gemCtx, &onuGemPkt)
4047 gemCtxcancel()
Akash Reddy Kankanalac6b6ca12025-06-12 14:26:57 +05304048 if err != nil {
4049 logger.Errorw(ctx, "Error received from openolt for GetGemPortStatistics", log.Fields{"onuID": onuID, "GemPortId": gem.GemportId, "Error": err})
4050 return err
4051 }
4052 gemStatsInfo := extension.OnuGemPortInfoFromOlt{}
4053 gemStatsInfo.GemId = onuGemStats.GemportId
4054 gemStatsInfo.RxBytes = onuGemStats.RxBytes
4055 gemStatsInfo.RxPackets = onuGemStats.RxPackets
4056 gemStatsInfo.TxBytes = onuGemStats.TxBytes
4057 gemStatsInfo.TxPackets = onuGemStats.TxPackets
4058
4059 onuStatsFromOlt.GemPortInfo = append(onuStatsFromOlt.GemPortInfo, &gemStatsInfo)
4060 }
4061 singleValResp.Response.GetOnuStatsFromOltResponse().AllocGemStatsInfo = append(singleValResp.Response.GetOnuStatsFromOltResponse().AllocGemStatsInfo, &onuStatsFromOlt)
4062
4063 default:
4064 logger.Errorw(ctx, "Invalid Techprofile type received", log.Fields{"onuID": onuID, "TpId": tpId})
4065 return err
4066 }
4067 } else {
4068 logger.Errorw(ctx, "No TpInstance found for the TpID", log.Fields{"onuID": onuID, "TpId": tpId})
4069 continue
4070 }
4071 }
4072 }
4073 return err
4074}
4075
4076//nolint:unparam
4077func (dh *DeviceHandler) getOnuStatsFromOlt(ctx context.Context, onuInfo *extension.GetOnuStatsFromOltRequest, onuDevice *voltha.Device) *extension.SingleGetValueResponse {
4078 singleValResp := extension.SingleGetValueResponse{
4079 Response: &extension.GetValueResponse{
4080 Status: extension.GetValueResponse_OK,
4081 Response: &extension.GetValueResponse_OnuStatsFromOltResponse{
4082 OnuStatsFromOltResponse: &extension.GetOnuStatsFromOltResponse{},
4083 },
4084 },
4085 }
4086 errResp := func(status extension.GetValueResponse_Status,
4087 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4088 return &extension.SingleGetValueResponse{
4089 Response: &extension.GetValueResponse{
4090 Status: status,
4091 ErrReason: reason,
4092 },
4093 }
4094 }
4095
4096 var intfID, onuID uint32
4097 if onuDevice != nil {
4098 onuID = onuDevice.ProxyAddress.OnuId
4099 intfID = plt.PortNoToIntfID(onuDevice.ParentPortNo, voltha.Port_PON_OLT)
4100 }
4101
4102 onuKey := dh.formOnuKey(intfID, onuID)
4103 if _, ok := dh.onus.Load(onuKey); !ok {
4104 logger.Errorw(ctx, "getOnuStatsFromOlt request received for invalid device", log.Fields{"deviceId": onuDevice.Id, "intfID": intfID, "onuID": onuID})
4105 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4106 }
4107 logger.Debugw(ctx, "getOnuStatsFromOlt request received", log.Fields{"intfID": intfID, "onuID": onuID})
4108
4109 onuGemInfo, err := dh.CheckOnuGemInfo(ctx, intfID, onuID)
4110 if err == nil {
4111 err = dh.getAllocGemStats(ctx, intfID, onuID, onuGemInfo, &singleValResp)
4112 if err != nil {
4113 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
4114 }
4115 } else {
4116 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4117 }
4118 return &singleValResp
4119}
4120
nikesh.krishnanc8473432023-06-14 12:14:54 +05304121func (dh *DeviceHandler) getOnuInfo(ctx context.Context, intfID uint32, onuID *uint32) (*oop.OnuInfo, error) {
nikesh.krishnanc8473432023-06-14 12:14:54 +05304122 Onu := oop.Onu{IntfId: intfID, OnuId: *onuID}
bseenivaa1622112025-12-11 18:24:02 +05304123 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4124 OnuInfo, err := dh.Client.GetOnuInfo(subCtx, &Onu)
4125 cancel()
nikesh.krishnanc8473432023-06-14 12:14:54 +05304126 if err != nil {
4127 return nil, err
4128 }
4129 return OnuInfo, nil
nikesh.krishnanc8473432023-06-14 12:14:54 +05304130}
4131
4132func (dh *DeviceHandler) getIntfInfo(ctx context.Context, intfID uint32) (*oop.PonIntfInfo, error) {
nikesh.krishnanc8473432023-06-14 12:14:54 +05304133 Intf := oop.Interface{IntfId: intfID}
bseenivaa1622112025-12-11 18:24:02 +05304134 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4135 IntfInfo, err := dh.Client.GetPonInterfaceInfo(subCtx, &Intf)
4136 cancel()
nikesh.krishnanc8473432023-06-14 12:14:54 +05304137 if err != nil {
4138 return nil, err
4139 }
4140 return IntfInfo, nil
nikesh.krishnanc8473432023-06-14 12:14:54 +05304141}
4142
Gamze Abaka85e9a142021-05-26 13:41:39 +00004143func (dh *DeviceHandler) getRxPower(ctx context.Context, rxPowerRequest *extension.GetRxPowerRequest) *extension.SingleGetValueResponse {
Gamze Abaka85e9a142021-05-26 13:41:39 +00004144 Onu := oop.Onu{IntfId: rxPowerRequest.IntfId, OnuId: rxPowerRequest.OnuId}
bseenivaa1622112025-12-11 18:24:02 +05304145 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4146 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4147 cancel()
Gamze Abaka85e9a142021-05-26 13:41:39 +00004148 if err != nil {
4149 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
4150 return generateSingleGetValueErrorResponse(err)
4151 }
4152 return &extension.SingleGetValueResponse{
4153 Response: &extension.GetValueResponse{
4154 Status: extension.GetValueResponse_OK,
4155 Response: &extension.GetValueResponse_RxPower{
4156 RxPower: &extension.GetRxPowerResponse{
4157 IntfId: rxPowerRequest.IntfId,
4158 OnuId: rxPowerRequest.OnuId,
4159 Status: rxPower.Status,
4160 FailReason: rxPower.FailReason.String(),
4161 RxPower: rxPower.RxPowerMeanDbm,
4162 },
4163 },
4164 },
4165 }
4166}
4167
praneeth nalmas55616d62023-02-06 09:19:18 +05304168func (dh *DeviceHandler) getPONRxPower(ctx context.Context, OltRxPowerRequest *extension.GetOltRxPowerRequest) *extension.SingleGetValueResponse {
Akash Kankanala041a2122024-10-16 15:49:22 +05304169 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
praneeth nalmas55616d62023-02-06 09:19:18 +05304170 return &extension.SingleGetValueResponse{
4171 Response: &extension.GetValueResponse{
4172 Status: status,
4173 ErrReason: reason,
4174 },
4175 }
4176 }
4177
4178 resp := extension.SingleGetValueResponse{
4179 Response: &extension.GetValueResponse{
4180 Status: extension.GetValueResponse_OK,
4181 Response: &extension.GetValueResponse_OltRxPower{
4182 OltRxPower: &extension.GetOltRxPowerResponse{},
4183 },
4184 },
4185 }
4186
4187 logger.Debugw(ctx, "getPONRxPower", log.Fields{"portLabel": OltRxPowerRequest.PortLabel, "OnuSerialNumber": OltRxPowerRequest.OnuSn, "device-id": dh.device.Id})
4188 portLabel := OltRxPowerRequest.PortLabel
4189 serialNumber := OltRxPowerRequest.OnuSn
4190
4191 portInfo := strings.Split(portLabel, "-")
4192 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4193
4194 if err != nil {
4195 logger.Errorw(ctx, "getPONRxPower invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4196 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4197 }
4198
4199 if portInfo[0] != "pon" {
4200 logger.Errorw(ctx, "getPONRxPower invalid portType", log.Fields{"oltPortType": portInfo[0]})
4201 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4202 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304203
4204 if serialNumber != "" {
praneeth nalmas55616d62023-02-06 09:19:18 +05304205 onuDev := dh.getChildDevice(ctx, serialNumber, (uint32)(portNumber))
4206 if onuDev != nil {
bseenivaa1622112025-12-11 18:24:02 +05304207 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
praneeth nalmas55616d62023-02-06 09:19:18 +05304208 Onu := oop.Onu{IntfId: uint32(portNumber), OnuId: onuDev.onuID}
bseenivaa1622112025-12-11 18:24:02 +05304209 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4210 cancel()
praneeth nalmas55616d62023-02-06 09:19:18 +05304211 if err != nil {
praneeth nalmas55616d62023-02-06 09:19:18 +05304212 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
4213 return generateSingleGetValueErrorResponse(err)
praneeth nalmas55616d62023-02-06 09:19:18 +05304214 }
4215
4216 rxPowerValue := extension.RxPower{}
4217 rxPowerValue.OnuSn = onuDev.serialNumber
4218 rxPowerValue.Status = rxPower.GetStatus()
4219 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
4220 rxPowerValue.FailReason = rxPower.GetFailReason().String()
4221
4222 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
praneeth nalmas55616d62023-02-06 09:19:18 +05304223 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304224 logger.Errorw(ctx, "getPONRxPower invalid Device", log.Fields{"portLabel": portLabel, "serialNumber": serialNumber})
4225 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4226 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304227 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304228 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
praneeth kumar nalmasb234f232023-11-29 12:50:46 +05304229 if onuInCache.(*OnuDevice).intfID == (uint32)(portNumber) {
praneeth kumar nalmasb234f232023-11-29 12:50:46 +05304230 Onu := oop.Onu{IntfId: (uint32)(portNumber), OnuId: onuInCache.(*OnuDevice).onuID}
bseenivaa1622112025-12-11 18:24:02 +05304231 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4232 rxPower, err := dh.Client.GetPonRxPower(subCtx, &Onu)
4233 cancel()
praneeth nalmas55616d62023-02-06 09:19:18 +05304234 if err != nil {
4235 logger.Errorw(ctx, "error-while-getting-rx-power, however considering to proceed further with other ONUs on PON", log.Fields{"Onu": Onu, "err": err})
4236 } else {
praneeth nalmas55616d62023-02-06 09:19:18 +05304237 rxPowerValue := extension.RxPower{}
4238 rxPowerValue.OnuSn = onuInCache.(*OnuDevice).serialNumber
4239 rxPowerValue.Status = rxPower.GetStatus()
4240 rxPowerValue.RxPower = rxPower.GetRxPowerMeanDbm()
4241 rxPowerValue.FailReason = rxPower.GetFailReason().String()
4242
4243 resp.Response.GetOltRxPower().RxPower = append(resp.Response.GetOltRxPower().RxPower, &rxPowerValue)
4244 }
praneeth nalmas55616d62023-02-06 09:19:18 +05304245 }
4246 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
4247 return true
4248 })
4249 }
4250 logger.Infow(ctx, "getPONRxPower response ", log.Fields{"Response": resp})
4251 return &resp
4252}
4253
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304254func (dh *DeviceHandler) getPonPortStats(ctx context.Context, ponStatsRequest *extension.GetPonStatsRequest) *extension.SingleGetValueResponse {
4255 errResp := func(status extension.GetValueResponse_Status,
4256 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4257 return &extension.SingleGetValueResponse{
4258 Response: &extension.GetValueResponse{
4259 Status: status,
4260 ErrReason: reason,
4261 },
4262 }
4263 }
4264
4265 resp := extension.SingleGetValueResponse{
4266 Response: &extension.GetValueResponse{
4267 Status: extension.GetValueResponse_OK,
4268 Response: &extension.GetValueResponse_OltPonStatsResponse{
4269 OltPonStatsResponse: &extension.GetPonStatsResponse{},
4270 },
4271 },
4272 }
4273
4274 portLabel := ponStatsRequest.GetPortLabel()
4275 logger.Debugw(ctx, "getPonPortStats", log.Fields{"portLabel": portLabel, "device-id": dh.device.Id})
4276
4277 portInfo := strings.Split(portLabel, "-")
4278 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4279
4280 if err != nil {
4281 logger.Errorw(ctx, "getPonPortStats invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4282 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4283 }
4284
4285 if portInfo[0] != "pon" {
4286 logger.Errorw(ctx, "getPonPortStats invalid portType", log.Fields{"oltPortType": portInfo[0]})
4287 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4288 }
4289
4290 Interface := oop.Interface{IntfId: uint32(portNumber)}
bseenivaa1622112025-12-11 18:24:02 +05304291 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4292 ponStats, err := dh.Client.GetPonPortStatistics(subCtx, &Interface)
4293 cancel()
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304294 if err != nil {
4295 logger.Errorw(ctx, "error-while-getting-pon-port-stats", log.Fields{"IntfId": portNumber, "err": err})
4296 return generateSingleGetValueErrorResponse(err)
4297 }
4298
4299 ponPortStats := resp.Response.GetOltPonStatsResponse()
4300 ponPortStats.PonPort = uint32(portNumber)
4301 ponPortStats.PortStatistics = ponStats
4302
4303 logger.Infow(ctx, "getPonPortStats response ", log.Fields{"Response": resp})
4304 return &resp
4305}
4306
4307func (dh *DeviceHandler) getNniPortStats(ctx context.Context, nniStatsRequest *extension.GetNNIStatsRequest) *extension.SingleGetValueResponse {
4308 errResp := func(status extension.GetValueResponse_Status,
4309 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
4310 return &extension.SingleGetValueResponse{
4311 Response: &extension.GetValueResponse{
4312 Status: status,
4313 ErrReason: reason,
4314 },
4315 }
4316 }
4317
4318 resp := extension.SingleGetValueResponse{
4319 Response: &extension.GetValueResponse{
4320 Status: extension.GetValueResponse_OK,
4321 Response: &extension.GetValueResponse_OltNniStatsResponse{
4322 OltNniStatsResponse: &extension.GetNNIStatsResponse{},
4323 },
4324 },
4325 }
4326
4327 portLabel := nniStatsRequest.GetPortLabel()
4328 logger.Debugw(ctx, "getNniPortStats", log.Fields{"portLabel": portLabel, "device-id": dh.device.Id})
4329
4330 portInfo := strings.Split(portLabel, "-")
4331 portNumber, err := strconv.ParseUint(portInfo[1], 10, 32)
4332
4333 if err != nil {
4334 logger.Errorw(ctx, "getNniPortStats invalid portNumber ", log.Fields{"oltPortNumber": portInfo[1]})
4335 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_REQ_TYPE)
4336 }
4337
4338 if portInfo[0] != "nni" {
4339 logger.Errorw(ctx, "getNniPortStats invalid portType", log.Fields{"oltPortType": portInfo[0]})
4340 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
4341 }
4342
4343 Interface := oop.Interface{IntfId: uint32(portNumber)}
bseenivaa1622112025-12-11 18:24:02 +05304344 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4345 nniStats, err := dh.Client.GetNniPortStatistics(subCtx, &Interface)
4346 cancel()
Akash Reddy Kankanalad9ec4822025-06-10 22:59:53 +05304347 if err != nil {
4348 logger.Errorw(ctx, "error-while-getting-nni-port-stats", log.Fields{"PortNo": portNumber, "err": err})
4349 return generateSingleGetValueErrorResponse(err)
4350 }
4351
4352 nniPortStats := resp.Response.GetOltNniStatsResponse()
4353 nniPortStats.NniPort = uint32(portNumber)
4354 nniPortStats.PortStatistics = nniStats
4355
4356 logger.Infow(ctx, "getNniPortStats response ", log.Fields{"Response": resp})
4357 return &resp
4358}
4359
Akash Kankanala041a2122024-10-16 15:49:22 +05304360// nolint: unparam
Gamze Abaka85e9a142021-05-26 13:41:39 +00004361func generateSingleGetValueErrorResponse(err error) *extension.SingleGetValueResponse {
Akash Kankanala041a2122024-10-16 15:49:22 +05304362 errResp := func(status extension.GetValueResponse_Status, reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
Gamze Abaka85e9a142021-05-26 13:41:39 +00004363 return &extension.SingleGetValueResponse{
4364 Response: &extension.GetValueResponse{
4365 Status: status,
4366 ErrReason: reason,
4367 },
4368 }
4369 }
4370
4371 if err != nil {
4372 if e, ok := status.FromError(err); ok {
4373 switch e.Code() {
4374 case codes.Internal:
4375 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
4376 case codes.DeadlineExceeded:
4377 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
4378 case codes.Unimplemented:
4379 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_UNSUPPORTED)
4380 case codes.NotFound:
4381 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
4382 }
4383 }
4384 }
4385
4386 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_REASON_UNDEFINED)
4387}
khenaidoo106c61a2021-08-11 18:05:46 -04004388
4389/*
4390Helper functions to communicate with Core
4391*/
4392
4393func (dh *DeviceHandler) getDeviceFromCore(ctx context.Context, deviceID string) (*voltha.Device, error) {
4394 cClient, err := dh.coreClient.GetCoreServiceClient()
4395 if err != nil || cClient == nil {
4396 return nil, err
4397 }
4398 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4399 defer cancel()
4400 return cClient.GetDevice(subCtx, &common.ID{Id: deviceID})
4401}
4402
khenaidoodc2116e2021-10-19 17:33:19 -04004403func (dh *DeviceHandler) getChildDeviceFromCore(ctx context.Context, childDeviceFilter *ca.ChildDeviceFilter) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004404 cClient, err := dh.coreClient.GetCoreServiceClient()
4405 if err != nil || cClient == nil {
4406 return nil, err
4407 }
4408 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4409 defer cancel()
4410 return cClient.GetChildDevice(subCtx, childDeviceFilter)
4411}
4412
khenaidoodc2116e2021-10-19 17:33:19 -04004413func (dh *DeviceHandler) updateDeviceStateInCore(ctx context.Context, deviceStateFilter *ca.DeviceStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004414 cClient, err := dh.coreClient.GetCoreServiceClient()
4415 if err != nil || cClient == nil {
4416 return err
4417 }
4418 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4419 defer cancel()
4420 _, err = cClient.DeviceStateUpdate(subCtx, deviceStateFilter)
4421 return err
4422}
4423
4424func (dh *DeviceHandler) getChildDevicesFromCore(ctx context.Context, deviceID string) (*voltha.Devices, error) {
4425 cClient, err := dh.coreClient.GetCoreServiceClient()
4426 if err != nil || cClient == nil {
4427 return nil, err
4428 }
4429 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4430 defer cancel()
4431 return cClient.GetChildDevices(subCtx, &common.ID{Id: deviceID})
4432}
4433
4434func (dh *DeviceHandler) listDevicePortsFromCore(ctx context.Context, deviceID string) (*voltha.Ports, error) {
4435 cClient, err := dh.coreClient.GetCoreServiceClient()
4436 if err != nil || cClient == nil {
4437 return nil, err
4438 }
4439 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4440 defer cancel()
4441 return cClient.ListDevicePorts(subCtx, &common.ID{Id: deviceID})
4442}
4443
4444func (dh *DeviceHandler) updateDeviceInCore(ctx context.Context, device *voltha.Device) error {
4445 cClient, err := dh.coreClient.GetCoreServiceClient()
4446 if err != nil || cClient == nil {
4447 return err
4448 }
4449 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4450 defer cancel()
4451 _, err = cClient.DeviceUpdate(subCtx, device)
4452 return err
4453}
4454
khenaidoodc2116e2021-10-19 17:33:19 -04004455func (dh *DeviceHandler) sendChildDeviceDetectedToCore(ctx context.Context, deviceDiscoveryInfo *ca.DeviceDiscovery) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004456 cClient, err := dh.coreClient.GetCoreServiceClient()
4457 if err != nil || cClient == nil {
4458 return nil, err
4459 }
4460 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4461 defer cancel()
4462 return cClient.ChildDeviceDetected(subCtx, deviceDiscoveryInfo)
4463}
4464
khenaidoodc2116e2021-10-19 17:33:19 -04004465func (dh *DeviceHandler) sendPacketToCore(ctx context.Context, pkt *ca.PacketIn) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004466 cClient, err := dh.coreClient.GetCoreServiceClient()
4467 if err != nil || cClient == nil {
4468 return err
4469 }
4470 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4471 defer cancel()
4472 _, err = cClient.SendPacketIn(subCtx, pkt)
4473 return err
4474}
4475
4476func (dh *DeviceHandler) createPortInCore(ctx context.Context, port *voltha.Port) error {
4477 cClient, err := dh.coreClient.GetCoreServiceClient()
4478 if err != nil || cClient == nil {
4479 return err
4480 }
4481 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4482 defer cancel()
4483 _, err = cClient.PortCreated(subCtx, port)
4484 return err
4485}
4486
khenaidoodc2116e2021-10-19 17:33:19 -04004487func (dh *DeviceHandler) updatePortsStateInCore(ctx context.Context, portFilter *ca.PortStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004488 cClient, err := dh.coreClient.GetCoreServiceClient()
4489 if err != nil || cClient == nil {
4490 return err
4491 }
4492 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4493 defer cancel()
4494 _, err = cClient.PortsStateUpdate(subCtx, portFilter)
4495 return err
4496}
4497
khenaidoodc2116e2021-10-19 17:33:19 -04004498func (dh *DeviceHandler) updatePortStateInCore(ctx context.Context, portState *ca.PortState) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004499 cClient, err := dh.coreClient.GetCoreServiceClient()
4500 if err != nil || cClient == nil {
4501 return err
4502 }
4503 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4504 defer cancel()
4505 _, err = cClient.PortStateUpdate(subCtx, portState)
4506 return err
4507}
4508
khenaidoodc2116e2021-10-19 17:33:19 -04004509func (dh *DeviceHandler) getPortFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Port, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004510 cClient, err := dh.coreClient.GetCoreServiceClient()
4511 if err != nil || cClient == nil {
4512 return nil, err
4513 }
4514 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4515 defer cancel()
4516 return cClient.GetDevicePort(subCtx, portFilter)
4517}
4518
nikesh.krishnanc8473432023-06-14 12:14:54 +05304519func (dh *DeviceHandler) getAllPortsFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Ports, error) {
4520 cClient, err := dh.coreClient.GetCoreServiceClient()
4521 if err != nil || cClient == nil {
4522 return nil, err
4523 }
4524 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4525 defer cancel()
4526 return cClient.GetPorts(subCtx, portFilter)
4527}
4528
khenaidoo106c61a2021-08-11 18:05:46 -04004529/*
4530Helper functions to communicate with child adapter
4531*/
4532
khenaidoodc2116e2021-10-19 17:33:19 -04004533func (dh *DeviceHandler) sendOmciIndicationToChildAdapter(ctx context.Context, childEndpoint string, response *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04004534 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
4535 if err != nil || aClient == nil {
4536 return err
4537 }
4538 logger.Debugw(ctx, "sending-omci-response", log.Fields{"response": response, "child-endpoint": childEndpoint})
4539 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4540 defer cancel()
4541 _, err = aClient.OmciIndication(subCtx, response)
4542 return err
4543}
4544
khenaidoodc2116e2021-10-19 17:33:19 -04004545func (dh *DeviceHandler) sendOnuIndicationToChildAdapter(ctx context.Context, childEndpoint string, onuInd *ia.OnuIndicationMessage) 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-onu-indication", log.Fields{"onu-indication": onuInd, "child-endpoint": childEndpoint})
4551 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4552 defer cancel()
4553 _, err = aClient.OnuIndication(subCtx, onuInd)
4554 return err
4555}
4556
khenaidoodc2116e2021-10-19 17:33:19 -04004557func (dh *DeviceHandler) sendDeleteTContToChildAdapter(ctx context.Context, childEndpoint string, tContInfo *ia.DeleteTcontMessage) 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-delete-tcont", log.Fields{"tcont": tContInfo, "child-endpoint": childEndpoint})
4563 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4564 defer cancel()
4565 _, err = aClient.DeleteTCont(subCtx, tContInfo)
4566 return err
4567}
4568
khenaidoodc2116e2021-10-19 17:33:19 -04004569func (dh *DeviceHandler) sendDeleteGemPortToChildAdapter(ctx context.Context, childEndpoint string, gemPortInfo *ia.DeleteGemPortMessage) 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-gem-port", log.Fields{"gem-port-info": gemPortInfo, "child-endpoint": childEndpoint})
4575 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4576 defer cancel()
4577 _, err = aClient.DeleteGemPort(subCtx, gemPortInfo)
4578 return err
4579}
4580
khenaidoodc2116e2021-10-19 17:33:19 -04004581func (dh *DeviceHandler) sendDownloadTechProfileToChildAdapter(ctx context.Context, childEndpoint string, tpDownloadInfo *ia.TechProfileDownloadMessage) 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-tech-profile-download", log.Fields{"tp-download-info": tpDownloadInfo, "child-endpoint": childEndpoint})
4587 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
4588 defer cancel()
4589 _, err = aClient.DownloadTechProfile(subCtx, tpDownloadInfo)
4590 return err
4591}
4592
4593/*
4594Helper functions for remote communication
4595*/
4596
4597// TODO: Use a connection tracker such that the adapter connection is stopped when the last device that adapter
4598// supports is deleted
4599func (dh *DeviceHandler) setupChildInterAdapterClient(ctx context.Context, endpoint string) error {
4600 logger.Infow(ctx, "setting-child-adapter-connection", log.Fields{"child-endpoint": endpoint})
4601
4602 dh.lockChildAdapterClients.Lock()
4603 defer dh.lockChildAdapterClients.Unlock()
4604 if _, ok := dh.childAdapterClients[endpoint]; ok {
4605 // Already set
4606 return nil
4607 }
4608
4609 // Setup child's adapter grpc connection
4610 var err error
khenaidoo27e7ac92021-12-08 14:43:09 -05004611 if dh.childAdapterClients[endpoint], err = vgrpc.NewClient(
4612 dh.cfg.AdapterEndpoint,
4613 endpoint,
khenaidooefff76e2021-12-15 16:51:30 -05004614 "onu_inter_adapter_service.OnuInterAdapterService",
4615 dh.onuInterAdapterRestarted,
4616 vgrpc.ClientContextData(dh.device.Id)); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04004617 logger.Errorw(ctx, "grpc-client-not-created", log.Fields{"error": err, "endpoint": endpoint})
4618 return err
4619 }
nikesh.krishnand9812542023-08-01 18:31:39 +05304620 retryCodes := []codes.Code{
4621 codes.Unavailable, // server is currently unavailable
4622 codes.DeadlineExceeded, // deadline for the operation was exceeded
4623 }
4624 backoffCtxOption := grpc_retry.WithBackoff(grpc_retry.BackoffLinearWithJitter(dh.cfg.PerRPCRetryTimeout, 0.2))
4625 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 -04004626
nikesh.krishnand9812542023-08-01 18:31:39 +05304627 go dh.childAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), dh.getOnuInterAdapterServiceClientHandler, grpcRetryOptions)
khenaidoo106c61a2021-08-11 18:05:46 -04004628 // Wait until we have a connection to the child adapter.
4629 // Unlimited retries or until context expires
4630 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
4631 backoff := vgrpc.NewBackoff(dh.cfg.MinBackoffRetryDelay, dh.cfg.MaxBackoffRetryDelay, 0)
4632 for {
4633 client, err := dh.childAdapterClients[endpoint].GetOnuInterAdapterServiceClient()
4634 if err == nil && client != nil {
4635 logger.Infow(subCtx, "connected-to-child-adapter", log.Fields{"child-endpoint": endpoint})
4636 break
4637 }
4638 logger.Warnw(subCtx, "connection-to-child-adapter-not-ready", log.Fields{"error": err, "child-endpoint": endpoint})
4639 // Backoff
4640 if err = backoff.Backoff(subCtx); err != nil {
4641 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "child-endpoint": endpoint})
4642 break
4643 }
4644 }
4645 return nil
4646}
4647
khenaidoodc2116e2021-10-19 17:33:19 -04004648func (dh *DeviceHandler) getChildAdapterServiceClient(endpoint string) (onu_inter_adapter_service.OnuInterAdapterServiceClient, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04004649 // First check from cache
4650 dh.lockChildAdapterClients.RLock()
4651 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4652 dh.lockChildAdapterClients.RUnlock()
4653 return cgClient.GetOnuInterAdapterServiceClient()
4654 }
4655 dh.lockChildAdapterClients.RUnlock()
4656
4657 // Set the child connection - can occur on restarts
4658 ctx, cancel := context.WithTimeout(context.Background(), dh.cfg.RPCTimeout)
4659 err := dh.setupChildInterAdapterClient(ctx, endpoint)
4660 cancel()
4661 if err != nil {
4662 return nil, err
4663 }
4664
4665 // Get the child client now
4666 dh.lockChildAdapterClients.RLock()
4667 defer dh.lockChildAdapterClients.RUnlock()
4668 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
4669 return cgClient.GetOnuInterAdapterServiceClient()
4670 }
4671 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
4672}
4673
4674func (dh *DeviceHandler) deleteAdapterClients(ctx context.Context) {
4675 dh.lockChildAdapterClients.Lock()
4676 defer dh.lockChildAdapterClients.Unlock()
4677 for key, client := range dh.childAdapterClients {
4678 client.Stop(ctx)
4679 delete(dh.childAdapterClients, key)
4680 }
4681}
4682
khenaidooefff76e2021-12-15 16:51:30 -05004683// TODO: Any action the adapter needs to do following a onu adapter inter adapter service restart?
4684func (dh *DeviceHandler) onuInterAdapterRestarted(ctx context.Context, endPoint string) error {
4685 logger.Warnw(ctx, "onu-inter-adapter-service-reconnected", log.Fields{"endpoint": endPoint})
khenaidoo106c61a2021-08-11 18:05:46 -04004686 return nil
4687}
4688
khenaidooefff76e2021-12-15 16:51:30 -05004689// getOnuInterAdapterServiceClientHandler is used to setup the remote gRPC service
4690func (dh *DeviceHandler) getOnuInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
4691 if conn == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04004692 return nil
4693 }
khenaidooefff76e2021-12-15 16:51:30 -05004694 return onu_inter_adapter_service.NewOnuInterAdapterServiceClient(conn)
khenaidoo106c61a2021-08-11 18:05:46 -04004695}
Girish Gowdra950326e2021-11-05 12:43:24 -07004696
4697func (dh *DeviceHandler) setDeviceDeletionInProgressFlag(flag bool) {
4698 dh.lockDevice.Lock()
4699 defer dh.lockDevice.Unlock()
4700 dh.isDeviceDeletionInProgress = flag
4701}
4702
4703func (dh *DeviceHandler) getDeviceDeletionInProgressFlag() bool {
4704 dh.lockDevice.RLock()
4705 defer dh.lockDevice.RUnlock()
4706 return dh.isDeviceDeletionInProgress
4707}
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08004708
4709// waitForTimeoutOrCompletion waits for the waitgroup for the specified max timeout.
4710// Returns false if waiting timed out.
4711func (dh *DeviceHandler) waitForTimeoutOrCompletion(wg *sync.WaitGroup, timeout time.Duration) bool {
4712 c := make(chan struct{})
4713 go func() {
4714 defer close(c)
4715 wg.Wait()
4716 }()
4717 select {
4718 case <-c:
4719 return true // completed normally
4720 case <-time.After(timeout):
4721 return false // timed out
4722 }
4723}
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05304724
4725func (dh *DeviceHandler) updateHeartbeatSignature(ctx context.Context, signature uint32) {
4726 val, err := json.Marshal(signature)
4727 if err != nil {
4728 logger.Error(ctx, "failed-to-marshal")
4729 return
4730 }
4731 if err = dh.kvStore.Put(ctx, heartbeatPath, val); err != nil {
4732 logger.Error(ctx, "failed-to-store-hearbeat-signature")
4733 }
4734}
4735
4736func (dh *DeviceHandler) getHeartbeatSignature(ctx context.Context) uint32 {
4737 var signature uint32
4738
4739 Value, er := dh.kvStore.Get(ctx, heartbeatPath)
4740 if er == nil {
4741 if Value != nil {
4742 Val, er := kvstore.ToByte(Value.Value)
4743 if er != nil {
4744 logger.Errorw(ctx, "Failed to convert into byte array", log.Fields{"err": er})
4745 return signature
4746 }
4747 if er = json.Unmarshal(Val, &signature); er != nil {
4748 logger.Error(ctx, "Failed to unmarshal signature", log.Fields{"err": er})
4749 return signature
4750 }
4751 }
4752 }
4753 return signature
4754}
Akash Reddy Kankanala78b627f2026-01-12 08:18:21 +00004755
4756func (dh *DeviceHandler) UpdateDevice(ctx context.Context, updateDevice *voltha.UpdateDevice) {
4757 var dhCtx context.Context
4758 logger.Debug(ctx, "UpdateDevice called", log.Fields{"deviceConfig": updateDevice})
4759 dh.lockDevice.Lock()
4760 if dh.transitionHandlerCancel != nil {
4761 dh.transitionHandlerCancel() //if the previous device transition was grpc blocked on old IP,this make that handler return/exit.
4762 dh.transitionHandlerCancel = nil
4763 }
4764 err := updateDeviceAddress(dh.device, updateDevice) //update the device handler with the new device which would have newIP
4765 if err != nil {
4766 dh.lockDevice.Unlock()
4767 logger.Errorw(ctx, "failed-to-update-device-address", log.Fields{"error": err})
4768 return
4769 }
4770 connectStatus := dh.device.ConnectStatus
4771 dhCtx, dh.transitionHandlerCancel = context.WithCancel(context.Background())
4772 dh.lockDevice.Unlock()
4773 if connectStatus == voltha.ConnectStatus_REACHABLE {
4774 dh.updateStateUnreachable(dhCtx)
4775 } else {
4776 dh.transitionMap.Handle(dhCtx, DeviceInit)
4777 }
4778}
4779
4780func updateDeviceAddress(device *voltha.Device, deviceConfig *voltha.UpdateDevice) error {
4781 switch addr := deviceConfig.Address.(type) {
4782 case *voltha.UpdateDevice_Ipv4Address:
4783 if current, ok := device.Address.(*voltha.Device_Ipv4Address); ok {
4784 if current.Ipv4Address == addr.Ipv4Address {
4785 return fmt.Errorf("no-change-in-IPV4-device-address")
4786 }
4787 device.Address = &voltha.Device_Ipv4Address{Ipv4Address: addr.Ipv4Address}
4788 }
4789 case *voltha.UpdateDevice_Ipv6Address:
4790 if current, ok := device.Address.(*voltha.Device_Ipv6Address); ok {
4791 if current.Ipv6Address == addr.Ipv6Address {
4792 return fmt.Errorf("no-change-in-IPV6-device-address")
4793 }
4794 device.Address = &voltha.Device_Ipv6Address{Ipv6Address: addr.Ipv6Address}
4795 }
4796 case *voltha.UpdateDevice_HostAndPort:
4797 if current, ok := device.Address.(*voltha.Device_HostAndPort); ok {
4798 if current.HostAndPort == addr.HostAndPort {
4799 return fmt.Errorf("no-change-in-HostAndPort-device-address")
4800 }
4801 device.Address = &voltha.Device_HostAndPort{HostAndPort: addr.HostAndPort}
4802 }
4803 default:
4804 return fmt.Errorf("invalid-device-config-address-type")
4805 }
4806 return nil
4807}