blob: 730be6c53ba4c0c1ecaaf04dc8c3830bb6675304 [file] [log] [blame]
Naveen Sampath04696f72022-06-13 15:19:14 +05301/*
2* Copyright 2022-present Open Networking Foundation
3* Licensed under the Apache License, Version 2.0 (the "License");
4* you may not use this file except in compliance with the License.
5* You may obtain a copy of the License at
6*
7* http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14 */
15
16package application
17
18import (
19 "context"
20 "encoding/hex"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "net"
25 "strconv"
26 "strings"
27 "sync"
28 "time"
29
30 "github.com/google/gopacket"
31 "github.com/google/gopacket/layers"
32
Akash Sonia8246972023-01-03 10:37:08 +053033 "voltha-go-controller/database"
Naveen Sampath04696f72022-06-13 15:19:14 +053034 "voltha-go-controller/internal/pkg/controller"
35 cntlr "voltha-go-controller/internal/pkg/controller"
Akash Sonia8246972023-01-03 10:37:08 +053036 errorCodes "voltha-go-controller/internal/pkg/errorcodes"
Naveen Sampath04696f72022-06-13 15:19:14 +053037 "voltha-go-controller/internal/pkg/intf"
38 "voltha-go-controller/internal/pkg/of"
39 "voltha-go-controller/internal/pkg/tasks"
40 "voltha-go-controller/internal/pkg/util"
Tinoj Joseph1d108322022-07-13 10:07:39 +053041 "voltha-go-controller/log"
Naveen Sampath04696f72022-06-13 15:19:14 +053042)
43
44var logger log.CLogger
45var ctx = context.TODO()
46
47func init() {
48 // Setup this package so that it's log level can be modified at run time
49 var err error
Tinoj Joseph1d108322022-07-13 10:07:39 +053050 logger, err = log.AddPackageWithDefaultParam()
Naveen Sampath04696f72022-06-13 15:19:14 +053051 if err != nil {
52 panic(err)
53 }
54}
55
56const (
57 // TODO - Need to identify a right place for this
58
59 // PriorityNone constant.
60 PriorityNone uint8 = 8
61 // AnyVlan constant.
62 AnyVlan uint16 = 0xFFFF
63)
64
65// List of Mac Learning Type
66const (
Tinoj Joseph1d108322022-07-13 10:07:39 +053067 MacLearningNone MacLearningType = iota
68 Learn
69 ReLearn
Naveen Sampath04696f72022-06-13 15:19:14 +053070)
71
72// MacLearningType represents Mac Learning Type
73type MacLearningType int
74
75var (
76 tickCount uint16
77 vgcRebooted bool
78 isUpgradeComplete bool
79)
80
81var db database.DBIntf
82
83// PacketHandlers : packet handler for different protocols
84var PacketHandlers map[string]CallBack
85
86// CallBack : registered call back function for different protocol packets
Tinoj Joseph07cc5372022-07-18 22:53:51 +053087type CallBack func(cntx context.Context, device string, port string, pkt gopacket.Packet)
Naveen Sampath04696f72022-06-13 15:19:14 +053088
89const (
90 // ARP packet
91 ARP string = "ARP"
92 // DHCPv4 packet
93 DHCPv4 string = "DHCPv4"
94 // DHCPv6 packet
95 DHCPv6 string = "DHCPv6"
96 // IGMP packet
97 IGMP string = "IGMP"
98 // PPPOE packet
99 PPPOE string = "PPPOE"
100 // US packet side
101 US string = "US"
102 // DS packet side
103 DS string = "DS"
104 // NNI port name
105 NNI string = "nni"
106)
107
108// RegisterPacketHandler : API to register callback function for every protocol
109func RegisterPacketHandler(protocol string, callback CallBack) {
110 if PacketHandlers == nil {
111 PacketHandlers = make(map[string]CallBack)
112 }
113 PacketHandlers[protocol] = callback
114}
115
116// ---------------------------------------------------------------------
117// VOLT Ports
118// ---------------------------------------------------------------------
119// VOLT Ports are ports associated with VOLT devices. Each port is classified into
120// Access/NNI. Each port is identified by Name (Identity known to the NB) and
121// Id (Identity used on the SB). Both identities are presented when a port is
122// discovered in the SB.
123
124// VoltPortType type for Port Type
125type VoltPortType uint8
126
127const (
128 // VoltPortTypeAccess constant.
129 VoltPortTypeAccess VoltPortType = 0
130 // VoltPortTypeNni constant.
131 VoltPortTypeNni VoltPortType = 1
132)
133
134// PortState type for Port State.
135type PortState uint8
136
137const (
138 // PortStateDown constant.
139 PortStateDown PortState = 0
140 // PortStateUp constant.
141 PortStateUp PortState = 1
142)
143
144// VoltPort structure that is used to store the ports. The name is the
145// the main identity used by the application. The SB and NB both present name
146// as the identity. The SB is abstracted by VPAgent and the VPAgent transacts
147// using name as identity
148type VoltPort struct {
149 ID uint32
150 Name string
151 Device string
152 PonPort uint32
153 Type VoltPortType
154 State PortState
155 ActiveChannels uint32
156 ChannelPerSubAlarmRaised bool
157}
158
159// NewVoltPort : Constructor for the port.
160func NewVoltPort(device string, name string, id uint32) *VoltPort {
161 var vp VoltPort
162 vp.Device = device
163 vp.Name = name
164 vp.ID = id
165 if util.IsNniPort(id) {
166 vp.Type = VoltPortTypeNni
167 } else {
168 vp.PonPort = GetPonPortIDFromUNIPort(id)
169 }
170 vp.State = PortStateDown
171 vp.ChannelPerSubAlarmRaised = false
172 return &vp
173}
174
175// SetPortID : The ID is used when constructing flows as the flows require ID.
176func (vp *VoltPort) SetPortID(id uint32) {
177 vp.ID = id
178 if util.IsNniPort(id) {
179 vp.Type = VoltPortTypeNni
180 }
181}
182
183// ---------------------------------------------------------------------
184// VOLT Device
185// ---------------------------------------------------------------------
186//
187// VoltDevice is an OLT which contains ports of type access and NNI. Each OLT
188// can only have one NNI port in the current release. The NNI port always uses
189// identity 65536 and all the access ports use identities less than 65535. The
190// identification of NNI is done by comparing the port identity with 65535
191
192// VoltDevice fields :
193// Name: This is the name presented by the device/VOLTHA. This doesn't
194// have any relation to the physical device
195// SerialNum: This is the serial number of the device and can be used to
196// correlate the devices
197// NniPort: The identity of the NNI port
198// Ports: List of all ports added to the device
199type VoltDevice struct {
200 Name string
201 SerialNum string
202 State controller.DeviceState
203 SouthBoundID string
204 NniPort string
205 Ports sync.Map
206 VlanPortStatus sync.Map
207 VpvsBySvlan *util.ConcurrentMap // map[svlan]map[vnet_port]*VoltPortVnet
208 IgmpDsFlowAppliedForMvlan map[uint16]bool
209 ConfiguredVlanForDeviceFlows *util.ConcurrentMap //map[string]map[string]bool
210 icmpv6GroupAdded bool
211 ActiveChannelsPerPon sync.Map // [PonPortID]*PonPortCfg
212 ActiveChannelCountLock sync.Mutex // This lock is used to update ActiveIGMPChannels
213 PonPortList sync.Map // [PonPortID]map[string]string
214 FlowAddEventMap *util.ConcurrentMap //map[string]*FlowEvent
215 FlowDelEventMap *util.ConcurrentMap //map[string]*FlowEvent
216 MigratingServices *util.ConcurrentMap //<vnetID,<RequestID, MigrateServicesRequest>>
217 GlobalDhcpFlowAdded bool
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530218 NniDhcpTrapVid of.VlanType
Naveen Sampath04696f72022-06-13 15:19:14 +0530219}
220
221// NewVoltDevice : Constructor for the device
222func NewVoltDevice(name string, slno, southBoundID string) *VoltDevice {
223 var d VoltDevice
224 d.Name = name
225 d.SouthBoundID = southBoundID
226 d.State = controller.DeviceStateDOWN
227 d.NniPort = ""
228 d.SouthBoundID = southBoundID
229 d.SerialNum = slno
230 d.icmpv6GroupAdded = false
231 d.IgmpDsFlowAppliedForMvlan = make(map[uint16]bool)
232 d.ConfiguredVlanForDeviceFlows = util.NewConcurrentMap()
233 d.MigratingServices = util.NewConcurrentMap()
234 d.VpvsBySvlan = util.NewConcurrentMap()
235 d.FlowAddEventMap = util.NewConcurrentMap()
236 d.FlowDelEventMap = util.NewConcurrentMap()
237 d.GlobalDhcpFlowAdded = false
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530238 if config, ok := GetApplication().DevicesConfig.Load(slno); ok {
239 //Update nni dhcp vid
240 deviceConfig := config.(DeviceConfig)
241 d.NniDhcpTrapVid = of.VlanType(deviceConfig.NniDhcpTrapVid)
242 }
Naveen Sampath04696f72022-06-13 15:19:14 +0530243 return &d
244}
245
246//GetAssociatedVpvsForDevice - return the associated VPVs for given device & svlan
247func (va *VoltApplication) GetAssociatedVpvsForDevice(device string, svlan of.VlanType) *util.ConcurrentMap {
248 if d := va.GetDevice(device); d != nil {
249 return d.GetAssociatedVpvs(svlan)
250 }
251 return nil
252}
253
254//AssociateVpvsToDevice - updates the associated VPVs for given device & svlan
255func (va *VoltApplication) AssociateVpvsToDevice(device string, vpv *VoltPortVnet) {
256 if d := va.GetDevice(device); d != nil {
257
258 vpvMap := d.GetAssociatedVpvs(vpv.SVlan)
259 vpvMap.Set(vpv, true)
260 d.VpvsBySvlan.Set(vpv.SVlan, vpvMap)
261 logger.Infow(ctx, "VPVMap: SET", log.Fields{"Map": vpvMap.Length()})
262 return
263 }
264 logger.Errorw(ctx, "Set VPVMap failed: Device Not Found", log.Fields{"Svlan": vpv.SVlan, "Device": device})
265}
266
267//DisassociateVpvsFromDevice - disassociated VPVs from given device & svlan
268func (va *VoltApplication) DisassociateVpvsFromDevice(device string, vpv *VoltPortVnet) {
269 if d := va.GetDevice(device); d != nil {
270 vpvMap := d.GetAssociatedVpvs(vpv.SVlan)
271 vpvMap.Remove(vpv)
272 d.VpvsBySvlan.Set(vpv.SVlan, vpvMap)
273 logger.Infow(ctx, "VPVMap: Remove", log.Fields{"Map": vpvMap.Length()})
274 return
275 }
276 logger.Errorw(ctx, "Remove VPVMap failed: Device Not Found", log.Fields{"Svlan": vpv.SVlan, "Device": device})
277}
278
279//GetAssociatedVpvs - returns the associated VPVs for the given Svlan
280func (d *VoltDevice) GetAssociatedVpvs(svlan of.VlanType) *util.ConcurrentMap {
281
282 var vpvMap *util.ConcurrentMap
283 var mapIntf interface{}
284 var ok bool
285
286 if mapIntf, ok = d.VpvsBySvlan.Get(svlan); ok {
287 vpvMap = mapIntf.(*util.ConcurrentMap)
288 } else {
289 vpvMap = util.NewConcurrentMap()
290 }
291 logger.Infow(ctx, "VPVMap: GET", log.Fields{"Map": vpvMap.Length()})
292 return vpvMap
293}
294
295// AddPort add port to the device.
296func (d *VoltDevice) AddPort(port string, id uint32) *VoltPort {
297 addPonPortFromUniPort := func(vPort *VoltPort) {
298 if vPort.Type == VoltPortTypeAccess {
299 ponPortID := GetPonPortIDFromUNIPort(vPort.ID)
300
301 if ponPortUniList, ok := d.PonPortList.Load(ponPortID); !ok {
302 uniList := make(map[string]uint32)
303 uniList[port] = vPort.ID
304 d.PonPortList.Store(ponPortID, uniList)
305 } else {
306 ponPortUniList.(map[string]uint32)[port] = vPort.ID
307 d.PonPortList.Store(ponPortID, ponPortUniList)
308 }
309 }
310 }
311 va := GetApplication()
312 if pIntf, ok := d.Ports.Load(port); ok {
313 voltPort := pIntf.(*VoltPort)
314 addPonPortFromUniPort(voltPort)
315 va.AggActiveChannelsCountPerSub(d.Name, port, voltPort)
316 d.Ports.Store(port, voltPort)
317 return voltPort
318 }
319 p := NewVoltPort(d.Name, port, id)
320 va.AggActiveChannelsCountPerSub(d.Name, port, p)
321 d.Ports.Store(port, p)
322 if util.IsNniPort(id) {
323 d.NniPort = port
324 }
325 addPonPortFromUniPort(p)
326 return p
327}
328
329// GetPort to get port information from the device.
330func (d *VoltDevice) GetPort(port string) *VoltPort {
331 if pIntf, ok := d.Ports.Load(port); ok {
332 return pIntf.(*VoltPort)
333 }
334 return nil
335}
336
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530337// GetPortByPortID to get port information from the device.
338func (d *VoltDevice) GetPortNameFromPortID(portID uint32) string {
339 portName := ""
340 d.Ports.Range(func(key, value interface{}) bool {
341 vp := value.(*VoltPort)
342 if vp.ID == portID {
343 portName = vp.Name
344 }
345 return true
346 })
347 return portName
348}
349
Naveen Sampath04696f72022-06-13 15:19:14 +0530350// DelPort to delete port from the device
351func (d *VoltDevice) DelPort(port string) {
352 if _, ok := d.Ports.Load(port); ok {
353 d.Ports.Delete(port)
354 } else {
355 logger.Warnw(ctx, "Port doesn't exist", log.Fields{"Device": d.Name, "Port": port})
356 }
357}
358
359// pushFlowsForUnis to send port-up-indication for uni ports.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530360func (d *VoltDevice) pushFlowsForUnis(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530361
362 logger.Info(ctx, "NNI Discovered, Sending Port UP Ind for UNIs")
363 d.Ports.Range(func(key, value interface{}) bool {
364 port := key.(string)
365 vp := value.(*VoltPort)
366
Akash Sonia8246972023-01-03 10:37:08 +0530367 logger.Infow(ctx, "NNI Discovered. Sending Port UP Ind for UNI", log.Fields{"Port": port})
Naveen Sampath04696f72022-06-13 15:19:14 +0530368 //Ignore if UNI port is not UP
369 if vp.State != PortStateUp {
370 return true
371 }
372
373 //Obtain all VPVs associated with the port
374 vnets, ok := GetApplication().VnetsByPort.Load(port)
375 if !ok {
376 return true
377 }
378
379 for _, vpv := range vnets.([]*VoltPortVnet) {
380 vpv.VpvLock.Lock()
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530381 vpv.PortUpInd(cntx, d, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530382 vpv.VpvLock.Unlock()
383
384 }
385 return true
386 })
387}
388
389// ----------------------------------------------------------
390// VOLT Application - hosts all other objects
391// ----------------------------------------------------------
392//
393// The VOLT application is a singleton implementation where
394// there is just one instance in the system and is the gateway
395// to all other components within the controller
396// The declaration of the singleton object
397var vapplication *VoltApplication
398
399// VoltApplication fields :
400// ServiceByName - Stores the services by the name as key
401// A record of NB configuration.
402// VnetsByPort - Stores the VNETs by the ports configured
403// from NB. A record of NB configuration.
404// VnetsByTag - Stores the VNETs by the VLANS configured
405// from NB. A record of NB configuration.
406// VnetsByName - Stores the VNETs by the name configured
407// from NB. A record of NB configuration.
408// DevicesDisc - Stores the devices discovered from SB.
409// Should be updated only by events from SB
410// PortsDisc - Stores the ports discovered from SB.
411// Should be updated only by events from SB
412type VoltApplication struct {
413 ServiceByName sync.Map // [serName]*VoltService
414 VnetsByPort sync.Map // [portName][]*VoltPortVnet
415 VnetsByTag sync.Map // [svlan-cvlan-uvlan]*VoltVnet
416 VnetsByName sync.Map // [vnetName]*VoltVnet
417 VnetsBySvlan *util.ConcurrentMap
418 DevicesDisc sync.Map
419 PortsDisc sync.Map
420 IgmpGroups sync.Map // [grpKey]*IgmpGroup
421 IgmpGroupIds []*IgmpGroup
422 MvlanProfilesByTag sync.Map
423 MvlanProfilesByName sync.Map
424 Icmpv6Receivers sync.Map
425 MeterMgr
426 IgmpTasks tasks.Tasks
427 IndicationsTasks tasks.Tasks
428 MulticastAlarmTasks tasks.Tasks
429 portLock sync.Mutex
430 DataMigrationInfo DataMigration
431 DeviceCounters sync.Map //[logicalDeviceId]*DeviceCounters
432 ServiceCounters sync.Map //[serviceName]*ServiceCounters
433 NbDevice sync.Map // [OLTSouthBoundID]*NbDevice
434 IgmpKPIsTasks tasks.Tasks
435 pppoeTasks tasks.Tasks
436 IgmpProfilesByName sync.Map
437 OltIgmpInfoBySerial sync.Map
438 McastConfigMap sync.Map //[OltSerialNo_MvlanProfileID]*McastConfig
439 // MacAddress-Port MAP to avoid swap of mac accross ports.
440 macPortLock sync.RWMutex
441 macPortMap map[string]string
442
Akash Sonia8246972023-01-03 10:37:08 +0530443 IgmpPendingPool map[string]map[*IgmpGroup]bool //[grpkey, map[groupObj]bool] //mvlan_grpName/IP
444 PendingPoolLock sync.RWMutex
445 VnetsToDelete map[string]bool
446 ServicesToDelete map[string]bool
447 VoltPortVnetsToDelete map[*VoltPortVnet]bool
448 PortAlarmProfileCache map[string]map[string]int // [portAlarmID][ThresholdLevelString]ThresholdLevel
449 vendorID string
450 OltFlowServiceConfig OltFlowService
451 DevicesConfig sync.Map //[serialNumber]*DeviceConfig
452}
Naveen Sampath04696f72022-06-13 15:19:14 +0530453
Akash Sonia8246972023-01-03 10:37:08 +0530454type DeviceConfig struct {
455 SerialNumber string `json:"id"`
456 HardwareIdentifier string `json:"hardwareIdentifier"`
Akash Soni87a19072023-02-28 00:46:59 +0530457 IPAddress string `json:"ipAddress"`
Akash Sonia8246972023-01-03 10:37:08 +0530458 UplinkPort int `json:"uplinkPort"`
459 NasID string `json:"nasId"`
460 NniDhcpTrapVid int `json:"nniDhcpTrapVid"`
Naveen Sampath04696f72022-06-13 15:19:14 +0530461}
462
463// PonPortCfg contains NB port config and activeIGMPChannels count
464type PonPortCfg struct {
465 PortID uint32
466 MaxActiveChannels uint32
467 ActiveIGMPChannels uint32
468 EnableMulticastKPI bool
469 PortAlarmProfileID string
470}
471
472// NbDevice OLT Device info
473type NbDevice struct {
474 SouthBoundID string
475 PonPorts sync.Map // [PortID]*PonPortCfg
476}
477
478// RestoreNbDeviceFromDb restores the NB Device in case of VGC pod restart.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530479func (va *VoltApplication) RestoreNbDeviceFromDb(cntx context.Context, deviceID string) *NbDevice {
Naveen Sampath04696f72022-06-13 15:19:14 +0530480
481 nbDevice := NewNbDevice()
482 nbDevice.SouthBoundID = deviceID
483
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530484 nbPorts, _ := db.GetAllNbPorts(cntx, deviceID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530485
486 for key, p := range nbPorts {
487 b, ok := p.Value.([]byte)
488 if !ok {
489 logger.Warn(ctx, "The value type is not []byte")
490 continue
491 }
492 var port PonPortCfg
493 err := json.Unmarshal(b, &port)
494 if err != nil {
495 logger.Warn(ctx, "Unmarshal of PonPortCfg failed")
496 continue
497 }
498 logger.Debugw(ctx, "Port recovered", log.Fields{"port": port})
499 ponPortID, _ := strconv.Atoi(key)
500 nbDevice.PonPorts.Store(uint32(ponPortID), &port)
501 }
502 va.NbDevice.Store(deviceID, nbDevice)
503 return nbDevice
504}
505
506// NewNbDevice Constructor for NbDevice
507func NewNbDevice() *NbDevice {
508 var nbDevice NbDevice
509 return &nbDevice
510}
511
512// WriteToDb writes nb device port config to kv store
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530513func (nbd *NbDevice) WriteToDb(cntx context.Context, portID uint32, ponPort *PonPortCfg) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530514 b, err := json.Marshal(ponPort)
515 if err != nil {
516 logger.Errorw(ctx, "PonPortConfig-marshal-failed", log.Fields{"err": err})
517 return
518 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530519 db.PutNbDevicePort(cntx, nbd.SouthBoundID, portID, string(b))
Naveen Sampath04696f72022-06-13 15:19:14 +0530520}
521
522// AddPortToNbDevice Adds pon port to NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530523func (nbd *NbDevice) AddPortToNbDevice(cntx context.Context, portID, allowedChannels uint32,
Naveen Sampath04696f72022-06-13 15:19:14 +0530524 enableMulticastKPI bool, portAlarmProfileID string) *PonPortCfg {
525
526 ponPort := &PonPortCfg{
527 PortID: portID,
528 MaxActiveChannels: allowedChannels,
529 EnableMulticastKPI: enableMulticastKPI,
530 PortAlarmProfileID: portAlarmProfileID,
531 }
532 nbd.PonPorts.Store(portID, ponPort)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530533 nbd.WriteToDb(cntx, portID, ponPort)
Naveen Sampath04696f72022-06-13 15:19:14 +0530534 return ponPort
535}
536
Akash Sonia8246972023-01-03 10:37:08 +0530537// RestoreDeviceConfigFromDb to restore vnet from port
538func (va *VoltApplication) RestoreDeviceConfigFromDb(cntx context.Context) {
539 // VNETS must be learnt first
540 dConfig, _ := db.GetDeviceConfig(cntx)
541 for _, device := range dConfig {
542 b, ok := device.Value.([]byte)
543 if !ok {
544 logger.Warn(ctx, "The value type is not []byte")
545 continue
546 }
547 devConfig := DeviceConfig{}
548 err := json.Unmarshal(b, &devConfig)
549 if err != nil {
550 logger.Warn(ctx, "Unmarshal of device configuration failed")
551 continue
552 }
553 logger.Debugw(ctx, "Retrieved device config", log.Fields{"Device Config": devConfig})
554 if err := va.AddDeviceConfig(cntx, devConfig.SerialNumber, devConfig.HardwareIdentifier, devConfig.NasID, devConfig.IPAddress, devConfig.UplinkPort, devConfig.NniDhcpTrapVid); err != nil {
555 logger.Warnw(ctx, "Add device config failed", log.Fields{"DeviceConfig": devConfig, "Error": err})
556 }
557
558 }
559}
560
561// WriteDeviceConfigToDb writes sb device config to kv store
562func (dc *DeviceConfig) WriteDeviceConfigToDb(cntx context.Context, serialNum string, deviceConfig *DeviceConfig) error {
563 b, err := json.Marshal(deviceConfig)
564 if err != nil {
565 logger.Errorw(ctx, "deviceConfig-marshal-failed", log.Fields{"err": err})
566 return err
567 }
568 dberr := db.PutDeviceConfig(cntx, serialNum, string(b))
569 if dberr != nil {
570 logger.Errorw(ctx, "update device config failed", log.Fields{"err": err})
571 return dberr
572 }
573 return nil
574}
575
Akash Soni87a19072023-02-28 00:46:59 +0530576func (va *VoltApplication) AddDeviceConfig(cntx context.Context, serialNum, hardwareIdentifier, nasID, ipAddress string, uplinkPort, nniDhcpTrapId int) error {
Akash Sonia8246972023-01-03 10:37:08 +0530577 var dc *DeviceConfig
578
Akash Soni87a19072023-02-28 00:46:59 +0530579 deviceConfig := &DeviceConfig{
580 SerialNumber: serialNum,
581 HardwareIdentifier: hardwareIdentifier,
582 NasID: nasID,
583 UplinkPort: uplinkPort,
584 IPAddress: ipAddress,
585 NniDhcpTrapVid: nniDhcpTrapId,
Akash Sonia8246972023-01-03 10:37:08 +0530586 }
Akash Soni87a19072023-02-28 00:46:59 +0530587 va.DevicesConfig.Store(serialNum, deviceConfig)
588 err := dc.WriteDeviceConfigToDb(cntx, serialNum, deviceConfig)
589 if err != nil {
590 logger.Errorw(ctx, "DB update for device config failed", log.Fields{"err": err})
591 return err
592 }
593
594 // If device is already discovered update the VoltDevice structure
595 device, id := va.GetDeviceBySerialNo(serialNum)
596 if device != nil {
597 device.NniDhcpTrapVid = of.VlanType(nniDhcpTrapId)
598 va.DevicesDisc.Store(id, device)
599 }
600
Akash Sonia8246972023-01-03 10:37:08 +0530601 return nil
602}
603
604// GetDeviceConfig to get a device config.
605func (va *VoltApplication) GetDeviceConfig(serNum string) *DeviceConfig {
606 if d, ok := va.DevicesConfig.Load(serNum); ok {
607 return d.(*DeviceConfig)
608 }
609 return nil
610}
611
Naveen Sampath04696f72022-06-13 15:19:14 +0530612// UpdatePortToNbDevice Adds pon port to NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530613func (nbd *NbDevice) UpdatePortToNbDevice(cntx context.Context, portID, allowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) *PonPortCfg {
Naveen Sampath04696f72022-06-13 15:19:14 +0530614
615 p, exists := nbd.PonPorts.Load(portID)
616 if !exists {
617 logger.Errorw(ctx, "PON port not exists in nb-device", log.Fields{"portID": portID})
618 return nil
619 }
620 port := p.(*PonPortCfg)
621 if allowedChannels != 0 {
622 port.MaxActiveChannels = allowedChannels
623 port.EnableMulticastKPI = enableMulticastKPI
624 port.PortAlarmProfileID = portAlarmProfileID
625 }
626
627 nbd.PonPorts.Store(portID, port)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530628 nbd.WriteToDb(cntx, portID, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530629 return port
630}
631
632// DeletePortFromNbDevice Deletes pon port from NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530633func (nbd *NbDevice) DeletePortFromNbDevice(cntx context.Context, portID uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530634
635 if _, ok := nbd.PonPorts.Load(portID); ok {
636 nbd.PonPorts.Delete(portID)
637 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530638 db.DelNbDevicePort(cntx, nbd.SouthBoundID, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530639}
640
641// GetApplication : Interface to access the singleton object
642func GetApplication() *VoltApplication {
643 if vapplication == nil {
644 vapplication = newVoltApplication()
645 }
646 return vapplication
647}
648
649// newVoltApplication : Constructor for the singleton object. Hence this is not
650// an exported function
651func newVoltApplication() *VoltApplication {
652 var va VoltApplication
653 va.IgmpTasks.Initialize(context.TODO())
654 va.MulticastAlarmTasks.Initialize(context.TODO())
655 va.IgmpKPIsTasks.Initialize(context.TODO())
656 va.pppoeTasks.Initialize(context.TODO())
657 va.storeIgmpProfileMap(DefaultIgmpProfID, newDefaultIgmpProfile())
658 va.MeterMgr.Init()
659 va.AddIgmpGroups(5000)
660 va.macPortMap = make(map[string]string)
661 va.IgmpPendingPool = make(map[string]map[*IgmpGroup]bool)
662 va.VnetsBySvlan = util.NewConcurrentMap()
663 va.VnetsToDelete = make(map[string]bool)
664 va.ServicesToDelete = make(map[string]bool)
665 va.VoltPortVnetsToDelete = make(map[*VoltPortVnet]bool)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530666 go va.Start(context.Background(), TimerCfg{tick: 100 * time.Millisecond}, tickTimer)
667 go va.Start(context.Background(), TimerCfg{tick: time.Duration(GroupExpiryTime) * time.Minute}, pendingPoolTimer)
Naveen Sampath04696f72022-06-13 15:19:14 +0530668 InitEventFuncMapper()
669 db = database.GetDatabase()
670 return &va
671}
672
673//GetFlowEventRegister - returs the register based on flow mod type
674func (d *VoltDevice) GetFlowEventRegister(flowModType of.Command) (*util.ConcurrentMap, error) {
675
676 switch flowModType {
677 case of.CommandDel:
678 return d.FlowDelEventMap, nil
679 case of.CommandAdd:
680 return d.FlowAddEventMap, nil
681 default:
682 logger.Error(ctx, "Unknown Flow Mod received")
683 }
684 return util.NewConcurrentMap(), errors.New("Unknown Flow Mod")
685}
686
687// RegisterFlowAddEvent to register a flow event.
688func (d *VoltDevice) RegisterFlowAddEvent(cookie string, event *FlowEvent) {
689 logger.Debugw(ctx, "Registered Flow Add Event", log.Fields{"Cookie": cookie, "Event": event})
690 d.FlowAddEventMap.MapLock.Lock()
691 defer d.FlowAddEventMap.MapLock.Unlock()
692 d.FlowAddEventMap.Set(cookie, event)
693}
694
695// RegisterFlowDelEvent to register a flow event.
696func (d *VoltDevice) RegisterFlowDelEvent(cookie string, event *FlowEvent) {
697 logger.Debugw(ctx, "Registered Flow Del Event", log.Fields{"Cookie": cookie, "Event": event})
698 d.FlowDelEventMap.MapLock.Lock()
699 defer d.FlowDelEventMap.MapLock.Unlock()
700 d.FlowDelEventMap.Set(cookie, event)
701}
702
703// UnRegisterFlowEvent to unregister a flow event.
704func (d *VoltDevice) UnRegisterFlowEvent(cookie string, flowModType of.Command) {
705 logger.Debugw(ctx, "UnRegistered Flow Add Event", log.Fields{"Cookie": cookie, "Type": flowModType})
706 flowEventMap, err := d.GetFlowEventRegister(flowModType)
707 if err != nil {
708 logger.Debugw(ctx, "Flow event map does not exists", log.Fields{"flowMod": flowModType, "Error": err})
709 return
710 }
711 flowEventMap.MapLock.Lock()
712 defer flowEventMap.MapLock.Unlock()
713 flowEventMap.Remove(cookie)
714}
715
716// AddIgmpGroups to add Igmp groups.
717func (va *VoltApplication) AddIgmpGroups(numOfGroups uint32) {
718 //TODO: Temp change to resolve group id issue in pOLT
719 //for i := 1; uint32(i) <= numOfGroups; i++ {
720 for i := 2; uint32(i) <= (numOfGroups + 1); i++ {
721 ig := IgmpGroup{}
722 ig.GroupID = uint32(i)
723 va.IgmpGroupIds = append(va.IgmpGroupIds, &ig)
724 }
725}
726
727// GetAvailIgmpGroupID to get id of available igmp group.
728func (va *VoltApplication) GetAvailIgmpGroupID() *IgmpGroup {
729 var ig *IgmpGroup
730 if len(va.IgmpGroupIds) > 0 {
731 ig, va.IgmpGroupIds = va.IgmpGroupIds[0], va.IgmpGroupIds[1:]
732 return ig
733 }
734 return nil
735}
736
737// GetIgmpGroupID to get id of igmp group.
738func (va *VoltApplication) GetIgmpGroupID(gid uint32) (*IgmpGroup, error) {
739 for id, ig := range va.IgmpGroupIds {
740 if ig.GroupID == gid {
741 va.IgmpGroupIds = append(va.IgmpGroupIds[0:id], va.IgmpGroupIds[id+1:]...)
742 return ig, nil
743 }
744 }
745 return nil, errors.New("Group Id Missing")
746}
747
748// PutIgmpGroupID to add id of igmp group.
749func (va *VoltApplication) PutIgmpGroupID(ig *IgmpGroup) {
750 va.IgmpGroupIds = append([]*IgmpGroup{ig}, va.IgmpGroupIds[0:]...)
751}
752
753//RestoreUpgradeStatus - gets upgrade/migration status from DB and updates local flags
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530754func (va *VoltApplication) RestoreUpgradeStatus(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530755 Migrate := new(DataMigration)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530756 if err := GetMigrationInfo(cntx, Migrate); err == nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530757 if Migrate.Status == MigrationInProgress {
758 isUpgradeComplete = false
759 return
760 }
761 }
762 isUpgradeComplete = true
763
764 logger.Infow(ctx, "Upgrade Status Restored", log.Fields{"Upgrade Completed": isUpgradeComplete})
765}
766
767// ReadAllFromDb : If we are restarted, learn from the database the current execution
768// stage
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530769func (va *VoltApplication) ReadAllFromDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530770 logger.Info(ctx, "Reading the meters from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530771 va.RestoreMetersFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530772 logger.Info(ctx, "Reading the VNETs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530773 va.RestoreVnetsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530774 logger.Info(ctx, "Reading the VPVs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530775 va.RestoreVpvsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530776 logger.Info(ctx, "Reading the Services from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530777 va.RestoreSvcsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530778 logger.Info(ctx, "Reading the MVLANs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530779 va.RestoreMvlansFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530780 logger.Info(ctx, "Reading the IGMP profiles from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530781 va.RestoreIGMPProfilesFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530782 logger.Info(ctx, "Reading the Mcast configs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530783 va.RestoreMcastConfigsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530784 logger.Info(ctx, "Reading the IGMP groups for DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530785 va.RestoreIgmpGroupsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530786 logger.Info(ctx, "Reading Upgrade status from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530787 va.RestoreUpgradeStatus(cntx)
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530788 logger.Info(ctx, "Reading OltFlowService from DB")
789 va.RestoreOltFlowService(cntx)
Akash Sonia8246972023-01-03 10:37:08 +0530790 logger.Info(ctx, "Reading device config from DB")
791 va.RestoreDeviceConfigFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530792 logger.Info(ctx, "Reconciled from DB")
793}
794
795// InitStaticConfig to initialise static config.
796func (va *VoltApplication) InitStaticConfig() {
797 va.InitIgmpSrcMac()
798}
799
800// SetVendorID to set vendor id
801func (va *VoltApplication) SetVendorID(vendorID string) {
802 va.vendorID = vendorID
803}
804
805// GetVendorID to get vendor id
806func (va *VoltApplication) GetVendorID() string {
807 return va.vendorID
808}
809
810// SetRebootFlag to set reboot flag
811func (va *VoltApplication) SetRebootFlag(flag bool) {
812 vgcRebooted = flag
813}
814
815// GetUpgradeFlag to get reboot status
816func (va *VoltApplication) GetUpgradeFlag() bool {
817 return isUpgradeComplete
818}
819
820// SetUpgradeFlag to set reboot status
821func (va *VoltApplication) SetUpgradeFlag(flag bool) {
822 isUpgradeComplete = flag
823}
824
825// ------------------------------------------------------------
826// Device related functions
827
828// AddDevice : Add a device and typically the device stores the NNI port on the device
829// The NNI port is used when the packets are emitted towards the network.
830// The outport is selected as the NNI port of the device. Today, we support
831// a single NNI port per OLT. This is true whether the network uses any
832// protection mechanism (LAG, ERPS, etc.). The aggregate of the such protection
833// is represented by a single NNI port
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530834func (va *VoltApplication) AddDevice(cntx context.Context, device string, slno, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530835 logger.Warnw(ctx, "Received Device Ind: Add", log.Fields{"Device": device, "SrNo": slno})
836 if _, ok := va.DevicesDisc.Load(device); ok {
837 logger.Warnw(ctx, "Device Exists", log.Fields{"Device": device})
838 }
839 d := NewVoltDevice(device, slno, southBoundID)
840
841 addPort := func(key, value interface{}) bool {
842 portID := key.(uint32)
843 port := value.(*PonPortCfg)
844 va.AggActiveChannelsCountForPonPort(device, portID, port)
845 d.ActiveChannelsPerPon.Store(portID, port)
846 return true
847 }
848 if nbDevice, exists := va.NbDevice.Load(southBoundID); exists {
849 // Pon Ports added before OLT activate.
850 nbDevice.(*NbDevice).PonPorts.Range(addPort)
851 } else {
852 // Check if NbPort exists in DB. VGC restart case.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530853 nbd := va.RestoreNbDeviceFromDb(cntx, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530854 nbd.PonPorts.Range(addPort)
855 }
856 va.DevicesDisc.Store(device, d)
857}
858
859// GetDevice to get a device.
860func (va *VoltApplication) GetDevice(device string) *VoltDevice {
861 if d, ok := va.DevicesDisc.Load(device); ok {
862 return d.(*VoltDevice)
863 }
864 return nil
865}
866
867// DelDevice to delete a device.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530868func (va *VoltApplication) DelDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530869 logger.Warnw(ctx, "Received Device Ind: Delete", log.Fields{"Device": device})
870 if vdIntf, ok := va.DevicesDisc.Load(device); ok {
871 vd := vdIntf.(*VoltDevice)
872 va.DevicesDisc.Delete(device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530873 _ = db.DelAllRoutesForDevice(cntx, device)
874 va.HandleFlowClearFlag(cntx, device, vd.SerialNum, vd.SouthBoundID)
875 _ = db.DelAllGroup(cntx, device)
876 _ = db.DelAllMeter(cntx, device)
877 _ = db.DelAllPorts(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +0530878 logger.Debugw(ctx, "Device deleted", log.Fields{"Device": device})
879 } else {
880 logger.Warnw(ctx, "Device Doesn't Exist", log.Fields{"Device": device})
881 }
882}
883
884// GetDeviceBySerialNo to get a device by serial number.
885// TODO - Transform this into a MAP instead
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530886func (va *VoltApplication) GetDeviceBySerialNo(slno string) (*VoltDevice, string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530887 var device *VoltDevice
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530888 var deviceID string
Naveen Sampath04696f72022-06-13 15:19:14 +0530889 getserial := func(key interface{}, value interface{}) bool {
890 device = value.(*VoltDevice)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530891 deviceID = key.(string)
Naveen Sampath04696f72022-06-13 15:19:14 +0530892 return device.SerialNum != slno
893 }
894 va.DevicesDisc.Range(getserial)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530895 return device, deviceID
Naveen Sampath04696f72022-06-13 15:19:14 +0530896}
897
898// PortAddInd : This is a PORT add indication coming from the VPAgent, which is essentially
899// a request coming from VOLTHA. The device and identity of the port is provided
900// in this request. Add them to the application for further use
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530901func (va *VoltApplication) PortAddInd(cntx context.Context, device string, id uint32, portName string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530902 logger.Infow(ctx, "Received Port Ind: Add", log.Fields{"Device": device, "Port": portName})
903 va.portLock.Lock()
904 if d := va.GetDevice(device); d != nil {
905 p := d.AddPort(portName, id)
906 va.PortsDisc.Store(portName, p)
907 va.portLock.Unlock()
908 nni, _ := va.GetNniPort(device)
909 if nni == portName {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530910 d.pushFlowsForUnis(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530911 }
912 } else {
913 va.portLock.Unlock()
914 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Add", log.Fields{"Device": device, "Port": portName})
915 }
916}
917
918// PortDelInd : Only the NNI ports are recorded in the device for now. When port delete
919// arrives, only the NNI ports need adjustments.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530920func (va *VoltApplication) PortDelInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530921 logger.Infow(ctx, "Received Port Ind: Delete", log.Fields{"Device": device, "Port": port})
922 if d := va.GetDevice(device); d != nil {
923 p := d.GetPort(port)
924 if p != nil && p.State == PortStateUp {
925 logger.Infow(ctx, "Port state is UP. Trigerring Port Down Ind before deleting", log.Fields{"Port": p})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530926 va.PortDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530927 }
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530928 // if RemoveFlowsOnDisable is flase, then flows will be existing till port delete. Remove the flows now
929 if !va.OltFlowServiceConfig.RemoveFlowsOnDisable {
Akash Sonia8246972023-01-03 10:37:08 +0530930 vpvs, ok := va.VnetsByPort.Load(port)
931 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530932 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
933 } else {
934 for _, vpv := range vpvs.([]*VoltPortVnet) {
935 vpv.VpvLock.Lock()
936 vpv.PortDownInd(cntx, device, port, true)
937 vpv.VpvLock.Unlock()
938 }
939 }
940 }
Naveen Sampath04696f72022-06-13 15:19:14 +0530941 va.portLock.Lock()
942 defer va.portLock.Unlock()
943 d.DelPort(port)
944 if _, ok := va.PortsDisc.Load(port); ok {
945 va.PortsDisc.Delete(port)
946 }
947 } else {
948 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Delete", log.Fields{"Device": device, "Port": port})
949 }
950}
951
952//PortUpdateInd Updates port Id incase of ONU movement
953func (va *VoltApplication) PortUpdateInd(device string, portName string, id uint32) {
954 logger.Infow(ctx, "Received Port Ind: Update", log.Fields{"Device": device, "Port": portName})
955 va.portLock.Lock()
956 defer va.portLock.Unlock()
957 if d := va.GetDevice(device); d != nil {
958 vp := d.GetPort(portName)
959 vp.ID = id
960 } else {
961 logger.Warnw(ctx, "Device Not Found", log.Fields{"Device": device, "Port": portName})
962 }
963}
964
965// AddNbPonPort Add pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530966func (va *VoltApplication) AddNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32,
Naveen Sampath04696f72022-06-13 15:19:14 +0530967 enableMulticastKPI bool, portAlarmProfileID string) error {
968
969 var nbd *NbDevice
970 nbDevice, ok := va.NbDevice.Load(oltSbID)
971
972 if !ok {
973 nbd = NewNbDevice()
974 nbd.SouthBoundID = oltSbID
975 } else {
976 nbd = nbDevice.(*NbDevice)
977 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530978 port := nbd.AddPortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530979
980 // Add this port to voltDevice
981 addPort := func(key, value interface{}) bool {
982 voltDevice := value.(*VoltDevice)
983 if oltSbID == voltDevice.SouthBoundID {
984 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); !exists {
985 voltDevice.ActiveChannelsPerPon.Store(portID, port)
986 }
987 return false
988 }
989 return true
990 }
991 va.DevicesDisc.Range(addPort)
992 va.NbDevice.Store(oltSbID, nbd)
993
994 return nil
995}
996
997// UpdateNbPonPort update pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530998func (va *VoltApplication) UpdateNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530999
1000 var nbd *NbDevice
1001 nbDevice, ok := va.NbDevice.Load(oltSbID)
1002
1003 if !ok {
1004 logger.Errorw(ctx, "Device-doesn't-exists", log.Fields{"deviceID": oltSbID})
1005 return fmt.Errorf("Device-doesn't-exists-%v", oltSbID)
1006 }
1007 nbd = nbDevice.(*NbDevice)
1008
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301009 port := nbd.UpdatePortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301010 if port == nil {
1011 return fmt.Errorf("Port-doesn't-exists-%v", portID)
1012 }
1013 va.NbDevice.Store(oltSbID, nbd)
1014
1015 // Add this port to voltDevice
1016 updPort := func(key, value interface{}) bool {
1017 voltDevice := value.(*VoltDevice)
1018 if oltSbID == voltDevice.SouthBoundID {
1019 voltDevice.ActiveChannelCountLock.Lock()
1020 if p, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
1021 oldPort := p.(*PonPortCfg)
1022 if port.MaxActiveChannels != 0 {
1023 oldPort.MaxActiveChannels = port.MaxActiveChannels
1024 oldPort.EnableMulticastKPI = port.EnableMulticastKPI
1025 voltDevice.ActiveChannelsPerPon.Store(portID, oldPort)
1026 }
1027 }
1028 voltDevice.ActiveChannelCountLock.Unlock()
1029 return false
1030 }
1031 return true
1032 }
1033 va.DevicesDisc.Range(updPort)
1034
1035 return nil
1036}
1037
1038// DeleteNbPonPort Delete pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301039func (va *VoltApplication) DeleteNbPonPort(cntx context.Context, oltSbID string, portID uint32) error {
Naveen Sampath04696f72022-06-13 15:19:14 +05301040 nbDevice, ok := va.NbDevice.Load(oltSbID)
1041 if ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301042 nbDevice.(*NbDevice).DeletePortFromNbDevice(cntx, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301043 va.NbDevice.Store(oltSbID, nbDevice.(*NbDevice))
1044 } else {
1045 logger.Warnw(ctx, "Delete pon received for unknown device", log.Fields{"oltSbID": oltSbID})
1046 return nil
1047 }
1048 // Delete this port from voltDevice
1049 delPort := func(key, value interface{}) bool {
1050 voltDevice := value.(*VoltDevice)
1051 if oltSbID == voltDevice.SouthBoundID {
1052 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
1053 voltDevice.ActiveChannelsPerPon.Delete(portID)
1054 }
1055 return false
1056 }
1057 return true
1058 }
1059 va.DevicesDisc.Range(delPort)
1060 return nil
1061}
1062
1063// GetNniPort : Get the NNI port for a device. Called from different other applications
1064// as a port to match or destination for a packet out. The VOLT application
1065// is written with the assumption that there is a single NNI port. The OLT
1066// device is responsible for translating the combination of VLAN and the
1067// NNI port ID to identify possibly a single physical port or a logical
1068// port which is a result of protection methods applied.
1069func (va *VoltApplication) GetNniPort(device string) (string, error) {
1070 va.portLock.Lock()
1071 defer va.portLock.Unlock()
1072 d, ok := va.DevicesDisc.Load(device)
1073 if !ok {
1074 return "", errors.New("Device Doesn't Exist")
1075 }
1076 return d.(*VoltDevice).NniPort, nil
1077}
1078
1079// NniDownInd process for Nni down indication.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301080func (va *VoltApplication) NniDownInd(cntx context.Context, deviceID string, devSrNo string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301081
1082 logger.Debugw(ctx, "NNI Down Ind", log.Fields{"device": devSrNo})
1083
1084 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1085 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301086 mvProfile.removeIgmpMcastFlows(cntx, devSrNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301087 return true
1088 }
1089 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1090
1091 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301092 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301093}
1094
1095// DeviceUpInd changes device state to up.
1096func (va *VoltApplication) DeviceUpInd(device string) {
1097 logger.Warnw(ctx, "Received Device Ind: UP", log.Fields{"Device": device})
1098 if d := va.GetDevice(device); d != nil {
1099 d.State = controller.DeviceStateUP
1100 } else {
1101 logger.Errorw(ctx, "Ignoring Device indication: UP. Device Missing", log.Fields{"Device": device})
1102 }
1103}
1104
1105// DeviceDownInd changes device state to down.
1106func (va *VoltApplication) DeviceDownInd(device string) {
1107 logger.Warnw(ctx, "Received Device Ind: DOWN", log.Fields{"Device": device})
1108 if d := va.GetDevice(device); d != nil {
1109 d.State = controller.DeviceStateDOWN
1110 } else {
1111 logger.Errorw(ctx, "Ignoring Device indication: DOWN. Device Missing", log.Fields{"Device": device})
1112 }
1113}
1114
1115// DeviceRebootInd process for handling flow clear flag for device reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301116func (va *VoltApplication) DeviceRebootInd(cntx context.Context, device string, serialNum string, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301117 logger.Warnw(ctx, "Received Device Ind: Reboot", log.Fields{"Device": device, "SerialNumber": serialNum})
1118
1119 if d := va.GetDevice(device); d != nil {
1120 if d.State == controller.DeviceStateREBOOTED {
1121 logger.Warnw(ctx, "Ignoring Device Ind: Reboot, Device already in Reboot state", log.Fields{"Device": device, "SerialNumber": serialNum, "State": d.State})
1122 return
1123 }
1124 d.State = controller.DeviceStateREBOOTED
1125 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301126 va.HandleFlowClearFlag(cntx, device, serialNum, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301127
1128}
1129
1130// DeviceDisableInd handles device deactivation process
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301131func (va *VoltApplication) DeviceDisableInd(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301132 logger.Warnw(ctx, "Received Device Ind: Disable", log.Fields{"Device": device})
1133
1134 d := va.GetDevice(device)
1135 if d == nil {
1136 logger.Errorw(ctx, "Ignoring Device indication: DISABLED. Device Missing", log.Fields{"Device": device})
1137 return
1138 }
1139
1140 d.State = controller.DeviceStateDISABLED
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301141 va.HandleFlowClearFlag(cntx, device, d.SerialNum, d.SouthBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301142}
1143
1144// ProcessIgmpDSFlowForMvlan for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301145func (va *VoltApplication) ProcessIgmpDSFlowForMvlan(cntx context.Context, d *VoltDevice, mvp *MvlanProfile, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301146
1147 logger.Debugw(ctx, "Process IGMP DS Flows for MVlan", log.Fields{"device": d.Name, "Mvlan": mvp.Mvlan, "addFlow": addFlow})
1148 portState := false
1149 p := d.GetPort(d.NniPort)
1150 if p != nil && p.State == PortStateUp {
1151 portState = true
1152 }
1153
1154 if addFlow {
1155 if portState {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301156 mvp.pushIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301157 }
1158 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301159 mvp.removeIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301160 }
1161}
1162
1163// ProcessIgmpDSFlowForDevice for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301164func (va *VoltApplication) ProcessIgmpDSFlowForDevice(cntx context.Context, d *VoltDevice, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301165 logger.Debugw(ctx, "Process IGMP DS Flows for device", log.Fields{"device": d.Name, "addFlow": addFlow})
1166
1167 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1168 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301169 va.ProcessIgmpDSFlowForMvlan(cntx, d, mvProfile, addFlow)
Naveen Sampath04696f72022-06-13 15:19:14 +05301170 return true
1171 }
1172 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1173}
1174
1175// GetDeviceFromPort : This is suitable only for access ports as their naming convention
1176// makes them unique across all the OLTs. This must be called with
1177// port name that is an access port. Currently called from VNETs, attached
1178// only to access ports, and the services which are also attached only
1179// to access ports
1180func (va *VoltApplication) GetDeviceFromPort(port string) (*VoltDevice, error) {
1181 va.portLock.Lock()
1182 defer va.portLock.Unlock()
1183 var err error
1184 err = nil
1185 p, ok := va.PortsDisc.Load(port)
1186 if !ok {
1187 return nil, errorCodes.ErrPortNotFound
1188 }
1189 d := va.GetDevice(p.(*VoltPort).Device)
1190 if d == nil {
1191 err = errorCodes.ErrDeviceNotFound
1192 }
1193 return d, err
1194}
1195
1196// GetPortID : This too applies only to access ports. The ports can be indexed
1197// purely by their names without the device forming part of the key
1198func (va *VoltApplication) GetPortID(port string) (uint32, error) {
1199 va.portLock.Lock()
1200 defer va.portLock.Unlock()
1201 p, ok := va.PortsDisc.Load(port)
1202 if !ok {
1203 return 0, errorCodes.ErrPortNotFound
1204 }
1205 return p.(*VoltPort).ID, nil
1206}
1207
1208// GetPortName : This too applies only to access ports. The ports can be indexed
1209// purely by their names without the device forming part of the key
1210func (va *VoltApplication) GetPortName(port uint32) (string, error) {
1211 va.portLock.Lock()
1212 defer va.portLock.Unlock()
1213 var portName string
1214 va.PortsDisc.Range(func(key interface{}, value interface{}) bool {
1215 portInfo := value.(*VoltPort)
1216 if portInfo.ID == port {
1217 portName = portInfo.Name
1218 return false
1219 }
1220 return true
1221 })
1222 return portName, nil
1223}
1224
1225// GetPonFromUniPort to get Pon info from UniPort
1226func (va *VoltApplication) GetPonFromUniPort(port string) (string, error) {
1227 uniPortID, err := va.GetPortID(port)
1228 if err == nil {
1229 ponPortID := (uniPortID & 0x0FF00000) >> 20 //pon(8) + onu(8) + uni(12)
1230 return strconv.FormatUint(uint64(ponPortID), 10), nil
1231 }
1232 return "", err
1233}
1234
1235// GetPortState : This too applies only to access ports. The ports can be indexed
1236// purely by their names without the device forming part of the key
1237func (va *VoltApplication) GetPortState(port string) (PortState, error) {
1238 va.portLock.Lock()
1239 defer va.portLock.Unlock()
1240 p, ok := va.PortsDisc.Load(port)
1241 if !ok {
1242 return 0, errors.New("Port not configured")
1243 }
1244 return p.(*VoltPort).State, nil
1245}
1246
1247// GetIcmpv6Receivers to get Icmp v6 receivers
1248func (va *VoltApplication) GetIcmpv6Receivers(device string) []uint32 {
1249 var receiverList []uint32
1250 receivers, _ := va.Icmpv6Receivers.Load(device)
1251 if receivers != nil {
1252 receiverList = receivers.([]uint32)
1253 }
1254 return receiverList
1255}
1256
1257// AddIcmpv6Receivers to add Icmp v6 receivers
1258func (va *VoltApplication) AddIcmpv6Receivers(device string, portID uint32) []uint32 {
1259 var receiverList []uint32
1260 receivers, _ := va.Icmpv6Receivers.Load(device)
1261 if receivers != nil {
1262 receiverList = receivers.([]uint32)
1263 }
1264 receiverList = append(receiverList, portID)
1265 va.Icmpv6Receivers.Store(device, receiverList)
1266 logger.Debugw(ctx, "Receivers after addition", log.Fields{"Receivers": receiverList})
1267 return receiverList
1268}
1269
1270// DelIcmpv6Receivers to delete Icmp v6 receievers
1271func (va *VoltApplication) DelIcmpv6Receivers(device string, portID uint32) []uint32 {
1272 var receiverList []uint32
1273 receivers, _ := va.Icmpv6Receivers.Load(device)
1274 if receivers != nil {
1275 receiverList = receivers.([]uint32)
1276 }
1277 for i, port := range receiverList {
1278 if port == portID {
1279 receiverList = append(receiverList[0:i], receiverList[i+1:]...)
1280 va.Icmpv6Receivers.Store(device, receiverList)
1281 break
1282 }
1283 }
1284 logger.Debugw(ctx, "Receivers After deletion", log.Fields{"Receivers": receiverList})
1285 return receiverList
1286}
1287
1288// ProcessDevFlowForDevice - Process DS ICMPv6 & ARP flow for provided device and vnet profile
1289// device - Device Obj
1290// vnet - vnet profile name
1291// enabled - vlan enabled/disabled - based on the status, the flow shall be added/removed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301292func (va *VoltApplication) ProcessDevFlowForDevice(cntx context.Context, device *VoltDevice, vnet *VoltVnet, enabled bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301293 _, applied := device.ConfiguredVlanForDeviceFlows.Get(VnetKey(vnet.SVlan, vnet.CVlan, 0))
1294 if enabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301295 va.PushDevFlowForVlan(cntx, vnet)
Naveen Sampath04696f72022-06-13 15:19:14 +05301296 } else if !enabled && applied {
1297 //va.DeleteDevFlowForVlan(vnet)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301298 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, device.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301299 }
1300}
1301
1302//NniVlanIndToIgmp - Trigger receiver up indication to all ports with igmp enabled
1303//and has the provided mvlan
1304func (va *VoltApplication) NniVlanIndToIgmp(device *VoltDevice, mvp *MvlanProfile) {
1305
1306 logger.Infow(ctx, "Sending Igmp Receiver UP indication for all Services", log.Fields{"Vlan": mvp.Mvlan})
1307
1308 //Trigger nni indication for receiver only for first time
1309 if device.IgmpDsFlowAppliedForMvlan[uint16(mvp.Mvlan)] {
1310 return
1311 }
1312 device.Ports.Range(func(key, value interface{}) bool {
1313 port := key.(string)
1314
1315 if state, _ := va.GetPortState(port); state == PortStateUp {
1316 vpvs, _ := va.VnetsByPort.Load(port)
1317 if vpvs == nil {
1318 return true
1319 }
1320 for _, vpv := range vpvs.([]*VoltPortVnet) {
1321 //Send indication only for subscribers with the received mvlan profile
1322 if vpv.IgmpEnabled && vpv.MvlanProfileName == mvp.Name {
1323 vpv.services.Range(ReceiverUpInd)
1324 }
1325 }
1326 }
1327 return true
1328 })
1329}
1330
1331// PortUpInd :
1332// -----------------------------------------------------------------------
1333// Port status change handling
1334// ----------------------------------------------------------------------
1335// Port UP indication is passed to all services associated with the port
1336// so that the services can configure flows applicable when the port goes
1337// up from down state
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301338func (va *VoltApplication) PortUpInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301339 d := va.GetDevice(device)
1340
1341 if d == nil {
1342 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: UP", log.Fields{"Device": device, "Port": port})
1343 return
1344 }
1345
1346 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1347 va.portLock.Lock()
1348 // Do not defer the port mutex unlock here
1349 // Some of the following func calls needs the port lock, so defering the lock here
1350 // may lead to dead-lock
1351 p := d.GetPort(port)
1352
1353 if p == nil {
1354 logger.Infow(ctx, "Ignoring Port Ind: UP, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1355 va.portLock.Unlock()
1356 return
1357 }
1358 p.State = PortStateUp
1359 va.portLock.Unlock()
1360
1361 logger.Infow(ctx, "Received SouthBound Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1362 if p.Type == VoltPortTypeNni {
1363
1364 logger.Warnw(ctx, "Received NNI Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1365 //va.PushDevFlowForDevice(d)
1366 //Build Igmp TrapFlowRule
1367 //va.ProcessIgmpDSFlowForDevice(d, true)
1368 }
1369 vpvs, ok := va.VnetsByPort.Load(port)
1370 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1371 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1372 //msgbus.ProcessPortInd(msgbus.PortUp, d.SerialNum, p.Name, false, getServiceList(port))
1373 return
1374 }
1375
1376 //If NNI port is not UP, do not push Flows
1377 if d.NniPort == "" {
1378 logger.Warnw(ctx, "NNI port not UP. Not sending Port UP Ind for VPVs", log.Fields{"NNI": d.NniPort})
1379 return
1380 }
1381
1382 vpvList := vpvs.([]*VoltPortVnet)
1383 if vpvList[0].PonPort != 0xFF && vpvList[0].PonPort != p.PonPort {
1384 logger.Errorw(ctx, "UNI port discovered on wrong PON Port. Dropping Port Indication", log.Fields{"Device": device, "Port": port, "DetectedPon": p.PonPort, "ExpectedPon": vpvList[0].PonPort})
1385
1386 //Remove the flow (if any) which are already installed - Valid for PON switching when VGC pod is DOWN
1387 for _, vpv := range vpvs.([]*VoltPortVnet) {
1388 vpv.VpvLock.Lock()
1389 logger.Warnw(ctx, "Removing existing VPVs/Services flows for for Subscriber: UNI Detected on wrong PON", log.Fields{"Port": vpv.Port, "Vnet": vpv.VnetName})
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05301390 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301391 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301392 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301393 }
1394 vpv.VpvLock.Unlock()
1395 }
1396 return
1397 }
1398
Naveen Sampath04696f72022-06-13 15:19:14 +05301399 for _, vpv := range vpvs.([]*VoltPortVnet) {
1400 vpv.VpvLock.Lock()
Tinoj Josephec742f62022-09-29 19:11:10 +05301401 //If no service is activated drop the portUpInd
1402 if vpv.IsServiceActivated(cntx) {
1403 //Do not trigger indication for the vpv which is already removed from vpv list as
1404 // part of service delete (during the lock wait duration)
1405 // In that case, the services associated wil be zero
1406 if vpv.servicesCount.Load() != 0 {
1407 vpv.PortUpInd(cntx, d, port)
1408 }
1409 } else {
1410 // Service not activated, still attach device to service
1411 vpv.setDevice(d.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +05301412 }
1413 vpv.VpvLock.Unlock()
1414 }
1415 // At the end of processing inform the other entities that
1416 // are interested in the events
1417}
1418
1419/*
1420func getServiceList(port string) map[string]bool {
1421 serviceList := make(map[string]bool)
1422
1423 getServiceNames := func(key interface{}, value interface{}) bool {
1424 serviceList[key.(string)] = value.(*VoltService).DsHSIAFlowsApplied
1425 return true
1426 }
1427
1428 if vpvs, _ := GetApplication().VnetsByPort.Load(port); vpvs != nil {
1429 vpvList := vpvs.([]*VoltPortVnet)
1430 for _, vpv := range vpvList {
1431 vpv.services.Range(getServiceNames)
1432 }
1433 }
1434 return serviceList
1435
1436}*/
1437
1438//ReceiverUpInd - Send receiver up indication for service with Igmp enabled
1439func ReceiverUpInd(key, value interface{}) bool {
1440 svc := value.(*VoltService)
1441 var vlan of.VlanType
1442
1443 if !svc.IPAssigned() {
1444 logger.Infow(ctx, "IP Not assigned, skipping general query", log.Fields{"Service": svc})
1445 return false
1446 }
1447
1448 //Send port up indication to igmp only for service with igmp enabled
1449 if svc.IgmpEnabled {
1450 if svc.VlanControl == ONUCVlan || svc.VlanControl == ONUCVlanOLTSVlan {
1451 vlan = svc.CVlan
1452 } else {
1453 vlan = svc.UniVlan
1454 }
1455 if device, _ := GetApplication().GetDeviceFromPort(svc.Port); device != nil {
1456 GetApplication().ReceiverUpInd(device.Name, svc.Port, svc.MvlanProfileName, vlan, svc.Pbits)
1457 }
1458 return false
1459 }
1460 return true
1461}
1462
1463// PortDownInd : Port down indication is passed on to the services so that the services
1464// can make changes at this transition.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301465func (va *VoltApplication) PortDownInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301466 logger.Infow(ctx, "Received SouthBound Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1467 d := va.GetDevice(device)
1468
1469 if d == nil {
1470 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1471 return
1472 }
1473 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1474 va.portLock.Lock()
1475 // Do not defer the port mutex unlock here
1476 // Some of the following func calls needs the port lock, so defering the lock here
1477 // may lead to dead-lock
1478 p := d.GetPort(port)
1479 if p == nil {
1480 logger.Infow(ctx, "Ignoring Port Ind: Down, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1481 va.portLock.Unlock()
1482 return
1483 }
1484 p.State = PortStateDown
1485 va.portLock.Unlock()
1486
1487 if d.State == controller.DeviceStateREBOOTED {
1488 logger.Infow(ctx, "Ignoring Port Ind: Down, Device has been Rebooted", log.Fields{"Device": device, "PortName": port, "PortId": p})
1489 return
1490 }
1491
1492 if p.Type == VoltPortTypeNni {
1493 logger.Warnw(ctx, "Received NNI Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301494 va.DeleteDevFlowForDevice(cntx, d)
1495 va.NniDownInd(cntx, device, d.SerialNum)
1496 va.RemovePendingGroups(cntx, device, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301497 }
1498 vpvs, ok := va.VnetsByPort.Load(port)
1499 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1500 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1501 //msgbus.ProcessPortInd(msgbus.PortDown, d.SerialNum, p.Name, false, getServiceList(port))
1502 return
1503 }
Akash Sonia8246972023-01-03 10:37:08 +05301504
Naveen Sampath04696f72022-06-13 15:19:14 +05301505 for _, vpv := range vpvs.([]*VoltPortVnet) {
1506 vpv.VpvLock.Lock()
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05301507 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301508 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301509 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301510 }
1511 vpv.VpvLock.Unlock()
1512 }
1513}
1514
1515// PacketInInd :
1516// -----------------------------------------------------------------------
1517// PacketIn Processing
1518// Packet In Indication processing. It arrives with the identities of
1519// the device and port on which the packet is received. At first, the
1520// packet is decoded and the right processor is called. Currently, we
1521// plan to support only DHCP and IGMP. In future, we can add more
1522// capabilities as needed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301523func (va *VoltApplication) PacketInInd(cntx context.Context, device string, port string, pkt []byte) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301524 // Decode the incoming packet
1525 packetSide := US
1526 if strings.Contains(port, NNI) {
1527 packetSide = DS
1528 }
1529
1530 logger.Debugw(ctx, "Received a Packet-In Indication", log.Fields{"Device": device, "Port": port})
1531
1532 gopkt := gopacket.NewPacket(pkt, layers.LayerTypeEthernet, gopacket.Default)
1533
1534 var dot1qFound = false
1535 for _, l := range gopkt.Layers() {
1536 if l.LayerType() == layers.LayerTypeDot1Q {
1537 dot1qFound = true
1538 break
1539 }
1540 }
1541
1542 if !dot1qFound {
1543 logger.Debugw(ctx, "Ignoring Received Packet-In Indication without Dot1Q Header",
1544 log.Fields{"Device": device, "Port": port})
1545 return
1546 }
1547
1548 logger.Debugw(ctx, "Received Southbound Packet In", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1549
1550 // Classify the packet into packet types that we support
1551 // The supported types are DHCP and IGMP. The DHCP packet is
1552 // identified by matching the L4 protocol to UDP. The IGMP packet
1553 // is identified by matching L3 protocol to IGMP
1554 arpl := gopkt.Layer(layers.LayerTypeARP)
1555 if arpl != nil {
1556 if callBack, ok := PacketHandlers[ARP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301557 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301558 } else {
1559 logger.Debugw(ctx, "ARP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1560 }
1561 return
1562 }
1563 ipv4l := gopkt.Layer(layers.LayerTypeIPv4)
1564 if ipv4l != nil {
1565 ip := ipv4l.(*layers.IPv4)
1566
1567 if ip.Protocol == layers.IPProtocolUDP {
1568 logger.Debugw(ctx, "Received Southbound UDP ipv4 packet in", log.Fields{"StreamSide": packetSide})
1569 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv4)
1570 if dhcpl != nil {
1571 if callBack, ok := PacketHandlers[DHCPv4]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301572 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301573 } else {
1574 logger.Debugw(ctx, "DHCPv4 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1575 }
1576 }
1577 } else if ip.Protocol == layers.IPProtocolIGMP {
1578 logger.Debugw(ctx, "Received Southbound IGMP packet in", log.Fields{"StreamSide": packetSide})
1579 if callBack, ok := PacketHandlers[IGMP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301580 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301581 } else {
1582 logger.Debugw(ctx, "IGMP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1583 }
1584 }
1585 return
1586 }
1587 ipv6l := gopkt.Layer(layers.LayerTypeIPv6)
1588 if ipv6l != nil {
1589 ip := ipv6l.(*layers.IPv6)
1590 if ip.NextHeader == layers.IPProtocolUDP {
1591 logger.Debug(ctx, "Received Southbound UDP ipv6 packet in")
1592 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv6)
1593 if dhcpl != nil {
1594 if callBack, ok := PacketHandlers[DHCPv6]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301595 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301596 } else {
1597 logger.Debugw(ctx, "DHCPv6 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1598 }
1599 }
1600 }
1601 return
1602 }
1603
1604 pppoel := gopkt.Layer(layers.LayerTypePPPoE)
1605 if pppoel != nil {
1606 logger.Debugw(ctx, "Received Southbound PPPoE packet in", log.Fields{"StreamSide": packetSide})
1607 if callBack, ok := PacketHandlers[PPPOE]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301608 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301609 } else {
1610 logger.Debugw(ctx, "PPPoE handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1611 }
1612 }
1613}
1614
1615// GetVlans : This utility gets the VLANs from the packet. The VLANs are
1616// used to identify the right service that must process the incoming
1617// packet
1618func GetVlans(pkt gopacket.Packet) []of.VlanType {
1619 var vlans []of.VlanType
1620 for _, l := range pkt.Layers() {
1621 if l.LayerType() == layers.LayerTypeDot1Q {
1622 q, ok := l.(*layers.Dot1Q)
1623 if ok {
1624 vlans = append(vlans, of.VlanType(q.VLANIdentifier))
1625 }
1626 }
1627 }
1628 return vlans
1629}
1630
1631// GetPriority to get priority
1632func GetPriority(pkt gopacket.Packet) uint8 {
1633 for _, l := range pkt.Layers() {
1634 if l.LayerType() == layers.LayerTypeDot1Q {
1635 q, ok := l.(*layers.Dot1Q)
1636 if ok {
1637 return q.Priority
1638 }
1639 }
1640 }
1641 return PriorityNone
1642}
1643
1644// HandleFlowClearFlag to handle flow clear flag during reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301645func (va *VoltApplication) HandleFlowClearFlag(cntx context.Context, deviceID string, serialNum, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301646 logger.Warnw(ctx, "Clear All flags for Device", log.Fields{"Device": deviceID, "SerialNum": serialNum, "SBID": southBoundID})
1647 dev, ok := va.DevicesDisc.Load(deviceID)
1648 if ok && dev != nil {
1649 logger.Infow(ctx, "Clear Flags for device", log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1650 dev.(*VoltDevice).icmpv6GroupAdded = false
1651 logger.Infow(ctx, "Clearing DS Icmpv6 Map",
1652 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1653 dev.(*VoltDevice).ConfiguredVlanForDeviceFlows = util.NewConcurrentMap()
1654 logger.Infow(ctx, "Clearing DS IGMP Map",
1655 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1656 for k := range dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan {
1657 delete(dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan, k)
1658 }
1659 //Delete group 1 - ICMPv6/ARP group
1660 if err := ProcessIcmpv6McGroup(deviceID, true); err != nil {
1661 logger.Errorw(ctx, "ProcessIcmpv6McGroup failed", log.Fields{"Device": deviceID, "Error": err})
1662 }
1663 } else {
1664 logger.Warnw(ctx, "VoltDevice not found for device ", log.Fields{"deviceID": deviceID})
1665 }
1666
1667 getVpvs := func(key interface{}, value interface{}) bool {
1668 vpvs := value.([]*VoltPortVnet)
1669 for _, vpv := range vpvs {
1670 if vpv.Device == deviceID {
1671 logger.Infow(ctx, "Clear Flags for vpv",
1672 log.Fields{"device": vpv.Device, "port": vpv.Port,
1673 "svlan": vpv.SVlan, "cvlan": vpv.CVlan, "univlan": vpv.UniVlan})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301674 vpv.ClearAllServiceFlags(cntx)
1675 vpv.ClearAllVpvFlags(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301676
1677 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301678 va.ReceiverDownInd(cntx, vpv.Device, vpv.Port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301679 //Also clear service igmp stats
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301680 vpv.ClearServiceCounters(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301681 }
1682 }
1683 }
1684 return true
1685 }
1686 va.VnetsByPort.Range(getVpvs)
1687
1688 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301689 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301690
1691 logger.Warnw(ctx, "All flags cleared for device", log.Fields{"Device": deviceID})
1692
1693 //Reset pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301694 va.RemovePendingGroups(cntx, deviceID, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301695
1696 //Process all Migrate Service Request - force udpate all profiles since resources are already cleaned up
1697 if dev != nil {
1698 triggerForceUpdate := func(key, value interface{}) bool {
1699 msrList := value.(*util.ConcurrentMap)
1700 forceUpdateServices := func(key, value interface{}) bool {
1701 msr := value.(*MigrateServicesRequest)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301702 forceUpdateAllServices(cntx, msr)
Naveen Sampath04696f72022-06-13 15:19:14 +05301703 return true
1704 }
1705 msrList.Range(forceUpdateServices)
1706 return true
1707 }
1708 dev.(*VoltDevice).MigratingServices.Range(triggerForceUpdate)
1709 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301710 va.FetchAndProcessAllMigrateServicesReq(cntx, deviceID, forceUpdateAllServices)
Naveen Sampath04696f72022-06-13 15:19:14 +05301711 }
1712}
1713
1714//GetPonPortIDFromUNIPort to get pon port id from uni port
1715func GetPonPortIDFromUNIPort(uniPortID uint32) uint32 {
1716 ponPortID := (uniPortID & 0x0FF00000) >> 20
1717 return ponPortID
1718}
1719
1720//ProcessFlowModResultIndication - Processes Flow mod operation indications from controller
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301721func (va *VoltApplication) ProcessFlowModResultIndication(cntx context.Context, flowStatus intf.FlowStatus) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301722
1723 d := va.GetDevice(flowStatus.Device)
1724 if d == nil {
1725 logger.Errorw(ctx, "Dropping Flow Mod Indication. Device not found", log.Fields{"Cookie": flowStatus.Cookie, "Device": flowStatus.Device})
1726 return
1727 }
1728
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301729 cookieExists := ExecuteFlowEvent(cntx, d, flowStatus.Cookie, flowStatus)
Naveen Sampath04696f72022-06-13 15:19:14 +05301730
1731 if flowStatus.Flow != nil {
1732 flowAdd := (flowStatus.FlowModType == of.CommandAdd)
1733 if !cookieExists && !isFlowStatusSuccess(flowStatus.Status, flowAdd) {
1734 pushFlowFailureNotif(flowStatus)
1735 }
1736 }
1737}
1738
1739func pushFlowFailureNotif(flowStatus intf.FlowStatus) {
1740 subFlow := flowStatus.Flow
1741 cookie := subFlow.Cookie
1742 uniPort := cookie >> 16 & 0xFFFFFFFF
1743 logger.Errorw(ctx, "Flow Failure Notification", log.Fields{"uniPort": uniPort, "Cookie": cookie})
Naveen Sampath04696f72022-06-13 15:19:14 +05301744}
1745
1746//UpdateMvlanProfilesForDevice to update mvlan profile for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301747func (va *VoltApplication) UpdateMvlanProfilesForDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301748
1749 checkAndAddMvlanUpdateTask := func(key, value interface{}) bool {
1750 mvp := value.(*MvlanProfile)
1751 if mvp.IsUpdateInProgressForDevice(device) {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301752 mvp.UpdateProfile(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301753 }
1754 return true
1755 }
1756 va.MvlanProfilesByName.Range(checkAndAddMvlanUpdateTask)
1757}
1758
1759// TaskInfo structure that is used to store the task Info.
1760type TaskInfo struct {
1761 ID string
1762 Name string
1763 Timestamp string
1764}
1765
1766// GetTaskList to get task list information.
1767func (va *VoltApplication) GetTaskList(device string) map[int]*TaskInfo {
1768 taskList := cntlr.GetController().GetTaskList(device)
1769 taskMap := make(map[int]*TaskInfo)
1770 for i, task := range taskList {
1771 taskID := strconv.Itoa(int(task.TaskID()))
1772 name := task.Name()
1773 timestamp := task.Timestamp()
1774 taskInfo := &TaskInfo{ID: taskID, Name: name, Timestamp: timestamp}
1775 taskMap[i] = taskInfo
1776 }
1777 return taskMap
1778}
1779
1780// UpdateDeviceSerialNumberList to update the device serial number list after device serial number is updated for vnet and mvlan
1781func (va *VoltApplication) UpdateDeviceSerialNumberList(oldOltSlNo string, newOltSlNo string) {
1782
Tinoj Joseph50d722c2022-12-06 22:53:22 +05301783 voltDevice, _ := va.GetDeviceBySerialNo(oldOltSlNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301784
1785 if voltDevice != nil {
1786 // Device is present with old serial number ID
1787 logger.Errorw(ctx, "OLT Migration cannot be completed as there are dangling devices", log.Fields{"Serial Number": oldOltSlNo})
1788
1789 } else {
1790 logger.Infow(ctx, "No device present with old serial number", log.Fields{"Serial Number": oldOltSlNo})
1791
1792 // Add Serial Number to Blocked Devices List.
1793 cntlr.GetController().AddBlockedDevices(oldOltSlNo)
1794 cntlr.GetController().AddBlockedDevices(newOltSlNo)
1795
1796 updateSlNoForVnet := func(key, value interface{}) bool {
1797 vnet := value.(*VoltVnet)
1798 for i, deviceSlNo := range vnet.VnetConfig.DevicesList {
1799 if deviceSlNo == oldOltSlNo {
1800 vnet.VnetConfig.DevicesList[i] = newOltSlNo
1801 logger.Infow(ctx, "device serial number updated for vnet profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1802 break
1803 }
1804 }
1805 return true
1806 }
1807
1808 updateSlNoforMvlan := func(key interface{}, value interface{}) bool {
1809 mvProfile := value.(*MvlanProfile)
1810 for deviceSlNo := range mvProfile.DevicesList {
1811 if deviceSlNo == oldOltSlNo {
1812 mvProfile.DevicesList[newOltSlNo] = mvProfile.DevicesList[oldOltSlNo]
1813 delete(mvProfile.DevicesList, oldOltSlNo)
1814 logger.Infow(ctx, "device serial number updated for mvlan profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1815 break
1816 }
1817 }
1818 return true
1819 }
1820
1821 va.VnetsByName.Range(updateSlNoForVnet)
1822 va.MvlanProfilesByName.Range(updateSlNoforMvlan)
1823
1824 // Clear the serial number from Blocked Devices List
1825 cntlr.GetController().DelBlockedDevices(oldOltSlNo)
1826 cntlr.GetController().DelBlockedDevices(newOltSlNo)
1827
1828 }
1829}
1830
1831// GetVpvsForDsPkt to get vpv for downstream packets
1832func (va *VoltApplication) GetVpvsForDsPkt(cvlan of.VlanType, svlan of.VlanType, clientMAC net.HardwareAddr,
1833 pbit uint8) ([]*VoltPortVnet, error) {
1834
1835 var matchVPVs []*VoltPortVnet
1836 findVpv := func(key, value interface{}) bool {
1837 vpvs := value.([]*VoltPortVnet)
1838 for _, vpv := range vpvs {
1839 if vpv.isVlanMatching(cvlan, svlan) && vpv.MatchesPriority(pbit) != nil {
1840 var subMac net.HardwareAddr
1841 if NonZeroMacAddress(vpv.MacAddr) {
1842 subMac = vpv.MacAddr
1843 } else if vpv.LearntMacAddr != nil && NonZeroMacAddress(vpv.LearntMacAddr) {
1844 subMac = vpv.LearntMacAddr
1845 } else {
1846 matchVPVs = append(matchVPVs, vpv)
1847 continue
1848 }
1849 if util.MacAddrsMatch(subMac, clientMAC) {
1850 matchVPVs = append([]*VoltPortVnet{}, vpv)
1851 logger.Infow(ctx, "Matching VPV found", log.Fields{"Port": vpv.Port, "SVLAN": vpv.SVlan, "CVLAN": vpv.CVlan, "UNIVlan": vpv.UniVlan, "MAC": clientMAC})
1852 return false
1853 }
1854 }
1855 }
1856 return true
1857 }
1858 va.VnetsByPort.Range(findVpv)
1859
1860 if len(matchVPVs) != 1 {
1861 logger.Infow(ctx, "No matching VPV found or multiple vpvs found", log.Fields{"Match VPVs": matchVPVs, "MAC": clientMAC})
1862 return nil, errors.New("No matching VPV found or multiple vpvs found")
1863 }
1864 return matchVPVs, nil
1865}
1866
1867// GetMacInPortMap to get PORT value based on MAC key
1868func (va *VoltApplication) GetMacInPortMap(macAddr net.HardwareAddr) string {
1869 if NonZeroMacAddress(macAddr) {
1870 va.macPortLock.Lock()
1871 defer va.macPortLock.Unlock()
1872 if port, ok := va.macPortMap[macAddr.String()]; ok {
1873 logger.Debugw(ctx, "found-entry-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1874 return port
1875 }
1876 }
1877 logger.Infow(ctx, "entry-not-found-macportmap", log.Fields{"MacAddr": macAddr.String()})
1878 return ""
1879}
1880
1881// UpdateMacInPortMap to update MAC PORT (key value) information in MacPortMap
1882func (va *VoltApplication) UpdateMacInPortMap(macAddr net.HardwareAddr, port string) {
1883 if NonZeroMacAddress(macAddr) {
1884 va.macPortLock.Lock()
1885 va.macPortMap[macAddr.String()] = port
1886 va.macPortLock.Unlock()
1887 logger.Debugw(ctx, "updated-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1888 }
1889}
1890
1891// DeleteMacInPortMap to remove MAC key from MacPortMap
1892func (va *VoltApplication) DeleteMacInPortMap(macAddr net.HardwareAddr) {
1893 if NonZeroMacAddress(macAddr) {
1894 port := va.GetMacInPortMap(macAddr)
1895 va.macPortLock.Lock()
1896 delete(va.macPortMap, macAddr.String())
1897 va.macPortLock.Unlock()
1898 logger.Debugw(ctx, "deleted-from-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1899 }
1900}
1901
1902//AddGroupToPendingPool - adds the IgmpGroup with active group table entry to global pending pool
1903func (va *VoltApplication) AddGroupToPendingPool(ig *IgmpGroup) {
1904 var grpMap map[*IgmpGroup]bool
1905 var ok bool
1906
1907 va.PendingPoolLock.Lock()
1908 defer va.PendingPoolLock.Unlock()
1909
1910 logger.Infow(ctx, "Adding IgmpGroup to Global Pending Pool", log.Fields{"GroupID": ig.GroupID, "GroupName": ig.GroupName, "GroupAddr": ig.GroupAddr, "PendingDevices": len(ig.Devices)})
1911 // Do Not Reset any current profile info since group table entry tied to mvlan profile
1912 // The PonVlan is part of set field in group installed
1913 // Hence, Group created is always tied to the same mvlan profile until deleted
1914
1915 for device := range ig.Devices {
1916 key := getPendingPoolKey(ig.Mvlan, device)
1917
1918 if grpMap, ok = va.IgmpPendingPool[key]; !ok {
1919 grpMap = make(map[*IgmpGroup]bool)
1920 }
1921 grpMap[ig] = true
1922
1923 //Add grpObj reference to all associated devices
1924 va.IgmpPendingPool[key] = grpMap
1925 }
1926}
1927
1928//RemoveGroupFromPendingPool - removes the group from global pending group pool
1929func (va *VoltApplication) RemoveGroupFromPendingPool(device string, ig *IgmpGroup) bool {
1930 GetApplication().PendingPoolLock.Lock()
1931 defer GetApplication().PendingPoolLock.Unlock()
1932
1933 logger.Infow(ctx, "Removing IgmpGroup from Global Pending Pool", log.Fields{"Device": device, "GroupID": ig.GroupID, "GroupName": ig.GroupName, "GroupAddr": ig.GroupAddr, "PendingDevices": len(ig.Devices)})
1934
1935 key := getPendingPoolKey(ig.Mvlan, device)
1936 if _, ok := va.IgmpPendingPool[key]; ok {
1937 delete(va.IgmpPendingPool[key], ig)
1938 return true
1939 }
1940 return false
1941}
1942
1943//RemoveGroupsFromPendingPool - removes the group from global pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301944func (va *VoltApplication) RemoveGroupsFromPendingPool(cntx context.Context, device string, mvlan of.VlanType) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301945 GetApplication().PendingPoolLock.Lock()
1946 defer GetApplication().PendingPoolLock.Unlock()
1947
1948 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool for given Deivce & Mvlan", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1949
1950 key := getPendingPoolKey(mvlan, device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301951 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05301952}
1953
1954//RemoveGroupListFromPendingPool - removes the groups for provided key
1955// 1. Deletes the group from device
1956// 2. Delete the IgmpGroup obj and release the group ID to pool
1957// Note: Make sure to obtain PendingPoolLock lock before calling this func
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301958func (va *VoltApplication) RemoveGroupListFromPendingPool(cntx context.Context, key string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301959 if grpMap, ok := va.IgmpPendingPool[key]; ok {
1960 delete(va.IgmpPendingPool, key)
1961 for ig := range grpMap {
1962 for device := range ig.Devices {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301963 ig.DeleteIgmpGroupDevice(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301964 }
1965 }
1966 }
1967}
1968
1969//RemoveGroupDevicesFromPendingPool - removes the group from global pending group pool
1970func (va *VoltApplication) RemoveGroupDevicesFromPendingPool(ig *IgmpGroup) {
1971
1972 logger.Infow(ctx, "Removing IgmpGroup for all devices from Global Pending Pool", log.Fields{"GroupID": ig.GroupID, "GroupName": ig.GroupName, "GroupAddr": ig.GroupAddr, "PendingDevices": len(ig.Devices)})
1973 for device := range ig.PendingGroupForDevice {
1974 va.RemoveGroupFromPendingPool(device, ig)
1975 }
1976}
1977
1978//GetGroupFromPendingPool - Returns IgmpGroup obj from global pending pool
1979func (va *VoltApplication) GetGroupFromPendingPool(mvlan of.VlanType, device string) *IgmpGroup {
1980
1981 var ig *IgmpGroup
1982
1983 va.PendingPoolLock.Lock()
1984 defer va.PendingPoolLock.Unlock()
1985
1986 key := getPendingPoolKey(mvlan, device)
1987 logger.Infow(ctx, "Getting IgmpGroup from Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String(), "Key": key})
1988
1989 //Gets all IgmpGrp Obj for the device
1990 grpMap, ok := va.IgmpPendingPool[key]
1991 if !ok || len(grpMap) == 0 {
1992 logger.Infow(ctx, "Matching IgmpGroup not found in Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1993 return nil
1994 }
1995
1996 //Gets a random obj from available grps
1997 for ig = range grpMap {
1998
1999 //Remove grp obj reference from all devices associated in pending pool
2000 for dev := range ig.Devices {
2001 key := getPendingPoolKey(mvlan, dev)
2002 delete(va.IgmpPendingPool[key], ig)
2003 }
2004
2005 //Safety check to avoid re-allocating group already in use
2006 if ig.NumDevicesActive() == 0 {
2007 return ig
2008 }
2009
2010 //Iteration will continue only if IG is not allocated
2011 }
2012 return nil
2013}
2014
2015//RemovePendingGroups - removes all pending groups for provided reference from global pending pool
2016// reference - mvlan/device ID
2017// isRefDevice - true - Device as reference
2018// false - Mvlan as reference
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302019func (va *VoltApplication) RemovePendingGroups(cntx context.Context, reference string, isRefDevice bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302020 va.PendingPoolLock.Lock()
2021 defer va.PendingPoolLock.Unlock()
2022
2023 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool", log.Fields{"Reference": reference, "isRefDevice": isRefDevice})
2024
2025 //Pending Pool key: "<mvlan>_<DeviceID>""
2026 paramPosition := 0
2027 if isRefDevice {
2028 paramPosition = 1
2029 }
2030
2031 // 1.Remove the Entry from pending pool
2032 // 2.Deletes the group from device
2033 // 3.Delete the IgmpGroup obj and release the group ID to pool
2034 for key := range va.IgmpPendingPool {
2035 keyParams := strings.Split(key, "_")
2036 if keyParams[paramPosition] == reference {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302037 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05302038 }
2039 }
2040}
2041
2042func getPendingPoolKey(mvlan of.VlanType, device string) string {
2043 return mvlan.String() + "_" + device
2044}
2045
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302046func (va *VoltApplication) removeExpiredGroups(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302047 logger.Debug(ctx, "Check for expired Igmp Groups")
2048 removeExpiredGroups := func(key interface{}, value interface{}) bool {
2049 ig := value.(*IgmpGroup)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302050 ig.removeExpiredGroupFromDevice(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302051 return true
2052 }
2053 va.IgmpGroups.Range(removeExpiredGroups)
2054}
2055
2056//TriggerPendingProfileDeleteReq - trigger pending profile delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302057func (va *VoltApplication) TriggerPendingProfileDeleteReq(cntx context.Context, device string) {
2058 va.TriggerPendingServiceDeleteReq(cntx, device)
2059 va.TriggerPendingVpvDeleteReq(cntx, device)
2060 va.TriggerPendingVnetDeleteReq(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05302061 logger.Warnw(ctx, "All Pending Profile Delete triggered for device", log.Fields{"Device": device})
2062}
2063
2064//TriggerPendingServiceDeleteReq - trigger pending service delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302065func (va *VoltApplication) TriggerPendingServiceDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302066
2067 logger.Warnw(ctx, "Pending Services to be deleted", log.Fields{"Count": len(va.ServicesToDelete)})
2068 for serviceName := range va.ServicesToDelete {
2069 logger.Debugw(ctx, "Trigger Service Delete", log.Fields{"Service": serviceName})
2070 if vs := va.GetService(serviceName); vs != nil {
2071 if vs.Device == device {
2072 logger.Warnw(ctx, "Triggering Pending Service delete", log.Fields{"Service": vs.Name})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302073 vs.DelHsiaFlows(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302074 if vs.ForceDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302075 vs.DelFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302076 }
2077 }
2078 } else {
2079 logger.Errorw(ctx, "Pending Service Not found", log.Fields{"Service": serviceName})
2080 }
2081 }
2082}
2083
2084//TriggerPendingVpvDeleteReq - trigger pending VPV delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302085func (va *VoltApplication) TriggerPendingVpvDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302086
2087 logger.Warnw(ctx, "Pending VPVs to be deleted", log.Fields{"Count": len(va.VoltPortVnetsToDelete)})
2088 for vpv := range va.VoltPortVnetsToDelete {
2089 if vpv.Device == device {
2090 logger.Warnw(ctx, "Triggering Pending VPv flow delete", log.Fields{"Port": vpv.Port, "Device": vpv.Device, "Vnet": vpv.VnetName})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302091 va.DelVnetFromPort(cntx, vpv.Port, vpv)
Naveen Sampath04696f72022-06-13 15:19:14 +05302092 }
2093 }
2094}
2095
2096//TriggerPendingVnetDeleteReq - trigger pending vnet delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302097func (va *VoltApplication) TriggerPendingVnetDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302098
2099 logger.Warnw(ctx, "Pending Vnets to be deleted", log.Fields{"Count": len(va.VnetsToDelete)})
2100 for vnetName := range va.VnetsToDelete {
2101 if vnetIntf, _ := va.VnetsByName.Load(vnetName); vnetIntf != nil {
2102 vnet := vnetIntf.(*VoltVnet)
2103 logger.Warnw(ctx, "Triggering Pending Vnet flows delete", log.Fields{"Vnet": vnet.Name})
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302104 if d, _ := va.GetDeviceBySerialNo(vnet.PendingDeviceToDelete); d != nil && d.SerialNum == vnet.PendingDeviceToDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302105 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, vnet.PendingDeviceToDelete)
Naveen Sampath04696f72022-06-13 15:19:14 +05302106 va.deleteVnetConfig(vnet)
2107 } else {
Tinoj Joseph1d108322022-07-13 10:07:39 +05302108 logger.Warnw(ctx, "Vnet Delete Failed : Device Not Found", log.Fields{"Vnet": vnet.Name, "Device": vnet.PendingDeviceToDelete})
Naveen Sampath04696f72022-06-13 15:19:14 +05302109 }
2110 }
2111 }
2112}
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302113
2114type OltFlowService struct {
Akash Sonia8246972023-01-03 10:37:08 +05302115 EnableDhcpOnNni bool `json:"enableDhcpOnNni"`
2116 DefaultTechProfileId int `json:"defaultTechProfileId"`
2117 EnableIgmpOnNni bool `json:"enableIgmpOnNni"`
2118 EnableEapol bool `json:"enableEapol"`
2119 EnableDhcpV6 bool `json:"enableDhcpV6"`
2120 EnableDhcpV4 bool `json:"enableDhcpV4"`
2121 RemoveFlowsOnDisable bool `json:"removeFlowsOnDisable"`
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302122}
2123
2124func (va *VoltApplication) UpdateOltFlowService(cntx context.Context, oltFlowService OltFlowService) {
2125 logger.Infow(ctx, "UpdateOltFlowService", log.Fields{"oldValue": va.OltFlowServiceConfig, "newValue": oltFlowService})
2126 va.OltFlowServiceConfig = oltFlowService
2127 b, err := json.Marshal(va.OltFlowServiceConfig)
2128 if err != nil {
2129 logger.Warnw(ctx, "Failed to Marshal OltFlowServiceConfig", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2130 return
2131 }
2132 _ = db.PutOltFlowService(cntx, string(b))
2133}
Akash Sonia8246972023-01-03 10:37:08 +05302134
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302135// RestoreOltFlowService to read from the DB and restore olt flow service config
2136func (va *VoltApplication) RestoreOltFlowService(cntx context.Context) {
2137 oltflowService, err := db.GetOltFlowService(cntx)
2138 if err != nil {
2139 logger.Warnw(ctx, "Failed to Get OltFlowServiceConfig from DB", log.Fields{"Error": err})
2140 return
2141 }
2142 err = json.Unmarshal([]byte(oltflowService), &va.OltFlowServiceConfig)
2143 if err != nil {
2144 logger.Warn(ctx, "Unmarshal of oltflowService failed")
2145 return
2146 }
2147 logger.Infow(ctx, "updated OltFlowServiceConfig from DB", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2148}
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302149
Akash Soni87a19072023-02-28 00:46:59 +05302150func (va *VoltApplication) UpdateDeviceConfig(cntx context.Context, deviceConfig *DeviceConfig) {
2151 var dc *DeviceConfig
2152 va.DevicesConfig.Store(deviceConfig.SerialNumber, deviceConfig)
2153 err := dc.WriteDeviceConfigToDb(cntx, deviceConfig.SerialNumber, deviceConfig)
2154 if err != nil {
2155 logger.Errorw(ctx, "DB update for device config failed", log.Fields{"err": err})
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302156 }
Akash Soni87a19072023-02-28 00:46:59 +05302157 logger.Infow(ctx, "Added OLT configurations", log.Fields{"DeviceInfo": deviceConfig})
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302158 // If device is already discovered update the VoltDevice structure
Akash Soni87a19072023-02-28 00:46:59 +05302159 device, id := va.GetDeviceBySerialNo(deviceConfig.SerialNumber)
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302160 if device != nil {
Akash Soni87a19072023-02-28 00:46:59 +05302161 device.NniDhcpTrapVid = of.VlanType(deviceConfig.NniDhcpTrapVid)
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302162 va.DevicesDisc.Store(id, device)
2163 }
2164}