blob: 773036bd04b0ccc19bb1183e9eaee1cbfb4ee954 [file] [log] [blame]
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Girish Gowdru6a80bbd2019-07-02 07:36:09 -070016
Scott Bakerdbd960e2020-02-28 08:57:51 -080017//Package core provides the utility for olt devices, flows and statistics
18package core
Phaneendra Manda4c62c802019-03-06 21:37:49 +053019
20import (
cuilin20187b2a8c32019-03-26 19:52:28 -070021 "context"
Matt Jeanneretceea2e02020-03-27 14:19:57 -040022 "encoding/binary"
Matt Jeanneret1359c732019-08-01 21:40:02 -040023 "encoding/hex"
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053024 "encoding/json"
Girish Gowdra491a9c62021-01-06 16:43:07 -080025 "errors"
cuilin20187b2a8c32019-03-26 19:52:28 -070026 "fmt"
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -040027 "net"
cuilin20187b2a8c32019-03-26 19:52:28 -070028 "strconv"
29 "strings"
30 "sync"
31 "time"
Phaneendra Manda4c62c802019-03-06 21:37:49 +053032
Elia Battiston599d25f2022-02-16 14:49:08 +010033 "github.com/opencord/voltha-lib-go/v7/pkg/db"
34 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
35
khenaidoo106c61a2021-08-11 18:05:46 -040036 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
khenaidoo106c61a2021-08-11 18:05:46 -040037
Matteo Scandolo945e4012019-12-12 14:16:11 -080038 "github.com/cenkalti/backoff/v3"
cuilin20187b2a8c32019-03-26 19:52:28 -070039 "github.com/gogo/protobuf/proto"
Girish Kumar93e91742020-07-27 16:43:19 +000040 grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
41 grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
khenaidoo106c61a2021-08-11 18:05:46 -040042 "github.com/opencord/voltha-lib-go/v7/pkg/config"
43 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
44 flow_utils "github.com/opencord/voltha-lib-go/v7/pkg/flows"
45 "github.com/opencord/voltha-lib-go/v7/pkg/log"
Mahir Gunyel85f61c12021-10-06 11:53:45 -070046 plt "github.com/opencord/voltha-lib-go/v7/pkg/platform"
khenaidoo106c61a2021-08-11 18:05:46 -040047 "github.com/opencord/voltha-lib-go/v7/pkg/pmmetrics"
Matteo Scandolodfa7a972020-11-06 13:03:40 -080048
khenaidoo106c61a2021-08-11 18:05:46 -040049 conf "github.com/opencord/voltha-openolt-adapter/internal/pkg/config"
Thomas Lee S94109f12020-03-03 16:39:29 +053050 "github.com/opencord/voltha-openolt-adapter/internal/pkg/olterrors"
Scott Bakerdbd960e2020-02-28 08:57:51 -080051 rsrcMgr "github.com/opencord/voltha-openolt-adapter/internal/pkg/resourcemanager"
khenaidoo106c61a2021-08-11 18:05:46 -040052 "github.com/opencord/voltha-protos/v5/go/common"
khenaidoodc2116e2021-10-19 17:33:19 -040053 ca "github.com/opencord/voltha-protos/v5/go/core_adapter"
khenaidoo106c61a2021-08-11 18:05:46 -040054 "github.com/opencord/voltha-protos/v5/go/extension"
khenaidoodc2116e2021-10-19 17:33:19 -040055 ia "github.com/opencord/voltha-protos/v5/go/inter_adapter"
56 "github.com/opencord/voltha-protos/v5/go/onu_inter_adapter_service"
khenaidoo106c61a2021-08-11 18:05:46 -040057 of "github.com/opencord/voltha-protos/v5/go/openflow_13"
58 oop "github.com/opencord/voltha-protos/v5/go/openolt"
59 "github.com/opencord/voltha-protos/v5/go/voltha"
cuilin20187b2a8c32019-03-26 19:52:28 -070060 "google.golang.org/grpc"
Devmalya Paula1efa642020-04-20 01:36:43 -040061 "google.golang.org/grpc/codes"
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -040062 "google.golang.org/grpc/status"
Phaneendra Manda4c62c802019-03-06 21:37:49 +053063)
64
salmansiddiqui7ac62132019-08-22 03:58:50 +000065// Constants for number of retries and for timeout
Manikkaraj kb1d51442019-07-23 10:41:02 -040066const (
Girish Gowdra491a9c62021-01-06 16:43:07 -080067 InvalidPort = 0xffffffff
68 MaxNumOfGroupHandlerChannels = 256
69
70 McastFlowOrGroupAdd = "McastFlowOrGroupAdd"
71 McastFlowOrGroupModify = "McastFlowOrGroupModify"
72 McastFlowOrGroupRemove = "McastFlowOrGroupRemove"
kesavand62126212021-01-12 04:56:06 -050073 oltPortInfoTimeout = 3
Elia Battiston596406d2022-02-02 12:19:00 +010074
75 defaultPortSpeedMbps = 1000
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053076 heartbeatPath = "heartbeat"
Manikkaraj kb1d51442019-07-23 10:41:02 -040077)
78
Phaneendra Manda4c62c802019-03-06 21:37:49 +053079//DeviceHandler will interact with the OLT device.
80type DeviceHandler struct {
khenaidoo106c61a2021-08-11 18:05:46 -040081 cm *config.ConfigManager
82 device *voltha.Device
83 cfg *conf.AdapterFlags
84 coreClient *vgrpc.Client
85 childAdapterClients map[string]*vgrpc.Client
86 lockChildAdapterClients sync.RWMutex
87 EventProxy eventif.EventProxy
88 openOLT *OpenOLT
khenaidooefff76e2021-12-15 16:51:30 -050089 exitChannel chan struct{}
khenaidoo106c61a2021-08-11 18:05:46 -040090 lockDevice sync.RWMutex
91 Client oop.OpenoltClient
92 transitionMap *TransitionMap
93 clientCon *grpc.ClientConn
94 flowMgr []*OpenOltFlowMgr
95 groupMgr *OpenOltGroupMgr
96 eventMgr *OpenOltEventMgr
97 resourceMgr []*rsrcMgr.OpenOltResourceMgr
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +053098 kvStore *db.Backend // backend kv store connection handle
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -070099
100 deviceInfo *oop.DeviceInfo
Naga Manjunatha8dc9372019-10-31 23:01:18 +0530101
Matteo Scandolo7eaec532022-06-23 15:54:57 -0700102 // discOnus (map[onuSn]bool) contains a list of ONUs that have been discovered, indexed by ONU SerialNumber.
103 // if the value is true that means the OnuDiscovery indication
104 // is currently being processed and thus we can ignore concurrent requests
105 // if it's false it means the processing has completed and we shouldn't be receiving a new indication
106 // if we do it means something went wrong and we need to retry
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700107 discOnus sync.Map
108 onus sync.Map
109 portStats *OpenOltStatisticsMgr
110 metrics *pmmetrics.PmMetrics
111 stopCollector chan bool
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000112 isCollectorActive bool
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700113 stopHeartbeatCheck chan bool
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000114 isHeartbeatCheckActive bool
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700115 activePorts sync.Map
116 stopIndications chan bool
117 isReadIndicationRoutineActive bool
Girish Gowdracefae192020-03-19 18:14:10 -0700118
Mahir Gunyelb0046752021-02-26 13:51:05 -0800119 totalPonPorts uint32
120 perPonOnuIndicationChannel map[uint32]onuIndicationChannels
121 perPonOnuIndicationChannelLock sync.Mutex
Girish Gowdra491a9c62021-01-06 16:43:07 -0800122
123 // Slice of channels. Each channel in slice, index by (mcast-group-id modulo MaxNumOfGroupHandlerChannels)
124 // 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 -0700125 incomingMcastFlowOrGroup []chan McastFlowOrGroupControlBlock
126 stopMcastHandlerRoutine []chan bool
127 mcastHandlerRoutineActive []bool
Gamze Abakac2c32a62021-03-11 11:44:18 +0000128
129 adapterPreviouslyConnected bool
130 agentPreviouslyConnected bool
Girish Gowdra950326e2021-11-05 12:43:24 -0700131
132 isDeviceDeletionInProgress bool
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530133 heartbeatSignature uint32
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700134}
135
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700136//OnuDevice represents ONU related info
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700137type OnuDevice struct {
khenaidoo106c61a2021-08-11 18:05:46 -0400138 deviceID string
139 deviceType string
140 serialNumber string
141 onuID uint32
142 intfID uint32
143 proxyDeviceID string
144 losRaised bool
145 rdiRaised bool
146 adapterEndpoint string
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700147}
148
Mahir Gunyelb0046752021-02-26 13:51:05 -0800149type onuIndicationMsg struct {
150 ctx context.Context
151 indication *oop.Indication
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800152}
153
154type onuIndicationChannels struct {
Mahir Gunyelb0046752021-02-26 13:51:05 -0800155 indicationChannel chan onuIndicationMsg
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800156 stopChannel chan struct{}
157}
158
Girish Gowdra491a9c62021-01-06 16:43:07 -0800159//McastFlowOrGroupControlBlock is created per mcast flow/group add/modify/remove and pushed on the incomingMcastFlowOrGroup channel slice
160//The McastFlowOrGroupControlBlock is then picked by the mcastFlowOrGroupChannelHandlerRoutine for further processing.
161//There are MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine routines which monitor for any incoming mcast flow/group messages
162//and process them serially. The mcast flow/group are assigned these routines based on formula (group-id modulo MaxNumOfGroupHandlerChannels)
163type McastFlowOrGroupControlBlock struct {
khenaidoodc2116e2021-10-19 17:33:19 -0400164 ctx context.Context // Flow/group handler context
165 flowOrGroupAction string // one of McastFlowOrGroupAdd, McastFlowOrGroupModify or McastFlowOrGroupDelete
166 flow *of.OfpFlowStats // Flow message (can be nil or valid flow)
167 group *of.OfpGroupEntry // Group message (can be nil or valid group)
168 errChan *chan error // channel to report the mcast Flow/group handling error
Girish Gowdra491a9c62021-01-06 16:43:07 -0800169}
170
Naga Manjunath7615e552019-10-11 22:35:47 +0530171var pmNames = []string{
172 "rx_bytes",
173 "rx_packets",
174 "rx_mcast_packets",
175 "rx_bcast_packets",
176 "tx_bytes",
177 "tx_packets",
178 "tx_mcast_packets",
179 "tx_bcast_packets",
180}
181
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700182//NewOnuDevice creates a new Onu Device
khenaidoo106c61a2021-08-11 18:05:46 -0400183func NewOnuDevice(devID, deviceTp, serialNum string, onuID, intfID uint32, proxyDevID string, losRaised bool, adapterEndpoint string) *OnuDevice {
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700184 var device OnuDevice
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700185 device.deviceID = devID
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700186 device.deviceType = deviceTp
187 device.serialNumber = serialNum
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700188 device.onuID = onuID
189 device.intfID = intfID
190 device.proxyDeviceID = proxyDevID
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +0530191 device.losRaised = losRaised
khenaidoo106c61a2021-08-11 18:05:46 -0400192 device.adapterEndpoint = adapterEndpoint
Mahir Gunyela3f9add2019-06-06 15:13:19 -0700193 return &device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530194}
195
196//NewDeviceHandler creates a new device handler
khenaidoo106c61a2021-08-11 18:05:46 -0400197func 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 -0700198 var dh DeviceHandler
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530199 ctx := context.Background()
Matteo Scandolodfa7a972020-11-06 13:03:40 -0800200 dh.cm = cm
khenaidoo106c61a2021-08-11 18:05:46 -0400201 dh.coreClient = cc
Devmalya Paulfb990a52019-07-09 10:01:49 -0400202 dh.EventProxy = ep
cuilin20187b2a8c32019-03-26 19:52:28 -0700203 cloned := (proto.Clone(device)).(*voltha.Device)
cuilin20187b2a8c32019-03-26 19:52:28 -0700204 dh.device = cloned
205 dh.openOLT = adapter
khenaidooefff76e2021-12-15 16:51:30 -0500206 dh.exitChannel = make(chan struct{})
cuilin20187b2a8c32019-03-26 19:52:28 -0700207 dh.lockDevice = sync.RWMutex{}
Holger Hildebrandte6c877b2022-09-15 13:51:39 +0000208 dh.stopCollector = make(chan bool, 1) // TODO: Why buffered?
209 dh.stopHeartbeatCheck = make(chan bool, 1) // TODO: Why buffered?
Naga Manjunath7615e552019-10-11 22:35:47 +0530210 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 -0500211 dh.activePorts = sync.Map{}
Girish Gowdraae56c722021-11-22 14:31:11 -0800212 dh.stopIndications = make(chan bool, 1) // TODO: Why buffered?
Mahir Gunyelb0046752021-02-26 13:51:05 -0800213 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
khenaidoo106c61a2021-08-11 18:05:46 -0400214 dh.childAdapterClients = make(map[string]*vgrpc.Client)
215 dh.cfg = cfg
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530216 kvStoreDevicePath := fmt.Sprintf(dh.cm.Backend.PathPrefix, "/%s/", dh.device.Id)
217 dh.kvStore = SetKVClient(ctx, dh.openOLT.KVStoreType, dh.openOLT.KVStoreAddress, dh.device.Id, kvStoreDevicePath)
218 if dh.kvStore == nil {
219 logger.Error(ctx, "Failed to setup KV store")
220 return nil
221 }
222
Girish Gowdra491a9c62021-01-06 16:43:07 -0800223 // Create a slice of buffered channels for handling concurrent mcast flow/group.
224 dh.incomingMcastFlowOrGroup = make([]chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700225 dh.stopMcastHandlerRoutine = make([]chan bool, MaxNumOfGroupHandlerChannels)
226 dh.mcastHandlerRoutineActive = make([]bool, MaxNumOfGroupHandlerChannels)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800227 for i := range dh.incomingMcastFlowOrGroup {
228 dh.incomingMcastFlowOrGroup[i] = make(chan McastFlowOrGroupControlBlock, MaxNumOfGroupHandlerChannels)
Girish Gowdraae56c722021-11-22 14:31:11 -0800229 dh.stopMcastHandlerRoutine[i] = make(chan bool)
Girish Gowdra491a9c62021-01-06 16:43:07 -0800230 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
231 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
232 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
233 // for incoming mcast flow/group to be processed serially.
Girish Gowdra4736e5c2021-08-25 15:19:10 -0700234 dh.mcastHandlerRoutineActive[i] = true
235 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
Girish Gowdra491a9c62021-01-06 16:43:07 -0800236 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700237 //TODO initialize the support classes.
238 return &dh
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530239}
240
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530241func newKVClient(ctx context.Context, storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
242 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
243 switch storeType {
244 case "etcd":
245 return kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)
246 }
247 return nil, errors.New("unsupported-kv-store")
248}
249
250// SetKVClient sets the KV client and return a kv backend
251func SetKVClient(ctx context.Context, backend string, addr string, DeviceID string, basePathKvStore string) *db.Backend {
252 kvClient, err := newKVClient(ctx, backend, addr, rsrcMgr.KvstoreTimeout)
253 if err != nil {
254 logger.Fatalw(ctx, "Failed to init KV client\n", log.Fields{"err": err})
255 return nil
256 }
257
258 kvbackend := &db.Backend{
259 Client: kvClient,
260 StoreType: backend,
261 Address: addr,
262 Timeout: rsrcMgr.KvstoreTimeout,
263 PathPrefix: fmt.Sprintf(rsrcMgr.BasePathKvStore, basePathKvStore, DeviceID)}
264
265 return kvbackend
266}
267
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530268// start save the device to the data model
269func (dh *DeviceHandler) start(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700270 dh.lockDevice.Lock()
271 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000272 logger.Debugw(ctx, "starting-device-agent", log.Fields{"device": dh.device})
cuilin20187b2a8c32019-03-26 19:52:28 -0700273 // Add the initial device to the local model
Neha Sharma96b7bf22020-06-15 10:37:32 +0000274 logger.Debug(ctx, "device-agent-started")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530275}
276
khenaidooefff76e2021-12-15 16:51:30 -0500277// Stop stops the device handler
278func (dh *DeviceHandler) Stop(ctx context.Context) {
cuilin20187b2a8c32019-03-26 19:52:28 -0700279 dh.lockDevice.Lock()
280 defer dh.lockDevice.Unlock()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000281 logger.Debug(ctx, "stopping-device-agent")
khenaidooefff76e2021-12-15 16:51:30 -0500282 close(dh.exitChannel)
khenaidoo106c61a2021-08-11 18:05:46 -0400283
khenaidooefff76e2021-12-15 16:51:30 -0500284 // Delete (which will stop also) all grpc connections to the child adapters
285 dh.deleteAdapterClients(ctx)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000286 logger.Debug(ctx, "device-agent-stopped")
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530287}
288
ssiddiqui04386ee2021-08-23 21:58:25 +0530289func (dh *DeviceHandler) getPonTechnology(intfID uint32) string {
290 for _, resourceRanges := range dh.deviceInfo.GetRanges() {
291 for _, pooledIntfID := range resourceRanges.GetIntfIds() {
292 if pooledIntfID == intfID {
293 return resourceRanges.GetTechnology()
294 }
295 }
296 }
297 return ""
298}
299
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400300func macifyIP(ip net.IP) string {
301 if len(ip) > 0 {
302 oct1 := strconv.FormatInt(int64(ip[12]), 16)
303 oct2 := strconv.FormatInt(int64(ip[13]), 16)
304 oct3 := strconv.FormatInt(int64(ip[14]), 16)
305 oct4 := strconv.FormatInt(int64(ip[15]), 16)
306 return fmt.Sprintf("00:00:%02v:%02v:%02v:%02v", oct1, oct2, oct3, oct4)
307 }
308 return ""
309}
310
Neha Sharma96b7bf22020-06-15 10:37:32 +0000311func generateMacFromHost(ctx context.Context, host string) (string, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400312 var genmac string
313 var addr net.IP
314 var ips []string
315 var err error
316
Neha Sharma96b7bf22020-06-15 10:37:32 +0000317 logger.Debugw(ctx, "generating-mac-from-host", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400318
319 if addr = net.ParseIP(host); addr == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000320 logger.Debugw(ctx, "looking-up-hostname", log.Fields{"host": host})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400321
322 if ips, err = net.LookupHost(host); err == nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000323 logger.Debugw(ctx, "dns-result-ips", log.Fields{"ips": ips})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400324 if addr = net.ParseIP(ips[0]); addr == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000325 return "", olterrors.NewErrInvalidValue(log.Fields{"ip": ips[0]}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400326 }
327 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000328 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530329 log.Fields{"host": ips[0],
330 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400331 return genmac, nil
332 }
Girish Kumarf26e4882020-03-05 06:49:10 +0000333 return "", olterrors.NewErrAdapter("cannot-resolve-hostname-to-ip", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400334 }
335
336 genmac = macifyIP(addr)
Neha Sharma96b7bf22020-06-15 10:37:32 +0000337 logger.Debugw(ctx, "using-ip-as-mac",
Shrey Baid807a2a02020-04-09 12:52:45 +0530338 log.Fields{"host": host,
339 "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -0400340 return genmac, nil
341}
342
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530343func macAddressToUint32Array(mac string) []uint32 {
cuilin20187b2a8c32019-03-26 19:52:28 -0700344 slist := strings.Split(mac, ":")
345 result := make([]uint32, len(slist))
346 var err error
347 var tmp int64
348 for index, val := range slist {
349 if tmp, err = strconv.ParseInt(val, 16, 32); err != nil {
350 return []uint32{1, 2, 3, 4, 5, 6}
351 }
352 result[index] = uint32(tmp)
353 }
354 return result
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530355}
356
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700357//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 -0800358func GetportLabel(portNum uint32, portType voltha.Port_PortType) (string, error) {
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530359
David K. Bainbridge794735f2020-02-11 21:01:37 -0800360 switch portType {
361 case voltha.Port_ETHERNET_NNI:
362 return fmt.Sprintf("nni-%d", portNum), nil
363 case voltha.Port_PON_OLT:
364 return fmt.Sprintf("pon-%d", portNum), nil
cuilin20187b2a8c32019-03-26 19:52:28 -0700365 }
David K. Bainbridge794735f2020-02-11 21:01:37 -0800366
Girish Kumarf26e4882020-03-05 06:49:10 +0000367 return "", olterrors.NewErrInvalidValue(log.Fields{"port-type": portType}, nil)
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530368}
369
Elia Battiston596406d2022-02-02 12:19:00 +0100370func makeOfpPort(macAddress string, speedMbps uint32) *of.OfpPort {
371 if speedMbps == 0 {
372 //In case it was not set in the indication
373 //and no other value was provided
374 speedMbps = defaultPortSpeedMbps
375 }
376
377 ofpPortSpeed := of.OfpPortFeatures_OFPPF_OTHER
378 switch speedMbps {
379 case 1000000:
380 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1TB_FD
381 case 100000:
382 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100GB_FD
383 case 40000:
384 ofpPortSpeed = of.OfpPortFeatures_OFPPF_40GB_FD
385 case 10000:
386 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10GB_FD
387 case 1000:
388 ofpPortSpeed = of.OfpPortFeatures_OFPPF_1GB_FD
389 case 100:
390 ofpPortSpeed = of.OfpPortFeatures_OFPPF_100MB_FD
391 case 10:
392 ofpPortSpeed = of.OfpPortFeatures_OFPPF_10MB_FD
393 }
394
395 capacity := uint32(ofpPortSpeed | of.OfpPortFeatures_OFPPF_FIBER)
396
397 port := &of.OfpPort{
398 HwAddr: macAddressToUint32Array(macAddress),
399 Config: 0,
400 State: uint32(of.OfpPortState_OFPPS_LIVE),
401 Curr: capacity,
402 Advertised: capacity,
403 Peer: capacity,
404 CurrSpeed: speedMbps * 1000, //kbps
405 MaxSpeed: speedMbps * 1000, //kbps
406 }
407
408 return port
409}
410
411func (dh *DeviceHandler) addPort(ctx context.Context, intfID uint32, portType voltha.Port_PortType, state string, speedMbps uint32) error {
Esin Karamanccb714b2019-11-29 15:02:06 +0000412 var operStatus common.OperStatus_Types
cuilin20187b2a8c32019-03-26 19:52:28 -0700413 if state == "up" {
414 operStatus = voltha.OperStatus_ACTIVE
kesavand39e0aa32020-01-28 20:58:50 -0500415 //populating the intfStatus map
Chaitrashree G Sef088112020-02-03 21:39:27 -0500416 dh.activePorts.Store(intfID, true)
cuilin20187b2a8c32019-03-26 19:52:28 -0700417 } else {
418 operStatus = voltha.OperStatus_DISCOVERED
Chaitrashree G Sef088112020-02-03 21:39:27 -0500419 dh.activePorts.Store(intfID, false)
cuilin20187b2a8c32019-03-26 19:52:28 -0700420 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -0700421 portNum := plt.IntfIDToPortNo(intfID, portType)
Chaitrashree G Sc0878ec2020-05-21 04:59:53 -0400422 label, err := GetportLabel(intfID, portType)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800423 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000424 return olterrors.NewErrNotFound("port-label", log.Fields{"port-number": portNum, "port-type": portType}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400425 }
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500426
khenaidoo106c61a2021-08-11 18:05:46 -0400427 // Check if port exists
khenaidoodc2116e2021-10-19 17:33:19 -0400428 port, err := dh.getPortFromCore(ctx, &ca.PortFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400429 DeviceId: dh.device.Id,
430 Port: portNum,
431 })
432 if err == nil && port.Type == portType {
Girish Kumara1ea2aa2020-08-19 18:14:22 +0000433 logger.Debug(ctx, "port-already-exists-updating-oper-status-of-port")
khenaidoodc2116e2021-10-19 17:33:19 -0400434 err = dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -0400435 DeviceId: dh.device.Id,
436 PortType: portType,
437 PortNo: portNum,
438 OperStatus: operStatus})
439 if err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400440 return olterrors.NewErrAdapter("failed-to-update-port-state", log.Fields{
441 "device-id": dh.device.Id,
442 "port-type": portType,
443 "port-number": portNum,
444 "oper-status": operStatus}, err).Log()
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500445 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400446 return nil
Chaitrashree G Sded0a832020-01-09 20:21:48 -0500447 }
khenaidoo106c61a2021-08-11 18:05:46 -0400448
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400449 // Now create Port
khenaidoo106c61a2021-08-11 18:05:46 -0400450 port = &voltha.Port{
451 DeviceId: dh.device.Id,
cuilin20187b2a8c32019-03-26 19:52:28 -0700452 PortNo: portNum,
453 Label: label,
454 Type: portType,
455 OperStatus: operStatus,
Elia Battiston596406d2022-02-02 12:19:00 +0100456 OfpPort: makeOfpPort(dh.device.MacAddress, speedMbps),
cuilin20187b2a8c32019-03-26 19:52:28 -0700457 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000458 logger.Debugw(ctx, "sending-port-update-to-core", log.Fields{"port": port})
cuilin20187b2a8c32019-03-26 19:52:28 -0700459 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -0400460 err = dh.createPortInCore(ctx, port)
461 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000462 return olterrors.NewErrAdapter("error-creating-port", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -0800463 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +0000464 "port-type": portType}, err)
Girish Gowdru1110ef22019-06-24 11:17:59 -0400465 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000466 go dh.updateLocalDevice(ctx)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530467 return nil
468}
469
Kent Hagermane6ff1012020-07-14 15:07:53 -0400470func (dh *DeviceHandler) updateLocalDevice(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -0400471 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530472 if err != nil || device == nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400473 logger.Errorf(ctx, "device-not-found", log.Fields{"device-id": dh.device.Id}, err)
474 return
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530475 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800476 dh.lockDevice.Lock()
477 defer dh.lockDevice.Unlock()
Kishore Darapuaaf9c102020-05-04 13:06:57 +0530478 dh.device = device
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530479}
480
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700481// nolint: gocyclo
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530482// readIndications to read the indications from the OLT device
David K. Bainbridge794735f2020-02-11 21:01:37 -0800483func (dh *DeviceHandler) readIndications(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000484 defer logger.Debugw(ctx, "indications-ended", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700485 defer func() {
486 dh.lockDevice.Lock()
487 dh.isReadIndicationRoutineActive = false
488 dh.lockDevice.Unlock()
489 }()
Girish Gowdra3f974912020-03-23 20:35:18 -0700490 indications, err := dh.startOpenOltIndicationStream(ctx)
cuilin20187b2a8c32019-03-26 19:52:28 -0700491 if err != nil {
Girish Gowdra3f974912020-03-23 20:35:18 -0700492 return err
cuilin20187b2a8c32019-03-26 19:52:28 -0700493 }
Girish Gowdru5ba46c92019-04-25 05:00:05 -0400494
David Bainbridgef5879ca2019-12-13 21:17:54 +0000495 // Create an exponential backoff around re-enabling indications. The
496 // maximum elapsed time for the back off is set to 0 so that we will
497 // continue to retry. The max interval defaults to 1m, but is set
498 // here for code clarity
499 indicationBackoff := backoff.NewExponentialBackOff()
500 indicationBackoff.MaxElapsedTime = 0
501 indicationBackoff.MaxInterval = 1 * time.Minute
Girish Gowdra3f974912020-03-23 20:35:18 -0700502
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700503 dh.lockDevice.Lock()
504 dh.isReadIndicationRoutineActive = true
505 dh.lockDevice.Unlock()
506
Girish Gowdra3f974912020-03-23 20:35:18 -0700507Loop:
cuilin20187b2a8c32019-03-26 19:52:28 -0700508 for {
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400509 select {
510 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000511 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700512 break Loop
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400513 default:
514 indication, err := indications.Recv()
Elia Battiston599d25f2022-02-16 14:49:08 +0100515
516 select {
517 case <-indications.Context().Done():
518 if err != nil {
519 logger.Warnw(ctx, "error-during-enable-indications",
520 log.Fields{"err": err,
521 "device-id": dh.device.Id})
522 }
523
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400524 // Use an exponential back off to prevent getting into a tight loop
525 duration := indicationBackoff.NextBackOff()
Elia Battiston599d25f2022-02-16 14:49:08 +0100526 logger.Infow(ctx, "backing-off-enable-indication", log.Fields{
527 "device-id": dh.device.Id,
528 "duration": duration,
529 })
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400530 if duration == backoff.Stop {
531 // If we reach a maximum then warn and reset the backoff
532 // timer and keep attempting.
Elia Battiston599d25f2022-02-16 14:49:08 +0100533 logger.Warnw(ctx, "maximum-indication-backoff-reached-resetting-backoff-timer",
Shrey Baid807a2a02020-04-09 12:52:45 +0530534 log.Fields{"max-indication-backoff": indicationBackoff.MaxElapsedTime,
Thomas Lee S985938d2020-05-04 11:40:41 +0530535 "device-id": dh.device.Id})
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400536 indicationBackoff.Reset()
537 }
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700538
539 // On failure process a backoff timer while watching for stopIndications
540 // events
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700541 backoffTimer := time.NewTimer(indicationBackoff.NextBackOff())
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700542 select {
543 case <-dh.stopIndications:
divyadesai3af43e12020-08-18 07:10:54 +0000544 logger.Debugw(ctx, "stopping-collecting-indications-for-olt", log.Fields{"device-id": dh.device.Id})
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700545 if !backoffTimer.Stop() {
546 <-backoffTimer.C
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700547 }
548 break Loop
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700549 case <-backoffTimer.C:
550 // backoffTimer expired continue
David Bainbridge95a3fcf2020-06-09 10:49:31 -0700551 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700552 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
553 return err
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400554 }
555 continue
Elia Battiston599d25f2022-02-16 14:49:08 +0100556 default:
557 if err != nil {
558 logger.Errorw(ctx, "read-indication-error",
Shrey Baid807a2a02020-04-09 12:52:45 +0530559 log.Fields{"err": err,
Thomas Lee S985938d2020-05-04 11:40:41 +0530560 "device-id": dh.device.Id})
Elia Battiston599d25f2022-02-16 14:49:08 +0100561 // Close the stream, and re-initialize it
562 if err = indications.CloseSend(); err != nil {
563 // Ok to ignore here, because we landed here due to a problem on the stream
564 // In all probability, the closeSend call may fail
565 logger.Debugw(ctx, "error-closing-send stream--error-ignored",
566 log.Fields{"err": err,
567 "device-id": dh.device.Id})
568 }
569 if indications, err = dh.startOpenOltIndicationStream(ctx); err != nil {
570 return err
571 }
572 // once we re-initialized the indication stream, continue to read indications
573 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700574 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100575 // Reset backoff if we have a successful receive
576 indicationBackoff.Reset()
577 // When OLT is admin down, ignore all indications.
578 if dh.device.AdminState == voltha.AdminState_DISABLED && !isIndicationAllowedDuringOltAdminDown(indication) {
579 logger.Debugw(ctx, "olt-is-admin-down, ignore indication",
580 log.Fields{"indication": indication,
581 "device-id": dh.device.Id})
582 continue
Girish Gowdra3f974912020-03-23 20:35:18 -0700583 }
Elia Battiston599d25f2022-02-16 14:49:08 +0100584 dh.handleIndication(ctx, indication)
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +0530585 }
cuilin20187b2a8c32019-03-26 19:52:28 -0700586 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700587 }
Girish Gowdra3f974912020-03-23 20:35:18 -0700588 // Close the send stream
589 _ = indications.CloseSend() // Ok to ignore error, as we stopping the readIndication anyway
Girish Gowdra3ab6d212020-03-24 17:33:15 -0700590
Girish Gowdra3f974912020-03-23 20:35:18 -0700591 return nil
592}
593
594func (dh *DeviceHandler) startOpenOltIndicationStream(ctx context.Context) (oop.Openolt_EnableIndicationClient, error) {
Girish Gowdra852ad912021-05-04 00:05:50 -0700595 logger.Infow(ctx, "enabling read indications", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700596 indications, err := dh.Client.EnableIndication(ctx, new(oop.Empty))
597 if err != nil {
598 return nil, olterrors.NewErrCommunication("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).Log()
599 }
600 if indications == nil {
601 return nil, olterrors.NewErrInvalidValue(log.Fields{"indications": nil, "device-id": dh.device.Id}, nil).Log()
602 }
Girish Gowdra852ad912021-05-04 00:05:50 -0700603 logger.Infow(ctx, "read indication started successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdra3f974912020-03-23 20:35:18 -0700604 return indications, nil
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400605}
606
607// isIndicationAllowedDuringOltAdminDown returns true if the indication is allowed during OLT Admin down, else false
608func isIndicationAllowedDuringOltAdminDown(indication *oop.Indication) bool {
609 switch indication.Data.(type) {
610 case *oop.Indication_OltInd, *oop.Indication_IntfInd, *oop.Indication_IntfOperInd:
611 return true
612
613 default:
614 return false
615 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700616}
617
David K. Bainbridge794735f2020-02-11 21:01:37 -0800618func (dh *DeviceHandler) handleOltIndication(ctx context.Context, oltIndication *oop.OltIndication) error {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700619 raisedTs := time.Now().Unix()
Gamze Abakaa1a50522019-10-03 19:28:27 +0000620 if oltIndication.OperState == "up" && dh.transitionMap.currentDeviceState != deviceStateUp {
npujarec5762e2020-01-01 14:08:48 +0530621 dh.transitionMap.Handle(ctx, DeviceUpInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700622 } else if oltIndication.OperState == "down" {
npujarec5762e2020-01-01 14:08:48 +0530623 dh.transitionMap.Handle(ctx, DeviceDownInd)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700624 }
Daniele Rossi051466a2019-07-26 13:39:37 +0000625 // Send or clear Alarm
Neha Sharma96b7bf22020-06-15 10:37:32 +0000626 if err := dh.eventMgr.oltUpDownIndication(ctx, oltIndication, dh.device.Id, raisedTs); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +0530627 return olterrors.NewErrAdapter("failed-indication", log.Fields{
divyadesai3af43e12020-08-18 07:10:54 +0000628 "device-id": dh.device.Id,
David K. Bainbridge794735f2020-02-11 21:01:37 -0800629 "indication": oltIndication,
Girish Kumarf26e4882020-03-05 06:49:10 +0000630 "timestamp": raisedTs}, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -0800631 }
632 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700633}
634
David K. Bainbridge794735f2020-02-11 21:01:37 -0800635// nolint: gocyclo
npujarec5762e2020-01-01 14:08:48 +0530636func (dh *DeviceHandler) handleIndication(ctx context.Context, indication *oop.Indication) {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700637 raisedTs := time.Now().Unix()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700638 switch indication.Data.(type) {
639 case *oop.Indication_OltInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000640 span, ctx := log.CreateChildSpan(ctx, "olt-indication", log.Fields{"device-id": dh.device.Id})
641 defer span.Finish()
Girish Gowdra852ad912021-05-04 00:05:50 -0700642 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 -0800643 if err := dh.handleOltIndication(ctx, indication.GetOltInd()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400644 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "olt", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800645 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700646 case *oop.Indication_IntfInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000647 span, ctx := log.CreateChildSpan(ctx, "interface-indication", log.Fields{"device-id": dh.device.Id})
648 defer span.Finish()
649
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700650 intfInd := indication.GetIntfInd()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800651 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100652 if err := dh.addPort(ctx, intfInd.GetIntfId(), voltha.Port_PON_OLT, intfInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400653 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "interface", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800654 }
655 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000656 logger.Infow(ctx, "received-interface-indication", log.Fields{"InterfaceInd": intfInd, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700657 case *oop.Indication_IntfOperInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000658 span, ctx := log.CreateChildSpan(ctx, "interface-oper-indication", log.Fields{"device-id": dh.device.Id})
659 defer span.Finish()
660
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700661 intfOperInd := indication.GetIntfOperInd()
662 if intfOperInd.GetType() == "nni" {
David K. Bainbridge794735f2020-02-11 21:01:37 -0800663 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100664 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_ETHERNET_NNI, intfOperInd.GetOperState(), intfOperInd.GetSpeed()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400665 _ = 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 -0800666 }
667 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700668 } else if intfOperInd.GetType() == "pon" {
669 // TODO: Check what needs to be handled here for When PON PORT down, ONU will be down
670 // Handle pon port update
David K. Bainbridge794735f2020-02-11 21:01:37 -0800671 go func() {
Elia Battiston596406d2022-02-02 12:19:00 +0100672 if err := dh.addPort(ctx, intfOperInd.GetIntfId(), voltha.Port_PON_OLT, intfOperInd.GetOperState(), defaultPortSpeedMbps); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400673 _ = 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 -0800674 }
675 }()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000676 go dh.eventMgr.oltIntfOperIndication(ctx, indication.GetIntfOperInd(), dh.device.Id, raisedTs)
cuilin20187b2a8c32019-03-26 19:52:28 -0700677 }
Neha Sharma96b7bf22020-06-15 10:37:32 +0000678 logger.Infow(ctx, "received-interface-oper-indication",
Shrey Baid807a2a02020-04-09 12:52:45 +0530679 log.Fields{"interfaceOperInd": intfOperInd,
Thomas Lee S985938d2020-05-04 11:40:41 +0530680 "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700681 case *oop.Indication_OnuDiscInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000682 span, ctx := log.CreateChildSpan(ctx, "onu-discovery-indication", log.Fields{"device-id": dh.device.Id})
683 defer span.Finish()
684
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700685 onuDiscInd := indication.GetOnuDiscInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000686 logger.Infow(ctx, "received-onu-discovery-indication", log.Fields{"OnuDiscInd": onuDiscInd, "device-id": dh.device.Id})
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800687 //put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800688 dh.putOnuIndicationToChannel(ctx, indication, onuDiscInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700689 case *oop.Indication_OnuInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000690 span, ctx := log.CreateChildSpan(ctx, "onu-indication", log.Fields{"device-id": dh.device.Id})
691 defer span.Finish()
692
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700693 onuInd := indication.GetOnuInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000694 logger.Infow(ctx, "received-onu-indication", log.Fields{"OnuInd": onuInd, "device-id": dh.device.Id})
Mahir Gunyel2fb81472020-12-16 23:18:34 -0800695 //put message to channel and return immediately
Mahir Gunyelb0046752021-02-26 13:51:05 -0800696 dh.putOnuIndicationToChannel(ctx, indication, onuInd.GetIntfId())
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700697 case *oop.Indication_OmciInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000698 span, ctx := log.CreateChildSpan(ctx, "omci-indication", log.Fields{"device-id": dh.device.Id})
699 defer span.Finish()
700
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700701 omciInd := indication.GetOmciInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000702 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 -0800703 go func() {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000704 if err := dh.omciIndication(ctx, omciInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400705 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "omci", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800706 }
707 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700708 case *oop.Indication_PktInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000709 span, ctx := log.CreateChildSpan(ctx, "packet-indication", log.Fields{"device-id": dh.device.Id})
710 defer span.Finish()
711
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700712 pktInd := indication.GetPktInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000713 logger.Debugw(ctx, "received-packet-indication", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700714 "intf-type": pktInd.IntfId,
715 "intf-id": pktInd.IntfId,
716 "gem-port-id": pktInd.GemportId,
717 "port-no": pktInd.PortNo,
718 "device-id": dh.device.Id,
719 })
720
721 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000722 logger.Debugw(ctx, "received-packet-indication-packet", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -0700723 "intf-type": pktInd.IntfId,
724 "intf-id": pktInd.IntfId,
725 "gem-port-id": pktInd.GemportId,
726 "port-no": pktInd.PortNo,
727 "packet": hex.EncodeToString(pktInd.Pkt),
728 "device-id": dh.device.Id,
729 })
730 }
731
David K. Bainbridge794735f2020-02-11 21:01:37 -0800732 go func() {
733 if err := dh.handlePacketIndication(ctx, pktInd); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400734 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{"type": "packet", "device-id": dh.device.Id}, err).Log()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800735 }
736 }()
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700737 case *oop.Indication_PortStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000738 span, ctx := log.CreateChildSpan(ctx, "port-statistics-indication", log.Fields{"device-id": dh.device.Id})
739 defer span.Finish()
740
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700741 portStats := indication.GetPortStats()
Girish Gowdra9602eb42020-09-09 15:50:39 -0700742 go dh.portStats.PortStatisticsIndication(ctx, portStats, dh.totalPonPorts)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700743 case *oop.Indication_FlowStats:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000744 span, ctx := log.CreateChildSpan(ctx, "flow-stats-indication", log.Fields{"device-id": dh.device.Id})
745 defer span.Finish()
746
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700747 flowStats := indication.GetFlowStats()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000748 logger.Infow(ctx, "received-flow-stats", log.Fields{"FlowStats": flowStats, "device-id": dh.device.Id})
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700749 case *oop.Indication_AlarmInd:
Neha Sharma8f4e4322020-08-06 10:51:53 +0000750 span, ctx := log.CreateChildSpan(ctx, "alarm-indication", log.Fields{"device-id": dh.device.Id})
751 defer span.Finish()
752
Girish Gowdru6a80bbd2019-07-02 07:36:09 -0700753 alarmInd := indication.GetAlarmInd()
Neha Sharma96b7bf22020-06-15 10:37:32 +0000754 logger.Infow(ctx, "received-alarm-indication", log.Fields{"AlarmInd": alarmInd, "device-id": dh.device.Id})
755 go dh.eventMgr.ProcessEvents(ctx, alarmInd, dh.device.Id, raisedTs)
cuilin20187b2a8c32019-03-26 19:52:28 -0700756 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530757}
758
759// doStateUp handle the olt up indication and update to voltha core
npujarec5762e2020-01-01 14:08:48 +0530760func (dh *DeviceHandler) doStateUp(ctx context.Context) error {
Thomas Lee S85f37312020-04-03 17:06:12 +0530761 //starting the stat collector
Neha Sharma96b7bf22020-06-15 10:37:32 +0000762 go startCollector(ctx, dh)
Thomas Lee S85f37312020-04-03 17:06:12 +0530763
Girish Gowdra618fa572021-09-01 17:19:29 -0700764 // instantiate the mcast handler routines.
765 for i := range dh.incomingMcastFlowOrGroup {
766 // We land inside the below "if" code path, after the OLT comes back from a reboot, otherwise the routines
767 // are already active when the DeviceHandler module is first instantiated (as part of Adopt_device RPC invocation).
768 if !dh.mcastHandlerRoutineActive[i] {
769 // Spin up a go routine to handling incoming mcast flow/group (add/modify/remove).
770 // There will be MaxNumOfGroupHandlerChannels number of mcastFlowOrGroupChannelHandlerRoutine go routines.
771 // These routines will be blocked on the dh.incomingMcastFlowOrGroup[mcast-group-id modulo MaxNumOfGroupHandlerChannels] channel
772 // for incoming mcast flow/group to be processed serially.
773 dh.mcastHandlerRoutineActive[i] = true
774 go dh.mcastFlowOrGroupChannelHandlerRoutine(i, dh.incomingMcastFlowOrGroup[i], dh.stopMcastHandlerRoutine[i])
775 }
776 }
777
Girish Gowdru0c588b22019-04-23 23:24:56 -0400778 // Synchronous call to update device state - this method is run in its own go routine
khenaidoodc2116e2021-10-19 17:33:19 -0400779 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400780 DeviceId: dh.device.Id,
781 OperStatus: voltha.OperStatus_ACTIVE,
782 ConnStatus: voltha.ConnectStatus_REACHABLE,
783 }); err != nil {
784 return olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400785 }
Gamze Abaka07868a52020-12-17 14:19:28 +0000786
787 //Clear olt communication failure event
788 dh.device.ConnectStatus = voltha.ConnectStatus_REACHABLE
789 dh.device.OperStatus = voltha.OperStatus_ACTIVE
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -0700790 raisedTs := time.Now().Unix()
Gamze Abaka07868a52020-12-17 14:19:28 +0000791 go dh.eventMgr.oltCommunicationEvent(ctx, dh.device, raisedTs)
792
Girish Gowdru0c588b22019-04-23 23:24:56 -0400793 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530794}
795
796// doStateDown handle the olt down indication
npujarec5762e2020-01-01 14:08:48 +0530797func (dh *DeviceHandler) doStateDown(ctx context.Context) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000798 logger.Debugw(ctx, "do-state-down-start", log.Fields{"device-id": dh.device.Id})
Girish Gowdrud4245152019-05-10 00:47:31 -0400799
khenaidoo106c61a2021-08-11 18:05:46 -0400800 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Girish Gowdrud4245152019-05-10 00:47:31 -0400801 if err != nil || device == nil {
802 /*TODO: needs to handle error scenarios */
Girish Kumarf26e4882020-03-05 06:49:10 +0000803 return olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -0400804 }
805
806 cloned := proto.Clone(device).(*voltha.Device)
Girish Gowdrud4245152019-05-10 00:47:31 -0400807
808 //Update the device oper state and connection status
809 cloned.OperStatus = voltha.OperStatus_UNKNOWN
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800810 dh.lockDevice.Lock()
Girish Gowdrud4245152019-05-10 00:47:31 -0400811 dh.device = cloned
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800812 dh.lockDevice.Unlock()
Girish Gowdrud4245152019-05-10 00:47:31 -0400813
khenaidoodc2116e2021-10-19 17:33:19 -0400814 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400815 DeviceId: cloned.Id,
816 OperStatus: cloned.OperStatus,
817 ConnStatus: cloned.ConnectStatus,
818 }); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000819 return olterrors.NewErrAdapter("state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -0400820 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400821
822 //get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -0400823 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400824 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +0000825 return olterrors.NewErrAdapter("child-device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400826 }
827 for _, onuDevice := range onuDevices.Items {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400828 // Update onu state as down in onu adapter
829 onuInd := oop.OnuIndication{}
830 onuInd.OperState = "down"
khenaidoo106c61a2021-08-11 18:05:46 -0400831
832 ogClient, err := dh.getChildAdapterServiceClient(onuDevice.AdapterEndpoint)
833 if err != nil {
834 return err
835 }
836 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
khenaidoodc2116e2021-10-19 17:33:19 -0400837 _, err = ogClient.OnuIndication(subCtx, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -0400838 DeviceId: onuDevice.Id,
839 OnuIndication: &onuInd,
840 })
841 cancel()
David K. Bainbridge794735f2020-02-11 21:01:37 -0800842 if err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -0400843 _ = olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -0400844 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -0800845 "onu-indicator": onuInd,
846 "device-type": onuDevice.Type,
847 "device-id": onuDevice.Id}, err).LogAt(log.ErrorLevel)
serkant.uluderya245caba2019-09-24 23:15:29 -0700848 //Do not return here and continue to process other ONUs
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800849 } else {
850 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 -0700851 }
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -0400852 }
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800853 dh.lockDevice.Lock()
serkant.uluderya245caba2019-09-24 23:15:29 -0700854 /* Discovered ONUs entries need to be cleared , since after OLT
855 is up, it starts sending discovery indications again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +0530856 dh.discOnus = sync.Map{}
Girish Gowdrabe811ff2021-01-26 17:12:12 -0800857 dh.lockDevice.Unlock()
858
Neha Sharma96b7bf22020-06-15 10:37:32 +0000859 logger.Debugw(ctx, "do-state-down-end", log.Fields{"device-id": device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -0700860 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530861}
862
863// doStateInit dial the grpc before going to init state
npujarec5762e2020-01-01 14:08:48 +0530864func (dh *DeviceHandler) doStateInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -0400865 var err error
Gamze Abaka49c40b32021-05-06 09:30:41 +0000866
867 // if the connection is already available, close the previous connection (olt reboot case)
868 if dh.clientCon != nil {
869 if err = dh.clientCon.Close(); err != nil {
870 logger.Errorw(ctx, "failed-to-close-previous-connection", log.Fields{"device-id": dh.device.Id})
871 } else {
872 logger.Debugw(ctx, "previous-grpc-channel-closed-successfully", log.Fields{"device-id": dh.device.Id})
873 }
874 }
875
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +0530876 logger.Debugw(ctx, "Dailing grpc", log.Fields{"device-id": dh.device.Id})
Gamze Abaka49c40b32021-05-06 09:30:41 +0000877 // Use Interceptors to automatically inject and publish Open Tracing Spans by this GRPC client
Girish Kumar93e91742020-07-27 16:43:19 +0000878 dh.clientCon, err = grpc.Dial(dh.device.GetHostAndPort(),
879 grpc.WithInsecure(),
880 grpc.WithBlock(),
881 grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(
Girish Kumar935f7af2020-08-18 11:59:42 +0000882 grpc_opentracing.StreamClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Girish Kumar93e91742020-07-27 16:43:19 +0000883 )),
884 grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
Girish Kumar935f7af2020-08-18 11:59:42 +0000885 grpc_opentracing.UnaryClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})),
Girish Kumar93e91742020-07-27 16:43:19 +0000886 )))
887
888 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +0530889 return olterrors.NewErrCommunication("dial-failure", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +0530890 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +0000891 "host-and-port": dh.device.GetHostAndPort()}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400892 }
893 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530894}
895
896// postInit create olt client instance to invoke RPC on the olt device
npujarec5762e2020-01-01 14:08:48 +0530897func (dh *DeviceHandler) postInit(ctx context.Context) error {
Girish Gowdru0c588b22019-04-23 23:24:56 -0400898 dh.Client = oop.NewOpenoltClient(dh.clientCon)
npujarec5762e2020-01-01 14:08:48 +0530899 dh.transitionMap.Handle(ctx, GrpcConnected)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400900 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530901}
902
903// doStateConnected get the device info and update to voltha core
npujarec5762e2020-01-01 14:08:48 +0530904func (dh *DeviceHandler) doStateConnected(ctx context.Context) error {
Thomas Lee S985938d2020-05-04 11:40:41 +0530905 var err error
Neha Sharma96b7bf22020-06-15 10:37:32 +0000906 logger.Debugw(ctx, "olt-device-connected", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400907
908 // Case where OLT is disabled and then rebooted.
khenaidoo106c61a2021-08-11 18:05:46 -0400909 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Thomas Lee S985938d2020-05-04 11:40:41 +0530910 if err != nil || device == nil {
911 /*TODO: needs to handle error scenarios */
912 return olterrors.NewErrAdapter("device-fetch-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
913 }
914 if device.AdminState == voltha.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000915 logger.Debugln(ctx, "do-state-connected--device-admin-state-down")
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400916
917 cloned := proto.Clone(device).(*voltha.Device)
918 cloned.ConnectStatus = voltha.ConnectStatus_REACHABLE
919 cloned.OperStatus = voltha.OperStatus_UNKNOWN
920 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -0400921
khenaidoodc2116e2021-10-19 17:33:19 -0400922 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -0400923 DeviceId: cloned.Id,
924 OperStatus: cloned.OperStatus,
925 ConnStatus: cloned.ConnectStatus,
926 }); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +0530927 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 -0400928 }
929
Chaitrashree G S44124192019-08-07 20:21:36 -0400930 // Since the device was disabled before the OLT was rebooted, enforce the OLT to be Disabled after re-connection.
npujarec5762e2020-01-01 14:08:48 +0530931 _, err = dh.Client.DisableOlt(ctx, new(oop.Empty))
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400932 if err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +0530933 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400934 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400935 // We should still go ahead an initialize various device handler modules so that when OLT is re-enabled, we have
936 // all the modules initialized and ready to handle incoming ONUs.
937
Thomas Lee S985938d2020-05-04 11:40:41 +0530938 err = dh.initializeDeviceHandlerModules(ctx)
939 if err != nil {
940 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 -0400941 }
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400942
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700943 go startHeartbeatCheck(ctx, dh)
944
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -0400945 return nil
946 }
947
khenaidoo106c61a2021-08-11 18:05:46 -0400948 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400949 if err != nil {
Girish Gowdrud4245152019-05-10 00:47:31 -0400950 /*TODO: needs to handle error scenarios */
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400951 return olterrors.NewErrAdapter("fetch-ports-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -0400952 }
khenaidoo106c61a2021-08-11 18:05:46 -0400953 dh.populateActivePorts(ctx, ports.Items)
954 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -0400955 return olterrors.NewErrAdapter("port-status-update-failed", log.Fields{"ports": ports}, err)
Girish Gowdrud4245152019-05-10 00:47:31 -0400956 }
957
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400958 if err := dh.initializeDeviceHandlerModules(ctx); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +0530959 return olterrors.NewErrAdapter("device-handler-initialization-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
Girish Gowdru0c588b22019-04-23 23:24:56 -0400960 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530961
Neha Sharma96b7bf22020-06-15 10:37:32 +0000962 go dh.updateLocalDevice(ctx)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +0000963
964 if device.PmConfigs != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +0000965 dh.UpdatePmConfig(ctx, device.PmConfigs)
Rohan Agrawalda5e0b22020-05-20 11:10:26 +0000966 }
Girish Gowdraa09aeab2020-09-14 16:30:52 -0700967
968 go startHeartbeatCheck(ctx, dh)
969
cuilin20187b2a8c32019-03-26 19:52:28 -0700970 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +0530971}
972
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400973func (dh *DeviceHandler) initializeDeviceHandlerModules(ctx context.Context) error {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700974 var err error
975 dh.deviceInfo, err = dh.populateDeviceInfo(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400976
977 if err != nil {
978 return olterrors.NewErrAdapter("populate-device-info-failed", log.Fields{"device-id": dh.device.Id}, err)
979 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700980 dh.totalPonPorts = dh.deviceInfo.GetPonPorts()
981 dh.agentPreviouslyConnected = dh.deviceInfo.PreviouslyConnected
yasin saplid0566272021-12-21 09:10:30 +0000982 // +1 is for NNI
983 dh.resourceMgr = make([]*rsrcMgr.OpenOltResourceMgr, dh.totalPonPorts+1)
984 dh.flowMgr = make([]*OpenOltFlowMgr, dh.totalPonPorts+1)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700985 var i uint32
yasin saplid0566272021-12-21 09:10:30 +0000986 // Index from 0 to until totalPonPorts ( Ex: 0 .. 15 ) -> PonPort Managers
987 // Index totalPonPorts ( Ex: 16 ) -> NniPort Manager
988 // There is only one NNI manager since multiple NNI is not supported for now
989 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700990 // Instantiate resource manager
991 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 -0700992 return olterrors.ErrResourceManagerInstantiating
993 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -0400994 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -0700995 // GroupManager instance is per OLT. But it needs a reference to any instance of resourceMgr to interface with
996 // the KV store to manage mcast group data. Provide the first instance (0th index)
997 if dh.groupMgr = NewGroupManager(ctx, dh, dh.resourceMgr[0]); dh.groupMgr == nil {
998 return olterrors.ErrGroupManagerInstantiating
999 }
yasin saplid0566272021-12-21 09:10:30 +00001000 for i = 0; i < dh.totalPonPorts+1; i++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001001 // Instantiate flow manager
1002 if dh.flowMgr[i] = NewFlowManager(ctx, dh, dh.resourceMgr[i], dh.groupMgr, i); dh.flowMgr[i] == nil {
1003 return olterrors.ErrFlowManagerInstantiating
1004 }
Girish Gowdra76a1b092021-07-28 10:07:04 -07001005 dh.resourceMgr[i].TechprofileRef = dh.flowMgr[i].techprofile
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001006 }
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001007 /* TODO: Instantiate Alarm , stats , BW managers */
1008 /* Instantiating Event Manager to handle Alarms and KPIs */
1009 dh.eventMgr = NewEventMgr(dh.EventProxy, dh)
1010
1011 // Stats config for new device
Neha Sharma96b7bf22020-06-15 10:37:32 +00001012 dh.portStats = NewOpenOltStatsMgr(ctx, dh)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04001013
1014 return nil
1015
1016}
1017
Neha Sharma96b7bf22020-06-15 10:37:32 +00001018func (dh *DeviceHandler) populateDeviceInfo(ctx context.Context) (*oop.DeviceInfo, error) {
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001019 var err error
1020 var deviceInfo *oop.DeviceInfo
1021
Neha Sharma8f4e4322020-08-06 10:51:53 +00001022 deviceInfo, err = dh.Client.GetDeviceInfo(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty))
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001023
1024 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001025 return nil, olterrors.NewErrPersistence("get", "device", 0, nil, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001026 }
1027 if deviceInfo == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001028 return nil, olterrors.NewErrInvalidValue(log.Fields{"device": nil}, nil)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001029 }
1030
Neha Sharma96b7bf22020-06-15 10:37:32 +00001031 logger.Debugw(ctx, "fetched-device-info", log.Fields{"deviceInfo": deviceInfo, "device-id": dh.device.Id})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001032 dh.device.Root = true
1033 dh.device.Vendor = deviceInfo.Vendor
1034 dh.device.Model = deviceInfo.Model
1035 dh.device.SerialNumber = deviceInfo.DeviceSerialNumber
1036 dh.device.HardwareVersion = deviceInfo.HardwareVersion
1037 dh.device.FirmwareVersion = deviceInfo.FirmwareVersion
1038
1039 if deviceInfo.DeviceId == "" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001040 logger.Warnw(ctx, "no-device-id-provided-using-host", log.Fields{"hostport": dh.device.GetHostAndPort()})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001041 host := strings.Split(dh.device.GetHostAndPort(), ":")[0]
Neha Sharma96b7bf22020-06-15 10:37:32 +00001042 genmac, err := generateMacFromHost(ctx, host)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001043 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001044 return nil, olterrors.NewErrAdapter("failed-to-generate-mac-host", log.Fields{"host": host}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001045 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001046 logger.Debugw(ctx, "using-host-for-mac-address", log.Fields{"host": host, "mac": genmac})
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001047 dh.device.MacAddress = genmac
1048 } else {
1049 dh.device.MacAddress = deviceInfo.DeviceId
1050 }
1051
1052 // Synchronous call to update device - this method is run in its own go routine
khenaidoo106c61a2021-08-11 18:05:46 -04001053 if err = dh.updateDeviceInCore(ctx, dh.device); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001054 return nil, olterrors.NewErrAdapter("device-update-failed", log.Fields{"device-id": dh.device.Id}, err)
Matt Jeanneretf4fdcd72019-07-19 20:03:23 -04001055 }
1056
1057 return deviceInfo, nil
1058}
1059
Neha Sharma96b7bf22020-06-15 10:37:32 +00001060func startCollector(ctx context.Context, dh *DeviceHandler) {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07001061 logger.Debugw(ctx, "starting-collector", log.Fields{"device-id": dh.device.Id})
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00001062
1063 defer func() {
1064 dh.lockDevice.Lock()
1065 dh.isCollectorActive = false
1066 dh.lockDevice.Unlock()
1067 }()
1068
1069 dh.lockDevice.Lock()
1070 dh.isCollectorActive = true
1071 dh.lockDevice.Unlock()
1072
Naga Manjunath7615e552019-10-11 22:35:47 +05301073 for {
1074 select {
1075 case <-dh.stopCollector:
divyadesai3af43e12020-08-18 07:10:54 +00001076 logger.Debugw(ctx, "stopping-collector-for-olt", log.Fields{"device-id": dh.device.Id})
Naga Manjunath7615e552019-10-11 22:35:47 +05301077 return
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001078 case <-time.After(time.Duration(dh.metrics.ToPmConfigs().DefaultFreq) * time.Second):
Girish Gowdra34815db2020-05-11 17:18:04 -07001079
khenaidoo106c61a2021-08-11 18:05:46 -04001080 ports, err := dh.listDevicePortsFromCore(ctx, dh.device.Id)
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001081 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001082 logger.Warnw(ctx, "failed-to-list-ports", log.Fields{"device-id": dh.device.Id, "err": err})
Kent Hagermanf1db18b2020-07-08 13:38:15 -04001083 continue
1084 }
khenaidoo106c61a2021-08-11 18:05:46 -04001085 for _, port := range ports.Items {
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301086 // NNI Stats
1087 if port.Type == voltha.Port_ETHERNET_NNI {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001088 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301089 cmnni := dh.portStats.collectNNIMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001090 logger.Debugw(ctx, "collect-nni-metrics", log.Fields{"metrics": cmnni})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001091 go dh.portStats.publishMetrics(ctx, NNIStats, cmnni, port, dh.device.Id, dh.device.Type)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001092 logger.Debugw(ctx, "publish-nni-metrics", log.Fields{"nni-port": port.Label})
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301093 }
1094 // PON Stats
1095 if port.Type == voltha.Port_PON_OLT {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001096 intfID := plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301097 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
1098 cmpon := dh.portStats.collectPONMetrics(intfID)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001099 logger.Debugw(ctx, "collect-pon-metrics", log.Fields{"metrics": cmpon})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001100 go dh.portStats.publishMetrics(ctx, PONStats, cmpon, port, dh.device.Id, dh.device.Type)
Kishore Darapuaaf9c102020-05-04 13:06:57 +05301101 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001102 logger.Debugw(ctx, "publish-pon-metrics", log.Fields{"pon-port": port.Label})
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001103
yasin sapli9e4c5092022-02-01 13:52:33 +00001104 onuGemInfoLst := dh.resourceMgr[intfID].GetOnuGemInfoList(ctx)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001105 if len(onuGemInfoLst) > 0 {
1106 go dh.portStats.collectOnuAndGemStats(ctx, onuGemInfoLst)
Gamze Abakafcbd6e72020-12-17 13:25:16 +00001107 }
Chaitrashree G Sef088112020-02-03 21:39:27 -05001108 }
Naga Manjunath7615e552019-10-11 22:35:47 +05301109 }
1110 }
1111 }
1112}
1113
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001114//AdoptDevice adopts the OLT device
npujarec5762e2020-01-01 14:08:48 +05301115func (dh *DeviceHandler) AdoptDevice(ctx context.Context, device *voltha.Device) {
Girish Gowdru0c588b22019-04-23 23:24:56 -04001116 dh.transitionMap = NewTransitionMap(dh)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001117 logger.Infow(ctx, "adopt-device", log.Fields{"device-id": device.Id, "Address": device.GetHostAndPort()})
npujarec5762e2020-01-01 14:08:48 +05301118 dh.transitionMap.Handle(ctx, DeviceInit)
Naga Manjunath7615e552019-10-11 22:35:47 +05301119
1120 // Now, set the initial PM configuration for that device
khenaidoo106c61a2021-08-11 18:05:46 -04001121 cgClient, err := dh.coreClient.GetCoreServiceClient()
1122 if err != nil {
1123 logger.Errorw(ctx, "no-core-connection", log.Fields{"device-id": dh.device.Id, "error": err})
1124 return
1125 }
1126
1127 // Now, set the initial PM configuration for that device
1128 if _, err := cgClient.DevicePMConfigUpdate(ctx, dh.metrics.ToPmConfigs()); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04001129 _ = olterrors.NewErrAdapter("error-updating-performance-metrics", log.Fields{"device-id": device.Id}, err).LogAt(log.ErrorLevel)
Naga Manjunath7615e552019-10-11 22:35:47 +05301130 }
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301131}
1132
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001133//GetOfpDeviceInfo Gets the Ofp information of the given device
khenaidoodc2116e2021-10-19 17:33:19 -04001134func (dh *DeviceHandler) GetOfpDeviceInfo(device *voltha.Device) (*ca.SwitchCapability, error) {
1135 return &ca.SwitchCapability{
cuilin20187b2a8c32019-03-26 19:52:28 -07001136 Desc: &of.OfpDesc{
Devmalya Paul70dd4972019-06-10 15:19:17 +05301137 MfrDesc: "VOLTHA Project",
cuilin20187b2a8c32019-03-26 19:52:28 -07001138 HwDesc: "open_pon",
1139 SwDesc: "open_pon",
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001140 SerialNum: device.SerialNumber,
cuilin20187b2a8c32019-03-26 19:52:28 -07001141 },
1142 SwitchFeatures: &of.OfpSwitchFeatures{
1143 NBuffers: 256,
1144 NTables: 2,
1145 Capabilities: uint32(of.OfpCapabilities_OFPC_FLOW_STATS |
1146 of.OfpCapabilities_OFPC_TABLE_STATS |
1147 of.OfpCapabilities_OFPC_PORT_STATS |
1148 of.OfpCapabilities_OFPC_GROUP_STATS),
1149 },
1150 }, nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301151}
1152
khenaidoo106c61a2021-08-11 18:05:46 -04001153// GetTechProfileDownloadMessage fetches the TechProfileDownloadMessage for the caller.
khenaidoodc2116e2021-10-19 17:33:19 -04001154func (dh *DeviceHandler) GetTechProfileDownloadMessage(ctx context.Context, request *ia.TechProfileInstanceRequestMessage) (*ia.TechProfileDownloadMessage, error) {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001155 ifID, err := plt.IntfIDFromPonPortNum(ctx, request.ParentPonPort)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001156 if err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001157 return nil, err
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001158 }
khenaidoo106c61a2021-08-11 18:05:46 -04001159 return dh.flowMgr[ifID].getTechProfileDownloadMessage(ctx, request.TpInstancePath, request.OnuId, request.DeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001160}
1161
Neha Sharma96b7bf22020-06-15 10:37:32 +00001162func (dh *DeviceHandler) omciIndication(ctx context.Context, omciInd *oop.OmciIndication) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001163 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 -07001164 var deviceType string
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001165 var deviceID string
1166 var proxyDeviceID string
khenaidoo106c61a2021-08-11 18:05:46 -04001167 var childAdapterEndpoint string
cuilin20187b2a8c32019-03-26 19:52:28 -07001168
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001169 transid := extractOmciTransactionID(omciInd.Pkt)
Matteo Scandolo92186242020-06-12 10:54:18 -07001170 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001171 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 -07001172 "omci-transaction-id": transid, "omci-msg": hex.EncodeToString(omciInd.Pkt)})
1173 }
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001174
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001175 onuKey := dh.formOnuKey(omciInd.IntfId, omciInd.OnuId)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301176
1177 if onuInCache, ok := dh.onus.Load(onuKey); !ok {
1178
Neha Sharma96b7bf22020-06-15 10:37:32 +00001179 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 -07001180 ponPort := plt.IntfIDToPortNo(omciInd.GetIntfId(), voltha.Port_PON_OLT)
cuilin20187b2a8c32019-03-26 19:52:28 -07001181
khenaidoodc2116e2021-10-19 17:33:19 -04001182 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001183 ParentId: dh.device.Id,
1184 OnuId: omciInd.OnuId,
1185 ParentPortNo: ponPort,
1186 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001187 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301188 return olterrors.NewErrNotFound("onu", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001189 "intf-id": omciInd.IntfId,
1190 "onu-id": omciInd.OnuId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001191 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001192 deviceType = onuDevice.Type
1193 deviceID = onuDevice.Id
1194 proxyDeviceID = onuDevice.ProxyAddress.DeviceId
khenaidoo106c61a2021-08-11 18:05:46 -04001195 childAdapterEndpoint = onuDevice.AdapterEndpoint
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001196 //if not exist in cache, then add to cache.
khenaidoo106c61a2021-08-11 18:05:46 -04001197 dh.onus.Store(onuKey, NewOnuDevice(deviceID, deviceType, onuDevice.SerialNumber, omciInd.OnuId, omciInd.IntfId, proxyDeviceID, false, onuDevice.AdapterEndpoint))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001198 } else {
1199 //found in cache
Neha Sharma96b7bf22020-06-15 10:37:32 +00001200 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 +05301201 deviceType = onuInCache.(*OnuDevice).deviceType
1202 deviceID = onuInCache.(*OnuDevice).deviceID
1203 proxyDeviceID = onuInCache.(*OnuDevice).proxyDeviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001204 childAdapterEndpoint = onuInCache.(*OnuDevice).adapterEndpoint
cuilin20187b2a8c32019-03-26 19:52:28 -07001205 }
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001206
khenaidoodc2116e2021-10-19 17:33:19 -04001207 if err := dh.sendOmciIndicationToChildAdapter(ctx, childAdapterEndpoint, &ia.OmciMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001208 ParentDeviceId: proxyDeviceID,
1209 ChildDeviceId: deviceID,
1210 Message: omciInd.Pkt,
1211 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301212 return olterrors.NewErrCommunication("omci-request", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001213 "source": dh.openOLT.config.AdapterEndpoint,
1214 "device-type": deviceType,
1215 "destination": childAdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001216 "onu-id": deviceID,
Girish Kumarf26e4882020-03-05 06:49:10 +00001217 "proxy-device-id": proxyDeviceID}, err)
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001218 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001219 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301220}
1221
khenaidoo106c61a2021-08-11 18:05:46 -04001222// //ProcessInterAdapterMessage sends the proxied messages to the target device
1223// // If the proxy address is not found in the unmarshalled message, it first fetches the onu device for which the message
1224// // is meant, and then send the unmarshalled omci message to this onu
khenaidoodc2116e2021-10-19 17:33:19 -04001225// func (dh *DeviceHandler) ProcessInterAdapterMessage(ctx context.Context, msg *ca.InterAdapterMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001226// logger.Debugw(ctx, "process-inter-adapter-message", log.Fields{"msgID": msg.Header.Id})
khenaidoodc2116e2021-10-19 17:33:19 -04001227// if msg.Header.Type == ca.InterAdapterMessageType_OMCI_REQUEST {
khenaidoo106c61a2021-08-11 18:05:46 -04001228// return dh.handleInterAdapterOmciMsg(ctx, msg)
1229// }
1230// return olterrors.NewErrInvalidValue(log.Fields{"inter-adapter-message-type": msg.Header.Type}, nil)
1231// }
cuilin20187b2a8c32019-03-26 19:52:28 -07001232
kesavandb9f54fd2021-11-25 20:08:04 +05301233// ProxyOmciRequests sends the proxied OMCI message to the target device
1234func (dh *DeviceHandler) ProxyOmciRequests(ctx context.Context, omciMsgs *ia.OmciMessages) error {
1235 if omciMsgs.GetProxyAddress() == nil {
1236 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsgs.ChildDeviceId)
1237 if err != nil {
1238 return olterrors.NewErrNotFound("onu", log.Fields{
1239 "parent-device-id": dh.device.Id,
1240 "child-device-id": omciMsgs.ChildDeviceId}, err)
1241 }
1242 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1243 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsgs); err != nil {
1244 return olterrors.NewErrCommunication("send-failed", log.Fields{
1245 "parent-device-id": dh.device.Id,
1246 "child-device-id": omciMsgs.ChildDeviceId}, err)
1247 }
1248 } else {
1249 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsgs.ProxyAddress})
1250 if err := dh.sendProxyOmciRequests(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsgs); err != nil {
1251 return olterrors.NewErrCommunication("send-failed", log.Fields{
1252 "parent-device-id": dh.device.Id,
1253 "child-device-id": omciMsgs.ChildDeviceId}, err)
1254 }
1255 }
1256 return nil
1257}
1258
1259func (dh *DeviceHandler) sendProxyOmciRequests(ctx context.Context, onuDevice *voltha.Device, omciMsgs *ia.OmciMessages) error {
1260 var intfID uint32
1261 var onuID uint32
1262 var connectStatus common.ConnectStatus_Types
1263 if onuDevice != nil {
1264 intfID = onuDevice.ProxyAddress.GetChannelId()
1265 onuID = onuDevice.ProxyAddress.GetOnuId()
1266 connectStatus = onuDevice.ConnectStatus
1267 } else {
1268 intfID = omciMsgs.GetProxyAddress().GetChannelId()
1269 onuID = omciMsgs.GetProxyAddress().GetOnuId()
1270 connectStatus = omciMsgs.GetConnectStatus()
1271 }
1272 if connectStatus != voltha.ConnectStatus_REACHABLE {
1273 logger.Debugw(ctx, "onu-not-reachable--cannot-send-omci", log.Fields{"intf-id": intfID, "onu-id": onuID})
1274
1275 return olterrors.NewErrCommunication("unreachable", log.Fields{
1276 "intf-id": intfID,
1277 "onu-id": onuID}, nil)
1278 }
1279
1280 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1281 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
1282
1283 onuSecOmciMsgList := omciMsgs.GetMessages()
1284
1285 for _, onuSecOmciMsg := range onuSecOmciMsgList {
1286
1287 var omciMessage *oop.OmciMsg
1288 hexPkt := make([]byte, hex.EncodedLen(len(onuSecOmciMsg)))
1289 hex.Encode(hexPkt, onuSecOmciMsg)
1290 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1291
1292 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1293 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1294 //https://jira.opencord.org/browse/VOL-4604
1295 transid := extractOmciTransactionID(onuSecOmciMsg)
1296 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
1297 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
1298
1299 _, err := dh.Client.OmciMsgOut(log.WithSpanFromContext(context.Background(), ctx), omciMessage)
1300 if err != nil {
1301 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
1302 "intf-id": intfID,
1303 "onu-id": onuID,
1304 "message": omciMessage}, err)
1305 }
1306 }
1307 return nil
1308}
1309
khenaidoo106c61a2021-08-11 18:05:46 -04001310// ProxyOmciMessage sends the proxied OMCI message to the target device
khenaidoodc2116e2021-10-19 17:33:19 -04001311func (dh *DeviceHandler) ProxyOmciMessage(ctx context.Context, omciMsg *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04001312 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 -07001313
1314 if omciMsg.GetProxyAddress() == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04001315 onuDevice, err := dh.getDeviceFromCore(ctx, omciMsg.ChildDeviceId)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001316 if err != nil {
1317 return olterrors.NewErrNotFound("onu", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001318 "parent-device-id": dh.device.Id,
1319 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001320 }
khenaidoo106c61a2021-08-11 18:05:46 -04001321 logger.Debugw(ctx, "device-retrieved-from-core", log.Fields{"onu-device-proxy-address": onuDevice.ProxyAddress})
1322 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), onuDevice, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001323 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001324 "parent-device-id": dh.device.Id,
1325 "child-device-id": omciMsg.ChildDeviceId}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001326 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001327 } else {
khenaidoo106c61a2021-08-11 18:05:46 -04001328 logger.Debugw(ctx, "proxy-address-found-in-omci-message", log.Fields{"onu-device-proxy-address": omciMsg.ProxyAddress})
1329 if err := dh.sendProxiedMessage(log.WithSpanFromContext(context.Background(), ctx), nil, omciMsg); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001330 return olterrors.NewErrCommunication("send-failed", log.Fields{
khenaidoo106c61a2021-08-11 18:05:46 -04001331 "parent-device-id": dh.device.Id,
1332 "child-device-id": omciMsg.ChildDeviceId}, err)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001333 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001334 }
1335 return nil
Phaneendra Manda4c62c802019-03-06 21:37:49 +05301336}
1337
khenaidoodc2116e2021-10-19 17:33:19 -04001338func (dh *DeviceHandler) sendProxiedMessage(ctx context.Context, onuDevice *voltha.Device, omciMsg *ia.OmciMessage) error {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001339 var intfID uint32
1340 var onuID uint32
Esin Karamanccb714b2019-11-29 15:02:06 +00001341 var connectStatus common.ConnectStatus_Types
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001342 if onuDevice != nil {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001343 intfID = onuDevice.ProxyAddress.GetChannelId()
1344 onuID = onuDevice.ProxyAddress.GetOnuId()
1345 connectStatus = onuDevice.ConnectStatus
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001346 } else {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001347 intfID = omciMsg.GetProxyAddress().GetChannelId()
1348 onuID = omciMsg.GetProxyAddress().GetOnuId()
1349 connectStatus = omciMsg.GetConnectStatus()
Mahir Gunyela3f9add2019-06-06 15:13:19 -07001350 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001351 if connectStatus != voltha.ConnectStatus_REACHABLE {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001352 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 -08001353
Thomas Lee S94109f12020-03-03 16:39:29 +05301354 return olterrors.NewErrCommunication("unreachable", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001355 "intf-id": intfID,
1356 "onu-id": onuID}, nil)
cuilin20187b2a8c32019-03-26 19:52:28 -07001357 }
1358
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001359 // TODO: OpenOLT Agent oop.OmciMsg expects a hex encoded string for OMCI packets rather than the actual bytes.
1360 // Fix this in the agent and then we can pass byte array as Pkt: omciMsg.Message.
kesavandb9f54fd2021-11-25 20:08:04 +05301361 // https://jira.opencord.org/browse/VOL-4604
lcuie24ef182019-04-29 22:58:36 -07001362 var omciMessage *oop.OmciMsg
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001363 hexPkt := make([]byte, hex.EncodedLen(len(omciMsg.Message)))
1364 hex.Encode(hexPkt, omciMsg.Message)
1365 omciMessage = &oop.OmciMsg{IntfId: intfID, OnuId: onuID, Pkt: hexPkt}
1366
1367 // TODO: Below logging illustrates the "stringify" of the omci Pkt.
1368 // once above is fixed this log line can change to just use hex.EncodeToString(omciMessage.Pkt)
1369 transid := extractOmciTransactionID(omciMsg.Message)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001370 logger.Debugw(ctx, "sent-omci-msg", log.Fields{"intf-id": intfID, "onu-id": onuID,
Matt Jeanneretceea2e02020-03-27 14:19:57 -04001371 "omciTransactionID": transid, "omciMsg": string(omciMessage.Pkt)})
cuilin20187b2a8c32019-03-26 19:52:28 -07001372
Neha Sharma8f4e4322020-08-06 10:51:53 +00001373 _, err := dh.Client.OmciMsgOut(log.WithSpanFromContext(context.Background(), ctx), omciMessage)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001374 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301375 return olterrors.NewErrCommunication("omci-send-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001376 "intf-id": intfID,
1377 "onu-id": onuID,
1378 "message": omciMessage}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001379 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001380 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001381}
1382
David K. Bainbridge794735f2020-02-11 21:01:37 -08001383func (dh *DeviceHandler) activateONU(ctx context.Context, intfID uint32, onuID int64, serialNum *oop.SerialNumber, serialNumber string) error {
kesavand494c2082020-08-31 11:16:12 +05301384 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 +00001385 if err := dh.resourceMgr[intfID].AddNewOnuGemInfoToCacheAndKvStore(ctx, uint32(onuID), serialNumber); err != nil {
Matteo Scandolo92186242020-06-12 10:54:18 -07001386 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": onuID, "intf-id": intfID}, err)
Andrea Campanellab83b39d2020-03-30 11:41:16 +02001387 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001388 var pir uint32 = 1000000
kesavand494c2082020-08-31 11:16:12 +05301389 Onu := oop.Onu{IntfId: intfID, OnuId: uint32(onuID), SerialNumber: serialNum, Pir: pir, OmccEncryption: dh.openOLT.config.OmccEncryption}
npujarec5762e2020-01-01 14:08:48 +05301390 if _, err := dh.Client.ActivateOnu(ctx, &Onu); err != nil {
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001391 st, _ := status.FromError(err)
1392 if st.Code() == codes.AlreadyExists {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001393 logger.Debugw(ctx, "onu-activation-in-progress", log.Fields{"SerialNumber": serialNumber, "onu-id": onuID, "device-id": dh.device.Id})
1394
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001395 } else {
Thomas Lee S985938d2020-05-04 11:40:41 +05301396 return olterrors.NewErrAdapter("onu-activate-failed", log.Fields{"onu": Onu, "device-id": dh.device.Id}, err)
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001397 }
cuilin20187b2a8c32019-03-26 19:52:28 -07001398 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001399 logger.Infow(ctx, "activated-onu", log.Fields{"SerialNumber": serialNumber, "device-id": dh.device.Id})
cuilin20187b2a8c32019-03-26 19:52:28 -07001400 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001401 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001402}
1403
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301404//getChildDevice function can be used in general to get child device, if not found in cache the function will
1405//get from core and update the cache and return the child device.
1406func (dh *DeviceHandler) getChildDevice(ctx context.Context, sn string, parentPortNo uint32) *OnuDevice {
1407 var InCacheOnuDev *OnuDevice
1408 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1409 if onuInCache.(*OnuDevice).serialNumber == sn {
1410 InCacheOnuDev = onuInCache.(*OnuDevice)
1411 return false
1412 }
1413 return true
1414 })
1415 //Got the onu device from cache return
1416 if InCacheOnuDev != nil {
1417 logger.Debugw(ctx, "Got child device from cache", log.Fields{"onudev": InCacheOnuDev.serialNumber})
1418 return InCacheOnuDev
1419 }
1420 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1421 ParentId: dh.device.Id,
1422 SerialNumber: sn,
1423 ParentPortNo: parentPortNo,
1424 })
1425 //No device found in core return nil
1426 if onuDevice == nil {
1427 return nil
1428 }
1429 onuID := onuDevice.ProxyAddress.OnuId
1430 intfID := plt.PortNoToIntfID(parentPortNo, voltha.Port_PON_OLT)
1431 onuKey := dh.formOnuKey(intfID, onuID)
1432
1433 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuDevice.ProxyAddress.OnuId, intfID, onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
1434 dh.onus.Store(onuKey, onuDev)
1435 logger.Debugw(ctx, "got child device from core", log.Fields{"onudev": onuDevice})
1436 return onuDev
1437}
1438
1439func (dh *DeviceHandler) checkForResourceExistance(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) (bool, error) {
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001440 channelID := onuDiscInd.GetIntfId()
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001441 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301442 tpInstExists := false
Matt Jeanneret53539512019-07-20 14:47:02 -04001443
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301444 //CheckOnuDevExistenceAtOnuDiscovery if true , a check will be made for the existence of the onu device. If the onu device
1445 // still exists , the onu discovery will be ignored, else a check for active techprofiles for ONU is checked.
1446 if !dh.openOLT.CheckOnuDevExistenceAtOnuDiscovery {
1447 onuDev := dh.getChildDevice(ctx, sn, parentPortNo)
1448 if onuDev != nil {
1449 var onuGemInfo *rsrcMgr.OnuGemInfo
1450 var err error
1451 if onuGemInfo, err = dh.resourceMgr[channelID].GetOnuGemInfo(ctx, onuDev.onuID); err != nil {
1452 logger.Warnw(ctx, "Unable to find onuGemInfo", log.Fields{"onuID": onuDev.onuID})
1453 return false, err
1454 }
1455 if onuGemInfo != nil {
1456 for _, uni := range onuGemInfo.UniPorts {
1457 uniID := plt.UniIDFromPortNum(uni)
1458 tpIDs := dh.resourceMgr[channelID].GetTechProfileIDForOnu(ctx, onuDev.onuID, uniID)
1459 if len(tpIDs) != 0 {
1460 logger.Warnw(ctx, "Techprofile present for ONU, ignoring onu discovery", log.Fields{"onuID": onuDev.onuID})
1461 tpInstExists = true
1462 break
1463 }
1464 }
1465 }
1466 }
1467 return tpInstExists, nil
1468 }
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301469
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301470 onuDevice, _ := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
1471 ParentId: dh.device.Id,
1472 SerialNumber: sn,
1473 ParentPortNo: parentPortNo,
1474 })
1475 if onuDevice != nil {
1476 logger.Infow(ctx, "Child device still present ignoring discovery indication", log.Fields{"sn": sn})
1477 return true, nil
1478 }
1479 logger.Infow(ctx, "No device present in core , continuing with discovery", log.Fields{"sn": sn})
1480
1481 return false, nil
1482
1483}
1484
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001485// processDiscONULOSClear clears the LOS Alarm if it's needed
1486func (dh *DeviceHandler) processDiscONULOSClear(ctx context.Context, onuDiscInd *oop.OnuDiscIndication, sn string) {
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301487 var alarmInd oop.OnuAlarmIndication
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001488 raisedTs := time.Now().Unix()
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301489
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001490 /* When PON cable disconnected and connected back from OLT, it was expected OnuAlarmIndication
1491 with "los_status: off" should be raised but BAL does not raise this Alarm hence manually sending
1492 OnuLosClear event on receiving OnuDiscoveryIndication for the Onu after checking whether
1493 OnuLosRaise event sent for it */
1494 dh.onus.Range(func(Onukey interface{}, onuInCache interface{}) bool {
1495 if onuInCache.(*OnuDevice).serialNumber == sn && onuInCache.(*OnuDevice).losRaised {
1496 if onuDiscInd.GetIntfId() != onuInCache.(*OnuDevice).intfID {
1497 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
1498 "previousIntfId": onuInCache.(*OnuDevice).intfID,
1499 "currentIntfId": onuDiscInd.GetIntfId()})
1500 // TODO:: Should we need to ignore raising OnuLosClear event
1501 // when onu connected to different PON?
Thiyagarajan Subramani34a00282020-03-10 20:19:31 +05301502 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001503 alarmInd.IntfId = onuInCache.(*OnuDevice).intfID
1504 alarmInd.OnuId = onuInCache.(*OnuDevice).onuID
1505 alarmInd.LosStatus = statusCheckOff
1506 go func() {
1507 if err := dh.eventMgr.onuAlarmIndication(ctx, &alarmInd, onuInCache.(*OnuDevice).deviceID, raisedTs); err != nil {
1508 logger.Errorw(ctx, "indication-failed", log.Fields{"err": err})
1509 }
1510 }()
1511 // stop iterating
1512 return false
1513 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301514 return true
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001515 })
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301516}
1517
1518func (dh *DeviceHandler) onuDiscIndication(ctx context.Context, onuDiscInd *oop.OnuDiscIndication) error {
1519 channelID := onuDiscInd.GetIntfId()
1520 parentPortNo := plt.IntfIDToPortNo(onuDiscInd.GetIntfId(), voltha.Port_PON_OLT)
1521
1522 sn := dh.stringifySerialNumber(onuDiscInd.SerialNumber)
1523 logger.Infow(ctx, "new-discovery-indication", log.Fields{"sn": sn})
1524
1525 tpInstExists, errtp := dh.checkForResourceExistance(ctx, onuDiscInd, sn)
1526 if errtp != nil {
1527 return errtp
1528 }
1529 if tpInstExists {
1530 //ignore the discovery if tpinstance is present.
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001531 logger.Debugw(ctx, "ignoring-onu-indication-as-tp-already-exists", log.Fields{"sn": sn})
David K. Bainbridge794735f2020-02-11 21:01:37 -08001532 return nil
Amit Ghoshe5c6a852020-02-10 15:09:46 +00001533 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001534 inProcess, existing := dh.discOnus.LoadOrStore(sn, true)
1535
1536 // if the ONU existed, handle the LOS Alarm
1537 if existing {
1538
1539 if inProcess.(bool) {
1540 // if we're currently processing the ONU on a different thread, do nothing
1541 logger.Warnw(ctx, "onu-sn-is-being-processed", log.Fields{"sn": sn})
1542 return nil
1543 }
1544 // if we had dealt with this ONU before, but the process didn't complete (this happens in case of errors)
1545 // then continue processing it
1546 logger.Debugw(ctx, "onu-processing-had-completed-but-new-indication", log.Fields{"sn": sn})
1547
1548 dh.processDiscONULOSClear(ctx, onuDiscInd, sn)
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05301549 }
Matteo Scandolo7eaec532022-06-23 15:54:57 -07001550
1551 defer func() {
1552 // once the function completes set the value to false so that
1553 // we know the processing has inProcess.
1554 // Note that this is done after checking if we are already processing
1555 // to avoid changing the value from a different thread
1556 logger.Infow(ctx, "onu-processing-completed", log.Fields{"sn": sn})
1557 dh.discOnus.Store(sn, false)
1558 }()
1559
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001560 var onuID uint32
Matteo Scandolo945e4012019-12-12 14:16:11 -08001561
1562 // check the ONU is already know to the OLT
1563 // NOTE the second time the ONU is discovered this should return a device
khenaidoodc2116e2021-10-19 17:33:19 -04001564 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001565 ParentId: dh.device.Id,
1566 SerialNumber: sn,
1567 })
Matteo Scandolo945e4012019-12-12 14:16:11 -08001568
1569 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001570 logger.Debugw(ctx, "core-proxy-get-child-device-failed", log.Fields{"parentDevice": dh.device.Id, "err": err, "sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001571 if e, ok := status.FromError(err); ok {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001572 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 -08001573 switch e.Code() {
1574 case codes.Internal:
1575 // this probably means NOT FOUND, so just create a new device
1576 onuDevice = nil
1577 case codes.DeadlineExceeded:
1578 // if the call times out, cleanup and exit
1579 dh.discOnus.Delete(sn)
Girish Kumarf26e4882020-03-05 06:49:10 +00001580 return olterrors.NewErrTimeout("get-child-device", log.Fields{"device-id": dh.device.Id}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001581 }
1582 }
1583 }
1584
1585 if onuDevice == nil {
1586 // NOTE this should happen a single time, and only if GetChildDevice returns NotFound
Neha Sharma96b7bf22020-06-15 10:37:32 +00001587 logger.Debugw(ctx, "creating-new-onu", log.Fields{"sn": sn})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001588 // we need to create a new ChildDevice
Matt Jeanneret53539512019-07-20 14:47:02 -04001589 ponintfid := onuDiscInd.GetIntfId()
yasin saplibddc2d72022-02-08 13:10:17 +00001590 onuID, err = dh.resourceMgr[ponintfid].GetONUID(ctx)
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001591
Neha Sharma96b7bf22020-06-15 10:37:32 +00001592 logger.Infow(ctx, "creating-new-onu-got-onu-id", log.Fields{"sn": sn, "onuId": onuID})
Matteo Scandolo945e4012019-12-12 14:16:11 -08001593
1594 if err != nil {
1595 // if we can't create an ID in resource manager,
1596 // cleanup and exit
Matteo Scandolo945e4012019-12-12 14:16:11 -08001597 dh.discOnus.Delete(sn)
Girish Kumarf26e4882020-03-05 06:49:10 +00001598 return olterrors.NewErrAdapter("resource-manager-get-onu-id-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001599 "pon-intf-id": ponintfid,
1600 "serial-number": sn}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001601 }
1602
khenaidoodc2116e2021-10-19 17:33:19 -04001603 if onuDevice, err = dh.sendChildDeviceDetectedToCore(ctx, &ca.DeviceDiscovery{
khenaidoo106c61a2021-08-11 18:05:46 -04001604 ParentId: dh.device.Id,
1605 ParentPortNo: parentPortNo,
1606 ChannelId: channelID,
1607 VendorId: string(onuDiscInd.SerialNumber.GetVendorId()),
1608 SerialNumber: sn,
1609 OnuId: onuID,
1610 }); err != nil {
Matteo Scandolo945e4012019-12-12 14:16:11 -08001611 dh.discOnus.Delete(sn)
yasin saplibddc2d72022-02-08 13:10:17 +00001612 dh.resourceMgr[ponintfid].FreeonuID(ctx, []uint32{onuID}) // NOTE I'm not sure this method is actually cleaning up the right thing
Thomas Lee S94109f12020-03-03 16:39:29 +05301613 return olterrors.NewErrAdapter("core-proxy-child-device-detected-failed", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001614 "pon-intf-id": ponintfid,
1615 "serial-number": sn}, err)
Matteo Scandolo945e4012019-12-12 14:16:11 -08001616 }
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001617 if err := dh.eventMgr.OnuDiscoveryIndication(ctx, onuDiscInd, dh.device.Id, onuDevice.Id, onuID, sn, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001618 logger.Warnw(ctx, "discovery-indication-failed", log.Fields{"err": err})
Kent Hagermane6ff1012020-07-14 15:07:53 -04001619 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001620 logger.Infow(ctx, "onu-child-device-added",
Shrey Baid807a2a02020-04-09 12:52:45 +05301621 log.Fields{"onuDevice": onuDevice,
1622 "sn": sn,
Matteo Scandolo92186242020-06-12 10:54:18 -07001623 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05301624 "device-id": dh.device.Id})
Chaitrashree G Sbe6ab942019-05-24 06:42:49 -04001625 }
Matteo Scandolo945e4012019-12-12 14:16:11 -08001626
khenaidoo106c61a2021-08-11 18:05:46 -04001627 // Setup the gRPC connection to the adapter responsible for that onuDevice, if not setup yet
1628 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
1629 err = dh.setupChildInterAdapterClient(subCtx, onuDevice.AdapterEndpoint)
1630 cancel()
1631 if err != nil {
1632 return olterrors.NewErrCommunication("no-connection-to-child-adapter", log.Fields{"device-id": onuDevice.Id}, err)
1633 }
1634
Matteo Scandolo945e4012019-12-12 14:16:11 -08001635 // we can now use the existing ONU Id
1636 onuID = onuDevice.ProxyAddress.OnuId
Mahir Gunyele77977b2019-06-27 05:36:22 -07001637 //Insert the ONU into cache to use in OnuIndication.
1638 //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 +00001639 logger.Debugw(ctx, "onu-discovery-indication-key-create",
Matteo Scandolo92186242020-06-12 10:54:18 -07001640 log.Fields{"onu-id": onuID,
Shrey Baid807a2a02020-04-09 12:52:45 +05301641 "intfId": onuDiscInd.GetIntfId(),
1642 "sn": sn})
Mahir Gunyele77977b2019-06-27 05:36:22 -07001643 onuKey := dh.formOnuKey(onuDiscInd.GetIntfId(), onuID)
Matt Jeanneret53539512019-07-20 14:47:02 -04001644
khenaidoo106c61a2021-08-11 18:05:46 -04001645 onuDev := NewOnuDevice(onuDevice.Id, onuDevice.Type, onuDevice.SerialNumber, onuID, onuDiscInd.GetIntfId(), onuDevice.ProxyAddress.DeviceId, false, onuDevice.AdapterEndpoint)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301646 dh.onus.Store(onuKey, onuDev)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001647 logger.Debugw(ctx, "new-onu-device-discovered",
Shrey Baid807a2a02020-04-09 12:52:45 +05301648 log.Fields{"onu": onuDev,
1649 "sn": sn})
Chaitrashree G S35b5d802019-07-08 23:12:03 -04001650
khenaidoodc2116e2021-10-19 17:33:19 -04001651 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001652 DeviceId: onuDevice.Id,
1653 ParentDeviceId: dh.device.Id,
1654 OperStatus: common.OperStatus_DISCOVERED,
1655 ConnStatus: common.ConnectStatus_REACHABLE,
1656 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301657 return olterrors.NewErrAdapter("failed-to-update-device-state", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001658 "device-id": onuDevice.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00001659 "serial-number": sn}, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001660 }
khenaidoo106c61a2021-08-11 18:05:46 -04001661
Neha Sharma96b7bf22020-06-15 10:37:32 +00001662 logger.Infow(ctx, "onu-discovered-reachable", log.Fields{"device-id": onuDevice.Id, "sn": sn})
Kent Hagermane6ff1012020-07-14 15:07:53 -04001663 if err := dh.activateONU(ctx, onuDiscInd.IntfId, int64(onuID), onuDiscInd.SerialNumber, sn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301664 return olterrors.NewErrAdapter("onu-activation-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001665 "device-id": onuDevice.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00001666 "serial-number": sn}, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08001667 }
1668 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001669}
1670
Mahir Gunyelb0046752021-02-26 13:51:05 -08001671func (dh *DeviceHandler) onuIndication(ctx context.Context, onuInd *oop.OnuIndication) error {
cuilin20187b2a8c32019-03-26 19:52:28 -07001672
Mahir Gunyel85f61c12021-10-06 11:53:45 -07001673 ponPort := plt.IntfIDToPortNo(onuInd.GetIntfId(), voltha.Port_PON_OLT)
Mahir Gunyele77977b2019-06-27 05:36:22 -07001674 var onuDevice *voltha.Device
David K. Bainbridge794735f2020-02-11 21:01:37 -08001675 var err error
Mahir Gunyele77977b2019-06-27 05:36:22 -07001676 foundInCache := false
Neha Sharma96b7bf22020-06-15 10:37:32 +00001677 logger.Debugw(ctx, "onu-indication-key-create",
Shrey Baid807a2a02020-04-09 12:52:45 +05301678 log.Fields{"onuId": onuInd.OnuId,
1679 "intfId": onuInd.GetIntfId(),
Thomas Lee S985938d2020-05-04 11:40:41 +05301680 "device-id": dh.device.Id})
Mahir Gunyele77977b2019-06-27 05:36:22 -07001681 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.OnuId)
Mahir Gunyelb0046752021-02-26 13:51:05 -08001682 serialNumber := dh.stringifySerialNumber(onuInd.SerialNumber)
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301683
David K. Bainbridge794735f2020-02-11 21:01:37 -08001684 errFields := log.Fields{"device-id": dh.device.Id}
1685
Naga Manjunatha8dc9372019-10-31 23:01:18 +05301686 if onuInCache, ok := dh.onus.Load(onuKey); ok {
1687
Mahir Gunyele77977b2019-06-27 05:36:22 -07001688 //If ONU id is discovered before then use GetDevice to get onuDevice because it is cheaper.
1689 foundInCache = true
David K. Bainbridge794735f2020-02-11 21:01:37 -08001690 errFields["onu-id"] = onuInCache.(*OnuDevice).deviceID
khenaidoo106c61a2021-08-11 18:05:46 -04001691 onuDevice, err = dh.getDeviceFromCore(ctx, onuInCache.(*OnuDevice).deviceID)
cuilin20187b2a8c32019-03-26 19:52:28 -07001692 } else {
Mahir Gunyele77977b2019-06-27 05:36:22 -07001693 //If ONU not found in adapter cache then we have to use GetChildDevice to get onuDevice
1694 if serialNumber != "" {
David K. Bainbridge794735f2020-02-11 21:01:37 -08001695 errFields["serial-number"] = serialNumber
Mahir Gunyele77977b2019-06-27 05:36:22 -07001696 } else {
David K. Bainbridge794735f2020-02-11 21:01:37 -08001697 errFields["onu-id"] = onuInd.OnuId
1698 errFields["parent-port-no"] = ponPort
Mahir Gunyele77977b2019-06-27 05:36:22 -07001699 }
khenaidoodc2116e2021-10-19 17:33:19 -04001700 onuDevice, err = dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001701 ParentId: dh.device.Id,
1702 SerialNumber: serialNumber,
1703 OnuId: onuInd.OnuId,
1704 ParentPortNo: ponPort,
1705 })
cuilin20187b2a8c32019-03-26 19:52:28 -07001706 }
Mahir Gunyele77977b2019-06-27 05:36:22 -07001707
David K. Bainbridge794735f2020-02-11 21:01:37 -08001708 if err != nil || onuDevice == nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001709 return olterrors.NewErrNotFound("onu-device", errFields, err)
cuilin20187b2a8c32019-03-26 19:52:28 -07001710 }
1711
David K. Bainbridge794735f2020-02-11 21:01:37 -08001712 if onuDevice.ParentPortNo != ponPort {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001713 logger.Warnw(ctx, "onu-is-on-a-different-intf-id-now", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001714 "previousIntfId": onuDevice.ParentPortNo,
1715 "currentIntfId": ponPort})
1716 }
1717
1718 if onuDevice.ProxyAddress.OnuId != onuInd.OnuId {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001719 logger.Warnw(ctx, "onu-id-mismatch-possible-if-voltha-and-olt-rebooted", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05301720 "expected-onu-id": onuDevice.ProxyAddress.OnuId,
1721 "received-onu-id": onuInd.OnuId,
Thomas Lee S985938d2020-05-04 11:40:41 +05301722 "device-id": dh.device.Id})
David K. Bainbridge794735f2020-02-11 21:01:37 -08001723 }
1724 if !foundInCache {
1725 onuKey := dh.formOnuKey(onuInd.GetIntfId(), onuInd.GetOnuId())
1726
khenaidoo106c61a2021-08-11 18:05:46 -04001727 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 -08001728
1729 }
kesavand7cf3a052020-08-28 12:49:18 +05301730 if onuInd.OperState == "down" && onuInd.FailReason != oop.OnuIndication_ONU_ACTIVATION_FAIL_REASON_NONE {
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07001731 if err := dh.eventMgr.onuActivationIndication(ctx, onuActivationFailEvent, onuInd, dh.device.Id, time.Now().Unix()); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07001732 logger.Warnw(ctx, "onu-activation-indication-reporting-failed", log.Fields{"err": err})
kesavand7cf3a052020-08-28 12:49:18 +05301733 }
1734 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001735 if err := dh.updateOnuStates(ctx, onuDevice, onuInd); err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001736 return olterrors.NewErrCommunication("state-update-failed", errFields, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08001737 }
1738 return nil
cuilin20187b2a8c32019-03-26 19:52:28 -07001739}
1740
Neha Sharma96b7bf22020-06-15 10:37:32 +00001741func (dh *DeviceHandler) updateOnuStates(ctx context.Context, onuDevice *voltha.Device, onuInd *oop.OnuIndication) error {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001742 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 -07001743 if onuInd.AdminState == "down" || onuInd.OperState == "down" {
1744 // The ONU has gone admin_state "down" or oper_state "down" - we expect the ONU to send discovery again
1745 // The ONU admin_state is "up" while "oper_state" is down in cases where ONU activation fails. In this case
1746 // the ONU sends Discovery again.
Girish Gowdra429f9502020-05-04 13:22:16 -07001747 dh.discOnus.Delete(onuDevice.SerialNumber)
Amit Ghosh9bbc5652020-02-17 13:37:32 +00001748 // Tests have shown that we sometimes get OperState as NOT down even if AdminState is down, forcing it
1749 if onuInd.OperState != "down" {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001750 logger.Warnw(ctx, "onu-admin-state-down", log.Fields{"operState": onuInd.OperState})
Amit Ghosh9bbc5652020-02-17 13:37:32 +00001751 onuInd.OperState = "down"
1752 }
1753 }
1754
David K. Bainbridge794735f2020-02-11 21:01:37 -08001755 switch onuInd.OperState {
khenaidoo106c61a2021-08-11 18:05:46 -04001756 case "up", "down":
Neha Sharma96b7bf22020-06-15 10:37:32 +00001757 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 -04001758
khenaidoodc2116e2021-10-19 17:33:19 -04001759 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04001760 DeviceId: onuDevice.Id,
1761 OnuIndication: onuInd,
1762 })
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001763 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301764 return olterrors.NewErrCommunication("inter-adapter-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001765 "onu-indicator": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04001766 "source": dh.openOLT.config.AdapterEndpoint,
David K. Bainbridge794735f2020-02-11 21:01:37 -08001767 "device-type": onuDevice.Type,
Girish Kumarf26e4882020-03-05 06:49:10 +00001768 "device-id": onuDevice.Id}, err)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001769 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001770 default:
Girish Kumarf26e4882020-03-05 06:49:10 +00001771 return olterrors.NewErrInvalidValue(log.Fields{"oper-state": onuInd.OperState}, nil)
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001772 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001773 return nil
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001774}
1775
cuilin20187b2a8c32019-03-26 19:52:28 -07001776func (dh *DeviceHandler) stringifySerialNumber(serialNum *oop.SerialNumber) string {
1777 if serialNum != nil {
1778 return string(serialNum.VendorId) + dh.stringifyVendorSpecific(serialNum.VendorSpecific)
cuilin20187b2a8c32019-03-26 19:52:28 -07001779 }
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001780 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07001781}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05001782func (dh *DeviceHandler) deStringifySerialNumber(serialNum string) (*oop.SerialNumber, error) {
1783 decodedStr, err := hex.DecodeString(serialNum[4:])
1784 if err != nil {
1785 return nil, err
1786 }
1787 return &oop.SerialNumber{
1788 VendorId: []byte(serialNum[:4]),
Girish Gowdraa09aeab2020-09-14 16:30:52 -07001789 VendorSpecific: decodedStr,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05001790 }, nil
1791}
cuilin20187b2a8c32019-03-26 19:52:28 -07001792
1793func (dh *DeviceHandler) stringifyVendorSpecific(vendorSpecific []byte) string {
Mahir Gunyelb0046752021-02-26 13:51:05 -08001794 if len(vendorSpecific) > 3 {
1795 tmp := fmt.Sprintf("%x", (uint32(vendorSpecific[0])>>4)&0x0f) +
1796 fmt.Sprintf("%x", uint32(vendorSpecific[0]&0x0f)) +
1797 fmt.Sprintf("%x", (uint32(vendorSpecific[1])>>4)&0x0f) +
1798 fmt.Sprintf("%x", (uint32(vendorSpecific[1]))&0x0f) +
1799 fmt.Sprintf("%x", (uint32(vendorSpecific[2])>>4)&0x0f) +
1800 fmt.Sprintf("%x", (uint32(vendorSpecific[2]))&0x0f) +
1801 fmt.Sprintf("%x", (uint32(vendorSpecific[3])>>4)&0x0f) +
1802 fmt.Sprintf("%x", (uint32(vendorSpecific[3]))&0x0f)
1803 return tmp
1804 }
1805 return ""
cuilin20187b2a8c32019-03-26 19:52:28 -07001806}
1807
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001808//UpdateFlowsBulk upates the bulk flow
1809func (dh *DeviceHandler) UpdateFlowsBulk() error {
Thomas Lee S94109f12020-03-03 16:39:29 +05301810 return olterrors.ErrNotImplemented
cuilin20187b2a8c32019-03-26 19:52:28 -07001811}
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001812
1813//GetChildDevice returns the child device for given parent port and onu id
Neha Sharma96b7bf22020-06-15 10:37:32 +00001814func (dh *DeviceHandler) GetChildDevice(ctx context.Context, parentPort, onuID uint32) (*voltha.Device, error) {
1815 logger.Debugw(ctx, "getchilddevice",
Shrey Baid807a2a02020-04-09 12:52:45 +05301816 log.Fields{"pon-port": parentPort,
Matteo Scandolo92186242020-06-12 10:54:18 -07001817 "onu-id": onuID,
Thomas Lee S985938d2020-05-04 11:40:41 +05301818 "device-id": dh.device.Id})
khenaidoo106c61a2021-08-11 18:05:46 -04001819
khenaidoodc2116e2021-10-19 17:33:19 -04001820 onuDevice, err := dh.getChildDeviceFromCore(ctx, &ca.ChildDeviceFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04001821 ParentId: dh.device.Id,
1822 OnuId: onuID,
1823 ParentPortNo: parentPort,
1824 })
1825
Girish Gowdru0c588b22019-04-23 23:24:56 -04001826 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00001827 return nil, olterrors.NewErrNotFound("onu-device", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001828 "intf-id": parentPort,
1829 "onu-id": onuID}, err)
Girish Gowdru0c588b22019-04-23 23:24:56 -04001830 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00001831 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 -08001832 return onuDevice, nil
manikkaraj kbf256be2019-03-25 00:13:48 +05301833}
1834
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07001835// SendPacketInToCore sends packet-in to core
1836// For this, it calls SendPacketIn of the core-proxy which uses a device specific topic to send the request.
1837// The adapter handling the device creates a device specific topic
Neha Sharma96b7bf22020-06-15 10:37:32 +00001838func (dh *DeviceHandler) SendPacketInToCore(ctx context.Context, logicalPort uint32, packetPayload []byte) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07001839 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001840 logger.Debugw(ctx, "send-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001841 "port": logicalPort,
1842 "packet": hex.EncodeToString(packetPayload),
1843 "device-id": dh.device.Id,
1844 })
1845 }
khenaidoo106c61a2021-08-11 18:05:46 -04001846
khenaidoodc2116e2021-10-19 17:33:19 -04001847 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04001848 DeviceId: dh.device.Id,
1849 Port: logicalPort,
1850 Packet: packetPayload,
1851 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05301852 return olterrors.NewErrCommunication("packet-send-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08001853 "source": "adapter",
1854 "destination": "core",
1855 "device-id": dh.device.Id,
1856 "logical-port": logicalPort,
Girish Kumarf26e4882020-03-05 06:49:10 +00001857 "packet": hex.EncodeToString(packetPayload)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04001858 }
Matteo Scandolo92186242020-06-12 10:54:18 -07001859 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001860 logger.Debugw(ctx, "sent-packet-in-to-core-successfully", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07001861 "packet": hex.EncodeToString(packetPayload),
1862 "device-id": dh.device.Id,
1863 })
1864 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08001865 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04001866}
1867
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001868// UpdatePmConfig updates the pm metrics.
Neha Sharma96b7bf22020-06-15 10:37:32 +00001869func (dh *DeviceHandler) UpdatePmConfig(ctx context.Context, pmConfigs *voltha.PmConfigs) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00001870 logger.Infow(ctx, "update-pm-configs", log.Fields{"device-id": dh.device.Id, "pm-configs": pmConfigs})
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001871
1872 if pmConfigs.DefaultFreq != dh.metrics.ToPmConfigs().DefaultFreq {
1873 dh.metrics.UpdateFrequency(pmConfigs.DefaultFreq)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001874 logger.Debugf(ctx, "frequency-updated")
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001875 }
1876
Kent Hagermane6ff1012020-07-14 15:07:53 -04001877 if !pmConfigs.Grouped {
Rohan Agrawalda5e0b22020-05-20 11:10:26 +00001878 metrics := dh.metrics.GetSubscriberMetrics()
1879 for _, m := range pmConfigs.Metrics {
1880 metrics[m.Name].Enabled = m.Enabled
1881
1882 }
1883 }
1884}
1885
khenaidoodc2116e2021-10-19 17:33:19 -04001886func (dh *DeviceHandler) handleFlows(ctx context.Context, device *voltha.Device, flows *of.FlowChanges, flowMetadata *of.FlowMetadata) []error {
Girish Gowdra491a9c62021-01-06 16:43:07 -08001887 var err error
Andrea Campanellac63bba92020-03-10 17:01:04 +01001888 var errorsList []error
1889
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08001890 if dh.getDeviceDeletionInProgressFlag() {
1891 // The device itself is going to be reset as part of deletion. So nothing to be done.
1892 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
1893 return nil
1894 }
1895
Girish Gowdru0c588b22019-04-23 23:24:56 -04001896 if flows != nil {
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04001897 for _, flow := range flows.ToRemove.Items {
yasin saplid0566272021-12-21 09:10:30 +00001898 intfID := dh.getIntfIDFromFlow(ctx, flow)
Girish Gowdracefae192020-03-19 18:14:10 -07001899
Neha Sharma96b7bf22020-06-15 10:37:32 +00001900 logger.Debugw(ctx, "removing-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05301901 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00001902 "intfId": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05301903 "flowToRemove": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08001904 if flow_utils.HasGroup(flow) {
1905 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupRemove)
1906 } else {
yasin saplid0566272021-12-21 09:10:30 +00001907 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, false, nil)
Girish Gowdra491a9c62021-01-06 16:43:07 -08001908 }
Girish Gowdracefae192020-03-19 18:14:10 -07001909 if err != nil {
Elia Battiston2aaf4342022-02-07 15:16:38 +01001910 if werr, ok := err.(olterrors.WrappedError); ok && status.Code(werr.Unwrap()) == codes.NotFound {
1911 //The flow we want to remove is not there, there is no need to throw an error
1912 logger.Warnw(ctx, "flow-to-remove-not-found",
1913 log.Fields{
1914 "ponIf": intfID,
1915 "flowToRemove": flow,
1916 "error": err,
1917 })
1918 } else {
1919 errorsList = append(errorsList, err)
1920 }
Girish Gowdracefae192020-03-19 18:14:10 -07001921 }
Manjunath Vanarajulu28c3e822019-05-16 11:14:28 -04001922 }
Girish Gowdra3d633032019-12-10 16:37:05 +05301923
1924 for _, flow := range flows.ToAdd.Items {
yasin saplid0566272021-12-21 09:10:30 +00001925 intfID := dh.getIntfIDFromFlow(ctx, flow)
Neha Sharma96b7bf22020-06-15 10:37:32 +00001926 logger.Debugw(ctx, "adding-flow",
Shrey Baid807a2a02020-04-09 12:52:45 +05301927 log.Fields{"device-id": device.Id,
yasin saplid0566272021-12-21 09:10:30 +00001928 "ponIf": intfID,
Shrey Baid807a2a02020-04-09 12:52:45 +05301929 "flowToAdd": flow})
Girish Gowdra491a9c62021-01-06 16:43:07 -08001930 if flow_utils.HasGroup(flow) {
1931 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, flow, nil, McastFlowOrGroupAdd)
1932 } else {
yasin saplid0566272021-12-21 09:10:30 +00001933 if dh.flowMgr == nil || dh.flowMgr[intfID] == nil {
Girish Gowdra0fb24a32021-10-27 15:15:27 -07001934 // The flow manager module could be uninitialized if the flow arrives too soon before the device has reconciled fully
1935 logger.Errorw(ctx, "flow-manager-uninitialized", log.Fields{"device-id": device.Id})
1936 err = fmt.Errorf("flow-manager-uninitialized-%v", device.Id)
1937 } else {
yasin saplid0566272021-12-21 09:10:30 +00001938 err = dh.flowMgr[intfID].RouteFlowToOnuChannel(ctx, flow, true, flowMetadata)
Girish Gowdra0fb24a32021-10-27 15:15:27 -07001939 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08001940 }
Andrea Campanellac63bba92020-03-10 17:01:04 +01001941 if err != nil {
1942 errorsList = append(errorsList, err)
1943 }
Girish Gowdra3d633032019-12-10 16:37:05 +05301944 }
Girish Gowdru0c588b22019-04-23 23:24:56 -04001945 }
Esin Karamanccb714b2019-11-29 15:02:06 +00001946
Girish Gowdra0fb24a32021-10-27 15:15:27 -07001947 return errorsList
1948}
1949
1950func (dh *DeviceHandler) handleGroups(ctx context.Context, groups *of.FlowGroupChanges) []error {
1951 var err error
1952 var errorsList []error
1953
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08001954 if dh.getDeviceDeletionInProgressFlag() {
1955 // The device itself is going to be reset as part of deletion. So nothing to be done.
1956 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
1957 return nil
1958 }
1959
Girish Gowdracefae192020-03-19 18:14:10 -07001960 // 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 +00001961 if groups != nil {
1962 for _, group := range groups.ToAdd.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08001963 // err = dh.groupMgr.AddGroup(ctx, group)
1964 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupAdd)
Andrea Campanellac63bba92020-03-10 17:01:04 +01001965 if err != nil {
1966 errorsList = append(errorsList, err)
1967 }
Esin Karamanccb714b2019-11-29 15:02:06 +00001968 }
1969 for _, group := range groups.ToUpdate.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08001970 // err = dh.groupMgr.ModifyGroup(ctx, group)
1971 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupModify)
Andrea Campanellac63bba92020-03-10 17:01:04 +01001972 if err != nil {
1973 errorsList = append(errorsList, err)
1974 }
Esin Karamanccb714b2019-11-29 15:02:06 +00001975 }
Esin Karamand519bbf2020-07-01 11:16:03 +00001976 for _, group := range groups.ToRemove.Items {
Girish Gowdra491a9c62021-01-06 16:43:07 -08001977 // err = dh.groupMgr.DeleteGroup(ctx, group)
1978 err = dh.RouteMcastFlowOrGroupMsgToChannel(ctx, nil, group, McastFlowOrGroupRemove)
Esin Karamand519bbf2020-07-01 11:16:03 +00001979 if err != nil {
1980 errorsList = append(errorsList, err)
1981 }
Esin Karamanccb714b2019-11-29 15:02:06 +00001982 }
1983 }
Girish Gowdra0fb24a32021-10-27 15:15:27 -07001984
1985 return errorsList
1986}
1987
1988//UpdateFlowsIncrementally updates the device flow
khenaidoodc2116e2021-10-19 17:33:19 -04001989func (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 -07001990
1991 var errorsList []error
Girish Gowdra950326e2021-11-05 12:43:24 -07001992
1993 if dh.getDeviceDeletionInProgressFlag() {
1994 // The device itself is going to be reset as part of deletion. So nothing to be done.
1995 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": device.Id})
1996 return nil
1997 }
1998
Girish Gowdra0fb24a32021-10-27 15:15:27 -07001999 logger.Debugw(ctx, "received-incremental-flowupdate-in-device-handler", log.Fields{"device-id": device.Id, "flows": flows, "groups": groups, "flowMetadata": flowMetadata})
2000 errorsList = append(errorsList, dh.handleFlows(ctx, device, flows, flowMetadata)...)
2001 errorsList = append(errorsList, dh.handleGroups(ctx, groups)...)
Andrea Campanellac63bba92020-03-10 17:01:04 +01002002 if len(errorsList) > 0 {
2003 return fmt.Errorf("errors-installing-flows-groups, errors:%v", errorsList)
2004 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002005 logger.Debugw(ctx, "updated-flows-incrementally-successfully", log.Fields{"device-id": dh.device.Id})
Girish Gowdru0c588b22019-04-23 23:24:56 -04002006 return nil
manikkaraj kbf256be2019-03-25 00:13:48 +05302007}
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002008
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002009//DisableDevice disables the given device
2010//It marks the following for the given device:
2011//Device-Handler Admin-State : down
2012//Device Port-State: UNKNOWN
2013//Device Oper-State: UNKNOWN
Neha Sharma96b7bf22020-06-15 10:37:32 +00002014func (dh *DeviceHandler) DisableDevice(ctx context.Context, device *voltha.Device) error {
Chaitrashree G S44124192019-08-07 20:21:36 -04002015 /* On device disable ,admin state update has to be done prior sending request to agent since
2016 the indication thread may processes invalid indications of ONU and OLT*/
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002017 if dh.Client != nil {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002018 if _, err := dh.Client.DisableOlt(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002019 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
Girish Kumarf26e4882020-03-05 06:49:10 +00002020 return olterrors.NewErrAdapter("olt-disable-failed", log.Fields{"device-id": device.Id}, err)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002021 }
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002022 }
Chaitrashree G S44124192019-08-07 20:21:36 -04002023 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002024 logger.Debugw(ctx, "olt-disabled", log.Fields{"device-id": device.Id})
Chaitrashree G S44124192019-08-07 20:21:36 -04002025 /* Discovered ONUs entries need to be cleared , since on device disable the child devices goes to
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002026 UNREACHABLE state which needs to be configured again*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302027
2028 dh.discOnus = sync.Map{}
2029 dh.onus = sync.Map{}
2030
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002031 dh.lockDevice.RLock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302032 //stopping the stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002033 if dh.isCollectorActive {
2034 dh.stopCollector <- true
2035 }
2036 dh.lockDevice.RUnlock()
Thomas Lee S85f37312020-04-03 17:06:12 +05302037
Neha Sharma96b7bf22020-06-15 10:37:32 +00002038 go dh.notifyChildDevices(ctx, "unreachable")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002039 cloned := proto.Clone(device).(*voltha.Device)
Thomas Lee S985938d2020-05-04 11:40:41 +05302040 //Update device Admin state
2041 dh.device = cloned
khenaidoo106c61a2021-08-11 18:05:46 -04002042
kdarapu1afeceb2020-02-12 01:38:09 -05002043 // 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 -04002044 if err := dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002045 DeviceId: cloned.Id,
2046 PortTypeFilter: ^uint32(1 << voltha.Port_PON_OLT),
2047 OperStatus: voltha.OperStatus_UNKNOWN,
2048 }); err != nil {
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002049 return olterrors.NewErrAdapter("ports-state-update-failed", log.Fields{"device-id": device.Id}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002050 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002051 logger.Debugw(ctx, "disable-device-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002052 return nil
2053}
2054
Neha Sharma96b7bf22020-06-15 10:37:32 +00002055func (dh *DeviceHandler) notifyChildDevices(ctx context.Context, state string) {
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002056 // Update onu state as unreachable in onu adapter
2057 onuInd := oop.OnuIndication{}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302058 onuInd.OperState = state
khenaidoo106c61a2021-08-11 18:05:46 -04002059
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002060 //get the child device for the parent device
khenaidoo106c61a2021-08-11 18:05:46 -04002061 onuDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002062 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002063 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 -04002064 }
2065 if onuDevices != nil {
2066 for _, onuDevice := range onuDevices.Items {
khenaidoodc2116e2021-10-19 17:33:19 -04002067 err := dh.sendOnuIndicationToChildAdapter(ctx, onuDevice.AdapterEndpoint, &ia.OnuIndicationMessage{
khenaidoo106c61a2021-08-11 18:05:46 -04002068 DeviceId: onuDevice.Id,
2069 OnuIndication: &onuInd,
2070 })
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002071 if err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002072 logger.Errorw(ctx, "failed-to-send-inter-adapter-message", log.Fields{"OnuInd": onuInd,
khenaidoo106c61a2021-08-11 18:05:46 -04002073 "From Adapter": dh.openOLT.config.AdapterEndpoint, "DeviceType": onuDevice.Type, "device-id": onuDevice.Id})
Chaitrashree G S3b4c0352019-09-09 20:59:29 -04002074 }
2075
2076 }
2077 }
2078
2079}
2080
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002081//ReenableDevice re-enables the olt device after disable
2082//It marks the following for the given device:
2083//Device-Handler Admin-State : up
2084//Device Port-State: ACTIVE
2085//Device Oper-State: ACTIVE
Neha Sharma96b7bf22020-06-15 10:37:32 +00002086func (dh *DeviceHandler) ReenableDevice(ctx context.Context, device *voltha.Device) error {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002087 if _, err := dh.Client.ReenableOlt(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302088 if e, ok := status.FromError(err); ok && e.Code() == codes.Internal {
Girish Kumarf26e4882020-03-05 06:49:10 +00002089 return olterrors.NewErrAdapter("olt-reenable-failed", log.Fields{"device-id": dh.device.Id}, err)
Abhilash Laxmeshwar5b302e12020-01-09 15:15:14 +05302090 }
2091 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002092 logger.Debug(ctx, "olt-reenabled")
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002093
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002094 // Update the all ports state on that device to enable
khenaidoo106c61a2021-08-11 18:05:46 -04002095 ports, err := dh.listDevicePortsFromCore(ctx, device.Id)
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002096 var retError error
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002097 if err != nil {
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002098 retError = olterrors.NewErrAdapter("list-ports-failed", log.Fields{"device-id": device.Id}, err)
2099 } else {
2100 if err := dh.disableAdminDownPorts(ctx, ports.Items); err != nil {
2101 retError = olterrors.NewErrAdapter("port-status-update-failed-after-olt-reenable", log.Fields{"device": device}, err)
2102 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002103 }
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002104 if retError == nil {
2105 //Update the device oper status as ACTIVE
2106 device.OperStatus = voltha.OperStatus_ACTIVE
2107 } else {
2108 //Update the device oper status as FAILED
2109 device.OperStatus = voltha.OperStatus_FAILED
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002110 }
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002111 dh.device = device
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002112
khenaidoodc2116e2021-10-19 17:33:19 -04002113 if err := dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002114 DeviceId: device.Id,
2115 OperStatus: device.OperStatus,
2116 ConnStatus: device.ConnectStatus,
2117 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302118 return olterrors.NewErrAdapter("state-update-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002119 "device-id": device.Id,
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002120 "connect-status": device.ConnectStatus,
2121 "oper-status": device.OperStatus}, err)
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002122 }
kesavand39e0aa32020-01-28 20:58:50 -05002123
Neha Sharma96b7bf22020-06-15 10:37:32 +00002124 logger.Debugw(ctx, "reenabledevice-end", log.Fields{"device-id": device.Id})
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002125
Mahir Gunyele5e807a2021-10-22 11:33:25 -07002126 return retError
Girish Gowdru5ba46c92019-04-25 05:00:05 -04002127}
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002128
npujarec5762e2020-01-01 14:08:48 +05302129func (dh *DeviceHandler) clearUNIData(ctx context.Context, onu *rsrcMgr.OnuGemInfo) error {
Devmalya Paul495b94a2019-08-27 19:42:00 -04002130 var uniID uint32
2131 var err error
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302132 for _, port := range onu.UniPorts {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002133 uniID = plt.UniIDFromPortNum(port)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002134 logger.Debugw(ctx, "clearing-resource-data-for-uni-port", log.Fields{"port": port, "uni-id": uniID})
A R Karthick1f85b802019-10-11 05:06:05 +00002135 /* Delete tech-profile instance from the KV store */
Girish Gowdraa09aeab2020-09-14 16:30:52 -07002136 if err = dh.flowMgr[onu.IntfID].DeleteTechProfileInstances(ctx, onu.IntfID, onu.OnuID, uniID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002137 logger.Debugw(ctx, "failed-to-remove-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
Devmalya Paul495b94a2019-08-27 19:42:00 -04002138 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002139 logger.Debugw(ctx, "deleted-tech-profile-instance-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002140 tpIDList := dh.resourceMgr[onu.IntfID].GetTechProfileIDForOnu(ctx, onu.OnuID, uniID)
Gamze Abakafee36392019-10-03 11:17:24 +00002141 for _, tpID := range tpIDList {
yasin saplibddc2d72022-02-08 13:10:17 +00002142 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "upstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002143 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
Gamze Abakafee36392019-10-03 11:17:24 +00002144 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002145 logger.Debugw(ctx, "removed-meter-id-for-onu-upstream", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002146 if err = dh.resourceMgr[onu.IntfID].RemoveMeterInfoForOnu(ctx, "downstream", onu.OnuID, uniID, tpID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002147 logger.Debugw(ctx, "failed-to-remove-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Gamze Abakafee36392019-10-03 11:17:24 +00002148 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002149 logger.Debugw(ctx, "removed-meter-id-for-onu-downstream", log.Fields{"onu-id": onu.OnuID})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302150 }
yasin saplibddc2d72022-02-08 13:10:17 +00002151 dh.resourceMgr[onu.IntfID].FreePONResourcesForONU(ctx, onu.OnuID, uniID)
2152 if err = dh.resourceMgr[onu.IntfID].RemoveTechProfileIDsForOnu(ctx, onu.OnuID, uniID); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002153 logger.Debugw(ctx, "failed-to-remove-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302154 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002155 logger.Debugw(ctx, "removed-tech-profile-id-for-onu", log.Fields{"onu-id": onu.OnuID})
yasin saplibddc2d72022-02-08 13:10:17 +00002156 if err = dh.resourceMgr[onu.IntfID].DeletePacketInGemPortForOnu(ctx, onu.OnuID, port); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002157 logger.Debugw(ctx, "failed-to-remove-gemport-pkt-in", log.Fields{"intfid": onu.IntfID, "onuid": onu.OnuID, "uniId": uniID})
A R Karthick1f85b802019-10-11 05:06:05 +00002158 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002159 }
2160 return nil
2161}
2162
Devmalya Paul495b94a2019-08-27 19:42:00 -04002163// 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 +05302164func (dh *DeviceHandler) DeleteDevice(ctx context.Context, device *voltha.Device) error {
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002165 logger.Debugw(ctx, "function-entry-delete-device", log.Fields{"device-id": dh.device.Id})
Devmalya Paul495b94a2019-08-27 19:42:00 -04002166 /* Clear the KV store data associated with the all the UNI ports
2167 This clears up flow data and also resource map data for various
2168 other pon resources like alloc_id and gemport_id
2169 */
Girish Gowdra950326e2021-11-05 12:43:24 -07002170
2171 dh.setDeviceDeletionInProgressFlag(true)
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08002172 var wg sync.WaitGroup
2173 wg.Add(1) // for the mcast routine below to finish
2174 go dh.StopAllMcastHandlerRoutines(ctx, &wg)
2175 for _, flMgr := range dh.flowMgr {
2176 wg.Add(1) // for the flow handler routine below to finish
2177 go flMgr.StopAllFlowHandlerRoutines(ctx, &wg)
2178 }
2179 if !dh.waitForTimeoutOrCompletion(&wg, time.Second*30) {
2180 logger.Warnw(ctx, "timed out waiting for stopping flow and group handlers", log.Fields{"deviceID": device.Id})
2181 } else {
2182 logger.Infow(ctx, "all flow and group handlers shutdown gracefully", log.Fields{"deviceID": device.Id})
2183 }
Girish Gowdra950326e2021-11-05 12:43:24 -07002184
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002185 dh.cleanupDeviceResources(ctx)
2186 logger.Debugw(ctx, "removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002187
Himani Chawla49a5d562020-11-25 11:53:44 +05302188 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002189 // Stop the Stats collector
2190 if dh.isCollectorActive {
2191 dh.stopCollector <- true
2192 }
2193 // stop the heartbeat check routine
2194 if dh.isHeartbeatCheckActive {
2195 dh.stopHeartbeatCheck <- true
2196 }
Himani Chawla49a5d562020-11-25 11:53:44 +05302197 // Stop the read indication only if it the routine is active
2198 if dh.isReadIndicationRoutineActive {
2199 dh.stopIndications <- true
2200 }
2201 dh.lockDevice.RUnlock()
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002202 dh.removeOnuIndicationChannels(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002203 //Reset the state
2204 if dh.Client != nil {
2205 if _, err := dh.Client.Reboot(ctx, new(oop.Empty)); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05302206 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002207 }
2208 }
Girish Gowdrab1caa442020-10-19 12:24:39 -07002209 // There is no need to update the core about operation status and connection status of the OLT.
2210 // The OLT is getting deleted anyway and the core might have already cleared the OLT device from its DB.
2211 // So any attempt to update the operation status and connection status of the OLT will result in core throwing an error back,
2212 // because the device does not exist in DB.
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002213
khenaidoo7eb2d672021-10-22 19:08:50 -04002214 // Stop the adapter grpc clients for that parent device
2215 dh.deleteAdapterClients(ctx)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002216 return nil
2217}
Kent Hagermane6ff1012020-07-14 15:07:53 -04002218func (dh *DeviceHandler) cleanupDeviceResources(ctx context.Context) {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002219
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002220 if dh.resourceMgr != nil {
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302221 var ponPort uint32
Girish Gowdra9602eb42020-09-09 15:50:39 -07002222 for ponPort = 0; ponPort < dh.totalPonPorts; ponPort++ {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002223 var err error
yasin sapli9e4c5092022-02-01 13:52:33 +00002224 onuGemData := dh.resourceMgr[ponPort].GetOnuGemInfoList(ctx)
Andrey Pozolotin32b36562021-06-02 10:23:26 +03002225 for i, onu := range onuGemData {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002226 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
Andrey Pozolotin32b36562021-06-02 10:23:26 +03002227 if err = dh.clearUNIData(ctx, &onuGemData[i]); err != nil {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002228 logger.Errorw(ctx, "failed-to-clear-data-for-onu", log.Fields{"onu-device": onu})
Abhilash Laxmeshwarab0bd522019-10-21 15:05:15 +05302229 }
2230 }
yasin saplibddc2d72022-02-08 13:10:17 +00002231 _ = dh.resourceMgr[ponPort].DeleteAllFlowIDsForGemForIntf(ctx)
2232 _ = dh.resourceMgr[ponPort].DeleteAllOnuGemInfoForIntf(ctx)
Girish Gowdraf3728b12022-02-02 21:46:51 -08002233 dh.resourceMgr[ponPort].DeleteMcastQueueForIntf(ctx)
Girish Gowdrab8f1b5a2021-06-27 20:42:40 -07002234 if err := dh.resourceMgr[ponPort].Delete(ctx, ponPort); err != nil {
2235 logger.Debug(ctx, err)
2236 }
Devmalya Paul495b94a2019-08-27 19:42:00 -04002237 }
yasin saplibddc2d72022-02-08 13:10:17 +00002238 // Clean up NNI manager's data
2239 _ = dh.resourceMgr[dh.totalPonPorts].DeleteAllFlowIDsForGemForIntf(ctx)
Serkant Uluderya89ff40c2019-10-17 16:02:25 -07002240 }
A R Karthick1f85b802019-10-11 05:06:05 +00002241
Girish Gowdra0f3190e2022-02-11 14:18:28 -08002242 // Take one final sweep at cleaning up KV store for the OLT device
2243 // Clean everything at <base-path-prefix>/openolt/<device-id>
2244 kvClient, err := kvstore.NewEtcdClient(ctx, dh.openOLT.KVStoreAddress, rsrcMgr.KvstoreTimeout, log.FatalLevel)
2245 if err == nil {
2246 kvBackend := &db.Backend{
2247 Client: kvClient,
2248 StoreType: dh.openOLT.KVStoreType,
2249 Address: dh.openOLT.KVStoreAddress,
2250 Timeout: rsrcMgr.KvstoreTimeout,
2251 PathPrefix: fmt.Sprintf(rsrcMgr.BasePathKvStore, dh.cm.Backend.PathPrefix, dh.device.Id)}
2252 _ = kvBackend.DeleteWithPrefix(ctx, "")
2253 }
2254
Devmalya Paul495b94a2019-08-27 19:42:00 -04002255 /*Delete ONU map for the device*/
Naga Manjunatha8dc9372019-10-31 23:01:18 +05302256 dh.onus.Range(func(key interface{}, value interface{}) bool {
2257 dh.onus.Delete(key)
2258 return true
2259 })
2260
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002261 /*Delete discovered ONU map for the device*/
2262 dh.discOnus.Range(func(key interface{}, value interface{}) bool {
2263 dh.discOnus.Delete(key)
2264 return true
2265 })
Devmalya Paul495b94a2019-08-27 19:42:00 -04002266}
2267
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002268//RebootDevice reboots the given device
Neha Sharma96b7bf22020-06-15 10:37:32 +00002269func (dh *DeviceHandler) RebootDevice(ctx context.Context, device *voltha.Device) error {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002270 if _, err := dh.Client.Reboot(log.WithSpanFromContext(context.Background(), ctx), new(oop.Empty)); err != nil {
Thomas Lee S985938d2020-05-04 11:40:41 +05302271 return olterrors.NewErrAdapter("olt-reboot-failed", log.Fields{"device-id": dh.device.Id}, err)
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002272 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002273 logger.Debugw(ctx, "rebooted-device-successfully", log.Fields{"device-id": device.Id})
Girish Gowdru0fe5f7e2019-05-28 05:12:27 -04002274 return nil
2275}
2276
David K. Bainbridge794735f2020-02-11 21:01:37 -08002277func (dh *DeviceHandler) handlePacketIndication(ctx context.Context, packetIn *oop.PacketIndication) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002278 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002279 logger.Debugw(ctx, "received-packet-in", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002280 "packet-indication": *packetIn,
2281 "device-id": dh.device.Id,
2282 "packet": hex.EncodeToString(packetIn.Pkt),
2283 })
2284 }
Girish Gowdra9602eb42020-09-09 15:50:39 -07002285 logicalPortNum, err := dh.flowMgr[packetIn.IntfId].GetLogicalPortFromPacketIn(ctx, packetIn)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002286 if err != nil {
Girish Kumarf26e4882020-03-05 06:49:10 +00002287 return olterrors.NewErrNotFound("logical-port", log.Fields{"packet": hex.EncodeToString(packetIn.Pkt)}, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002288 }
Matteo Scandolo92186242020-06-12 10:54:18 -07002289 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002290 logger.Debugw(ctx, "sending-packet-in-to-core", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002291 "logical-port-num": logicalPortNum,
2292 "device-id": dh.device.Id,
2293 "packet": hex.EncodeToString(packetIn.Pkt),
2294 })
2295 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002296
khenaidoodc2116e2021-10-19 17:33:19 -04002297 if err := dh.sendPacketToCore(ctx, &ca.PacketIn{
khenaidoo106c61a2021-08-11 18:05:46 -04002298 DeviceId: dh.device.Id,
2299 Port: logicalPortNum,
2300 Packet: packetIn.Pkt,
2301 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302302 return olterrors.NewErrCommunication("send-packet-in", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002303 "destination": "core",
Thomas Lee S985938d2020-05-04 11:40:41 +05302304 "source": dh.device.Type,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002305 "device-id": dh.device.Id,
2306 "packet": hex.EncodeToString(packetIn.Pkt),
2307 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002308 }
Neha Sharma96b7bf22020-06-15 10:37:32 +00002309
Matteo Scandolo92186242020-06-12 10:54:18 -07002310 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002311 logger.Debugw(ctx, "success-sending-packet-in-to-core!", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002312 "packet": hex.EncodeToString(packetIn.Pkt),
2313 "device-id": dh.device.Id,
2314 })
2315 }
David K. Bainbridge794735f2020-02-11 21:01:37 -08002316 return nil
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002317}
2318
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002319// PacketOut sends packet-out from VOLTHA to OLT on the egress port provided
khenaidoo106c61a2021-08-11 18:05:46 -04002320func (dh *DeviceHandler) PacketOut(ctx context.Context, egressPortNo uint32, packet *of.OfpPacketOut) error {
Matteo Scandolo92186242020-06-12 10:54:18 -07002321 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002322 logger.Debugw(ctx, "incoming-packet-out", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002323 "device-id": dh.device.Id,
2324 "egress-port-no": egressPortNo,
2325 "pkt-length": len(packet.Data),
2326 "packet": hex.EncodeToString(packet.Data),
2327 })
2328 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002329
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002330 egressPortType := plt.IntfIDToPortTypeName(uint32(egressPortNo))
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002331 if egressPortType == voltha.Port_ETHERNET_UNI {
Matt Jeanneret1359c732019-08-01 21:40:02 -04002332 outerEthType := (uint16(packet.Data[12]) << 8) | uint16(packet.Data[13])
2333 innerEthType := (uint16(packet.Data[16]) << 8) | uint16(packet.Data[17])
Girish Gowdra6e1534a2019-11-15 19:24:04 +05302334 if outerEthType == 0x8942 || outerEthType == 0x88cc {
2335 // Do not packet-out lldp packets on uni port.
2336 // ONOS has no clue about uni/nni ports, it just packets out on all
2337 // available ports on the Logical Switch. It should not be interested
2338 // in the UNI links.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002339 logger.Debugw(ctx, "dropping-lldp-packet-out-on-uni", log.Fields{
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002340 "device-id": dh.device.Id,
2341 })
Girish Gowdra6e1534a2019-11-15 19:24:04 +05302342 return nil
2343 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002344 if outerEthType == 0x88a8 || outerEthType == 0x8100 {
2345 if innerEthType == 0x8100 {
2346 // q-in-q 802.1ad or 802.1q double tagged packet.
2347 // slice out the outer tag.
2348 packet.Data = append(packet.Data[:12], packet.Data[16:]...)
Matteo Scandolo92186242020-06-12 10:54:18 -07002349 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002350 logger.Debugw(ctx, "packet-now-single-tagged", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002351 "packet-data": hex.EncodeToString(packet.Data),
2352 "device-id": dh.device.Id,
2353 })
2354 }
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002355 }
2356 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002357 intfID := plt.IntfIDFromUniPortNum(uint32(egressPortNo))
2358 onuID := plt.OnuIDFromPortNum(uint32(egressPortNo))
2359 uniID := plt.UniIDFromPortNum(uint32(egressPortNo))
Manikkaraj kb1d51442019-07-23 10:41:02 -04002360
Girish Gowdra9602eb42020-09-09 15:50:39 -07002361 gemPortID, err := dh.flowMgr[intfID].GetPacketOutGemPortID(ctx, intfID, onuID, uint32(egressPortNo), packet.Data)
Manikkaraj kb1d51442019-07-23 10:41:02 -04002362 if err != nil {
2363 // In this case the openolt agent will receive the gemPortID as 0.
2364 // The agent tries to retrieve the gemPortID in this case.
2365 // This may not always succeed at the agent and packetOut may fail.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002366 logger.Errorw(ctx, "failed-to-retrieve-gemport-id-for-packet-out", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002367 "intf-id": intfID,
2368 "onu-id": onuID,
2369 "uni-id": uniID,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002370 "packet": hex.EncodeToString(packet.Data),
Thomas Lee S985938d2020-05-04 11:40:41 +05302371 "device-id": dh.device.Id,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002372 })
Manikkaraj kb1d51442019-07-23 10:41:02 -04002373 }
2374
2375 onuPkt := oop.OnuPacket{IntfId: intfID, OnuId: onuID, PortNo: uint32(egressPortNo), GemportId: gemPortID, Pkt: packet.Data}
Matteo Scandolo92186242020-06-12 10:54:18 -07002376 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002377 logger.Debugw(ctx, "sending-packet-to-onu", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002378 "egress-port-no": egressPortNo,
2379 "intf-id": intfID,
2380 "onu-id": onuID,
2381 "uni-id": uniID,
2382 "gem-port-id": gemPortID,
2383 "packet": hex.EncodeToString(packet.Data),
2384 "device-id": dh.device.Id,
2385 })
2386 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002387
npujarec5762e2020-01-01 14:08:48 +05302388 if _, err := dh.Client.OnuPacketOut(ctx, &onuPkt); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302389 return olterrors.NewErrCommunication("packet-out-send", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002390 "source": "adapter",
2391 "destination": "onu",
2392 "egress-port-number": egressPortNo,
Matteo Scandolo92186242020-06-12 10:54:18 -07002393 "intf-id": intfID,
David K. Bainbridge794735f2020-02-11 21:01:37 -08002394 "oni-id": onuID,
2395 "uni-id": uniID,
2396 "gem-port-id": gemPortID,
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002397 "packet": hex.EncodeToString(packet.Data),
2398 "device-id": dh.device.Id,
2399 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002400 }
2401 } else if egressPortType == voltha.Port_ETHERNET_NNI {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002402 nniIntfID, err := plt.IntfIDFromNniPortNum(ctx, uint32(egressPortNo))
David K. Bainbridge794735f2020-02-11 21:01:37 -08002403 if err != nil {
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002404 return olterrors.NewErrInvalidValue(log.Fields{
2405 "egress-nni-port": egressPortNo,
2406 "device-id": dh.device.Id,
2407 }, err)
David K. Bainbridge794735f2020-02-11 21:01:37 -08002408 }
2409 uplinkPkt := oop.UplinkPacket{IntfId: nniIntfID, Pkt: packet.Data}
Matt Jeanneret1359c732019-08-01 21:40:02 -04002410
Matteo Scandolo92186242020-06-12 10:54:18 -07002411 if logger.V(log.DebugLevel) {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002412 logger.Debugw(ctx, "sending-packet-to-nni", log.Fields{
Matteo Scandolo92186242020-06-12 10:54:18 -07002413 "uplink-pkt": uplinkPkt,
2414 "packet": hex.EncodeToString(packet.Data),
2415 "device-id": dh.device.Id,
2416 })
2417 }
Matt Jeanneret1359c732019-08-01 21:40:02 -04002418
npujarec5762e2020-01-01 14:08:48 +05302419 if _, err := dh.Client.UplinkPacketOut(ctx, &uplinkPkt); err != nil {
Matteo Scandolod625b4c2020-04-02 16:16:01 -07002420 return olterrors.NewErrCommunication("packet-out-to-nni", log.Fields{
2421 "packet": hex.EncodeToString(packet.Data),
2422 "device-id": dh.device.Id,
2423 }, err)
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002424 }
2425 } else {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002426 logger.Warnw(ctx, "packet-out-to-this-interface-type-not-implemented", log.Fields{
Shrey Baid807a2a02020-04-09 12:52:45 +05302427 "egress-port-no": egressPortNo,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002428 "egressPortType": egressPortType,
2429 "packet": hex.EncodeToString(packet.Data),
Thomas Lee S985938d2020-05-04 11:40:41 +05302430 "device-id": dh.device.Id,
Matteo Scandolo6056e822019-11-13 14:05:29 -08002431 })
manikkaraj k9eb6cac2019-05-09 12:32:03 -04002432 }
2433 return nil
2434}
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002435
Girish Gowdru6a80bbd2019-07-02 07:36:09 -07002436func (dh *DeviceHandler) formOnuKey(intfID, onuID uint32) string {
2437 return "" + strconv.Itoa(int(intfID)) + "." + strconv.Itoa(int(onuID))
Mahir Gunyela3f9add2019-06-06 15:13:19 -07002438}
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302439
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002440func startHeartbeatCheck(ctx context.Context, dh *DeviceHandler) {
Neha Sharma8f4e4322020-08-06 10:51:53 +00002441
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002442 defer func() {
2443 dh.lockDevice.Lock()
2444 dh.isHeartbeatCheckActive = false
2445 dh.lockDevice.Unlock()
2446 }()
2447
2448 dh.lockDevice.Lock()
2449 dh.isHeartbeatCheckActive = true
2450 dh.lockDevice.Unlock()
2451
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302452 // start the heartbeat check towards the OLT.
2453 var timerCheck *time.Timer
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302454 dh.heartbeatSignature = dh.getHeartbeatSignature(ctx)
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302455
2456 for {
2457 heartbeatTimer := time.NewTimer(dh.openOLT.HeartbeatCheckInterval)
2458 select {
2459 case <-heartbeatTimer.C:
Neha Sharma8f4e4322020-08-06 10:51:53 +00002460 ctxWithTimeout, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.openOLT.GrpcTimeoutInterval)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002461 if heartBeat, err := dh.Client.HeartbeatCheck(ctxWithTimeout, new(oop.Empty)); err != nil {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002462 logger.Warnw(ctx, "heartbeat-failed", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302463 if timerCheck == nil {
2464 // start a after func, when expired will update the state to the core
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002465 timerCheck = time.AfterFunc(dh.openOLT.HeartbeatFailReportInterval, func() { dh.updateStateUnreachable(ctx) })
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302466 }
2467 } else {
2468 if timerCheck != nil {
2469 if timerCheck.Stop() {
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002470 logger.Debugw(ctx, "got-heartbeat-within-timeout", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302471 }
2472 timerCheck = nil
2473 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302474 if dh.heartbeatSignature == 0 || dh.heartbeatSignature == heartBeat.HeartbeatSignature {
2475 if dh.heartbeatSignature == 0 {
2476 // First time the signature will be 0, update the signture to DB when not found.
2477 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
2478 dh.heartbeatSignature = heartBeat.HeartbeatSignature
2479 }
2480 logger.Infow(ctx, "heartbeat signature", log.Fields{"sign": dh.heartbeatSignature})
2481
2482 dh.lockDevice.RLock()
2483 // Stop the read indication only if it the routine is active
2484 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2485 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2486 // on next execution of the readIndication routine.
2487 if !dh.isReadIndicationRoutineActive {
2488 // Start reading indications
2489 go func() {
2490 if err = dh.readIndications(ctx); err != nil {
2491 _ = olterrors.NewErrAdapter("indication-read-failure", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
2492 }
2493 }()
2494 }
2495 dh.lockDevice.RUnlock()
2496
2497 } else {
2498 logger.Warn(ctx, "Heartbeat signature changed, OLT is rebooted. Cleaningup resources.")
2499 dh.updateHeartbeatSignature(ctx, heartBeat.HeartbeatSignature)
2500 dh.heartbeatSignature = heartBeat.HeartbeatSignature
2501 go dh.updateStateRebooted(ctx)
2502 }
2503
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302504 }
2505 cancel()
2506 case <-dh.stopHeartbeatCheck:
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002507 logger.Debugw(ctx, "stopping-heartbeat-check", log.Fields{"device-id": dh.device.Id})
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302508 return
2509 }
2510 }
2511}
2512
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002513func (dh *DeviceHandler) updateStateUnreachable(ctx context.Context) {
khenaidoo106c61a2021-08-11 18:05:46 -04002514 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002515 if err != nil || device == nil {
Girish Gowdrab1caa442020-10-19 12:24:39 -07002516 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
2517 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
2518 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
2519 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
2520 // cleanup in the adapter was already done during DeleteDevice API handler routine.
Kent Hagermane6ff1012020-07-14 15:07:53 -04002521 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
Girish Gowdrab1caa442020-10-19 12:24:39 -07002522 // Immediately return, otherwise accessing a null 'device' struct would cause panic
2523 return
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002524 }
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302525
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302526 logger.Warnw(ctx, "update-state-unreachable", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
Matteo Scandolo861e06e2021-05-26 11:51:46 -07002527 "admin-state": device.AdminState, "oper-status": device.OperStatus})
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002528 if device.ConnectStatus == voltha.ConnectStatus_REACHABLE {
khenaidoodc2116e2021-10-19 17:33:19 -04002529 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
khenaidoo106c61a2021-08-11 18:05:46 -04002530 DeviceId: dh.device.Id,
2531 OperStatus: voltha.OperStatus_UNKNOWN,
2532 ConnStatus: voltha.ConnectStatus_UNREACHABLE,
2533 }); err != nil {
Kent Hagermane6ff1012020-07-14 15:07:53 -04002534 _ = 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 -04002535 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302536 /*
2537 if err = dh.updatePortsStateInCore(ctx, &ca.PortStateFilter{
2538 DeviceId: dh.device.Id,
2539 PortTypeFilter: 0,
2540 OperStatus: voltha.OperStatus_UNKNOWN,
2541 }); err != nil {
2542 _ = olterrors.NewErrAdapter("port-update-failed", log.Fields{"device-id": dh.device.Id}, err).Log()
2543 }
2544 */
Gamze Abaka07868a52020-12-17 14:19:28 +00002545
2546 //raise olt communication failure event
Girish Gowdrac1b9d5e2021-04-22 12:47:44 -07002547 raisedTs := time.Now().Unix()
khenaidoo106c61a2021-08-11 18:05:46 -04002548 cloned := proto.Clone(device).(*voltha.Device)
2549 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
2550 cloned.OperStatus = voltha.OperStatus_UNKNOWN
2551 dh.device = cloned // update local copy of the device
2552 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
Gamze Abaka07868a52020-12-17 14:19:28 +00002553
Girish Gowdra3ab6d212020-03-24 17:33:15 -07002554 dh.lockDevice.RLock()
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002555 // Stop the Stats collector
2556 if dh.isCollectorActive {
2557 dh.stopCollector <- true
2558 }
2559 // stop the heartbeat check routine
2560 if dh.isHeartbeatCheckActive {
2561 dh.stopHeartbeatCheck <- true
2562 }
Girish Gowdra3ab6d212020-03-24 17:33:15 -07002563 // Stop the read indication only if it the routine is active
2564 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2565 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2566 // on next execution of the readIndication routine.
2567 if dh.isReadIndicationRoutineActive {
2568 dh.stopIndications <- true
2569 }
2570 dh.lockDevice.RUnlock()
Chaitrashree G Sa4649252020-03-11 21:24:11 -04002571 dh.transitionMap.Handle(ctx, DeviceInit)
2572
Abhilash Laxmeshwarf9942e92020-01-07 15:32:44 +05302573 }
2574}
kesavand39e0aa32020-01-28 20:58:50 -05002575
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302576func (dh *DeviceHandler) updateStateRebooted(ctx context.Context) {
2577 device, err := dh.getDeviceFromCore(ctx, dh.device.Id)
2578 if err != nil || device == nil {
2579 // One case where we have seen core returning an error for GetDevice call is after OLT device delete.
2580 // After OLT delete, the adapter asks for OLT to reboot. When OLT is rebooted, shortly we loose heartbeat.
2581 // The 'startHeartbeatCheck' then asks the device to be marked unreachable towards the core, but the core
2582 // has already deleted the device and returns error. In this particular scenario, it is Ok because any necessary
2583 // cleanup in the adapter was already done during DeleteDevice API handler routine.
2584 _ = olterrors.NewErrNotFound("device", log.Fields{"device-id": dh.device.Id}, err).Log()
2585 // Immediately return, otherwise accessing a null 'device' struct would cause panic
2586 return
2587 }
2588
2589 logger.Warnw(ctx, "update-state-rebooted", log.Fields{"device-id": dh.device.Id, "connect-status": device.ConnectStatus,
2590 "admin-state": device.AdminState, "oper-status": device.OperStatus, "conn-status": voltha.ConnectStatus_UNREACHABLE})
2591 if err = dh.updateDeviceStateInCore(ctx, &ca.DeviceStateFilter{
2592 DeviceId: dh.device.Id,
2593 OperStatus: voltha.OperStatus_REBOOTED,
2594 ConnStatus: voltha.ConnectStatus_REACHABLE,
2595 }); err != nil {
2596 _ = olterrors.NewErrAdapter("device-state-update-failed", log.Fields{"device-id": dh.device.Id}, err).LogAt(log.ErrorLevel)
2597 }
2598
2599 dh.lockDevice.RLock()
2600 // Stop the read indication only if it the routine is active
2601 // The read indication would have already stopped due to failure on the gRPC stream following OLT going unreachable
2602 // Sending message on the 'stopIndication' channel again will cause the readIndication routine to immediately stop
2603 // on next execution of the readIndication routine.
2604 if dh.isReadIndicationRoutineActive {
2605 dh.stopIndications <- true
2606 }
2607 dh.lockDevice.RUnlock()
2608
2609 //raise olt communication failure event
2610 raisedTs := time.Now().Unix()
2611 cloned := proto.Clone(device).(*voltha.Device)
2612 cloned.ConnectStatus = voltha.ConnectStatus_UNREACHABLE
2613 cloned.OperStatus = voltha.OperStatus_UNKNOWN
2614 dh.device = cloned // update local copy of the device
2615 go dh.eventMgr.oltCommunicationEvent(ctx, cloned, raisedTs)
2616
2617 dh.cleanupDeviceResources(ctx)
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002618
2619 dh.lockDevice.RLock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302620 // Stop the Stats collector
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002621 if dh.isCollectorActive {
2622 dh.stopCollector <- true
2623 }
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302624 // stop the heartbeat check routine
Holger Hildebrandte6c877b2022-09-15 13:51:39 +00002625 if dh.isHeartbeatCheckActive {
2626 dh.stopHeartbeatCheck <- true
2627 }
2628 dh.lockDevice.RUnlock()
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05302629
2630 var wg sync.WaitGroup
2631 wg.Add(1) // for the multicast handler routine
2632 go dh.StopAllMcastHandlerRoutines(ctx, &wg)
2633 for _, flMgr := range dh.flowMgr {
2634 wg.Add(1) // for the flow handler routine
2635 go flMgr.StopAllFlowHandlerRoutines(ctx, &wg)
2636 }
2637 if !dh.waitForTimeoutOrCompletion(&wg, time.Second*30) {
2638 logger.Warnw(ctx, "timed out waiting for stopping flow and group handlers", log.Fields{"deviceID": device.Id})
2639 } else {
2640 logger.Infow(ctx, "all flow and group handlers shutdown gracefully", log.Fields{"deviceID": device.Id})
2641 }
2642
2643 //reset adapter reconcile flag
2644 dh.adapterPreviouslyConnected = false
2645 for {
2646
2647 childDevices, err := dh.getChildDevicesFromCore(ctx, dh.device.Id)
2648 if err != nil || childDevices == nil {
2649 logger.Errorw(ctx, "Failed to get child devices from core", log.Fields{"deviceID": dh.device.Id})
2650 continue
2651 }
2652 if len(childDevices.Items) == 0 {
2653 logger.Infow(ctx, "All childDevices cleared from core, proceed with device init", log.Fields{"deviceID": dh.device.Id})
2654 break
2655 } else {
2656 logger.Warn(ctx, "Not all child devices are cleared, continuing to wait")
2657 time.Sleep(5 * time.Second)
2658 }
2659
2660 }
2661 logger.Infow(ctx, "cleanup complete after reboot , moving to init", log.Fields{"deviceID": device.Id})
2662 dh.transitionMap.Handle(ctx, DeviceInit)
2663
2664}
2665
kesavand39e0aa32020-01-28 20:58:50 -05002666// EnablePort to enable Pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00002667func (dh *DeviceHandler) EnablePort(ctx context.Context, port *voltha.Port) error {
2668 logger.Debugw(ctx, "enable-port", log.Fields{"Device": dh.device, "port": port})
2669 return dh.modifyPhyPort(ctx, port, true)
kesavand39e0aa32020-01-28 20:58:50 -05002670}
2671
2672// DisablePort to disable pon interface
Neha Sharma96b7bf22020-06-15 10:37:32 +00002673func (dh *DeviceHandler) DisablePort(ctx context.Context, port *voltha.Port) error {
2674 logger.Debugw(ctx, "disable-port", log.Fields{"Device": dh.device, "port": port})
2675 return dh.modifyPhyPort(ctx, port, false)
kesavand39e0aa32020-01-28 20:58:50 -05002676}
2677
kdarapu1afeceb2020-02-12 01:38:09 -05002678//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 +00002679func (dh *DeviceHandler) modifyPhyPort(ctx context.Context, port *voltha.Port, enablePort bool) error {
2680 logger.Infow(ctx, "modifyPhyPort", log.Fields{"port": port, "Enable": enablePort, "device-id": dh.device.Id})
kesavand39e0aa32020-01-28 20:58:50 -05002681 if port.GetType() == voltha.Port_ETHERNET_NNI {
2682 // Bug is opened for VOL-2505 to support NNI disable feature.
Neha Sharma96b7bf22020-06-15 10:37:32 +00002683 logger.Infow(ctx, "voltha-supports-single-nni-hence-disable-of-nni-not-allowed",
Shrey Baid807a2a02020-04-09 12:52:45 +05302684 log.Fields{"device": dh.device, "port": port})
Thomas Lee S94109f12020-03-03 16:39:29 +05302685 return olterrors.NewErrAdapter("illegal-port-request", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002686 "port-type": port.GetType,
Girish Kumarf26e4882020-03-05 06:49:10 +00002687 "enable-state": enablePort}, nil)
kesavand39e0aa32020-01-28 20:58:50 -05002688 }
2689 // fetch interfaceid from PortNo
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002690 ponID := plt.PortNoToIntfID(port.GetPortNo(), voltha.Port_PON_OLT)
kesavand39e0aa32020-01-28 20:58:50 -05002691 ponIntf := &oop.Interface{IntfId: ponID}
2692 var operStatus voltha.OperStatus_Types
2693 if enablePort {
2694 operStatus = voltha.OperStatus_ACTIVE
npujarec5762e2020-01-01 14:08:48 +05302695 out, err := dh.Client.EnablePonIf(ctx, ponIntf)
kesavand39e0aa32020-01-28 20:58:50 -05002696
2697 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302698 return olterrors.NewErrAdapter("pon-port-enable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002699 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002700 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05002701 }
2702 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05002703 dh.activePorts.Store(ponID, true)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002704 logger.Infow(ctx, "enabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05002705 } else {
2706 operStatus = voltha.OperStatus_UNKNOWN
npujarec5762e2020-01-01 14:08:48 +05302707 out, err := dh.Client.DisablePonIf(ctx, ponIntf)
kesavand39e0aa32020-01-28 20:58:50 -05002708 if err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302709 return olterrors.NewErrAdapter("pon-port-disable-failed", log.Fields{
David K. Bainbridge794735f2020-02-11 21:01:37 -08002710 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002711 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05002712 }
2713 // updating interface local cache for collecting stats
Chaitrashree G Sef088112020-02-03 21:39:27 -05002714 dh.activePorts.Store(ponID, false)
Neha Sharma96b7bf22020-06-15 10:37:32 +00002715 logger.Infow(ctx, "disabled-pon-port", log.Fields{"out": out, "device-id": dh.device, "Port": port})
kesavand39e0aa32020-01-28 20:58:50 -05002716 }
khenaidoodc2116e2021-10-19 17:33:19 -04002717 if err := dh.updatePortStateInCore(ctx, &ca.PortState{
khenaidoo106c61a2021-08-11 18:05:46 -04002718 DeviceId: dh.device.Id,
2719 PortType: voltha.Port_PON_OLT,
2720 PortNo: port.PortNo,
2721 OperStatus: operStatus,
2722 }); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302723 return olterrors.NewErrAdapter("port-state-update-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05302724 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002725 "port": port.PortNo}, err)
kesavand39e0aa32020-01-28 20:58:50 -05002726 }
2727 return nil
2728}
2729
kdarapu1afeceb2020-02-12 01:38:09 -05002730//disableAdminDownPorts disables the ports, if the corresponding port Adminstate is disabled on reboot and Renable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002731func (dh *DeviceHandler) disableAdminDownPorts(ctx context.Context, ports []*voltha.Port) error {
kesavand39e0aa32020-01-28 20:58:50 -05002732 // Disable the port and update the oper_port_status to core
2733 // if the Admin state of the port is disabled on reboot and re-enable device.
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002734 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05002735 if port.AdminState == common.AdminState_DISABLED {
Neha Sharma96b7bf22020-06-15 10:37:32 +00002736 if err := dh.DisablePort(ctx, port); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302737 return olterrors.NewErrAdapter("port-disable-failed", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05302738 "device-id": dh.device.Id,
Girish Kumarf26e4882020-03-05 06:49:10 +00002739 "port": port}, err)
kesavand39e0aa32020-01-28 20:58:50 -05002740 }
2741 }
2742 }
2743 return nil
2744}
2745
2746//populateActivePorts to populate activePorts map
Kent Hagermanf1db18b2020-07-08 13:38:15 -04002747func (dh *DeviceHandler) populateActivePorts(ctx context.Context, ports []*voltha.Port) {
2748 logger.Infow(ctx, "populateActivePorts", log.Fields{"device-id": dh.device.Id})
2749 for _, port := range ports {
kesavand39e0aa32020-01-28 20:58:50 -05002750 if port.Type == voltha.Port_ETHERNET_NNI {
2751 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002752 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), true)
kesavand39e0aa32020-01-28 20:58:50 -05002753 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002754 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_ETHERNET_NNI), false)
kesavand39e0aa32020-01-28 20:58:50 -05002755 }
2756 }
2757 if port.Type == voltha.Port_PON_OLT {
2758 if port.OperStatus == voltha.OperStatus_ACTIVE {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002759 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), true)
kesavand39e0aa32020-01-28 20:58:50 -05002760 } else {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002761 dh.activePorts.Store(plt.PortNoToIntfID(port.PortNo, voltha.Port_PON_OLT), false)
kesavand39e0aa32020-01-28 20:58:50 -05002762 }
2763 }
2764 }
2765}
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002766
2767// ChildDeviceLost deletes ONU and clears pon resources related to it.
Girish Gowdraa0870562021-03-11 14:30:14 -08002768func (dh *DeviceHandler) ChildDeviceLost(ctx context.Context, pPortNo uint32, onuID uint32, onuSn string) error {
divyadesai3af43e12020-08-18 07:10:54 +00002769 logger.Debugw(ctx, "child-device-lost", log.Fields{"parent-device-id": dh.device.Id})
Girish Gowdrab4c33302022-03-18 15:07:38 -07002770 if dh.getDeviceDeletionInProgressFlag() {
2771 // Given that the OLT device itself is getting deleted, everything will be cleaned up in the DB and the OLT
2772 // will reboot, so everything will be reset on the pOLT too.
2773 logger.Infow(ctx, "olt-device-delete-in-progress-not-handling-child-device-lost",
2774 log.Fields{"parent-device-id": dh.device.Id, "pon-port": pPortNo, "onuID": onuID, "onuSN": onuSn})
2775 return nil
2776 }
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002777 intfID := plt.PortNoToIntfID(pPortNo, voltha.Port_PON_OLT)
Girish Gowdra89ae6d82020-05-28 23:40:53 -07002778 onuKey := dh.formOnuKey(intfID, onuID)
Girish Gowdraa0870562021-03-11 14:30:14 -08002779
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002780 var sn *oop.SerialNumber
2781 var err error
Girish Gowdraa0870562021-03-11 14:30:14 -08002782 if sn, err = dh.deStringifySerialNumber(onuSn); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302783 return olterrors.NewErrAdapter("failed-to-destringify-serial-number",
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002784 log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05302785 "devicer-id": dh.device.Id,
Girish Gowdraa0870562021-03-11 14:30:14 -08002786 "serial-number": onuSn}, err).Log()
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002787 }
Girish Gowdra89ae6d82020-05-28 23:40:53 -07002788
Girish Gowdra89ae6d82020-05-28 23:40:53 -07002789 onu := &oop.Onu{IntfId: intfID, OnuId: onuID, SerialNumber: sn}
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002790 //clear PON resources associated with ONU
yasin saplibddc2d72022-02-08 13:10:17 +00002791 onuGem, err := dh.resourceMgr[intfID].GetOnuGemInfo(ctx, onuID)
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002792 if err != nil || onuGem == nil || onuGem.OnuID != onuID {
2793 logger.Warnw(ctx, "failed-to-get-onu-info-for-pon-port", log.Fields{
2794 "device-id": dh.device.Id,
2795 "intf-id": intfID,
2796 "onuID": onuID,
2797 "err": err})
2798 } else {
2799 logger.Debugw(ctx, "onu-data", log.Fields{"onu": onu})
yasin saplie87d4bd2021-12-06 09:04:03 +00002800 // Delete flows from device before schedulers and queue
2801 // Clear flowids for gem cache.
2802 removedFlows := []uint64{}
2803 for _, gem := range onuGem.GemPorts {
2804 if flowIDs, err := dh.resourceMgr[intfID].GetFlowIDsForGem(ctx, gem); err == nil {
2805 for _, flowID := range flowIDs {
2806 //multiple gem port can have the same flow id
2807 //it is better to send only one flowRemove request to the agent
2808 var alreadyRemoved bool
2809 for _, removedFlowID := range removedFlows {
2810 if removedFlowID == flowID {
2811 logger.Debugw(ctx, "flow-is-already-removed-due-to-another-gem", log.Fields{"flowID": flowID})
2812 alreadyRemoved = true
2813 break
2814 }
2815 }
2816 if !alreadyRemoved {
2817 flow := &oop.Flow{FlowId: flowID}
2818 if err := dh.flowMgr[intfID].removeFlowFromDevice(ctx, flow, flowID); err != nil {
2819 logger.Warnw(ctx, "failed-to-remove-flow-from-device", log.Fields{
2820 "device-id": dh.device.Id,
2821 "onu-device": onu,
2822 "err": err})
2823 }
2824 removedFlows = appendUnique64bit(removedFlows, flowID)
2825 }
2826 }
2827 }
2828 _ = dh.resourceMgr[intfID].DeleteFlowIDsForGem(ctx, gem)
2829 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002830 if err := dh.clearUNIData(ctx, onuGem); err != nil {
2831 logger.Warnw(ctx, "failed-to-clear-uni-data-for-onu", log.Fields{
2832 "device-id": dh.device.Id,
2833 "onu-device": onu,
2834 "err": err})
2835 }
yasin saplibddc2d72022-02-08 13:10:17 +00002836 if err := dh.resourceMgr[intfID].DelOnuGemInfo(ctx, onuID); err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002837 logger.Warnw(ctx, "persistence-update-onu-gem-info-failed", log.Fields{
2838 "intf-id": intfID,
2839 "onu-device": onu,
2840 "onu-gem": onuGem,
2841 "err": err})
2842 //Not returning error on cleanup.
2843 }
2844 logger.Debugw(ctx, "removed-onu-gem-info", log.Fields{"intf": intfID, "onu-device": onu, "onugem": onuGem})
Himani Chawlabcc95852021-10-27 10:55:40 +05302845
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002846 }
yasin saplibddc2d72022-02-08 13:10:17 +00002847 dh.resourceMgr[intfID].FreeonuID(ctx, []uint32{onuID})
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002848 dh.onus.Delete(onuKey)
2849 dh.discOnus.Delete(onuSn)
2850
2851 // Now clear the ONU on the OLT
Neha Sharma8f4e4322020-08-06 10:51:53 +00002852 if _, err := dh.Client.DeleteOnu(log.WithSpanFromContext(context.Background(), ctx), onu); err != nil {
Thomas Lee S94109f12020-03-03 16:39:29 +05302853 return olterrors.NewErrAdapter("failed-to-delete-onu", log.Fields{
Thomas Lee S985938d2020-05-04 11:40:41 +05302854 "device-id": dh.device.Id,
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002855 "onu-id": onuID}, err).Log()
2856 }
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002857
Chaitrashree G S1a55b882020-02-04 17:35:35 -05002858 return nil
2859}
Girish Gowdracefae192020-03-19 18:14:10 -07002860
2861func getInPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002862 for _, field := range flow_utils.GetOfbFields(flow) {
2863 if field.Type == flow_utils.IN_PORT {
Girish Gowdracefae192020-03-19 18:14:10 -07002864 return field.GetPort()
2865 }
2866 }
2867 return InvalidPort
2868}
2869
2870func getOutPortFromFlow(flow *of.OfpFlowStats) uint32 {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002871 for _, action := range flow_utils.GetActions(flow) {
2872 if action.Type == flow_utils.OUTPUT {
Girish Gowdracefae192020-03-19 18:14:10 -07002873 if out := action.GetOutput(); out != nil {
2874 return out.GetPort()
2875 }
2876 }
2877 }
2878 return InvalidPort
2879}
2880
Girish Gowdracefae192020-03-19 18:14:10 -07002881func getPorts(flow *of.OfpFlowStats) (uint32, uint32) {
2882 inPort := getInPortFromFlow(flow)
2883 outPort := getOutPortFromFlow(flow)
2884
2885 if inPort == InvalidPort || outPort == InvalidPort {
2886 return inPort, outPort
2887 }
2888
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002889 if isControllerFlow := plt.IsControllerBoundFlow(outPort); isControllerFlow {
Girish Gowdracefae192020-03-19 18:14:10 -07002890 /* Get UNI port/ IN Port from tunnel ID field for upstream controller bound flows */
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002891 if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002892 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07002893 return uniPort, outPort
2894 }
2895 }
2896 } else {
2897 // Downstream flow from NNI to PON port , Use tunnel ID as new OUT port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002898 if portType := plt.IntfIDToPortTypeName(outPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002899 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07002900 return inPort, uniPort
2901 }
2902 // Upstream flow from PON to NNI port , Use tunnel ID as new IN port / UNI port
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002903 } else if portType := plt.IntfIDToPortTypeName(inPort); portType == voltha.Port_PON_OLT {
Girish Gowdra491a9c62021-01-06 16:43:07 -08002904 if uniPort := flow_utils.GetChildPortFromTunnelId(flow); uniPort != 0 {
Girish Gowdracefae192020-03-19 18:14:10 -07002905 return uniPort, outPort
2906 }
2907 }
2908 }
2909
2910 return InvalidPort, InvalidPort
2911}
Matt Jeanneretceea2e02020-03-27 14:19:57 -04002912
2913func extractOmciTransactionID(omciPkt []byte) uint16 {
2914 if len(omciPkt) > 3 {
2915 d := omciPkt[0:2]
2916 transid := binary.BigEndian.Uint16(d)
2917 return transid
2918 }
2919 return 0
2920}
Mahir Gunyel0f89fd22020-04-11 18:24:42 -07002921
2922// StoreOnuDevice stores the onu parameters to the local cache.
2923func (dh *DeviceHandler) StoreOnuDevice(onuDevice *OnuDevice) {
2924 onuKey := dh.formOnuKey(onuDevice.intfID, onuDevice.onuID)
2925 dh.onus.Store(onuKey, onuDevice)
2926}
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08002927
khenaidoodc2116e2021-10-19 17:33:19 -04002928func (dh *DeviceHandler) getExtValue(ctx context.Context, device *voltha.Device, value extension.ValueType_Type) (*extension.ReturnValues, error) {
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08002929 var err error
Andrea Campanella9931ad62020-04-28 15:11:06 +02002930 var sn *oop.SerialNumber
Gamze Abaka78a1d2a2020-04-27 10:17:27 +00002931 var ID uint32
khenaidoodc2116e2021-10-19 17:33:19 -04002932 resp := new(extension.ReturnValues)
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08002933 valueparam := new(oop.ValueParam)
Neha Sharma8f4e4322020-08-06 10:51:53 +00002934 ctx = log.WithSpanFromContext(context.Background(), ctx)
Girish Kumara1ea2aa2020-08-19 18:14:22 +00002935 logger.Infow(ctx, "getExtValue", log.Fields{"onu-id": device.Id, "pon-intf": device.ParentPortNo})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08002936 if sn, err = dh.deStringifySerialNumber(device.SerialNumber); err != nil {
2937 return nil, err
2938 }
2939 ID = device.ProxyAddress.GetOnuId()
2940 Onu := oop.Onu{IntfId: device.ParentPortNo, OnuId: ID, SerialNumber: sn}
2941 valueparam.Onu = &Onu
2942 valueparam.Value = value
2943
2944 // This API is unsupported until agent patch is added
2945 resp.Unsupported = uint32(value)
2946 _ = ctx
2947
2948 // Uncomment this code once agent changes are complete and tests
2949 /*
2950 resp, err = dh.Client.GetValue(ctx, valueparam)
2951 if err != nil {
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07002952 logger.Errorw("error-while-getValue", log.Fields{"DeviceID": dh.device, "onu-id": onuid, "err": err})
Dinesh Belwalkardb587af2020-02-27 15:37:16 -08002953 return nil, err
2954 }
2955 */
2956
Girish Kumara1ea2aa2020-08-19 18:14:22 +00002957 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 -08002958 return resp, nil
2959}
Girish Gowdra9602eb42020-09-09 15:50:39 -07002960
yasin saplid0566272021-12-21 09:10:30 +00002961func (dh *DeviceHandler) getIntfIDFromFlow(ctx context.Context, flow *of.OfpFlowStats) uint32 {
2962 // Default to NNI
2963 var intfID = dh.totalPonPorts
Girish Gowdra9602eb42020-09-09 15:50:39 -07002964 inPort, outPort := getPorts(flow)
Girish Gowdra9602eb42020-09-09 15:50:39 -07002965 if inPort != InvalidPort && outPort != InvalidPort {
Mahir Gunyel85f61c12021-10-06 11:53:45 -07002966 _, intfID, _, _ = plt.ExtractAccessFromFlow(inPort, outPort)
Girish Gowdra9602eb42020-09-09 15:50:39 -07002967 }
2968 return intfID
2969}
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002970
Mahir Gunyelb0046752021-02-26 13:51:05 -08002971func (dh *DeviceHandler) getOnuIndicationChannel(ctx context.Context, intfID uint32) chan onuIndicationMsg {
2972 dh.perPonOnuIndicationChannelLock.Lock()
2973 if ch, ok := dh.perPonOnuIndicationChannel[intfID]; ok {
2974 dh.perPonOnuIndicationChannelLock.Unlock()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002975 return ch.indicationChannel
2976 }
2977 channels := onuIndicationChannels{
2978 //We create a buffered channel here to avoid calling function to be blocked
Mahir Gunyelb0046752021-02-26 13:51:05 -08002979 //in case of multiple indications from the ONUs,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002980 //especially in the case where indications are buffered in OLT.
Mahir Gunyelb0046752021-02-26 13:51:05 -08002981 indicationChannel: make(chan onuIndicationMsg, 500),
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002982 stopChannel: make(chan struct{}),
2983 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08002984 dh.perPonOnuIndicationChannel[intfID] = channels
2985 dh.perPonOnuIndicationChannelLock.Unlock()
2986 go dh.onuIndicationsRoutine(&channels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002987 return channels.indicationChannel
2988
2989}
2990
Mahir Gunyelb0046752021-02-26 13:51:05 -08002991func (dh *DeviceHandler) removeOnuIndicationChannels(ctx context.Context) {
2992 logger.Debug(ctx, "remove-onu-indication-channels", log.Fields{"device-id": dh.device.Id})
2993 dh.perPonOnuIndicationChannelLock.Lock()
2994 defer dh.perPonOnuIndicationChannelLock.Unlock()
2995 for _, v := range dh.perPonOnuIndicationChannel {
2996 close(v.stopChannel)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002997 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08002998 dh.perPonOnuIndicationChannel = make(map[uint32]onuIndicationChannels)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08002999}
3000
Mahir Gunyelb0046752021-02-26 13:51:05 -08003001func (dh *DeviceHandler) putOnuIndicationToChannel(ctx context.Context, indication *oop.Indication, intfID uint32) {
3002 ind := onuIndicationMsg{
3003 ctx: ctx,
3004 indication: indication,
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003005 }
Mahir Gunyelb0046752021-02-26 13:51:05 -08003006 logger.Debugw(ctx, "put-onu-indication-to-channel", log.Fields{"indication": indication, "intfID": intfID})
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003007 // Send the onuIndication on the ONU channel
Mahir Gunyelb0046752021-02-26 13:51:05 -08003008 dh.getOnuIndicationChannel(ctx, intfID) <- ind
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003009}
3010
Mahir Gunyelb0046752021-02-26 13:51:05 -08003011func (dh *DeviceHandler) onuIndicationsRoutine(onuChannels *onuIndicationChannels) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003012 for {
3013 select {
3014 // process one indication per onu, before proceeding to the next one
3015 case onuInd := <-onuChannels.indicationChannel:
Andrea Campanella46b01402021-11-15 16:58:05 -08003016 indication := *(proto.Clone(onuInd.indication)).(*oop.Indication)
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003017 logger.Debugw(onuInd.ctx, "calling-indication", log.Fields{"device-id": dh.device.Id,
Andrea Campanella46b01402021-11-15 16:58:05 -08003018 "ind": indication})
3019 switch indication.Data.(type) {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003020 case *oop.Indication_OnuInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003021 if err := dh.onuIndication(onuInd.ctx, indication.GetOnuInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003022 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3023 "type": "onu-indication",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003024 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003025 }
3026 case *oop.Indication_OnuDiscInd:
Andrea Campanella46b01402021-11-15 16:58:05 -08003027 if err := dh.onuDiscIndication(onuInd.ctx, indication.GetOnuDiscInd()); err != nil {
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003028 _ = olterrors.NewErrAdapter("handle-indication-error", log.Fields{
3029 "type": "onu-discovery",
Mahir Gunyelb0046752021-02-26 13:51:05 -08003030 "device-id": dh.device.Id}, err).Log()
Mahir Gunyel2fb81472020-12-16 23:18:34 -08003031 }
3032 }
3033 case <-onuChannels.stopChannel:
3034 logger.Debugw(context.Background(), "stop-signal-received-for-onu-channel", log.Fields{"device-id": dh.device.Id})
3035 close(onuChannels.indicationChannel)
3036 return
3037 }
3038 }
3039}
Girish Gowdra491a9c62021-01-06 16:43:07 -08003040
3041// RouteMcastFlowOrGroupMsgToChannel routes incoming mcast flow or group to a channel to be handled by the a specific
3042// instance of mcastFlowOrGroupChannelHandlerRoutine meant to handle messages for that group.
khenaidoodc2116e2021-10-19 17:33:19 -04003043func (dh *DeviceHandler) RouteMcastFlowOrGroupMsgToChannel(ctx context.Context, flow *of.OfpFlowStats, group *of.OfpGroupEntry, action string) error {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003044 if dh.getDeviceDeletionInProgressFlag() {
3045 // The device itself is going to be reset as part of deletion. So nothing to be done.
3046 logger.Infow(ctx, "device-deletion-in-progress--not-handling-flows-or-groups", log.Fields{"device-id": dh.device.Id})
3047 return nil
3048 }
3049
Girish Gowdra491a9c62021-01-06 16:43:07 -08003050 // Step1 : Fill McastFlowOrGroupControlBlock
3051 // Step2 : Push the McastFlowOrGroupControlBlock to appropriate channel
3052 // Step3 : Wait on response channel for response
3053 // Step4 : Return error value
Girish Gowdra8a0bdcd2021-05-13 12:31:04 -07003054 startTime := time.Now()
Girish Gowdra491a9c62021-01-06 16:43:07 -08003055 logger.Debugw(ctx, "process-flow-or-group", log.Fields{"flow": flow, "group": group, "action": action})
3056 errChan := make(chan error)
3057 var groupID uint32
3058 mcastFlowOrGroupCb := McastFlowOrGroupControlBlock{
3059 ctx: ctx,
3060 flowOrGroupAction: action,
3061 flow: flow,
3062 group: group,
3063 errChan: &errChan,
3064 }
3065 if flow != nil {
3066 groupID = flow_utils.GetGroup(flow)
3067 } else if group != nil {
3068 groupID = group.Desc.GroupId
3069 } else {
3070 return errors.New("flow-and-group-both-nil")
3071 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003072 mcastRoutineIdx := groupID % MaxNumOfGroupHandlerChannels
3073 if dh.mcastHandlerRoutineActive[mcastRoutineIdx] {
3074 // Derive the appropriate go routine to handle the request by a simple module operation.
3075 // There are only MaxNumOfGroupHandlerChannels number of channels to handle the mcast flow or group
3076 dh.incomingMcastFlowOrGroup[groupID%MaxNumOfGroupHandlerChannels] <- mcastFlowOrGroupCb
3077 // Wait for handler to return error value
3078 err := <-errChan
3079 logger.Debugw(ctx, "process-flow-or-group--received-resp", log.Fields{"err": err, "totalTimeInSeconds": time.Since(startTime).Milliseconds()})
3080 return err
3081 }
3082 logger.Errorw(ctx, "mcast handler routine not active for onu", log.Fields{"mcastRoutineIdx": mcastRoutineIdx})
3083 return fmt.Errorf("mcast-handler-routine-not-active-for-index-%v", mcastRoutineIdx)
Girish Gowdra491a9c62021-01-06 16:43:07 -08003084}
3085
3086// mcastFlowOrGroupChannelHandlerRoutine routine to handle incoming mcast flow/group message
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003087func (dh *DeviceHandler) mcastFlowOrGroupChannelHandlerRoutine(routineIndex int, mcastFlowOrGroupChannel chan McastFlowOrGroupControlBlock, stopHandler chan bool) {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003088 for {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003089 select {
Girish Gowdra491a9c62021-01-06 16:43:07 -08003090 // block on the channel to receive an incoming mcast flow/group
3091 // process the flow completely before proceeding to handle the next flow
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003092 case mcastFlowOrGroupCb := <-mcastFlowOrGroupChannel:
3093 if mcastFlowOrGroupCb.flow != nil {
3094 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3095 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-flow",
3096 log.Fields{"device-id": dh.device.Id,
3097 "flowToAdd": mcastFlowOrGroupCb.flow})
3098 // The mcast flow is not unique to any particular PON port, so it is OK to default to PON0
3099 err := dh.flowMgr[0].AddFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow, nil)
3100 // Pass the return value over the return channel
3101 *mcastFlowOrGroupCb.errChan <- err
3102 } else { // flow remove
3103 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-flow",
3104 log.Fields{"device-id": dh.device.Id,
3105 "flowToRemove": mcastFlowOrGroupCb.flow})
3106 // The mcast flow is not unique to any particular PON port, so it is OK to default to PON0
3107 err := dh.flowMgr[0].RemoveFlow(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.flow)
3108 // Pass the return value over the return channel
3109 *mcastFlowOrGroupCb.errChan <- err
3110 }
3111 } else { // mcast group
3112 if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupAdd {
3113 logger.Debugw(mcastFlowOrGroupCb.ctx, "adding-mcast-group",
3114 log.Fields{"device-id": dh.device.Id,
3115 "groupToAdd": mcastFlowOrGroupCb.group})
3116 err := dh.groupMgr.AddGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3117 // Pass the return value over the return channel
3118 *mcastFlowOrGroupCb.errChan <- err
3119 } else if mcastFlowOrGroupCb.flowOrGroupAction == McastFlowOrGroupModify { // group modify
3120 logger.Debugw(mcastFlowOrGroupCb.ctx, "modifying-mcast-group",
3121 log.Fields{"device-id": dh.device.Id,
3122 "groupToModify": mcastFlowOrGroupCb.group})
3123 err := dh.groupMgr.ModifyGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3124 // Pass the return value over the return channel
3125 *mcastFlowOrGroupCb.errChan <- err
3126 } else { // group remove
3127 logger.Debugw(mcastFlowOrGroupCb.ctx, "removing-mcast-group",
3128 log.Fields{"device-id": dh.device.Id,
3129 "groupToRemove": mcastFlowOrGroupCb.group})
3130 err := dh.groupMgr.DeleteGroup(mcastFlowOrGroupCb.ctx, mcastFlowOrGroupCb.group)
3131 // Pass the return value over the return channel
3132 *mcastFlowOrGroupCb.errChan <- err
3133 }
Girish Gowdra491a9c62021-01-06 16:43:07 -08003134 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003135 case <-stopHandler:
3136 dh.mcastHandlerRoutineActive[routineIndex] = false
3137 return
Girish Gowdra491a9c62021-01-06 16:43:07 -08003138 }
3139 }
3140}
kesavand62126212021-01-12 04:56:06 -05003141
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003142// StopAllMcastHandlerRoutines stops all flow handler routines. Call this when device is being rebooted or deleted
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003143func (dh *DeviceHandler) StopAllMcastHandlerRoutines(ctx context.Context, wg *sync.WaitGroup) {
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003144 for i, v := range dh.stopMcastHandlerRoutine {
3145 if dh.mcastHandlerRoutineActive[i] {
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003146 select {
3147 case v <- true:
3148 case <-time.After(time.Second * 5):
3149 logger.Warnw(ctx, "timeout stopping mcast handler routine", log.Fields{"idx": i, "deviceID": dh.device.Id})
3150 }
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003151 }
3152 }
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003153 wg.Done()
Girish Gowdra4736e5c2021-08-25 15:19:10 -07003154 logger.Debug(ctx, "stopped all mcast handler routines")
3155}
3156
kesavand62126212021-01-12 04:56:06 -05003157func (dh *DeviceHandler) getOltPortCounters(ctx context.Context, oltPortInfo *extension.GetOltPortCounters) *extension.SingleGetValueResponse {
3158
3159 singleValResp := extension.SingleGetValueResponse{
3160 Response: &extension.GetValueResponse{
3161 Response: &extension.GetValueResponse_PortCoutners{
3162 PortCoutners: &extension.GetOltPortCountersResponse{},
3163 },
3164 },
3165 }
3166
3167 errResp := func(status extension.GetValueResponse_Status,
3168 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3169 return &extension.SingleGetValueResponse{
3170 Response: &extension.GetValueResponse{
3171 Status: status,
3172 ErrReason: reason,
3173 },
3174 }
3175 }
3176
3177 if oltPortInfo.PortType != extension.GetOltPortCounters_Port_ETHERNET_NNI &&
3178 oltPortInfo.PortType != extension.GetOltPortCounters_Port_PON_OLT {
3179 //send error response
3180 logger.Debugw(ctx, "getOltPortCounters invalid portType", log.Fields{"oltPortInfo": oltPortInfo.PortType})
3181 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_PORT_TYPE)
3182 }
3183 statIndChn := make(chan bool, 1)
3184 dh.portStats.RegisterForStatIndication(ctx, portStatsType, statIndChn, oltPortInfo.PortNo, oltPortInfo.PortType)
3185 defer dh.portStats.DeRegisterFromStatIndication(ctx, portStatsType, statIndChn)
3186 //request openOlt agent to send the the port statistics indication
3187
3188 go func() {
3189 _, err := dh.Client.CollectStatistics(ctx, new(oop.Empty))
3190 if err != nil {
3191 logger.Errorw(ctx, "getOltPortCounters CollectStatistics failed ", log.Fields{"err": err})
3192 }
3193 }()
3194 select {
3195 case <-statIndChn:
3196 //indication received for ports stats
3197 logger.Debugw(ctx, "getOltPortCounters recvd statIndChn", log.Fields{"oltPortInfo": oltPortInfo})
3198 case <-time.After(oltPortInfoTimeout * time.Second):
3199 logger.Debugw(ctx, "getOltPortCounters timeout happened", log.Fields{"oltPortInfo": oltPortInfo})
3200 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3201 case <-ctx.Done():
3202 logger.Debugw(ctx, "getOltPortCounters ctx Done ", log.Fields{"oltPortInfo": oltPortInfo})
3203 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3204 }
3205 if oltPortInfo.PortType == extension.GetOltPortCounters_Port_ETHERNET_NNI {
3206 //get nni stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003207 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_ETHERNET_NNI)
kesavand62126212021-01-12 04:56:06 -05003208 logger.Debugw(ctx, "getOltPortCounters intfID ", log.Fields{"intfID": intfID})
3209 cmnni := dh.portStats.collectNNIMetrics(intfID)
3210 if cmnni == nil {
3211 //TODO define the error reason
3212 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3213 }
3214 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmnni)
3215 return &singleValResp
3216
3217 } else if oltPortInfo.PortType == extension.GetOltPortCounters_Port_PON_OLT {
3218 // get pon stats
Mahir Gunyel85f61c12021-10-06 11:53:45 -07003219 intfID := plt.PortNoToIntfID(oltPortInfo.PortNo, voltha.Port_PON_OLT)
kesavand62126212021-01-12 04:56:06 -05003220 if val, ok := dh.activePorts.Load(intfID); ok && val == true {
3221 cmpon := dh.portStats.collectPONMetrics(intfID)
3222 if cmpon == nil {
3223 //TODO define the error reason
3224 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3225 }
3226 dh.portStats.updateGetOltPortCountersResponse(ctx, &singleValResp, cmpon)
3227 return &singleValResp
3228 }
3229 }
3230 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3231}
Himani Chawla2c8ae0f2021-05-18 23:27:00 +05303232
3233func (dh *DeviceHandler) getOnuPonCounters(ctx context.Context, onuPonInfo *extension.GetOnuCountersRequest) *extension.SingleGetValueResponse {
3234
3235 singleValResp := extension.SingleGetValueResponse{
3236 Response: &extension.GetValueResponse{
3237 Response: &extension.GetValueResponse_OnuPonCounters{
3238 OnuPonCounters: &extension.GetOnuCountersResponse{},
3239 },
3240 },
3241 }
3242
3243 errResp := func(status extension.GetValueResponse_Status,
3244 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3245 return &extension.SingleGetValueResponse{
3246 Response: &extension.GetValueResponse{
3247 Status: status,
3248 ErrReason: reason,
3249 },
3250 }
3251 }
3252 intfID := onuPonInfo.IntfId
3253 onuID := onuPonInfo.OnuId
3254 onuKey := dh.formOnuKey(intfID, onuID)
3255
3256 if _, ok := dh.onus.Load(onuKey); !ok {
3257 logger.Errorw(ctx, "get-onui-pon-counters-request-invalid-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3258 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3259 }
3260 logger.Debugw(ctx, "get-onui-pon-counters-request-received", log.Fields{"intfID": intfID, "onuID": onuID})
3261 cmnni := dh.portStats.collectOnDemandOnuStats(ctx, intfID, onuID)
3262 if cmnni == nil {
3263 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3264 }
3265 dh.portStats.updateGetOnuPonCountersResponse(ctx, &singleValResp, cmnni)
3266 return &singleValResp
3267
3268}
Gamze Abaka85e9a142021-05-26 13:41:39 +00003269
3270func (dh *DeviceHandler) getRxPower(ctx context.Context, rxPowerRequest *extension.GetRxPowerRequest) *extension.SingleGetValueResponse {
3271
3272 Onu := oop.Onu{IntfId: rxPowerRequest.IntfId, OnuId: rxPowerRequest.OnuId}
3273 rxPower, err := dh.Client.GetPonRxPower(ctx, &Onu)
3274 if err != nil {
3275 logger.Errorw(ctx, "error-while-getting-rx-power", log.Fields{"Onu": Onu, "err": err})
3276 return generateSingleGetValueErrorResponse(err)
3277 }
3278 return &extension.SingleGetValueResponse{
3279 Response: &extension.GetValueResponse{
3280 Status: extension.GetValueResponse_OK,
3281 Response: &extension.GetValueResponse_RxPower{
3282 RxPower: &extension.GetRxPowerResponse{
3283 IntfId: rxPowerRequest.IntfId,
3284 OnuId: rxPowerRequest.OnuId,
3285 Status: rxPower.Status,
3286 FailReason: rxPower.FailReason.String(),
3287 RxPower: rxPower.RxPowerMeanDbm,
3288 },
3289 },
3290 },
3291 }
3292}
3293
3294func generateSingleGetValueErrorResponse(err error) *extension.SingleGetValueResponse {
3295 errResp := func(status extension.GetValueResponse_Status,
3296 reason extension.GetValueResponse_ErrorReason) *extension.SingleGetValueResponse {
3297 return &extension.SingleGetValueResponse{
3298 Response: &extension.GetValueResponse{
3299 Status: status,
3300 ErrReason: reason,
3301 },
3302 }
3303 }
3304
3305 if err != nil {
3306 if e, ok := status.FromError(err); ok {
3307 switch e.Code() {
3308 case codes.Internal:
3309 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INTERNAL_ERROR)
3310 case codes.DeadlineExceeded:
3311 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_TIMEOUT)
3312 case codes.Unimplemented:
3313 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_UNSUPPORTED)
3314 case codes.NotFound:
3315 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_INVALID_DEVICE)
3316 }
3317 }
3318 }
3319
3320 return errResp(extension.GetValueResponse_ERROR, extension.GetValueResponse_REASON_UNDEFINED)
3321}
khenaidoo106c61a2021-08-11 18:05:46 -04003322
3323/*
3324Helper functions to communicate with Core
3325*/
3326
3327func (dh *DeviceHandler) getDeviceFromCore(ctx context.Context, deviceID string) (*voltha.Device, error) {
3328 cClient, err := dh.coreClient.GetCoreServiceClient()
3329 if err != nil || cClient == nil {
3330 return nil, err
3331 }
3332 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3333 defer cancel()
3334 return cClient.GetDevice(subCtx, &common.ID{Id: deviceID})
3335}
3336
khenaidoodc2116e2021-10-19 17:33:19 -04003337func (dh *DeviceHandler) getChildDeviceFromCore(ctx context.Context, childDeviceFilter *ca.ChildDeviceFilter) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003338 cClient, err := dh.coreClient.GetCoreServiceClient()
3339 if err != nil || cClient == nil {
3340 return nil, err
3341 }
3342 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3343 defer cancel()
3344 return cClient.GetChildDevice(subCtx, childDeviceFilter)
3345}
3346
khenaidoodc2116e2021-10-19 17:33:19 -04003347func (dh *DeviceHandler) updateDeviceStateInCore(ctx context.Context, deviceStateFilter *ca.DeviceStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003348 cClient, err := dh.coreClient.GetCoreServiceClient()
3349 if err != nil || cClient == nil {
3350 return err
3351 }
3352 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3353 defer cancel()
3354 _, err = cClient.DeviceStateUpdate(subCtx, deviceStateFilter)
3355 return err
3356}
3357
3358func (dh *DeviceHandler) getChildDevicesFromCore(ctx context.Context, deviceID string) (*voltha.Devices, error) {
3359 cClient, err := dh.coreClient.GetCoreServiceClient()
3360 if err != nil || cClient == nil {
3361 return nil, err
3362 }
3363 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3364 defer cancel()
3365 return cClient.GetChildDevices(subCtx, &common.ID{Id: deviceID})
3366}
3367
3368func (dh *DeviceHandler) listDevicePortsFromCore(ctx context.Context, deviceID string) (*voltha.Ports, error) {
3369 cClient, err := dh.coreClient.GetCoreServiceClient()
3370 if err != nil || cClient == nil {
3371 return nil, err
3372 }
3373 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3374 defer cancel()
3375 return cClient.ListDevicePorts(subCtx, &common.ID{Id: deviceID})
3376}
3377
3378func (dh *DeviceHandler) updateDeviceInCore(ctx context.Context, device *voltha.Device) error {
3379 cClient, err := dh.coreClient.GetCoreServiceClient()
3380 if err != nil || cClient == nil {
3381 return err
3382 }
3383 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3384 defer cancel()
3385 _, err = cClient.DeviceUpdate(subCtx, device)
3386 return err
3387}
3388
khenaidoodc2116e2021-10-19 17:33:19 -04003389func (dh *DeviceHandler) sendChildDeviceDetectedToCore(ctx context.Context, deviceDiscoveryInfo *ca.DeviceDiscovery) (*voltha.Device, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003390 cClient, err := dh.coreClient.GetCoreServiceClient()
3391 if err != nil || cClient == nil {
3392 return nil, err
3393 }
3394 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3395 defer cancel()
3396 return cClient.ChildDeviceDetected(subCtx, deviceDiscoveryInfo)
3397}
3398
khenaidoodc2116e2021-10-19 17:33:19 -04003399func (dh *DeviceHandler) sendPacketToCore(ctx context.Context, pkt *ca.PacketIn) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003400 cClient, err := dh.coreClient.GetCoreServiceClient()
3401 if err != nil || cClient == nil {
3402 return err
3403 }
3404 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3405 defer cancel()
3406 _, err = cClient.SendPacketIn(subCtx, pkt)
3407 return err
3408}
3409
3410func (dh *DeviceHandler) createPortInCore(ctx context.Context, port *voltha.Port) error {
3411 cClient, err := dh.coreClient.GetCoreServiceClient()
3412 if err != nil || cClient == nil {
3413 return err
3414 }
3415 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3416 defer cancel()
3417 _, err = cClient.PortCreated(subCtx, port)
3418 return err
3419}
3420
khenaidoodc2116e2021-10-19 17:33:19 -04003421func (dh *DeviceHandler) updatePortsStateInCore(ctx context.Context, portFilter *ca.PortStateFilter) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003422 cClient, err := dh.coreClient.GetCoreServiceClient()
3423 if err != nil || cClient == nil {
3424 return err
3425 }
3426 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3427 defer cancel()
3428 _, err = cClient.PortsStateUpdate(subCtx, portFilter)
3429 return err
3430}
3431
khenaidoodc2116e2021-10-19 17:33:19 -04003432func (dh *DeviceHandler) updatePortStateInCore(ctx context.Context, portState *ca.PortState) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003433 cClient, err := dh.coreClient.GetCoreServiceClient()
3434 if err != nil || cClient == nil {
3435 return err
3436 }
3437 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3438 defer cancel()
3439 _, err = cClient.PortStateUpdate(subCtx, portState)
3440 return err
3441}
3442
khenaidoodc2116e2021-10-19 17:33:19 -04003443func (dh *DeviceHandler) getPortFromCore(ctx context.Context, portFilter *ca.PortFilter) (*voltha.Port, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003444 cClient, err := dh.coreClient.GetCoreServiceClient()
3445 if err != nil || cClient == nil {
3446 return nil, err
3447 }
3448 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3449 defer cancel()
3450 return cClient.GetDevicePort(subCtx, portFilter)
3451}
3452
3453/*
3454Helper functions to communicate with child adapter
3455*/
3456
khenaidoodc2116e2021-10-19 17:33:19 -04003457func (dh *DeviceHandler) sendOmciIndicationToChildAdapter(ctx context.Context, childEndpoint string, response *ia.OmciMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003458 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3459 if err != nil || aClient == nil {
3460 return err
3461 }
3462 logger.Debugw(ctx, "sending-omci-response", log.Fields{"response": response, "child-endpoint": childEndpoint})
3463 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3464 defer cancel()
3465 _, err = aClient.OmciIndication(subCtx, response)
3466 return err
3467}
3468
khenaidoodc2116e2021-10-19 17:33:19 -04003469func (dh *DeviceHandler) sendOnuIndicationToChildAdapter(ctx context.Context, childEndpoint string, onuInd *ia.OnuIndicationMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003470 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3471 if err != nil || aClient == nil {
3472 return err
3473 }
3474 logger.Debugw(ctx, "sending-onu-indication", log.Fields{"onu-indication": onuInd, "child-endpoint": childEndpoint})
3475 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3476 defer cancel()
3477 _, err = aClient.OnuIndication(subCtx, onuInd)
3478 return err
3479}
3480
khenaidoodc2116e2021-10-19 17:33:19 -04003481func (dh *DeviceHandler) sendDeleteTContToChildAdapter(ctx context.Context, childEndpoint string, tContInfo *ia.DeleteTcontMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003482 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3483 if err != nil || aClient == nil {
3484 return err
3485 }
3486 logger.Debugw(ctx, "sending-delete-tcont", log.Fields{"tcont": tContInfo, "child-endpoint": childEndpoint})
3487 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3488 defer cancel()
3489 _, err = aClient.DeleteTCont(subCtx, tContInfo)
3490 return err
3491}
3492
khenaidoodc2116e2021-10-19 17:33:19 -04003493func (dh *DeviceHandler) sendDeleteGemPortToChildAdapter(ctx context.Context, childEndpoint string, gemPortInfo *ia.DeleteGemPortMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003494 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3495 if err != nil || aClient == nil {
3496 return err
3497 }
3498 logger.Debugw(ctx, "sending-delete-gem-port", log.Fields{"gem-port-info": gemPortInfo, "child-endpoint": childEndpoint})
3499 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3500 defer cancel()
3501 _, err = aClient.DeleteGemPort(subCtx, gemPortInfo)
3502 return err
3503}
3504
khenaidoodc2116e2021-10-19 17:33:19 -04003505func (dh *DeviceHandler) sendDownloadTechProfileToChildAdapter(ctx context.Context, childEndpoint string, tpDownloadInfo *ia.TechProfileDownloadMessage) error {
khenaidoo106c61a2021-08-11 18:05:46 -04003506 aClient, err := dh.getChildAdapterServiceClient(childEndpoint)
3507 if err != nil || aClient == nil {
3508 return err
3509 }
3510 logger.Debugw(ctx, "sending-tech-profile-download", log.Fields{"tp-download-info": tpDownloadInfo, "child-endpoint": childEndpoint})
3511 subCtx, cancel := context.WithTimeout(log.WithSpanFromContext(context.Background(), ctx), dh.cfg.RPCTimeout)
3512 defer cancel()
3513 _, err = aClient.DownloadTechProfile(subCtx, tpDownloadInfo)
3514 return err
3515}
3516
3517/*
3518Helper functions for remote communication
3519*/
3520
3521// TODO: Use a connection tracker such that the adapter connection is stopped when the last device that adapter
3522// supports is deleted
3523func (dh *DeviceHandler) setupChildInterAdapterClient(ctx context.Context, endpoint string) error {
3524 logger.Infow(ctx, "setting-child-adapter-connection", log.Fields{"child-endpoint": endpoint})
3525
3526 dh.lockChildAdapterClients.Lock()
3527 defer dh.lockChildAdapterClients.Unlock()
3528 if _, ok := dh.childAdapterClients[endpoint]; ok {
3529 // Already set
3530 return nil
3531 }
3532
3533 // Setup child's adapter grpc connection
3534 var err error
khenaidoo27e7ac92021-12-08 14:43:09 -05003535 if dh.childAdapterClients[endpoint], err = vgrpc.NewClient(
3536 dh.cfg.AdapterEndpoint,
3537 endpoint,
khenaidooefff76e2021-12-15 16:51:30 -05003538 "onu_inter_adapter_service.OnuInterAdapterService",
3539 dh.onuInterAdapterRestarted,
3540 vgrpc.ClientContextData(dh.device.Id)); err != nil {
khenaidoo106c61a2021-08-11 18:05:46 -04003541 logger.Errorw(ctx, "grpc-client-not-created", log.Fields{"error": err, "endpoint": endpoint})
3542 return err
3543 }
khenaidooefff76e2021-12-15 16:51:30 -05003544 go dh.childAdapterClients[endpoint].Start(log.WithSpanFromContext(context.TODO(), ctx), dh.getOnuInterAdapterServiceClientHandler)
khenaidoo106c61a2021-08-11 18:05:46 -04003545
3546 // Wait until we have a connection to the child adapter.
3547 // Unlimited retries or until context expires
3548 subCtx := log.WithSpanFromContext(context.TODO(), ctx)
3549 backoff := vgrpc.NewBackoff(dh.cfg.MinBackoffRetryDelay, dh.cfg.MaxBackoffRetryDelay, 0)
3550 for {
3551 client, err := dh.childAdapterClients[endpoint].GetOnuInterAdapterServiceClient()
3552 if err == nil && client != nil {
3553 logger.Infow(subCtx, "connected-to-child-adapter", log.Fields{"child-endpoint": endpoint})
3554 break
3555 }
3556 logger.Warnw(subCtx, "connection-to-child-adapter-not-ready", log.Fields{"error": err, "child-endpoint": endpoint})
3557 // Backoff
3558 if err = backoff.Backoff(subCtx); err != nil {
3559 logger.Errorw(subCtx, "received-error-on-backoff", log.Fields{"error": err, "child-endpoint": endpoint})
3560 break
3561 }
3562 }
3563 return nil
3564}
3565
khenaidoodc2116e2021-10-19 17:33:19 -04003566func (dh *DeviceHandler) getChildAdapterServiceClient(endpoint string) (onu_inter_adapter_service.OnuInterAdapterServiceClient, error) {
khenaidoo106c61a2021-08-11 18:05:46 -04003567
3568 // First check from cache
3569 dh.lockChildAdapterClients.RLock()
3570 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
3571 dh.lockChildAdapterClients.RUnlock()
3572 return cgClient.GetOnuInterAdapterServiceClient()
3573 }
3574 dh.lockChildAdapterClients.RUnlock()
3575
3576 // Set the child connection - can occur on restarts
3577 ctx, cancel := context.WithTimeout(context.Background(), dh.cfg.RPCTimeout)
3578 err := dh.setupChildInterAdapterClient(ctx, endpoint)
3579 cancel()
3580 if err != nil {
3581 return nil, err
3582 }
3583
3584 // Get the child client now
3585 dh.lockChildAdapterClients.RLock()
3586 defer dh.lockChildAdapterClients.RUnlock()
3587 if cgClient, ok := dh.childAdapterClients[endpoint]; ok {
3588 return cgClient.GetOnuInterAdapterServiceClient()
3589 }
3590 return nil, fmt.Errorf("no-client-for-endpoint-%s", endpoint)
3591}
3592
3593func (dh *DeviceHandler) deleteAdapterClients(ctx context.Context) {
3594 dh.lockChildAdapterClients.Lock()
3595 defer dh.lockChildAdapterClients.Unlock()
3596 for key, client := range dh.childAdapterClients {
3597 client.Stop(ctx)
3598 delete(dh.childAdapterClients, key)
3599 }
3600}
3601
khenaidooefff76e2021-12-15 16:51:30 -05003602// TODO: Any action the adapter needs to do following a onu adapter inter adapter service restart?
3603func (dh *DeviceHandler) onuInterAdapterRestarted(ctx context.Context, endPoint string) error {
3604 logger.Warnw(ctx, "onu-inter-adapter-service-reconnected", log.Fields{"endpoint": endPoint})
khenaidoo106c61a2021-08-11 18:05:46 -04003605 return nil
3606}
3607
khenaidooefff76e2021-12-15 16:51:30 -05003608// getOnuInterAdapterServiceClientHandler is used to setup the remote gRPC service
3609func (dh *DeviceHandler) getOnuInterAdapterServiceClientHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
3610 if conn == nil {
khenaidoo106c61a2021-08-11 18:05:46 -04003611 return nil
3612 }
khenaidooefff76e2021-12-15 16:51:30 -05003613 return onu_inter_adapter_service.NewOnuInterAdapterServiceClient(conn)
khenaidoo106c61a2021-08-11 18:05:46 -04003614}
Girish Gowdra950326e2021-11-05 12:43:24 -07003615
3616func (dh *DeviceHandler) setDeviceDeletionInProgressFlag(flag bool) {
3617 dh.lockDevice.Lock()
3618 defer dh.lockDevice.Unlock()
3619 dh.isDeviceDeletionInProgress = flag
3620}
3621
3622func (dh *DeviceHandler) getDeviceDeletionInProgressFlag() bool {
3623 dh.lockDevice.RLock()
3624 defer dh.lockDevice.RUnlock()
3625 return dh.isDeviceDeletionInProgress
3626}
Girish Gowdra20e3dcd2021-11-18 22:56:49 -08003627
3628// waitForTimeoutOrCompletion waits for the waitgroup for the specified max timeout.
3629// Returns false if waiting timed out.
3630func (dh *DeviceHandler) waitForTimeoutOrCompletion(wg *sync.WaitGroup, timeout time.Duration) bool {
3631 c := make(chan struct{})
3632 go func() {
3633 defer close(c)
3634 wg.Wait()
3635 }()
3636 select {
3637 case <-c:
3638 return true // completed normally
3639 case <-time.After(timeout):
3640 return false // timed out
3641 }
3642}
Abhilash Laxmeshward0f58cf2022-06-01 12:15:19 +05303643
3644func (dh *DeviceHandler) updateHeartbeatSignature(ctx context.Context, signature uint32) {
3645 val, err := json.Marshal(signature)
3646 if err != nil {
3647 logger.Error(ctx, "failed-to-marshal")
3648 return
3649 }
3650 if err = dh.kvStore.Put(ctx, heartbeatPath, val); err != nil {
3651 logger.Error(ctx, "failed-to-store-hearbeat-signature")
3652 }
3653}
3654
3655func (dh *DeviceHandler) getHeartbeatSignature(ctx context.Context) uint32 {
3656 var signature uint32
3657
3658 Value, er := dh.kvStore.Get(ctx, heartbeatPath)
3659 if er == nil {
3660 if Value != nil {
3661 Val, er := kvstore.ToByte(Value.Value)
3662 if er != nil {
3663 logger.Errorw(ctx, "Failed to convert into byte array", log.Fields{"err": er})
3664 return signature
3665 }
3666 if er = json.Unmarshal(Val, &signature); er != nil {
3667 logger.Error(ctx, "Failed to unmarshal signature", log.Fields{"err": er})
3668 return signature
3669 }
3670 }
3671 }
3672 return signature
3673}