blob: 1f31149e97647107a00a04faec08d80ffc78dff0 [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"`
457 IPAddress net.IP `json:"ipAddress"`
458 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
576func (va *VoltApplication) AddDeviceConfig(cntx context.Context, serialNum, hardwareIdentifier, nasID string, ipAddress net.IP, uplinkPort, nniDhcpTrapId int) error {
577 var dc *DeviceConfig
578
579 d := va.GetDeviceConfig(serialNum)
580 if d == nil {
581 deviceConfig := &DeviceConfig{
582 SerialNumber: serialNum,
583 HardwareIdentifier: hardwareIdentifier,
584 NasID: nasID,
585 UplinkPort: uplinkPort,
586 IPAddress: ipAddress,
587 NniDhcpTrapVid: nniDhcpTrapId,
588 }
589 va.DevicesConfig.Store(serialNum, deviceConfig)
590 err := dc.WriteDeviceConfigToDb(cntx, serialNum, deviceConfig)
591 if err != nil {
592 logger.Errorw(ctx, "DB update for device config failed", log.Fields{"err": err})
593 return err
594 }
595 } else {
596 logger.Errorw(ctx, "Device config already exist", log.Fields{"DeviceID": serialNum})
597 return errors.New("Device config already exist")
598 }
599 return nil
600}
601
602// GetDeviceConfig to get a device config.
603func (va *VoltApplication) GetDeviceConfig(serNum string) *DeviceConfig {
604 if d, ok := va.DevicesConfig.Load(serNum); ok {
605 return d.(*DeviceConfig)
606 }
607 return nil
608}
609
Naveen Sampath04696f72022-06-13 15:19:14 +0530610// UpdatePortToNbDevice Adds pon port to NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530611func (nbd *NbDevice) UpdatePortToNbDevice(cntx context.Context, portID, allowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) *PonPortCfg {
Naveen Sampath04696f72022-06-13 15:19:14 +0530612
613 p, exists := nbd.PonPorts.Load(portID)
614 if !exists {
615 logger.Errorw(ctx, "PON port not exists in nb-device", log.Fields{"portID": portID})
616 return nil
617 }
618 port := p.(*PonPortCfg)
619 if allowedChannels != 0 {
620 port.MaxActiveChannels = allowedChannels
621 port.EnableMulticastKPI = enableMulticastKPI
622 port.PortAlarmProfileID = portAlarmProfileID
623 }
624
625 nbd.PonPorts.Store(portID, port)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530626 nbd.WriteToDb(cntx, portID, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530627 return port
628}
629
630// DeletePortFromNbDevice Deletes pon port from NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530631func (nbd *NbDevice) DeletePortFromNbDevice(cntx context.Context, portID uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530632
633 if _, ok := nbd.PonPorts.Load(portID); ok {
634 nbd.PonPorts.Delete(portID)
635 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530636 db.DelNbDevicePort(cntx, nbd.SouthBoundID, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530637}
638
639// GetApplication : Interface to access the singleton object
640func GetApplication() *VoltApplication {
641 if vapplication == nil {
642 vapplication = newVoltApplication()
643 }
644 return vapplication
645}
646
647// newVoltApplication : Constructor for the singleton object. Hence this is not
648// an exported function
649func newVoltApplication() *VoltApplication {
650 var va VoltApplication
651 va.IgmpTasks.Initialize(context.TODO())
652 va.MulticastAlarmTasks.Initialize(context.TODO())
653 va.IgmpKPIsTasks.Initialize(context.TODO())
654 va.pppoeTasks.Initialize(context.TODO())
655 va.storeIgmpProfileMap(DefaultIgmpProfID, newDefaultIgmpProfile())
656 va.MeterMgr.Init()
657 va.AddIgmpGroups(5000)
658 va.macPortMap = make(map[string]string)
659 va.IgmpPendingPool = make(map[string]map[*IgmpGroup]bool)
660 va.VnetsBySvlan = util.NewConcurrentMap()
661 va.VnetsToDelete = make(map[string]bool)
662 va.ServicesToDelete = make(map[string]bool)
663 va.VoltPortVnetsToDelete = make(map[*VoltPortVnet]bool)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530664 go va.Start(context.Background(), TimerCfg{tick: 100 * time.Millisecond}, tickTimer)
665 go va.Start(context.Background(), TimerCfg{tick: time.Duration(GroupExpiryTime) * time.Minute}, pendingPoolTimer)
Naveen Sampath04696f72022-06-13 15:19:14 +0530666 InitEventFuncMapper()
667 db = database.GetDatabase()
668 return &va
669}
670
671//GetFlowEventRegister - returs the register based on flow mod type
672func (d *VoltDevice) GetFlowEventRegister(flowModType of.Command) (*util.ConcurrentMap, error) {
673
674 switch flowModType {
675 case of.CommandDel:
676 return d.FlowDelEventMap, nil
677 case of.CommandAdd:
678 return d.FlowAddEventMap, nil
679 default:
680 logger.Error(ctx, "Unknown Flow Mod received")
681 }
682 return util.NewConcurrentMap(), errors.New("Unknown Flow Mod")
683}
684
685// RegisterFlowAddEvent to register a flow event.
686func (d *VoltDevice) RegisterFlowAddEvent(cookie string, event *FlowEvent) {
687 logger.Debugw(ctx, "Registered Flow Add Event", log.Fields{"Cookie": cookie, "Event": event})
688 d.FlowAddEventMap.MapLock.Lock()
689 defer d.FlowAddEventMap.MapLock.Unlock()
690 d.FlowAddEventMap.Set(cookie, event)
691}
692
693// RegisterFlowDelEvent to register a flow event.
694func (d *VoltDevice) RegisterFlowDelEvent(cookie string, event *FlowEvent) {
695 logger.Debugw(ctx, "Registered Flow Del Event", log.Fields{"Cookie": cookie, "Event": event})
696 d.FlowDelEventMap.MapLock.Lock()
697 defer d.FlowDelEventMap.MapLock.Unlock()
698 d.FlowDelEventMap.Set(cookie, event)
699}
700
701// UnRegisterFlowEvent to unregister a flow event.
702func (d *VoltDevice) UnRegisterFlowEvent(cookie string, flowModType of.Command) {
703 logger.Debugw(ctx, "UnRegistered Flow Add Event", log.Fields{"Cookie": cookie, "Type": flowModType})
704 flowEventMap, err := d.GetFlowEventRegister(flowModType)
705 if err != nil {
706 logger.Debugw(ctx, "Flow event map does not exists", log.Fields{"flowMod": flowModType, "Error": err})
707 return
708 }
709 flowEventMap.MapLock.Lock()
710 defer flowEventMap.MapLock.Unlock()
711 flowEventMap.Remove(cookie)
712}
713
714// AddIgmpGroups to add Igmp groups.
715func (va *VoltApplication) AddIgmpGroups(numOfGroups uint32) {
716 //TODO: Temp change to resolve group id issue in pOLT
717 //for i := 1; uint32(i) <= numOfGroups; i++ {
718 for i := 2; uint32(i) <= (numOfGroups + 1); i++ {
719 ig := IgmpGroup{}
720 ig.GroupID = uint32(i)
721 va.IgmpGroupIds = append(va.IgmpGroupIds, &ig)
722 }
723}
724
725// GetAvailIgmpGroupID to get id of available igmp group.
726func (va *VoltApplication) GetAvailIgmpGroupID() *IgmpGroup {
727 var ig *IgmpGroup
728 if len(va.IgmpGroupIds) > 0 {
729 ig, va.IgmpGroupIds = va.IgmpGroupIds[0], va.IgmpGroupIds[1:]
730 return ig
731 }
732 return nil
733}
734
735// GetIgmpGroupID to get id of igmp group.
736func (va *VoltApplication) GetIgmpGroupID(gid uint32) (*IgmpGroup, error) {
737 for id, ig := range va.IgmpGroupIds {
738 if ig.GroupID == gid {
739 va.IgmpGroupIds = append(va.IgmpGroupIds[0:id], va.IgmpGroupIds[id+1:]...)
740 return ig, nil
741 }
742 }
743 return nil, errors.New("Group Id Missing")
744}
745
746// PutIgmpGroupID to add id of igmp group.
747func (va *VoltApplication) PutIgmpGroupID(ig *IgmpGroup) {
748 va.IgmpGroupIds = append([]*IgmpGroup{ig}, va.IgmpGroupIds[0:]...)
749}
750
751//RestoreUpgradeStatus - gets upgrade/migration status from DB and updates local flags
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530752func (va *VoltApplication) RestoreUpgradeStatus(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530753 Migrate := new(DataMigration)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530754 if err := GetMigrationInfo(cntx, Migrate); err == nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530755 if Migrate.Status == MigrationInProgress {
756 isUpgradeComplete = false
757 return
758 }
759 }
760 isUpgradeComplete = true
761
762 logger.Infow(ctx, "Upgrade Status Restored", log.Fields{"Upgrade Completed": isUpgradeComplete})
763}
764
765// ReadAllFromDb : If we are restarted, learn from the database the current execution
766// stage
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530767func (va *VoltApplication) ReadAllFromDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530768 logger.Info(ctx, "Reading the meters from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530769 va.RestoreMetersFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530770 logger.Info(ctx, "Reading the VNETs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530771 va.RestoreVnetsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530772 logger.Info(ctx, "Reading the VPVs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530773 va.RestoreVpvsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530774 logger.Info(ctx, "Reading the Services from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530775 va.RestoreSvcsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530776 logger.Info(ctx, "Reading the MVLANs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530777 va.RestoreMvlansFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530778 logger.Info(ctx, "Reading the IGMP profiles from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530779 va.RestoreIGMPProfilesFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530780 logger.Info(ctx, "Reading the Mcast configs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530781 va.RestoreMcastConfigsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530782 logger.Info(ctx, "Reading the IGMP groups for DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530783 va.RestoreIgmpGroupsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530784 logger.Info(ctx, "Reading Upgrade status from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530785 va.RestoreUpgradeStatus(cntx)
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530786 logger.Info(ctx, "Reading OltFlowService from DB")
787 va.RestoreOltFlowService(cntx)
Akash Sonia8246972023-01-03 10:37:08 +0530788 logger.Info(ctx, "Reading device config from DB")
789 va.RestoreDeviceConfigFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530790 logger.Info(ctx, "Reconciled from DB")
791}
792
793// InitStaticConfig to initialise static config.
794func (va *VoltApplication) InitStaticConfig() {
795 va.InitIgmpSrcMac()
796}
797
798// SetVendorID to set vendor id
799func (va *VoltApplication) SetVendorID(vendorID string) {
800 va.vendorID = vendorID
801}
802
803// GetVendorID to get vendor id
804func (va *VoltApplication) GetVendorID() string {
805 return va.vendorID
806}
807
808// SetRebootFlag to set reboot flag
809func (va *VoltApplication) SetRebootFlag(flag bool) {
810 vgcRebooted = flag
811}
812
813// GetUpgradeFlag to get reboot status
814func (va *VoltApplication) GetUpgradeFlag() bool {
815 return isUpgradeComplete
816}
817
818// SetUpgradeFlag to set reboot status
819func (va *VoltApplication) SetUpgradeFlag(flag bool) {
820 isUpgradeComplete = flag
821}
822
823// ------------------------------------------------------------
824// Device related functions
825
826// AddDevice : Add a device and typically the device stores the NNI port on the device
827// The NNI port is used when the packets are emitted towards the network.
828// The outport is selected as the NNI port of the device. Today, we support
829// a single NNI port per OLT. This is true whether the network uses any
830// protection mechanism (LAG, ERPS, etc.). The aggregate of the such protection
831// is represented by a single NNI port
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530832func (va *VoltApplication) AddDevice(cntx context.Context, device string, slno, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530833 logger.Warnw(ctx, "Received Device Ind: Add", log.Fields{"Device": device, "SrNo": slno})
834 if _, ok := va.DevicesDisc.Load(device); ok {
835 logger.Warnw(ctx, "Device Exists", log.Fields{"Device": device})
836 }
837 d := NewVoltDevice(device, slno, southBoundID)
838
839 addPort := func(key, value interface{}) bool {
840 portID := key.(uint32)
841 port := value.(*PonPortCfg)
842 va.AggActiveChannelsCountForPonPort(device, portID, port)
843 d.ActiveChannelsPerPon.Store(portID, port)
844 return true
845 }
846 if nbDevice, exists := va.NbDevice.Load(southBoundID); exists {
847 // Pon Ports added before OLT activate.
848 nbDevice.(*NbDevice).PonPorts.Range(addPort)
849 } else {
850 // Check if NbPort exists in DB. VGC restart case.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530851 nbd := va.RestoreNbDeviceFromDb(cntx, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530852 nbd.PonPorts.Range(addPort)
853 }
854 va.DevicesDisc.Store(device, d)
855}
856
857// GetDevice to get a device.
858func (va *VoltApplication) GetDevice(device string) *VoltDevice {
859 if d, ok := va.DevicesDisc.Load(device); ok {
860 return d.(*VoltDevice)
861 }
862 return nil
863}
864
865// DelDevice to delete a device.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530866func (va *VoltApplication) DelDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530867 logger.Warnw(ctx, "Received Device Ind: Delete", log.Fields{"Device": device})
868 if vdIntf, ok := va.DevicesDisc.Load(device); ok {
869 vd := vdIntf.(*VoltDevice)
870 va.DevicesDisc.Delete(device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530871 _ = db.DelAllRoutesForDevice(cntx, device)
872 va.HandleFlowClearFlag(cntx, device, vd.SerialNum, vd.SouthBoundID)
873 _ = db.DelAllGroup(cntx, device)
874 _ = db.DelAllMeter(cntx, device)
875 _ = db.DelAllPorts(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +0530876 logger.Debugw(ctx, "Device deleted", log.Fields{"Device": device})
877 } else {
878 logger.Warnw(ctx, "Device Doesn't Exist", log.Fields{"Device": device})
879 }
880}
881
882// GetDeviceBySerialNo to get a device by serial number.
883// TODO - Transform this into a MAP instead
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530884func (va *VoltApplication) GetDeviceBySerialNo(slno string) (*VoltDevice, string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530885 var device *VoltDevice
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530886 var deviceID string
Naveen Sampath04696f72022-06-13 15:19:14 +0530887 getserial := func(key interface{}, value interface{}) bool {
888 device = value.(*VoltDevice)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530889 deviceID = key.(string)
Naveen Sampath04696f72022-06-13 15:19:14 +0530890 return device.SerialNum != slno
891 }
892 va.DevicesDisc.Range(getserial)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530893 return device, deviceID
Naveen Sampath04696f72022-06-13 15:19:14 +0530894}
895
896// PortAddInd : This is a PORT add indication coming from the VPAgent, which is essentially
897// a request coming from VOLTHA. The device and identity of the port is provided
898// in this request. Add them to the application for further use
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530899func (va *VoltApplication) PortAddInd(cntx context.Context, device string, id uint32, portName string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530900 logger.Infow(ctx, "Received Port Ind: Add", log.Fields{"Device": device, "Port": portName})
901 va.portLock.Lock()
902 if d := va.GetDevice(device); d != nil {
903 p := d.AddPort(portName, id)
904 va.PortsDisc.Store(portName, p)
905 va.portLock.Unlock()
906 nni, _ := va.GetNniPort(device)
907 if nni == portName {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530908 d.pushFlowsForUnis(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530909 }
910 } else {
911 va.portLock.Unlock()
912 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Add", log.Fields{"Device": device, "Port": portName})
913 }
914}
915
916// PortDelInd : Only the NNI ports are recorded in the device for now. When port delete
917// arrives, only the NNI ports need adjustments.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530918func (va *VoltApplication) PortDelInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530919 logger.Infow(ctx, "Received Port Ind: Delete", log.Fields{"Device": device, "Port": port})
920 if d := va.GetDevice(device); d != nil {
921 p := d.GetPort(port)
922 if p != nil && p.State == PortStateUp {
923 logger.Infow(ctx, "Port state is UP. Trigerring Port Down Ind before deleting", log.Fields{"Port": p})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530924 va.PortDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530925 }
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530926 // if RemoveFlowsOnDisable is flase, then flows will be existing till port delete. Remove the flows now
927 if !va.OltFlowServiceConfig.RemoveFlowsOnDisable {
Akash Sonia8246972023-01-03 10:37:08 +0530928 vpvs, ok := va.VnetsByPort.Load(port)
929 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530930 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
931 } else {
932 for _, vpv := range vpvs.([]*VoltPortVnet) {
933 vpv.VpvLock.Lock()
934 vpv.PortDownInd(cntx, device, port, true)
935 vpv.VpvLock.Unlock()
936 }
937 }
938 }
Naveen Sampath04696f72022-06-13 15:19:14 +0530939 va.portLock.Lock()
940 defer va.portLock.Unlock()
941 d.DelPort(port)
942 if _, ok := va.PortsDisc.Load(port); ok {
943 va.PortsDisc.Delete(port)
944 }
945 } else {
946 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Delete", log.Fields{"Device": device, "Port": port})
947 }
948}
949
950//PortUpdateInd Updates port Id incase of ONU movement
951func (va *VoltApplication) PortUpdateInd(device string, portName string, id uint32) {
952 logger.Infow(ctx, "Received Port Ind: Update", log.Fields{"Device": device, "Port": portName})
953 va.portLock.Lock()
954 defer va.portLock.Unlock()
955 if d := va.GetDevice(device); d != nil {
956 vp := d.GetPort(portName)
957 vp.ID = id
958 } else {
959 logger.Warnw(ctx, "Device Not Found", log.Fields{"Device": device, "Port": portName})
960 }
961}
962
963// AddNbPonPort Add pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530964func (va *VoltApplication) AddNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32,
Naveen Sampath04696f72022-06-13 15:19:14 +0530965 enableMulticastKPI bool, portAlarmProfileID string) error {
966
967 var nbd *NbDevice
968 nbDevice, ok := va.NbDevice.Load(oltSbID)
969
970 if !ok {
971 nbd = NewNbDevice()
972 nbd.SouthBoundID = oltSbID
973 } else {
974 nbd = nbDevice.(*NbDevice)
975 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530976 port := nbd.AddPortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530977
978 // Add this port to voltDevice
979 addPort := func(key, value interface{}) bool {
980 voltDevice := value.(*VoltDevice)
981 if oltSbID == voltDevice.SouthBoundID {
982 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); !exists {
983 voltDevice.ActiveChannelsPerPon.Store(portID, port)
984 }
985 return false
986 }
987 return true
988 }
989 va.DevicesDisc.Range(addPort)
990 va.NbDevice.Store(oltSbID, nbd)
991
992 return nil
993}
994
995// UpdateNbPonPort update pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530996func (va *VoltApplication) UpdateNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530997
998 var nbd *NbDevice
999 nbDevice, ok := va.NbDevice.Load(oltSbID)
1000
1001 if !ok {
1002 logger.Errorw(ctx, "Device-doesn't-exists", log.Fields{"deviceID": oltSbID})
1003 return fmt.Errorf("Device-doesn't-exists-%v", oltSbID)
1004 }
1005 nbd = nbDevice.(*NbDevice)
1006
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301007 port := nbd.UpdatePortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301008 if port == nil {
1009 return fmt.Errorf("Port-doesn't-exists-%v", portID)
1010 }
1011 va.NbDevice.Store(oltSbID, nbd)
1012
1013 // Add this port to voltDevice
1014 updPort := func(key, value interface{}) bool {
1015 voltDevice := value.(*VoltDevice)
1016 if oltSbID == voltDevice.SouthBoundID {
1017 voltDevice.ActiveChannelCountLock.Lock()
1018 if p, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
1019 oldPort := p.(*PonPortCfg)
1020 if port.MaxActiveChannels != 0 {
1021 oldPort.MaxActiveChannels = port.MaxActiveChannels
1022 oldPort.EnableMulticastKPI = port.EnableMulticastKPI
1023 voltDevice.ActiveChannelsPerPon.Store(portID, oldPort)
1024 }
1025 }
1026 voltDevice.ActiveChannelCountLock.Unlock()
1027 return false
1028 }
1029 return true
1030 }
1031 va.DevicesDisc.Range(updPort)
1032
1033 return nil
1034}
1035
1036// DeleteNbPonPort Delete pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301037func (va *VoltApplication) DeleteNbPonPort(cntx context.Context, oltSbID string, portID uint32) error {
Naveen Sampath04696f72022-06-13 15:19:14 +05301038 nbDevice, ok := va.NbDevice.Load(oltSbID)
1039 if ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301040 nbDevice.(*NbDevice).DeletePortFromNbDevice(cntx, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301041 va.NbDevice.Store(oltSbID, nbDevice.(*NbDevice))
1042 } else {
1043 logger.Warnw(ctx, "Delete pon received for unknown device", log.Fields{"oltSbID": oltSbID})
1044 return nil
1045 }
1046 // Delete this port from voltDevice
1047 delPort := func(key, value interface{}) bool {
1048 voltDevice := value.(*VoltDevice)
1049 if oltSbID == voltDevice.SouthBoundID {
1050 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
1051 voltDevice.ActiveChannelsPerPon.Delete(portID)
1052 }
1053 return false
1054 }
1055 return true
1056 }
1057 va.DevicesDisc.Range(delPort)
1058 return nil
1059}
1060
1061// GetNniPort : Get the NNI port for a device. Called from different other applications
1062// as a port to match or destination for a packet out. The VOLT application
1063// is written with the assumption that there is a single NNI port. The OLT
1064// device is responsible for translating the combination of VLAN and the
1065// NNI port ID to identify possibly a single physical port or a logical
1066// port which is a result of protection methods applied.
1067func (va *VoltApplication) GetNniPort(device string) (string, error) {
1068 va.portLock.Lock()
1069 defer va.portLock.Unlock()
1070 d, ok := va.DevicesDisc.Load(device)
1071 if !ok {
1072 return "", errors.New("Device Doesn't Exist")
1073 }
1074 return d.(*VoltDevice).NniPort, nil
1075}
1076
1077// NniDownInd process for Nni down indication.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301078func (va *VoltApplication) NniDownInd(cntx context.Context, deviceID string, devSrNo string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301079
1080 logger.Debugw(ctx, "NNI Down Ind", log.Fields{"device": devSrNo})
1081
1082 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1083 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301084 mvProfile.removeIgmpMcastFlows(cntx, devSrNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301085 return true
1086 }
1087 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1088
1089 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301090 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301091}
1092
1093// DeviceUpInd changes device state to up.
1094func (va *VoltApplication) DeviceUpInd(device string) {
1095 logger.Warnw(ctx, "Received Device Ind: UP", log.Fields{"Device": device})
1096 if d := va.GetDevice(device); d != nil {
1097 d.State = controller.DeviceStateUP
1098 } else {
1099 logger.Errorw(ctx, "Ignoring Device indication: UP. Device Missing", log.Fields{"Device": device})
1100 }
1101}
1102
1103// DeviceDownInd changes device state to down.
1104func (va *VoltApplication) DeviceDownInd(device string) {
1105 logger.Warnw(ctx, "Received Device Ind: DOWN", log.Fields{"Device": device})
1106 if d := va.GetDevice(device); d != nil {
1107 d.State = controller.DeviceStateDOWN
1108 } else {
1109 logger.Errorw(ctx, "Ignoring Device indication: DOWN. Device Missing", log.Fields{"Device": device})
1110 }
1111}
1112
1113// DeviceRebootInd process for handling flow clear flag for device reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301114func (va *VoltApplication) DeviceRebootInd(cntx context.Context, device string, serialNum string, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301115 logger.Warnw(ctx, "Received Device Ind: Reboot", log.Fields{"Device": device, "SerialNumber": serialNum})
1116
1117 if d := va.GetDevice(device); d != nil {
1118 if d.State == controller.DeviceStateREBOOTED {
1119 logger.Warnw(ctx, "Ignoring Device Ind: Reboot, Device already in Reboot state", log.Fields{"Device": device, "SerialNumber": serialNum, "State": d.State})
1120 return
1121 }
1122 d.State = controller.DeviceStateREBOOTED
1123 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301124 va.HandleFlowClearFlag(cntx, device, serialNum, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301125
1126}
1127
1128// DeviceDisableInd handles device deactivation process
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301129func (va *VoltApplication) DeviceDisableInd(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301130 logger.Warnw(ctx, "Received Device Ind: Disable", log.Fields{"Device": device})
1131
1132 d := va.GetDevice(device)
1133 if d == nil {
1134 logger.Errorw(ctx, "Ignoring Device indication: DISABLED. Device Missing", log.Fields{"Device": device})
1135 return
1136 }
1137
1138 d.State = controller.DeviceStateDISABLED
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301139 va.HandleFlowClearFlag(cntx, device, d.SerialNum, d.SouthBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301140}
1141
1142// ProcessIgmpDSFlowForMvlan for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301143func (va *VoltApplication) ProcessIgmpDSFlowForMvlan(cntx context.Context, d *VoltDevice, mvp *MvlanProfile, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301144
1145 logger.Debugw(ctx, "Process IGMP DS Flows for MVlan", log.Fields{"device": d.Name, "Mvlan": mvp.Mvlan, "addFlow": addFlow})
1146 portState := false
1147 p := d.GetPort(d.NniPort)
1148 if p != nil && p.State == PortStateUp {
1149 portState = true
1150 }
1151
1152 if addFlow {
1153 if portState {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301154 mvp.pushIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301155 }
1156 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301157 mvp.removeIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301158 }
1159}
1160
1161// ProcessIgmpDSFlowForDevice for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301162func (va *VoltApplication) ProcessIgmpDSFlowForDevice(cntx context.Context, d *VoltDevice, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301163 logger.Debugw(ctx, "Process IGMP DS Flows for device", log.Fields{"device": d.Name, "addFlow": addFlow})
1164
1165 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1166 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301167 va.ProcessIgmpDSFlowForMvlan(cntx, d, mvProfile, addFlow)
Naveen Sampath04696f72022-06-13 15:19:14 +05301168 return true
1169 }
1170 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1171}
1172
1173// GetDeviceFromPort : This is suitable only for access ports as their naming convention
1174// makes them unique across all the OLTs. This must be called with
1175// port name that is an access port. Currently called from VNETs, attached
1176// only to access ports, and the services which are also attached only
1177// to access ports
1178func (va *VoltApplication) GetDeviceFromPort(port string) (*VoltDevice, error) {
1179 va.portLock.Lock()
1180 defer va.portLock.Unlock()
1181 var err error
1182 err = nil
1183 p, ok := va.PortsDisc.Load(port)
1184 if !ok {
1185 return nil, errorCodes.ErrPortNotFound
1186 }
1187 d := va.GetDevice(p.(*VoltPort).Device)
1188 if d == nil {
1189 err = errorCodes.ErrDeviceNotFound
1190 }
1191 return d, err
1192}
1193
1194// GetPortID : This too applies only to access ports. The ports can be indexed
1195// purely by their names without the device forming part of the key
1196func (va *VoltApplication) GetPortID(port string) (uint32, error) {
1197 va.portLock.Lock()
1198 defer va.portLock.Unlock()
1199 p, ok := va.PortsDisc.Load(port)
1200 if !ok {
1201 return 0, errorCodes.ErrPortNotFound
1202 }
1203 return p.(*VoltPort).ID, nil
1204}
1205
1206// GetPortName : This too applies only to access ports. The ports can be indexed
1207// purely by their names without the device forming part of the key
1208func (va *VoltApplication) GetPortName(port uint32) (string, error) {
1209 va.portLock.Lock()
1210 defer va.portLock.Unlock()
1211 var portName string
1212 va.PortsDisc.Range(func(key interface{}, value interface{}) bool {
1213 portInfo := value.(*VoltPort)
1214 if portInfo.ID == port {
1215 portName = portInfo.Name
1216 return false
1217 }
1218 return true
1219 })
1220 return portName, nil
1221}
1222
1223// GetPonFromUniPort to get Pon info from UniPort
1224func (va *VoltApplication) GetPonFromUniPort(port string) (string, error) {
1225 uniPortID, err := va.GetPortID(port)
1226 if err == nil {
1227 ponPortID := (uniPortID & 0x0FF00000) >> 20 //pon(8) + onu(8) + uni(12)
1228 return strconv.FormatUint(uint64(ponPortID), 10), nil
1229 }
1230 return "", err
1231}
1232
1233// GetPortState : This too applies only to access ports. The ports can be indexed
1234// purely by their names without the device forming part of the key
1235func (va *VoltApplication) GetPortState(port string) (PortState, error) {
1236 va.portLock.Lock()
1237 defer va.portLock.Unlock()
1238 p, ok := va.PortsDisc.Load(port)
1239 if !ok {
1240 return 0, errors.New("Port not configured")
1241 }
1242 return p.(*VoltPort).State, nil
1243}
1244
1245// GetIcmpv6Receivers to get Icmp v6 receivers
1246func (va *VoltApplication) GetIcmpv6Receivers(device string) []uint32 {
1247 var receiverList []uint32
1248 receivers, _ := va.Icmpv6Receivers.Load(device)
1249 if receivers != nil {
1250 receiverList = receivers.([]uint32)
1251 }
1252 return receiverList
1253}
1254
1255// AddIcmpv6Receivers to add Icmp v6 receivers
1256func (va *VoltApplication) AddIcmpv6Receivers(device string, portID uint32) []uint32 {
1257 var receiverList []uint32
1258 receivers, _ := va.Icmpv6Receivers.Load(device)
1259 if receivers != nil {
1260 receiverList = receivers.([]uint32)
1261 }
1262 receiverList = append(receiverList, portID)
1263 va.Icmpv6Receivers.Store(device, receiverList)
1264 logger.Debugw(ctx, "Receivers after addition", log.Fields{"Receivers": receiverList})
1265 return receiverList
1266}
1267
1268// DelIcmpv6Receivers to delete Icmp v6 receievers
1269func (va *VoltApplication) DelIcmpv6Receivers(device string, portID uint32) []uint32 {
1270 var receiverList []uint32
1271 receivers, _ := va.Icmpv6Receivers.Load(device)
1272 if receivers != nil {
1273 receiverList = receivers.([]uint32)
1274 }
1275 for i, port := range receiverList {
1276 if port == portID {
1277 receiverList = append(receiverList[0:i], receiverList[i+1:]...)
1278 va.Icmpv6Receivers.Store(device, receiverList)
1279 break
1280 }
1281 }
1282 logger.Debugw(ctx, "Receivers After deletion", log.Fields{"Receivers": receiverList})
1283 return receiverList
1284}
1285
1286// ProcessDevFlowForDevice - Process DS ICMPv6 & ARP flow for provided device and vnet profile
1287// device - Device Obj
1288// vnet - vnet profile name
1289// enabled - vlan enabled/disabled - based on the status, the flow shall be added/removed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301290func (va *VoltApplication) ProcessDevFlowForDevice(cntx context.Context, device *VoltDevice, vnet *VoltVnet, enabled bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301291 _, applied := device.ConfiguredVlanForDeviceFlows.Get(VnetKey(vnet.SVlan, vnet.CVlan, 0))
1292 if enabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301293 va.PushDevFlowForVlan(cntx, vnet)
Naveen Sampath04696f72022-06-13 15:19:14 +05301294 } else if !enabled && applied {
1295 //va.DeleteDevFlowForVlan(vnet)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301296 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, device.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301297 }
1298}
1299
1300//NniVlanIndToIgmp - Trigger receiver up indication to all ports with igmp enabled
1301//and has the provided mvlan
1302func (va *VoltApplication) NniVlanIndToIgmp(device *VoltDevice, mvp *MvlanProfile) {
1303
1304 logger.Infow(ctx, "Sending Igmp Receiver UP indication for all Services", log.Fields{"Vlan": mvp.Mvlan})
1305
1306 //Trigger nni indication for receiver only for first time
1307 if device.IgmpDsFlowAppliedForMvlan[uint16(mvp.Mvlan)] {
1308 return
1309 }
1310 device.Ports.Range(func(key, value interface{}) bool {
1311 port := key.(string)
1312
1313 if state, _ := va.GetPortState(port); state == PortStateUp {
1314 vpvs, _ := va.VnetsByPort.Load(port)
1315 if vpvs == nil {
1316 return true
1317 }
1318 for _, vpv := range vpvs.([]*VoltPortVnet) {
1319 //Send indication only for subscribers with the received mvlan profile
1320 if vpv.IgmpEnabled && vpv.MvlanProfileName == mvp.Name {
1321 vpv.services.Range(ReceiverUpInd)
1322 }
1323 }
1324 }
1325 return true
1326 })
1327}
1328
1329// PortUpInd :
1330// -----------------------------------------------------------------------
1331// Port status change handling
1332// ----------------------------------------------------------------------
1333// Port UP indication is passed to all services associated with the port
1334// so that the services can configure flows applicable when the port goes
1335// up from down state
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301336func (va *VoltApplication) PortUpInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301337 d := va.GetDevice(device)
1338
1339 if d == nil {
1340 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: UP", log.Fields{"Device": device, "Port": port})
1341 return
1342 }
1343
1344 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1345 va.portLock.Lock()
1346 // Do not defer the port mutex unlock here
1347 // Some of the following func calls needs the port lock, so defering the lock here
1348 // may lead to dead-lock
1349 p := d.GetPort(port)
1350
1351 if p == nil {
1352 logger.Infow(ctx, "Ignoring Port Ind: UP, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1353 va.portLock.Unlock()
1354 return
1355 }
1356 p.State = PortStateUp
1357 va.portLock.Unlock()
1358
1359 logger.Infow(ctx, "Received SouthBound Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1360 if p.Type == VoltPortTypeNni {
1361
1362 logger.Warnw(ctx, "Received NNI Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1363 //va.PushDevFlowForDevice(d)
1364 //Build Igmp TrapFlowRule
1365 //va.ProcessIgmpDSFlowForDevice(d, true)
1366 }
1367 vpvs, ok := va.VnetsByPort.Load(port)
1368 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1369 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1370 //msgbus.ProcessPortInd(msgbus.PortUp, d.SerialNum, p.Name, false, getServiceList(port))
1371 return
1372 }
1373
1374 //If NNI port is not UP, do not push Flows
1375 if d.NniPort == "" {
1376 logger.Warnw(ctx, "NNI port not UP. Not sending Port UP Ind for VPVs", log.Fields{"NNI": d.NniPort})
1377 return
1378 }
1379
1380 vpvList := vpvs.([]*VoltPortVnet)
1381 if vpvList[0].PonPort != 0xFF && vpvList[0].PonPort != p.PonPort {
1382 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})
1383
1384 //Remove the flow (if any) which are already installed - Valid for PON switching when VGC pod is DOWN
1385 for _, vpv := range vpvs.([]*VoltPortVnet) {
1386 vpv.VpvLock.Lock()
1387 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 +05301388 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301389 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301390 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301391 }
1392 vpv.VpvLock.Unlock()
1393 }
1394 return
1395 }
1396
Naveen Sampath04696f72022-06-13 15:19:14 +05301397 for _, vpv := range vpvs.([]*VoltPortVnet) {
1398 vpv.VpvLock.Lock()
Tinoj Josephec742f62022-09-29 19:11:10 +05301399 //If no service is activated drop the portUpInd
1400 if vpv.IsServiceActivated(cntx) {
1401 //Do not trigger indication for the vpv which is already removed from vpv list as
1402 // part of service delete (during the lock wait duration)
1403 // In that case, the services associated wil be zero
1404 if vpv.servicesCount.Load() != 0 {
1405 vpv.PortUpInd(cntx, d, port)
1406 }
1407 } else {
1408 // Service not activated, still attach device to service
1409 vpv.setDevice(d.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +05301410 }
1411 vpv.VpvLock.Unlock()
1412 }
1413 // At the end of processing inform the other entities that
1414 // are interested in the events
1415}
1416
1417/*
1418func getServiceList(port string) map[string]bool {
1419 serviceList := make(map[string]bool)
1420
1421 getServiceNames := func(key interface{}, value interface{}) bool {
1422 serviceList[key.(string)] = value.(*VoltService).DsHSIAFlowsApplied
1423 return true
1424 }
1425
1426 if vpvs, _ := GetApplication().VnetsByPort.Load(port); vpvs != nil {
1427 vpvList := vpvs.([]*VoltPortVnet)
1428 for _, vpv := range vpvList {
1429 vpv.services.Range(getServiceNames)
1430 }
1431 }
1432 return serviceList
1433
1434}*/
1435
1436//ReceiverUpInd - Send receiver up indication for service with Igmp enabled
1437func ReceiverUpInd(key, value interface{}) bool {
1438 svc := value.(*VoltService)
1439 var vlan of.VlanType
1440
1441 if !svc.IPAssigned() {
1442 logger.Infow(ctx, "IP Not assigned, skipping general query", log.Fields{"Service": svc})
1443 return false
1444 }
1445
1446 //Send port up indication to igmp only for service with igmp enabled
1447 if svc.IgmpEnabled {
1448 if svc.VlanControl == ONUCVlan || svc.VlanControl == ONUCVlanOLTSVlan {
1449 vlan = svc.CVlan
1450 } else {
1451 vlan = svc.UniVlan
1452 }
1453 if device, _ := GetApplication().GetDeviceFromPort(svc.Port); device != nil {
1454 GetApplication().ReceiverUpInd(device.Name, svc.Port, svc.MvlanProfileName, vlan, svc.Pbits)
1455 }
1456 return false
1457 }
1458 return true
1459}
1460
1461// PortDownInd : Port down indication is passed on to the services so that the services
1462// can make changes at this transition.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301463func (va *VoltApplication) PortDownInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301464 logger.Infow(ctx, "Received SouthBound Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1465 d := va.GetDevice(device)
1466
1467 if d == nil {
1468 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1469 return
1470 }
1471 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1472 va.portLock.Lock()
1473 // Do not defer the port mutex unlock here
1474 // Some of the following func calls needs the port lock, so defering the lock here
1475 // may lead to dead-lock
1476 p := d.GetPort(port)
1477 if p == nil {
1478 logger.Infow(ctx, "Ignoring Port Ind: Down, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1479 va.portLock.Unlock()
1480 return
1481 }
1482 p.State = PortStateDown
1483 va.portLock.Unlock()
1484
1485 if d.State == controller.DeviceStateREBOOTED {
1486 logger.Infow(ctx, "Ignoring Port Ind: Down, Device has been Rebooted", log.Fields{"Device": device, "PortName": port, "PortId": p})
1487 return
1488 }
1489
1490 if p.Type == VoltPortTypeNni {
1491 logger.Warnw(ctx, "Received NNI Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301492 va.DeleteDevFlowForDevice(cntx, d)
1493 va.NniDownInd(cntx, device, d.SerialNum)
1494 va.RemovePendingGroups(cntx, device, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301495 }
1496 vpvs, ok := va.VnetsByPort.Load(port)
1497 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1498 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1499 //msgbus.ProcessPortInd(msgbus.PortDown, d.SerialNum, p.Name, false, getServiceList(port))
1500 return
1501 }
Akash Sonia8246972023-01-03 10:37:08 +05301502
Naveen Sampath04696f72022-06-13 15:19:14 +05301503 for _, vpv := range vpvs.([]*VoltPortVnet) {
1504 vpv.VpvLock.Lock()
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05301505 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301506 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301507 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301508 }
1509 vpv.VpvLock.Unlock()
1510 }
1511}
1512
1513// PacketInInd :
1514// -----------------------------------------------------------------------
1515// PacketIn Processing
1516// Packet In Indication processing. It arrives with the identities of
1517// the device and port on which the packet is received. At first, the
1518// packet is decoded and the right processor is called. Currently, we
1519// plan to support only DHCP and IGMP. In future, we can add more
1520// capabilities as needed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301521func (va *VoltApplication) PacketInInd(cntx context.Context, device string, port string, pkt []byte) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301522 // Decode the incoming packet
1523 packetSide := US
1524 if strings.Contains(port, NNI) {
1525 packetSide = DS
1526 }
1527
1528 logger.Debugw(ctx, "Received a Packet-In Indication", log.Fields{"Device": device, "Port": port})
1529
1530 gopkt := gopacket.NewPacket(pkt, layers.LayerTypeEthernet, gopacket.Default)
1531
1532 var dot1qFound = false
1533 for _, l := range gopkt.Layers() {
1534 if l.LayerType() == layers.LayerTypeDot1Q {
1535 dot1qFound = true
1536 break
1537 }
1538 }
1539
1540 if !dot1qFound {
1541 logger.Debugw(ctx, "Ignoring Received Packet-In Indication without Dot1Q Header",
1542 log.Fields{"Device": device, "Port": port})
1543 return
1544 }
1545
1546 logger.Debugw(ctx, "Received Southbound Packet In", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1547
1548 // Classify the packet into packet types that we support
1549 // The supported types are DHCP and IGMP. The DHCP packet is
1550 // identified by matching the L4 protocol to UDP. The IGMP packet
1551 // is identified by matching L3 protocol to IGMP
1552 arpl := gopkt.Layer(layers.LayerTypeARP)
1553 if arpl != nil {
1554 if callBack, ok := PacketHandlers[ARP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301555 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301556 } else {
1557 logger.Debugw(ctx, "ARP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1558 }
1559 return
1560 }
1561 ipv4l := gopkt.Layer(layers.LayerTypeIPv4)
1562 if ipv4l != nil {
1563 ip := ipv4l.(*layers.IPv4)
1564
1565 if ip.Protocol == layers.IPProtocolUDP {
1566 logger.Debugw(ctx, "Received Southbound UDP ipv4 packet in", log.Fields{"StreamSide": packetSide})
1567 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv4)
1568 if dhcpl != nil {
1569 if callBack, ok := PacketHandlers[DHCPv4]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301570 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301571 } else {
1572 logger.Debugw(ctx, "DHCPv4 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1573 }
1574 }
1575 } else if ip.Protocol == layers.IPProtocolIGMP {
1576 logger.Debugw(ctx, "Received Southbound IGMP packet in", log.Fields{"StreamSide": packetSide})
1577 if callBack, ok := PacketHandlers[IGMP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301578 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301579 } else {
1580 logger.Debugw(ctx, "IGMP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1581 }
1582 }
1583 return
1584 }
1585 ipv6l := gopkt.Layer(layers.LayerTypeIPv6)
1586 if ipv6l != nil {
1587 ip := ipv6l.(*layers.IPv6)
1588 if ip.NextHeader == layers.IPProtocolUDP {
1589 logger.Debug(ctx, "Received Southbound UDP ipv6 packet in")
1590 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv6)
1591 if dhcpl != nil {
1592 if callBack, ok := PacketHandlers[DHCPv6]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301593 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301594 } else {
1595 logger.Debugw(ctx, "DHCPv6 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1596 }
1597 }
1598 }
1599 return
1600 }
1601
1602 pppoel := gopkt.Layer(layers.LayerTypePPPoE)
1603 if pppoel != nil {
1604 logger.Debugw(ctx, "Received Southbound PPPoE packet in", log.Fields{"StreamSide": packetSide})
1605 if callBack, ok := PacketHandlers[PPPOE]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301606 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301607 } else {
1608 logger.Debugw(ctx, "PPPoE handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1609 }
1610 }
1611}
1612
1613// GetVlans : This utility gets the VLANs from the packet. The VLANs are
1614// used to identify the right service that must process the incoming
1615// packet
1616func GetVlans(pkt gopacket.Packet) []of.VlanType {
1617 var vlans []of.VlanType
1618 for _, l := range pkt.Layers() {
1619 if l.LayerType() == layers.LayerTypeDot1Q {
1620 q, ok := l.(*layers.Dot1Q)
1621 if ok {
1622 vlans = append(vlans, of.VlanType(q.VLANIdentifier))
1623 }
1624 }
1625 }
1626 return vlans
1627}
1628
1629// GetPriority to get priority
1630func GetPriority(pkt gopacket.Packet) uint8 {
1631 for _, l := range pkt.Layers() {
1632 if l.LayerType() == layers.LayerTypeDot1Q {
1633 q, ok := l.(*layers.Dot1Q)
1634 if ok {
1635 return q.Priority
1636 }
1637 }
1638 }
1639 return PriorityNone
1640}
1641
1642// HandleFlowClearFlag to handle flow clear flag during reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301643func (va *VoltApplication) HandleFlowClearFlag(cntx context.Context, deviceID string, serialNum, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301644 logger.Warnw(ctx, "Clear All flags for Device", log.Fields{"Device": deviceID, "SerialNum": serialNum, "SBID": southBoundID})
1645 dev, ok := va.DevicesDisc.Load(deviceID)
1646 if ok && dev != nil {
1647 logger.Infow(ctx, "Clear Flags for device", log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1648 dev.(*VoltDevice).icmpv6GroupAdded = false
1649 logger.Infow(ctx, "Clearing DS Icmpv6 Map",
1650 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1651 dev.(*VoltDevice).ConfiguredVlanForDeviceFlows = util.NewConcurrentMap()
1652 logger.Infow(ctx, "Clearing DS IGMP Map",
1653 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1654 for k := range dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan {
1655 delete(dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan, k)
1656 }
1657 //Delete group 1 - ICMPv6/ARP group
1658 if err := ProcessIcmpv6McGroup(deviceID, true); err != nil {
1659 logger.Errorw(ctx, "ProcessIcmpv6McGroup failed", log.Fields{"Device": deviceID, "Error": err})
1660 }
1661 } else {
1662 logger.Warnw(ctx, "VoltDevice not found for device ", log.Fields{"deviceID": deviceID})
1663 }
1664
1665 getVpvs := func(key interface{}, value interface{}) bool {
1666 vpvs := value.([]*VoltPortVnet)
1667 for _, vpv := range vpvs {
1668 if vpv.Device == deviceID {
1669 logger.Infow(ctx, "Clear Flags for vpv",
1670 log.Fields{"device": vpv.Device, "port": vpv.Port,
1671 "svlan": vpv.SVlan, "cvlan": vpv.CVlan, "univlan": vpv.UniVlan})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301672 vpv.ClearAllServiceFlags(cntx)
1673 vpv.ClearAllVpvFlags(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301674
1675 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301676 va.ReceiverDownInd(cntx, vpv.Device, vpv.Port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301677 //Also clear service igmp stats
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301678 vpv.ClearServiceCounters(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301679 }
1680 }
1681 }
1682 return true
1683 }
1684 va.VnetsByPort.Range(getVpvs)
1685
1686 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301687 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301688
1689 logger.Warnw(ctx, "All flags cleared for device", log.Fields{"Device": deviceID})
1690
1691 //Reset pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301692 va.RemovePendingGroups(cntx, deviceID, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301693
1694 //Process all Migrate Service Request - force udpate all profiles since resources are already cleaned up
1695 if dev != nil {
1696 triggerForceUpdate := func(key, value interface{}) bool {
1697 msrList := value.(*util.ConcurrentMap)
1698 forceUpdateServices := func(key, value interface{}) bool {
1699 msr := value.(*MigrateServicesRequest)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301700 forceUpdateAllServices(cntx, msr)
Naveen Sampath04696f72022-06-13 15:19:14 +05301701 return true
1702 }
1703 msrList.Range(forceUpdateServices)
1704 return true
1705 }
1706 dev.(*VoltDevice).MigratingServices.Range(triggerForceUpdate)
1707 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301708 va.FetchAndProcessAllMigrateServicesReq(cntx, deviceID, forceUpdateAllServices)
Naveen Sampath04696f72022-06-13 15:19:14 +05301709 }
1710}
1711
1712//GetPonPortIDFromUNIPort to get pon port id from uni port
1713func GetPonPortIDFromUNIPort(uniPortID uint32) uint32 {
1714 ponPortID := (uniPortID & 0x0FF00000) >> 20
1715 return ponPortID
1716}
1717
1718//ProcessFlowModResultIndication - Processes Flow mod operation indications from controller
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301719func (va *VoltApplication) ProcessFlowModResultIndication(cntx context.Context, flowStatus intf.FlowStatus) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301720
1721 d := va.GetDevice(flowStatus.Device)
1722 if d == nil {
1723 logger.Errorw(ctx, "Dropping Flow Mod Indication. Device not found", log.Fields{"Cookie": flowStatus.Cookie, "Device": flowStatus.Device})
1724 return
1725 }
1726
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301727 cookieExists := ExecuteFlowEvent(cntx, d, flowStatus.Cookie, flowStatus)
Naveen Sampath04696f72022-06-13 15:19:14 +05301728
1729 if flowStatus.Flow != nil {
1730 flowAdd := (flowStatus.FlowModType == of.CommandAdd)
1731 if !cookieExists && !isFlowStatusSuccess(flowStatus.Status, flowAdd) {
1732 pushFlowFailureNotif(flowStatus)
1733 }
1734 }
1735}
1736
1737func pushFlowFailureNotif(flowStatus intf.FlowStatus) {
1738 subFlow := flowStatus.Flow
1739 cookie := subFlow.Cookie
1740 uniPort := cookie >> 16 & 0xFFFFFFFF
1741 logger.Errorw(ctx, "Flow Failure Notification", log.Fields{"uniPort": uniPort, "Cookie": cookie})
Naveen Sampath04696f72022-06-13 15:19:14 +05301742}
1743
1744//UpdateMvlanProfilesForDevice to update mvlan profile for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301745func (va *VoltApplication) UpdateMvlanProfilesForDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301746
1747 checkAndAddMvlanUpdateTask := func(key, value interface{}) bool {
1748 mvp := value.(*MvlanProfile)
1749 if mvp.IsUpdateInProgressForDevice(device) {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301750 mvp.UpdateProfile(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301751 }
1752 return true
1753 }
1754 va.MvlanProfilesByName.Range(checkAndAddMvlanUpdateTask)
1755}
1756
1757// TaskInfo structure that is used to store the task Info.
1758type TaskInfo struct {
1759 ID string
1760 Name string
1761 Timestamp string
1762}
1763
1764// GetTaskList to get task list information.
1765func (va *VoltApplication) GetTaskList(device string) map[int]*TaskInfo {
1766 taskList := cntlr.GetController().GetTaskList(device)
1767 taskMap := make(map[int]*TaskInfo)
1768 for i, task := range taskList {
1769 taskID := strconv.Itoa(int(task.TaskID()))
1770 name := task.Name()
1771 timestamp := task.Timestamp()
1772 taskInfo := &TaskInfo{ID: taskID, Name: name, Timestamp: timestamp}
1773 taskMap[i] = taskInfo
1774 }
1775 return taskMap
1776}
1777
1778// UpdateDeviceSerialNumberList to update the device serial number list after device serial number is updated for vnet and mvlan
1779func (va *VoltApplication) UpdateDeviceSerialNumberList(oldOltSlNo string, newOltSlNo string) {
1780
Tinoj Joseph50d722c2022-12-06 22:53:22 +05301781 voltDevice, _ := va.GetDeviceBySerialNo(oldOltSlNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301782
1783 if voltDevice != nil {
1784 // Device is present with old serial number ID
1785 logger.Errorw(ctx, "OLT Migration cannot be completed as there are dangling devices", log.Fields{"Serial Number": oldOltSlNo})
1786
1787 } else {
1788 logger.Infow(ctx, "No device present with old serial number", log.Fields{"Serial Number": oldOltSlNo})
1789
1790 // Add Serial Number to Blocked Devices List.
1791 cntlr.GetController().AddBlockedDevices(oldOltSlNo)
1792 cntlr.GetController().AddBlockedDevices(newOltSlNo)
1793
1794 updateSlNoForVnet := func(key, value interface{}) bool {
1795 vnet := value.(*VoltVnet)
1796 for i, deviceSlNo := range vnet.VnetConfig.DevicesList {
1797 if deviceSlNo == oldOltSlNo {
1798 vnet.VnetConfig.DevicesList[i] = newOltSlNo
1799 logger.Infow(ctx, "device serial number updated for vnet profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1800 break
1801 }
1802 }
1803 return true
1804 }
1805
1806 updateSlNoforMvlan := func(key interface{}, value interface{}) bool {
1807 mvProfile := value.(*MvlanProfile)
1808 for deviceSlNo := range mvProfile.DevicesList {
1809 if deviceSlNo == oldOltSlNo {
1810 mvProfile.DevicesList[newOltSlNo] = mvProfile.DevicesList[oldOltSlNo]
1811 delete(mvProfile.DevicesList, oldOltSlNo)
1812 logger.Infow(ctx, "device serial number updated for mvlan profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1813 break
1814 }
1815 }
1816 return true
1817 }
1818
1819 va.VnetsByName.Range(updateSlNoForVnet)
1820 va.MvlanProfilesByName.Range(updateSlNoforMvlan)
1821
1822 // Clear the serial number from Blocked Devices List
1823 cntlr.GetController().DelBlockedDevices(oldOltSlNo)
1824 cntlr.GetController().DelBlockedDevices(newOltSlNo)
1825
1826 }
1827}
1828
1829// GetVpvsForDsPkt to get vpv for downstream packets
1830func (va *VoltApplication) GetVpvsForDsPkt(cvlan of.VlanType, svlan of.VlanType, clientMAC net.HardwareAddr,
1831 pbit uint8) ([]*VoltPortVnet, error) {
1832
1833 var matchVPVs []*VoltPortVnet
1834 findVpv := func(key, value interface{}) bool {
1835 vpvs := value.([]*VoltPortVnet)
1836 for _, vpv := range vpvs {
1837 if vpv.isVlanMatching(cvlan, svlan) && vpv.MatchesPriority(pbit) != nil {
1838 var subMac net.HardwareAddr
1839 if NonZeroMacAddress(vpv.MacAddr) {
1840 subMac = vpv.MacAddr
1841 } else if vpv.LearntMacAddr != nil && NonZeroMacAddress(vpv.LearntMacAddr) {
1842 subMac = vpv.LearntMacAddr
1843 } else {
1844 matchVPVs = append(matchVPVs, vpv)
1845 continue
1846 }
1847 if util.MacAddrsMatch(subMac, clientMAC) {
1848 matchVPVs = append([]*VoltPortVnet{}, vpv)
1849 logger.Infow(ctx, "Matching VPV found", log.Fields{"Port": vpv.Port, "SVLAN": vpv.SVlan, "CVLAN": vpv.CVlan, "UNIVlan": vpv.UniVlan, "MAC": clientMAC})
1850 return false
1851 }
1852 }
1853 }
1854 return true
1855 }
1856 va.VnetsByPort.Range(findVpv)
1857
1858 if len(matchVPVs) != 1 {
1859 logger.Infow(ctx, "No matching VPV found or multiple vpvs found", log.Fields{"Match VPVs": matchVPVs, "MAC": clientMAC})
1860 return nil, errors.New("No matching VPV found or multiple vpvs found")
1861 }
1862 return matchVPVs, nil
1863}
1864
1865// GetMacInPortMap to get PORT value based on MAC key
1866func (va *VoltApplication) GetMacInPortMap(macAddr net.HardwareAddr) string {
1867 if NonZeroMacAddress(macAddr) {
1868 va.macPortLock.Lock()
1869 defer va.macPortLock.Unlock()
1870 if port, ok := va.macPortMap[macAddr.String()]; ok {
1871 logger.Debugw(ctx, "found-entry-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1872 return port
1873 }
1874 }
1875 logger.Infow(ctx, "entry-not-found-macportmap", log.Fields{"MacAddr": macAddr.String()})
1876 return ""
1877}
1878
1879// UpdateMacInPortMap to update MAC PORT (key value) information in MacPortMap
1880func (va *VoltApplication) UpdateMacInPortMap(macAddr net.HardwareAddr, port string) {
1881 if NonZeroMacAddress(macAddr) {
1882 va.macPortLock.Lock()
1883 va.macPortMap[macAddr.String()] = port
1884 va.macPortLock.Unlock()
1885 logger.Debugw(ctx, "updated-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1886 }
1887}
1888
1889// DeleteMacInPortMap to remove MAC key from MacPortMap
1890func (va *VoltApplication) DeleteMacInPortMap(macAddr net.HardwareAddr) {
1891 if NonZeroMacAddress(macAddr) {
1892 port := va.GetMacInPortMap(macAddr)
1893 va.macPortLock.Lock()
1894 delete(va.macPortMap, macAddr.String())
1895 va.macPortLock.Unlock()
1896 logger.Debugw(ctx, "deleted-from-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1897 }
1898}
1899
1900//AddGroupToPendingPool - adds the IgmpGroup with active group table entry to global pending pool
1901func (va *VoltApplication) AddGroupToPendingPool(ig *IgmpGroup) {
1902 var grpMap map[*IgmpGroup]bool
1903 var ok bool
1904
1905 va.PendingPoolLock.Lock()
1906 defer va.PendingPoolLock.Unlock()
1907
1908 logger.Infow(ctx, "Adding IgmpGroup to Global Pending Pool", log.Fields{"GroupID": ig.GroupID, "GroupName": ig.GroupName, "GroupAddr": ig.GroupAddr, "PendingDevices": len(ig.Devices)})
1909 // Do Not Reset any current profile info since group table entry tied to mvlan profile
1910 // The PonVlan is part of set field in group installed
1911 // Hence, Group created is always tied to the same mvlan profile until deleted
1912
1913 for device := range ig.Devices {
1914 key := getPendingPoolKey(ig.Mvlan, device)
1915
1916 if grpMap, ok = va.IgmpPendingPool[key]; !ok {
1917 grpMap = make(map[*IgmpGroup]bool)
1918 }
1919 grpMap[ig] = true
1920
1921 //Add grpObj reference to all associated devices
1922 va.IgmpPendingPool[key] = grpMap
1923 }
1924}
1925
1926//RemoveGroupFromPendingPool - removes the group from global pending group pool
1927func (va *VoltApplication) RemoveGroupFromPendingPool(device string, ig *IgmpGroup) bool {
1928 GetApplication().PendingPoolLock.Lock()
1929 defer GetApplication().PendingPoolLock.Unlock()
1930
1931 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)})
1932
1933 key := getPendingPoolKey(ig.Mvlan, device)
1934 if _, ok := va.IgmpPendingPool[key]; ok {
1935 delete(va.IgmpPendingPool[key], ig)
1936 return true
1937 }
1938 return false
1939}
1940
1941//RemoveGroupsFromPendingPool - removes the group from global pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301942func (va *VoltApplication) RemoveGroupsFromPendingPool(cntx context.Context, device string, mvlan of.VlanType) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301943 GetApplication().PendingPoolLock.Lock()
1944 defer GetApplication().PendingPoolLock.Unlock()
1945
1946 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool for given Deivce & Mvlan", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1947
1948 key := getPendingPoolKey(mvlan, device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301949 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05301950}
1951
1952//RemoveGroupListFromPendingPool - removes the groups for provided key
1953// 1. Deletes the group from device
1954// 2. Delete the IgmpGroup obj and release the group ID to pool
1955// Note: Make sure to obtain PendingPoolLock lock before calling this func
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301956func (va *VoltApplication) RemoveGroupListFromPendingPool(cntx context.Context, key string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301957 if grpMap, ok := va.IgmpPendingPool[key]; ok {
1958 delete(va.IgmpPendingPool, key)
1959 for ig := range grpMap {
1960 for device := range ig.Devices {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301961 ig.DeleteIgmpGroupDevice(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301962 }
1963 }
1964 }
1965}
1966
1967//RemoveGroupDevicesFromPendingPool - removes the group from global pending group pool
1968func (va *VoltApplication) RemoveGroupDevicesFromPendingPool(ig *IgmpGroup) {
1969
1970 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)})
1971 for device := range ig.PendingGroupForDevice {
1972 va.RemoveGroupFromPendingPool(device, ig)
1973 }
1974}
1975
1976//GetGroupFromPendingPool - Returns IgmpGroup obj from global pending pool
1977func (va *VoltApplication) GetGroupFromPendingPool(mvlan of.VlanType, device string) *IgmpGroup {
1978
1979 var ig *IgmpGroup
1980
1981 va.PendingPoolLock.Lock()
1982 defer va.PendingPoolLock.Unlock()
1983
1984 key := getPendingPoolKey(mvlan, device)
1985 logger.Infow(ctx, "Getting IgmpGroup from Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String(), "Key": key})
1986
1987 //Gets all IgmpGrp Obj for the device
1988 grpMap, ok := va.IgmpPendingPool[key]
1989 if !ok || len(grpMap) == 0 {
1990 logger.Infow(ctx, "Matching IgmpGroup not found in Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1991 return nil
1992 }
1993
1994 //Gets a random obj from available grps
1995 for ig = range grpMap {
1996
1997 //Remove grp obj reference from all devices associated in pending pool
1998 for dev := range ig.Devices {
1999 key := getPendingPoolKey(mvlan, dev)
2000 delete(va.IgmpPendingPool[key], ig)
2001 }
2002
2003 //Safety check to avoid re-allocating group already in use
2004 if ig.NumDevicesActive() == 0 {
2005 return ig
2006 }
2007
2008 //Iteration will continue only if IG is not allocated
2009 }
2010 return nil
2011}
2012
2013//RemovePendingGroups - removes all pending groups for provided reference from global pending pool
2014// reference - mvlan/device ID
2015// isRefDevice - true - Device as reference
2016// false - Mvlan as reference
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302017func (va *VoltApplication) RemovePendingGroups(cntx context.Context, reference string, isRefDevice bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302018 va.PendingPoolLock.Lock()
2019 defer va.PendingPoolLock.Unlock()
2020
2021 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool", log.Fields{"Reference": reference, "isRefDevice": isRefDevice})
2022
2023 //Pending Pool key: "<mvlan>_<DeviceID>""
2024 paramPosition := 0
2025 if isRefDevice {
2026 paramPosition = 1
2027 }
2028
2029 // 1.Remove the Entry from pending pool
2030 // 2.Deletes the group from device
2031 // 3.Delete the IgmpGroup obj and release the group ID to pool
2032 for key := range va.IgmpPendingPool {
2033 keyParams := strings.Split(key, "_")
2034 if keyParams[paramPosition] == reference {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302035 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05302036 }
2037 }
2038}
2039
2040func getPendingPoolKey(mvlan of.VlanType, device string) string {
2041 return mvlan.String() + "_" + device
2042}
2043
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302044func (va *VoltApplication) removeExpiredGroups(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302045 logger.Debug(ctx, "Check for expired Igmp Groups")
2046 removeExpiredGroups := func(key interface{}, value interface{}) bool {
2047 ig := value.(*IgmpGroup)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302048 ig.removeExpiredGroupFromDevice(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302049 return true
2050 }
2051 va.IgmpGroups.Range(removeExpiredGroups)
2052}
2053
2054//TriggerPendingProfileDeleteReq - trigger pending profile delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302055func (va *VoltApplication) TriggerPendingProfileDeleteReq(cntx context.Context, device string) {
2056 va.TriggerPendingServiceDeleteReq(cntx, device)
2057 va.TriggerPendingVpvDeleteReq(cntx, device)
2058 va.TriggerPendingVnetDeleteReq(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05302059 logger.Warnw(ctx, "All Pending Profile Delete triggered for device", log.Fields{"Device": device})
2060}
2061
2062//TriggerPendingServiceDeleteReq - trigger pending service delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302063func (va *VoltApplication) TriggerPendingServiceDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302064
2065 logger.Warnw(ctx, "Pending Services to be deleted", log.Fields{"Count": len(va.ServicesToDelete)})
2066 for serviceName := range va.ServicesToDelete {
2067 logger.Debugw(ctx, "Trigger Service Delete", log.Fields{"Service": serviceName})
2068 if vs := va.GetService(serviceName); vs != nil {
2069 if vs.Device == device {
2070 logger.Warnw(ctx, "Triggering Pending Service delete", log.Fields{"Service": vs.Name})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302071 vs.DelHsiaFlows(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302072 if vs.ForceDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302073 vs.DelFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302074 }
2075 }
2076 } else {
2077 logger.Errorw(ctx, "Pending Service Not found", log.Fields{"Service": serviceName})
2078 }
2079 }
2080}
2081
2082//TriggerPendingVpvDeleteReq - trigger pending VPV delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302083func (va *VoltApplication) TriggerPendingVpvDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302084
2085 logger.Warnw(ctx, "Pending VPVs to be deleted", log.Fields{"Count": len(va.VoltPortVnetsToDelete)})
2086 for vpv := range va.VoltPortVnetsToDelete {
2087 if vpv.Device == device {
2088 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 +05302089 va.DelVnetFromPort(cntx, vpv.Port, vpv)
Naveen Sampath04696f72022-06-13 15:19:14 +05302090 }
2091 }
2092}
2093
2094//TriggerPendingVnetDeleteReq - trigger pending vnet delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302095func (va *VoltApplication) TriggerPendingVnetDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302096
2097 logger.Warnw(ctx, "Pending Vnets to be deleted", log.Fields{"Count": len(va.VnetsToDelete)})
2098 for vnetName := range va.VnetsToDelete {
2099 if vnetIntf, _ := va.VnetsByName.Load(vnetName); vnetIntf != nil {
2100 vnet := vnetIntf.(*VoltVnet)
2101 logger.Warnw(ctx, "Triggering Pending Vnet flows delete", log.Fields{"Vnet": vnet.Name})
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302102 if d, _ := va.GetDeviceBySerialNo(vnet.PendingDeviceToDelete); d != nil && d.SerialNum == vnet.PendingDeviceToDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302103 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, vnet.PendingDeviceToDelete)
Naveen Sampath04696f72022-06-13 15:19:14 +05302104 va.deleteVnetConfig(vnet)
2105 } else {
Tinoj Joseph1d108322022-07-13 10:07:39 +05302106 logger.Warnw(ctx, "Vnet Delete Failed : Device Not Found", log.Fields{"Vnet": vnet.Name, "Device": vnet.PendingDeviceToDelete})
Naveen Sampath04696f72022-06-13 15:19:14 +05302107 }
2108 }
2109 }
2110}
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302111
2112type OltFlowService struct {
Akash Sonia8246972023-01-03 10:37:08 +05302113 EnableDhcpOnNni bool `json:"enableDhcpOnNni"`
2114 DefaultTechProfileId int `json:"defaultTechProfileId"`
2115 EnableIgmpOnNni bool `json:"enableIgmpOnNni"`
2116 EnableEapol bool `json:"enableEapol"`
2117 EnableDhcpV6 bool `json:"enableDhcpV6"`
2118 EnableDhcpV4 bool `json:"enableDhcpV4"`
2119 RemoveFlowsOnDisable bool `json:"removeFlowsOnDisable"`
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302120}
2121
2122func (va *VoltApplication) UpdateOltFlowService(cntx context.Context, oltFlowService OltFlowService) {
2123 logger.Infow(ctx, "UpdateOltFlowService", log.Fields{"oldValue": va.OltFlowServiceConfig, "newValue": oltFlowService})
2124 va.OltFlowServiceConfig = oltFlowService
2125 b, err := json.Marshal(va.OltFlowServiceConfig)
2126 if err != nil {
2127 logger.Warnw(ctx, "Failed to Marshal OltFlowServiceConfig", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2128 return
2129 }
2130 _ = db.PutOltFlowService(cntx, string(b))
2131}
Akash Sonia8246972023-01-03 10:37:08 +05302132
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302133// RestoreOltFlowService to read from the DB and restore olt flow service config
2134func (va *VoltApplication) RestoreOltFlowService(cntx context.Context) {
2135 oltflowService, err := db.GetOltFlowService(cntx)
2136 if err != nil {
2137 logger.Warnw(ctx, "Failed to Get OltFlowServiceConfig from DB", log.Fields{"Error": err})
2138 return
2139 }
2140 err = json.Unmarshal([]byte(oltflowService), &va.OltFlowServiceConfig)
2141 if err != nil {
2142 logger.Warn(ctx, "Unmarshal of oltflowService failed")
2143 return
2144 }
2145 logger.Infow(ctx, "updated OltFlowServiceConfig from DB", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2146}
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302147
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302148func (va *VoltApplication) UpdateDeviceConfig(cntx context.Context, sn, mac, nasID string, port, dhcpVid int, ip net.IP) {
2149 if d, ok := va.DevicesConfig.Load(sn); ok {
2150 logger.Infow(ctx, "Device configuration already exists", log.Fields{"DeviceInfo": d})
2151 }
Akash Sonia8246972023-01-03 10:37:08 +05302152 d := DeviceConfig{
2153 SerialNumber: sn,
2154 UplinkPort: port,
2155 HardwareIdentifier: mac,
2156 IPAddress: ip,
2157 NasID: nasID,
2158 NniDhcpTrapVid: dhcpVid,
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302159 }
2160 logger.Infow(ctx, "Added OLT configurations", log.Fields{"DeviceInfo": d})
2161 va.DevicesConfig.Store(sn, d)
2162 // If device is already discovered update the VoltDevice structure
2163 device, id := va.GetDeviceBySerialNo(sn)
2164 if device != nil {
2165 device.NniDhcpTrapVid = of.VlanType(dhcpVid)
2166 va.DevicesDisc.Store(id, device)
2167 }
2168}