blob: 74b72f8ac3800f8a4c0361b17a358231db64b3c4 [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
33 "voltha-go-controller/internal/pkg/controller"
34 cntlr "voltha-go-controller/internal/pkg/controller"
35 "voltha-go-controller/database"
36 "voltha-go-controller/internal/pkg/intf"
37 "voltha-go-controller/internal/pkg/of"
38 "voltha-go-controller/internal/pkg/tasks"
39 "voltha-go-controller/internal/pkg/util"
40 errorCodes "voltha-go-controller/internal/pkg/errorcodes"
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
367 logger.Infow(ctx, "NNI Discovered. Sending Port UP Ind for UNI", log.Fields{"Port" : port})
368 //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
443 IgmpPendingPool map[string]map[*IgmpGroup]bool //[grpkey, map[groupObj]bool] //mvlan_grpName/IP
444 PendingPoolLock sync.RWMutex
445
446 VnetsToDelete map[string]bool
447 ServicesToDelete map[string]bool
448 VoltPortVnetsToDelete map[*VoltPortVnet]bool
449 PortAlarmProfileCache map[string]map[string]int // [portAlarmID][ThresholdLevelString]ThresholdLevel
450 vendorID string
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530451 OltFlowServiceConfig OltFlowService
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530452 DevicesConfig sync.Map
Naveen Sampath04696f72022-06-13 15:19:14 +0530453}
454
455// PonPortCfg contains NB port config and activeIGMPChannels count
456type PonPortCfg struct {
457 PortID uint32
458 MaxActiveChannels uint32
459 ActiveIGMPChannels uint32
460 EnableMulticastKPI bool
461 PortAlarmProfileID string
462}
463
464// NbDevice OLT Device info
465type NbDevice struct {
466 SouthBoundID string
467 PonPorts sync.Map // [PortID]*PonPortCfg
468}
469
470// RestoreNbDeviceFromDb restores the NB Device in case of VGC pod restart.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530471func (va *VoltApplication) RestoreNbDeviceFromDb(cntx context.Context, deviceID string) *NbDevice {
Naveen Sampath04696f72022-06-13 15:19:14 +0530472
473 nbDevice := NewNbDevice()
474 nbDevice.SouthBoundID = deviceID
475
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530476 nbPorts, _ := db.GetAllNbPorts(cntx, deviceID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530477
478 for key, p := range nbPorts {
479 b, ok := p.Value.([]byte)
480 if !ok {
481 logger.Warn(ctx, "The value type is not []byte")
482 continue
483 }
484 var port PonPortCfg
485 err := json.Unmarshal(b, &port)
486 if err != nil {
487 logger.Warn(ctx, "Unmarshal of PonPortCfg failed")
488 continue
489 }
490 logger.Debugw(ctx, "Port recovered", log.Fields{"port": port})
491 ponPortID, _ := strconv.Atoi(key)
492 nbDevice.PonPorts.Store(uint32(ponPortID), &port)
493 }
494 va.NbDevice.Store(deviceID, nbDevice)
495 return nbDevice
496}
497
498// NewNbDevice Constructor for NbDevice
499func NewNbDevice() *NbDevice {
500 var nbDevice NbDevice
501 return &nbDevice
502}
503
504// WriteToDb writes nb device port config to kv store
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530505func (nbd *NbDevice) WriteToDb(cntx context.Context, portID uint32, ponPort *PonPortCfg) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530506 b, err := json.Marshal(ponPort)
507 if err != nil {
508 logger.Errorw(ctx, "PonPortConfig-marshal-failed", log.Fields{"err": err})
509 return
510 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530511 db.PutNbDevicePort(cntx, nbd.SouthBoundID, portID, string(b))
Naveen Sampath04696f72022-06-13 15:19:14 +0530512}
513
514// AddPortToNbDevice Adds pon port to NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530515func (nbd *NbDevice) AddPortToNbDevice(cntx context.Context, portID, allowedChannels uint32,
Naveen Sampath04696f72022-06-13 15:19:14 +0530516 enableMulticastKPI bool, portAlarmProfileID string) *PonPortCfg {
517
518 ponPort := &PonPortCfg{
519 PortID: portID,
520 MaxActiveChannels: allowedChannels,
521 EnableMulticastKPI: enableMulticastKPI,
522 PortAlarmProfileID: portAlarmProfileID,
523 }
524 nbd.PonPorts.Store(portID, ponPort)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530525 nbd.WriteToDb(cntx, portID, ponPort)
Naveen Sampath04696f72022-06-13 15:19:14 +0530526 return ponPort
527}
528
529// UpdatePortToNbDevice Adds pon port to NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530530func (nbd *NbDevice) UpdatePortToNbDevice(cntx context.Context, portID, allowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) *PonPortCfg {
Naveen Sampath04696f72022-06-13 15:19:14 +0530531
532 p, exists := nbd.PonPorts.Load(portID)
533 if !exists {
534 logger.Errorw(ctx, "PON port not exists in nb-device", log.Fields{"portID": portID})
535 return nil
536 }
537 port := p.(*PonPortCfg)
538 if allowedChannels != 0 {
539 port.MaxActiveChannels = allowedChannels
540 port.EnableMulticastKPI = enableMulticastKPI
541 port.PortAlarmProfileID = portAlarmProfileID
542 }
543
544 nbd.PonPorts.Store(portID, port)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530545 nbd.WriteToDb(cntx, portID, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530546 return port
547}
548
549// DeletePortFromNbDevice Deletes pon port from NB Device and DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530550func (nbd *NbDevice) DeletePortFromNbDevice(cntx context.Context, portID uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530551
552 if _, ok := nbd.PonPorts.Load(portID); ok {
553 nbd.PonPorts.Delete(portID)
554 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530555 db.DelNbDevicePort(cntx, nbd.SouthBoundID, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530556}
557
558// GetApplication : Interface to access the singleton object
559func GetApplication() *VoltApplication {
560 if vapplication == nil {
561 vapplication = newVoltApplication()
562 }
563 return vapplication
564}
565
566// newVoltApplication : Constructor for the singleton object. Hence this is not
567// an exported function
568func newVoltApplication() *VoltApplication {
569 var va VoltApplication
570 va.IgmpTasks.Initialize(context.TODO())
571 va.MulticastAlarmTasks.Initialize(context.TODO())
572 va.IgmpKPIsTasks.Initialize(context.TODO())
573 va.pppoeTasks.Initialize(context.TODO())
574 va.storeIgmpProfileMap(DefaultIgmpProfID, newDefaultIgmpProfile())
575 va.MeterMgr.Init()
576 va.AddIgmpGroups(5000)
577 va.macPortMap = make(map[string]string)
578 va.IgmpPendingPool = make(map[string]map[*IgmpGroup]bool)
579 va.VnetsBySvlan = util.NewConcurrentMap()
580 va.VnetsToDelete = make(map[string]bool)
581 va.ServicesToDelete = make(map[string]bool)
582 va.VoltPortVnetsToDelete = make(map[*VoltPortVnet]bool)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530583 go va.Start(context.Background(), TimerCfg{tick: 100 * time.Millisecond}, tickTimer)
584 go va.Start(context.Background(), TimerCfg{tick: time.Duration(GroupExpiryTime) * time.Minute}, pendingPoolTimer)
Naveen Sampath04696f72022-06-13 15:19:14 +0530585 InitEventFuncMapper()
586 db = database.GetDatabase()
587 return &va
588}
589
590//GetFlowEventRegister - returs the register based on flow mod type
591func (d *VoltDevice) GetFlowEventRegister(flowModType of.Command) (*util.ConcurrentMap, error) {
592
593 switch flowModType {
594 case of.CommandDel:
595 return d.FlowDelEventMap, nil
596 case of.CommandAdd:
597 return d.FlowAddEventMap, nil
598 default:
599 logger.Error(ctx, "Unknown Flow Mod received")
600 }
601 return util.NewConcurrentMap(), errors.New("Unknown Flow Mod")
602}
603
604// RegisterFlowAddEvent to register a flow event.
605func (d *VoltDevice) RegisterFlowAddEvent(cookie string, event *FlowEvent) {
606 logger.Debugw(ctx, "Registered Flow Add Event", log.Fields{"Cookie": cookie, "Event": event})
607 d.FlowAddEventMap.MapLock.Lock()
608 defer d.FlowAddEventMap.MapLock.Unlock()
609 d.FlowAddEventMap.Set(cookie, event)
610}
611
612// RegisterFlowDelEvent to register a flow event.
613func (d *VoltDevice) RegisterFlowDelEvent(cookie string, event *FlowEvent) {
614 logger.Debugw(ctx, "Registered Flow Del Event", log.Fields{"Cookie": cookie, "Event": event})
615 d.FlowDelEventMap.MapLock.Lock()
616 defer d.FlowDelEventMap.MapLock.Unlock()
617 d.FlowDelEventMap.Set(cookie, event)
618}
619
620// UnRegisterFlowEvent to unregister a flow event.
621func (d *VoltDevice) UnRegisterFlowEvent(cookie string, flowModType of.Command) {
622 logger.Debugw(ctx, "UnRegistered Flow Add Event", log.Fields{"Cookie": cookie, "Type": flowModType})
623 flowEventMap, err := d.GetFlowEventRegister(flowModType)
624 if err != nil {
625 logger.Debugw(ctx, "Flow event map does not exists", log.Fields{"flowMod": flowModType, "Error": err})
626 return
627 }
628 flowEventMap.MapLock.Lock()
629 defer flowEventMap.MapLock.Unlock()
630 flowEventMap.Remove(cookie)
631}
632
633// AddIgmpGroups to add Igmp groups.
634func (va *VoltApplication) AddIgmpGroups(numOfGroups uint32) {
635 //TODO: Temp change to resolve group id issue in pOLT
636 //for i := 1; uint32(i) <= numOfGroups; i++ {
637 for i := 2; uint32(i) <= (numOfGroups + 1); i++ {
638 ig := IgmpGroup{}
639 ig.GroupID = uint32(i)
640 va.IgmpGroupIds = append(va.IgmpGroupIds, &ig)
641 }
642}
643
644// GetAvailIgmpGroupID to get id of available igmp group.
645func (va *VoltApplication) GetAvailIgmpGroupID() *IgmpGroup {
646 var ig *IgmpGroup
647 if len(va.IgmpGroupIds) > 0 {
648 ig, va.IgmpGroupIds = va.IgmpGroupIds[0], va.IgmpGroupIds[1:]
649 return ig
650 }
651 return nil
652}
653
654// GetIgmpGroupID to get id of igmp group.
655func (va *VoltApplication) GetIgmpGroupID(gid uint32) (*IgmpGroup, error) {
656 for id, ig := range va.IgmpGroupIds {
657 if ig.GroupID == gid {
658 va.IgmpGroupIds = append(va.IgmpGroupIds[0:id], va.IgmpGroupIds[id+1:]...)
659 return ig, nil
660 }
661 }
662 return nil, errors.New("Group Id Missing")
663}
664
665// PutIgmpGroupID to add id of igmp group.
666func (va *VoltApplication) PutIgmpGroupID(ig *IgmpGroup) {
667 va.IgmpGroupIds = append([]*IgmpGroup{ig}, va.IgmpGroupIds[0:]...)
668}
669
670//RestoreUpgradeStatus - gets upgrade/migration status from DB and updates local flags
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530671func (va *VoltApplication) RestoreUpgradeStatus(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530672 Migrate := new(DataMigration)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530673 if err := GetMigrationInfo(cntx, Migrate); err == nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530674 if Migrate.Status == MigrationInProgress {
675 isUpgradeComplete = false
676 return
677 }
678 }
679 isUpgradeComplete = true
680
681 logger.Infow(ctx, "Upgrade Status Restored", log.Fields{"Upgrade Completed": isUpgradeComplete})
682}
683
684// ReadAllFromDb : If we are restarted, learn from the database the current execution
685// stage
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530686func (va *VoltApplication) ReadAllFromDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530687 logger.Info(ctx, "Reading the meters from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530688 va.RestoreMetersFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530689 logger.Info(ctx, "Reading the VNETs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530690 va.RestoreVnetsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530691 logger.Info(ctx, "Reading the VPVs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530692 va.RestoreVpvsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530693 logger.Info(ctx, "Reading the Services from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530694 va.RestoreSvcsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530695 logger.Info(ctx, "Reading the MVLANs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530696 va.RestoreMvlansFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530697 logger.Info(ctx, "Reading the IGMP profiles from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530698 va.RestoreIGMPProfilesFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530699 logger.Info(ctx, "Reading the Mcast configs from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530700 va.RestoreMcastConfigsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530701 logger.Info(ctx, "Reading the IGMP groups for DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530702 va.RestoreIgmpGroupsFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530703 logger.Info(ctx, "Reading Upgrade status from DB")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530704 va.RestoreUpgradeStatus(cntx)
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530705 logger.Info(ctx, "Reading OltFlowService from DB")
706 va.RestoreOltFlowService(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530707 logger.Info(ctx, "Reconciled from DB")
708}
709
710// InitStaticConfig to initialise static config.
711func (va *VoltApplication) InitStaticConfig() {
712 va.InitIgmpSrcMac()
713}
714
715// SetVendorID to set vendor id
716func (va *VoltApplication) SetVendorID(vendorID string) {
717 va.vendorID = vendorID
718}
719
720// GetVendorID to get vendor id
721func (va *VoltApplication) GetVendorID() string {
722 return va.vendorID
723}
724
725// SetRebootFlag to set reboot flag
726func (va *VoltApplication) SetRebootFlag(flag bool) {
727 vgcRebooted = flag
728}
729
730// GetUpgradeFlag to get reboot status
731func (va *VoltApplication) GetUpgradeFlag() bool {
732 return isUpgradeComplete
733}
734
735// SetUpgradeFlag to set reboot status
736func (va *VoltApplication) SetUpgradeFlag(flag bool) {
737 isUpgradeComplete = flag
738}
739
740// ------------------------------------------------------------
741// Device related functions
742
743// AddDevice : Add a device and typically the device stores the NNI port on the device
744// The NNI port is used when the packets are emitted towards the network.
745// The outport is selected as the NNI port of the device. Today, we support
746// a single NNI port per OLT. This is true whether the network uses any
747// protection mechanism (LAG, ERPS, etc.). The aggregate of the such protection
748// is represented by a single NNI port
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530749func (va *VoltApplication) AddDevice(cntx context.Context, device string, slno, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530750 logger.Warnw(ctx, "Received Device Ind: Add", log.Fields{"Device": device, "SrNo": slno})
751 if _, ok := va.DevicesDisc.Load(device); ok {
752 logger.Warnw(ctx, "Device Exists", log.Fields{"Device": device})
753 }
754 d := NewVoltDevice(device, slno, southBoundID)
755
756 addPort := func(key, value interface{}) bool {
757 portID := key.(uint32)
758 port := value.(*PonPortCfg)
759 va.AggActiveChannelsCountForPonPort(device, portID, port)
760 d.ActiveChannelsPerPon.Store(portID, port)
761 return true
762 }
763 if nbDevice, exists := va.NbDevice.Load(southBoundID); exists {
764 // Pon Ports added before OLT activate.
765 nbDevice.(*NbDevice).PonPorts.Range(addPort)
766 } else {
767 // Check if NbPort exists in DB. VGC restart case.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530768 nbd := va.RestoreNbDeviceFromDb(cntx, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530769 nbd.PonPorts.Range(addPort)
770 }
771 va.DevicesDisc.Store(device, d)
772}
773
774// GetDevice to get a device.
775func (va *VoltApplication) GetDevice(device string) *VoltDevice {
776 if d, ok := va.DevicesDisc.Load(device); ok {
777 return d.(*VoltDevice)
778 }
779 return nil
780}
781
782// DelDevice to delete a device.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530783func (va *VoltApplication) DelDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530784 logger.Warnw(ctx, "Received Device Ind: Delete", log.Fields{"Device": device})
785 if vdIntf, ok := va.DevicesDisc.Load(device); ok {
786 vd := vdIntf.(*VoltDevice)
787 va.DevicesDisc.Delete(device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530788 _ = db.DelAllRoutesForDevice(cntx, device)
789 va.HandleFlowClearFlag(cntx, device, vd.SerialNum, vd.SouthBoundID)
790 _ = db.DelAllGroup(cntx, device)
791 _ = db.DelAllMeter(cntx, device)
792 _ = db.DelAllPorts(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +0530793 logger.Debugw(ctx, "Device deleted", log.Fields{"Device": device})
794 } else {
795 logger.Warnw(ctx, "Device Doesn't Exist", log.Fields{"Device": device})
796 }
797}
798
799// GetDeviceBySerialNo to get a device by serial number.
800// TODO - Transform this into a MAP instead
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530801func (va *VoltApplication) GetDeviceBySerialNo(slno string) (*VoltDevice, string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530802 var device *VoltDevice
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530803 var deviceID string
Naveen Sampath04696f72022-06-13 15:19:14 +0530804 getserial := func(key interface{}, value interface{}) bool {
805 device = value.(*VoltDevice)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530806 deviceID = key.(string)
Naveen Sampath04696f72022-06-13 15:19:14 +0530807 return device.SerialNum != slno
808 }
809 va.DevicesDisc.Range(getserial)
Tinoj Joseph50d722c2022-12-06 22:53:22 +0530810 return device, deviceID
Naveen Sampath04696f72022-06-13 15:19:14 +0530811}
812
813// PortAddInd : This is a PORT add indication coming from the VPAgent, which is essentially
814// a request coming from VOLTHA. The device and identity of the port is provided
815// in this request. Add them to the application for further use
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530816func (va *VoltApplication) PortAddInd(cntx context.Context, device string, id uint32, portName string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530817 logger.Infow(ctx, "Received Port Ind: Add", log.Fields{"Device": device, "Port": portName})
818 va.portLock.Lock()
819 if d := va.GetDevice(device); d != nil {
820 p := d.AddPort(portName, id)
821 va.PortsDisc.Store(portName, p)
822 va.portLock.Unlock()
823 nni, _ := va.GetNniPort(device)
824 if nni == portName {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530825 d.pushFlowsForUnis(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530826 }
827 } else {
828 va.portLock.Unlock()
829 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Add", log.Fields{"Device": device, "Port": portName})
830 }
831}
832
833// PortDelInd : Only the NNI ports are recorded in the device for now. When port delete
834// arrives, only the NNI ports need adjustments.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530835func (va *VoltApplication) PortDelInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530836 logger.Infow(ctx, "Received Port Ind: Delete", log.Fields{"Device": device, "Port": port})
837 if d := va.GetDevice(device); d != nil {
838 p := d.GetPort(port)
839 if p != nil && p.State == PortStateUp {
840 logger.Infow(ctx, "Port state is UP. Trigerring Port Down Ind before deleting", log.Fields{"Port": p})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530841 va.PortDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530842 }
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530843 // if RemoveFlowsOnDisable is flase, then flows will be existing till port delete. Remove the flows now
844 if !va.OltFlowServiceConfig.RemoveFlowsOnDisable {
845 vpvs, ok := va.VnetsByPort.Load(port)
846 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
847 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
848 } else {
849 for _, vpv := range vpvs.([]*VoltPortVnet) {
850 vpv.VpvLock.Lock()
851 vpv.PortDownInd(cntx, device, port, true)
852 vpv.VpvLock.Unlock()
853 }
854 }
855 }
Naveen Sampath04696f72022-06-13 15:19:14 +0530856 va.portLock.Lock()
857 defer va.portLock.Unlock()
858 d.DelPort(port)
859 if _, ok := va.PortsDisc.Load(port); ok {
860 va.PortsDisc.Delete(port)
861 }
862 } else {
863 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: Delete", log.Fields{"Device": device, "Port": port})
864 }
865}
866
867//PortUpdateInd Updates port Id incase of ONU movement
868func (va *VoltApplication) PortUpdateInd(device string, portName string, id uint32) {
869 logger.Infow(ctx, "Received Port Ind: Update", log.Fields{"Device": device, "Port": portName})
870 va.portLock.Lock()
871 defer va.portLock.Unlock()
872 if d := va.GetDevice(device); d != nil {
873 vp := d.GetPort(portName)
874 vp.ID = id
875 } else {
876 logger.Warnw(ctx, "Device Not Found", log.Fields{"Device": device, "Port": portName})
877 }
878}
879
880// AddNbPonPort Add pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530881func (va *VoltApplication) AddNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32,
Naveen Sampath04696f72022-06-13 15:19:14 +0530882 enableMulticastKPI bool, portAlarmProfileID string) error {
883
884 var nbd *NbDevice
885 nbDevice, ok := va.NbDevice.Load(oltSbID)
886
887 if !ok {
888 nbd = NewNbDevice()
889 nbd.SouthBoundID = oltSbID
890 } else {
891 nbd = nbDevice.(*NbDevice)
892 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530893 port := nbd.AddPortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530894
895 // Add this port to voltDevice
896 addPort := func(key, value interface{}) bool {
897 voltDevice := value.(*VoltDevice)
898 if oltSbID == voltDevice.SouthBoundID {
899 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); !exists {
900 voltDevice.ActiveChannelsPerPon.Store(portID, port)
901 }
902 return false
903 }
904 return true
905 }
906 va.DevicesDisc.Range(addPort)
907 va.NbDevice.Store(oltSbID, nbd)
908
909 return nil
910}
911
912// UpdateNbPonPort update pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530913func (va *VoltApplication) UpdateNbPonPort(cntx context.Context, oltSbID string, portID, maxAllowedChannels uint32, enableMulticastKPI bool, portAlarmProfileID string) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530914
915 var nbd *NbDevice
916 nbDevice, ok := va.NbDevice.Load(oltSbID)
917
918 if !ok {
919 logger.Errorw(ctx, "Device-doesn't-exists", log.Fields{"deviceID": oltSbID})
920 return fmt.Errorf("Device-doesn't-exists-%v", oltSbID)
921 }
922 nbd = nbDevice.(*NbDevice)
923
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530924 port := nbd.UpdatePortToNbDevice(cntx, portID, maxAllowedChannels, enableMulticastKPI, portAlarmProfileID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530925 if port == nil {
926 return fmt.Errorf("Port-doesn't-exists-%v", portID)
927 }
928 va.NbDevice.Store(oltSbID, nbd)
929
930 // Add this port to voltDevice
931 updPort := func(key, value interface{}) bool {
932 voltDevice := value.(*VoltDevice)
933 if oltSbID == voltDevice.SouthBoundID {
934 voltDevice.ActiveChannelCountLock.Lock()
935 if p, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
936 oldPort := p.(*PonPortCfg)
937 if port.MaxActiveChannels != 0 {
938 oldPort.MaxActiveChannels = port.MaxActiveChannels
939 oldPort.EnableMulticastKPI = port.EnableMulticastKPI
940 voltDevice.ActiveChannelsPerPon.Store(portID, oldPort)
941 }
942 }
943 voltDevice.ActiveChannelCountLock.Unlock()
944 return false
945 }
946 return true
947 }
948 va.DevicesDisc.Range(updPort)
949
950 return nil
951}
952
953// DeleteNbPonPort Delete pon port to nbDevice
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530954func (va *VoltApplication) DeleteNbPonPort(cntx context.Context, oltSbID string, portID uint32) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530955 nbDevice, ok := va.NbDevice.Load(oltSbID)
956 if ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530957 nbDevice.(*NbDevice).DeletePortFromNbDevice(cntx, portID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530958 va.NbDevice.Store(oltSbID, nbDevice.(*NbDevice))
959 } else {
960 logger.Warnw(ctx, "Delete pon received for unknown device", log.Fields{"oltSbID": oltSbID})
961 return nil
962 }
963 // Delete this port from voltDevice
964 delPort := func(key, value interface{}) bool {
965 voltDevice := value.(*VoltDevice)
966 if oltSbID == voltDevice.SouthBoundID {
967 if _, exists := voltDevice.ActiveChannelsPerPon.Load(portID); exists {
968 voltDevice.ActiveChannelsPerPon.Delete(portID)
969 }
970 return false
971 }
972 return true
973 }
974 va.DevicesDisc.Range(delPort)
975 return nil
976}
977
978// GetNniPort : Get the NNI port for a device. Called from different other applications
979// as a port to match or destination for a packet out. The VOLT application
980// is written with the assumption that there is a single NNI port. The OLT
981// device is responsible for translating the combination of VLAN and the
982// NNI port ID to identify possibly a single physical port or a logical
983// port which is a result of protection methods applied.
984func (va *VoltApplication) GetNniPort(device string) (string, error) {
985 va.portLock.Lock()
986 defer va.portLock.Unlock()
987 d, ok := va.DevicesDisc.Load(device)
988 if !ok {
989 return "", errors.New("Device Doesn't Exist")
990 }
991 return d.(*VoltDevice).NniPort, nil
992}
993
994// NniDownInd process for Nni down indication.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530995func (va *VoltApplication) NniDownInd(cntx context.Context, deviceID string, devSrNo string) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530996
997 logger.Debugw(ctx, "NNI Down Ind", log.Fields{"device": devSrNo})
998
999 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1000 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301001 mvProfile.removeIgmpMcastFlows(cntx, devSrNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301002 return true
1003 }
1004 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1005
1006 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301007 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301008}
1009
1010// DeviceUpInd changes device state to up.
1011func (va *VoltApplication) DeviceUpInd(device string) {
1012 logger.Warnw(ctx, "Received Device Ind: UP", log.Fields{"Device": device})
1013 if d := va.GetDevice(device); d != nil {
1014 d.State = controller.DeviceStateUP
1015 } else {
1016 logger.Errorw(ctx, "Ignoring Device indication: UP. Device Missing", log.Fields{"Device": device})
1017 }
1018}
1019
1020// DeviceDownInd changes device state to down.
1021func (va *VoltApplication) DeviceDownInd(device string) {
1022 logger.Warnw(ctx, "Received Device Ind: DOWN", log.Fields{"Device": device})
1023 if d := va.GetDevice(device); d != nil {
1024 d.State = controller.DeviceStateDOWN
1025 } else {
1026 logger.Errorw(ctx, "Ignoring Device indication: DOWN. Device Missing", log.Fields{"Device": device})
1027 }
1028}
1029
1030// DeviceRebootInd process for handling flow clear flag for device reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301031func (va *VoltApplication) DeviceRebootInd(cntx context.Context, device string, serialNum string, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301032 logger.Warnw(ctx, "Received Device Ind: Reboot", log.Fields{"Device": device, "SerialNumber": serialNum})
1033
1034 if d := va.GetDevice(device); d != nil {
1035 if d.State == controller.DeviceStateREBOOTED {
1036 logger.Warnw(ctx, "Ignoring Device Ind: Reboot, Device already in Reboot state", log.Fields{"Device": device, "SerialNumber": serialNum, "State": d.State})
1037 return
1038 }
1039 d.State = controller.DeviceStateREBOOTED
1040 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301041 va.HandleFlowClearFlag(cntx, device, serialNum, southBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301042
1043}
1044
1045// DeviceDisableInd handles device deactivation process
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301046func (va *VoltApplication) DeviceDisableInd(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301047 logger.Warnw(ctx, "Received Device Ind: Disable", log.Fields{"Device": device})
1048
1049 d := va.GetDevice(device)
1050 if d == nil {
1051 logger.Errorw(ctx, "Ignoring Device indication: DISABLED. Device Missing", log.Fields{"Device": device})
1052 return
1053 }
1054
1055 d.State = controller.DeviceStateDISABLED
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301056 va.HandleFlowClearFlag(cntx, device, d.SerialNum, d.SouthBoundID)
Naveen Sampath04696f72022-06-13 15:19:14 +05301057}
1058
1059// ProcessIgmpDSFlowForMvlan for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301060func (va *VoltApplication) ProcessIgmpDSFlowForMvlan(cntx context.Context, d *VoltDevice, mvp *MvlanProfile, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301061
1062 logger.Debugw(ctx, "Process IGMP DS Flows for MVlan", log.Fields{"device": d.Name, "Mvlan": mvp.Mvlan, "addFlow": addFlow})
1063 portState := false
1064 p := d.GetPort(d.NniPort)
1065 if p != nil && p.State == PortStateUp {
1066 portState = true
1067 }
1068
1069 if addFlow {
1070 if portState {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301071 mvp.pushIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301072 }
1073 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301074 mvp.removeIgmpMcastFlows(cntx, d.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301075 }
1076}
1077
1078// ProcessIgmpDSFlowForDevice for processing Igmp DS flow for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301079func (va *VoltApplication) ProcessIgmpDSFlowForDevice(cntx context.Context, d *VoltDevice, addFlow bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301080 logger.Debugw(ctx, "Process IGMP DS Flows for device", log.Fields{"device": d.Name, "addFlow": addFlow})
1081
1082 handleIgmpDsFlows := func(key interface{}, value interface{}) bool {
1083 mvProfile := value.(*MvlanProfile)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301084 va.ProcessIgmpDSFlowForMvlan(cntx, d, mvProfile, addFlow)
Naveen Sampath04696f72022-06-13 15:19:14 +05301085 return true
1086 }
1087 va.MvlanProfilesByName.Range(handleIgmpDsFlows)
1088}
1089
1090// GetDeviceFromPort : This is suitable only for access ports as their naming convention
1091// makes them unique across all the OLTs. This must be called with
1092// port name that is an access port. Currently called from VNETs, attached
1093// only to access ports, and the services which are also attached only
1094// to access ports
1095func (va *VoltApplication) GetDeviceFromPort(port string) (*VoltDevice, error) {
1096 va.portLock.Lock()
1097 defer va.portLock.Unlock()
1098 var err error
1099 err = nil
1100 p, ok := va.PortsDisc.Load(port)
1101 if !ok {
1102 return nil, errorCodes.ErrPortNotFound
1103 }
1104 d := va.GetDevice(p.(*VoltPort).Device)
1105 if d == nil {
1106 err = errorCodes.ErrDeviceNotFound
1107 }
1108 return d, err
1109}
1110
1111// GetPortID : This too applies only to access ports. The ports can be indexed
1112// purely by their names without the device forming part of the key
1113func (va *VoltApplication) GetPortID(port string) (uint32, error) {
1114 va.portLock.Lock()
1115 defer va.portLock.Unlock()
1116 p, ok := va.PortsDisc.Load(port)
1117 if !ok {
1118 return 0, errorCodes.ErrPortNotFound
1119 }
1120 return p.(*VoltPort).ID, nil
1121}
1122
1123// GetPortName : This too applies only to access ports. The ports can be indexed
1124// purely by their names without the device forming part of the key
1125func (va *VoltApplication) GetPortName(port uint32) (string, error) {
1126 va.portLock.Lock()
1127 defer va.portLock.Unlock()
1128 var portName string
1129 va.PortsDisc.Range(func(key interface{}, value interface{}) bool {
1130 portInfo := value.(*VoltPort)
1131 if portInfo.ID == port {
1132 portName = portInfo.Name
1133 return false
1134 }
1135 return true
1136 })
1137 return portName, nil
1138}
1139
1140// GetPonFromUniPort to get Pon info from UniPort
1141func (va *VoltApplication) GetPonFromUniPort(port string) (string, error) {
1142 uniPortID, err := va.GetPortID(port)
1143 if err == nil {
1144 ponPortID := (uniPortID & 0x0FF00000) >> 20 //pon(8) + onu(8) + uni(12)
1145 return strconv.FormatUint(uint64(ponPortID), 10), nil
1146 }
1147 return "", err
1148}
1149
1150// GetPortState : This too applies only to access ports. The ports can be indexed
1151// purely by their names without the device forming part of the key
1152func (va *VoltApplication) GetPortState(port string) (PortState, error) {
1153 va.portLock.Lock()
1154 defer va.portLock.Unlock()
1155 p, ok := va.PortsDisc.Load(port)
1156 if !ok {
1157 return 0, errors.New("Port not configured")
1158 }
1159 return p.(*VoltPort).State, nil
1160}
1161
1162// GetIcmpv6Receivers to get Icmp v6 receivers
1163func (va *VoltApplication) GetIcmpv6Receivers(device string) []uint32 {
1164 var receiverList []uint32
1165 receivers, _ := va.Icmpv6Receivers.Load(device)
1166 if receivers != nil {
1167 receiverList = receivers.([]uint32)
1168 }
1169 return receiverList
1170}
1171
1172// AddIcmpv6Receivers to add Icmp v6 receivers
1173func (va *VoltApplication) AddIcmpv6Receivers(device string, portID uint32) []uint32 {
1174 var receiverList []uint32
1175 receivers, _ := va.Icmpv6Receivers.Load(device)
1176 if receivers != nil {
1177 receiverList = receivers.([]uint32)
1178 }
1179 receiverList = append(receiverList, portID)
1180 va.Icmpv6Receivers.Store(device, receiverList)
1181 logger.Debugw(ctx, "Receivers after addition", log.Fields{"Receivers": receiverList})
1182 return receiverList
1183}
1184
1185// DelIcmpv6Receivers to delete Icmp v6 receievers
1186func (va *VoltApplication) DelIcmpv6Receivers(device string, portID uint32) []uint32 {
1187 var receiverList []uint32
1188 receivers, _ := va.Icmpv6Receivers.Load(device)
1189 if receivers != nil {
1190 receiverList = receivers.([]uint32)
1191 }
1192 for i, port := range receiverList {
1193 if port == portID {
1194 receiverList = append(receiverList[0:i], receiverList[i+1:]...)
1195 va.Icmpv6Receivers.Store(device, receiverList)
1196 break
1197 }
1198 }
1199 logger.Debugw(ctx, "Receivers After deletion", log.Fields{"Receivers": receiverList})
1200 return receiverList
1201}
1202
1203// ProcessDevFlowForDevice - Process DS ICMPv6 & ARP flow for provided device and vnet profile
1204// device - Device Obj
1205// vnet - vnet profile name
1206// enabled - vlan enabled/disabled - based on the status, the flow shall be added/removed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301207func (va *VoltApplication) ProcessDevFlowForDevice(cntx context.Context, device *VoltDevice, vnet *VoltVnet, enabled bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301208 _, applied := device.ConfiguredVlanForDeviceFlows.Get(VnetKey(vnet.SVlan, vnet.CVlan, 0))
1209 if enabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301210 va.PushDevFlowForVlan(cntx, vnet)
Naveen Sampath04696f72022-06-13 15:19:14 +05301211 } else if !enabled && applied {
1212 //va.DeleteDevFlowForVlan(vnet)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301213 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, device.SerialNum)
Naveen Sampath04696f72022-06-13 15:19:14 +05301214 }
1215}
1216
1217//NniVlanIndToIgmp - Trigger receiver up indication to all ports with igmp enabled
1218//and has the provided mvlan
1219func (va *VoltApplication) NniVlanIndToIgmp(device *VoltDevice, mvp *MvlanProfile) {
1220
1221 logger.Infow(ctx, "Sending Igmp Receiver UP indication for all Services", log.Fields{"Vlan": mvp.Mvlan})
1222
1223 //Trigger nni indication for receiver only for first time
1224 if device.IgmpDsFlowAppliedForMvlan[uint16(mvp.Mvlan)] {
1225 return
1226 }
1227 device.Ports.Range(func(key, value interface{}) bool {
1228 port := key.(string)
1229
1230 if state, _ := va.GetPortState(port); state == PortStateUp {
1231 vpvs, _ := va.VnetsByPort.Load(port)
1232 if vpvs == nil {
1233 return true
1234 }
1235 for _, vpv := range vpvs.([]*VoltPortVnet) {
1236 //Send indication only for subscribers with the received mvlan profile
1237 if vpv.IgmpEnabled && vpv.MvlanProfileName == mvp.Name {
1238 vpv.services.Range(ReceiverUpInd)
1239 }
1240 }
1241 }
1242 return true
1243 })
1244}
1245
1246// PortUpInd :
1247// -----------------------------------------------------------------------
1248// Port status change handling
1249// ----------------------------------------------------------------------
1250// Port UP indication is passed to all services associated with the port
1251// so that the services can configure flows applicable when the port goes
1252// up from down state
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301253func (va *VoltApplication) PortUpInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301254 d := va.GetDevice(device)
1255
1256 if d == nil {
1257 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: UP", log.Fields{"Device": device, "Port": port})
1258 return
1259 }
1260
1261 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1262 va.portLock.Lock()
1263 // Do not defer the port mutex unlock here
1264 // Some of the following func calls needs the port lock, so defering the lock here
1265 // may lead to dead-lock
1266 p := d.GetPort(port)
1267
1268 if p == nil {
1269 logger.Infow(ctx, "Ignoring Port Ind: UP, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1270 va.portLock.Unlock()
1271 return
1272 }
1273 p.State = PortStateUp
1274 va.portLock.Unlock()
1275
1276 logger.Infow(ctx, "Received SouthBound Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1277 if p.Type == VoltPortTypeNni {
1278
1279 logger.Warnw(ctx, "Received NNI Port Ind: UP", log.Fields{"Device": device, "PortName": port, "PortId": p.ID})
1280 //va.PushDevFlowForDevice(d)
1281 //Build Igmp TrapFlowRule
1282 //va.ProcessIgmpDSFlowForDevice(d, true)
1283 }
1284 vpvs, ok := va.VnetsByPort.Load(port)
1285 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1286 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1287 //msgbus.ProcessPortInd(msgbus.PortUp, d.SerialNum, p.Name, false, getServiceList(port))
1288 return
1289 }
1290
1291 //If NNI port is not UP, do not push Flows
1292 if d.NniPort == "" {
1293 logger.Warnw(ctx, "NNI port not UP. Not sending Port UP Ind for VPVs", log.Fields{"NNI": d.NniPort})
1294 return
1295 }
1296
1297 vpvList := vpvs.([]*VoltPortVnet)
1298 if vpvList[0].PonPort != 0xFF && vpvList[0].PonPort != p.PonPort {
1299 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})
1300
1301 //Remove the flow (if any) which are already installed - Valid for PON switching when VGC pod is DOWN
1302 for _, vpv := range vpvs.([]*VoltPortVnet) {
1303 vpv.VpvLock.Lock()
1304 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 +05301305 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301306 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301307 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301308 }
1309 vpv.VpvLock.Unlock()
1310 }
1311 return
1312 }
1313
1314/*
1315 if p.Type != VoltPortTypeNni {
1316 // Process port up indication
1317 indTask := cntlr.NewAddPortInd(p.Name, msgbus.PortUp, d.SerialNum, true, getServiceList(port))
1318 cntlr.GetController().PostIndication(device, indTask)
1319 }
1320*/
1321
1322 for _, vpv := range vpvs.([]*VoltPortVnet) {
1323 vpv.VpvLock.Lock()
Tinoj Josephec742f62022-09-29 19:11:10 +05301324 //If no service is activated drop the portUpInd
1325 if vpv.IsServiceActivated(cntx) {
1326 //Do not trigger indication for the vpv which is already removed from vpv list as
1327 // part of service delete (during the lock wait duration)
1328 // In that case, the services associated wil be zero
1329 if vpv.servicesCount.Load() != 0 {
1330 vpv.PortUpInd(cntx, d, port)
1331 }
1332 } else {
1333 // Service not activated, still attach device to service
1334 vpv.setDevice(d.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +05301335 }
1336 vpv.VpvLock.Unlock()
1337 }
1338 // At the end of processing inform the other entities that
1339 // are interested in the events
1340}
1341
1342/*
1343func getServiceList(port string) map[string]bool {
1344 serviceList := make(map[string]bool)
1345
1346 getServiceNames := func(key interface{}, value interface{}) bool {
1347 serviceList[key.(string)] = value.(*VoltService).DsHSIAFlowsApplied
1348 return true
1349 }
1350
1351 if vpvs, _ := GetApplication().VnetsByPort.Load(port); vpvs != nil {
1352 vpvList := vpvs.([]*VoltPortVnet)
1353 for _, vpv := range vpvList {
1354 vpv.services.Range(getServiceNames)
1355 }
1356 }
1357 return serviceList
1358
1359}*/
1360
1361//ReceiverUpInd - Send receiver up indication for service with Igmp enabled
1362func ReceiverUpInd(key, value interface{}) bool {
1363 svc := value.(*VoltService)
1364 var vlan of.VlanType
1365
1366 if !svc.IPAssigned() {
1367 logger.Infow(ctx, "IP Not assigned, skipping general query", log.Fields{"Service": svc})
1368 return false
1369 }
1370
1371 //Send port up indication to igmp only for service with igmp enabled
1372 if svc.IgmpEnabled {
1373 if svc.VlanControl == ONUCVlan || svc.VlanControl == ONUCVlanOLTSVlan {
1374 vlan = svc.CVlan
1375 } else {
1376 vlan = svc.UniVlan
1377 }
1378 if device, _ := GetApplication().GetDeviceFromPort(svc.Port); device != nil {
1379 GetApplication().ReceiverUpInd(device.Name, svc.Port, svc.MvlanProfileName, vlan, svc.Pbits)
1380 }
1381 return false
1382 }
1383 return true
1384}
1385
1386// PortDownInd : Port down indication is passed on to the services so that the services
1387// can make changes at this transition.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301388func (va *VoltApplication) PortDownInd(cntx context.Context, device string, port string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301389 logger.Infow(ctx, "Received SouthBound Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1390 d := va.GetDevice(device)
1391
1392 if d == nil {
1393 logger.Warnw(ctx, "Device Not Found - Dropping Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
1394 return
1395 }
1396 //Fixme: If Port Update Comes in large numbers, this will result in slow update per device
1397 va.portLock.Lock()
1398 // Do not defer the port mutex unlock here
1399 // Some of the following func calls needs the port lock, so defering the lock here
1400 // may lead to dead-lock
1401 p := d.GetPort(port)
1402 if p == nil {
1403 logger.Infow(ctx, "Ignoring Port Ind: Down, Port doesnt exist", log.Fields{"Device": device, "PortName": port, "PortId": p})
1404 va.portLock.Unlock()
1405 return
1406 }
1407 p.State = PortStateDown
1408 va.portLock.Unlock()
1409
1410 if d.State == controller.DeviceStateREBOOTED {
1411 logger.Infow(ctx, "Ignoring Port Ind: Down, Device has been Rebooted", log.Fields{"Device": device, "PortName": port, "PortId": p})
1412 return
1413 }
1414
1415 if p.Type == VoltPortTypeNni {
1416 logger.Warnw(ctx, "Received NNI Port Ind: DOWN", log.Fields{"Device": device, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301417 va.DeleteDevFlowForDevice(cntx, d)
1418 va.NniDownInd(cntx, device, d.SerialNum)
1419 va.RemovePendingGroups(cntx, device, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301420 }
1421 vpvs, ok := va.VnetsByPort.Load(port)
1422 if !ok || nil == vpvs || len(vpvs.([]*VoltPortVnet)) == 0 {
1423 logger.Infow(ctx, "No VNETs on port", log.Fields{"Device": device, "Port": port})
1424 //msgbus.ProcessPortInd(msgbus.PortDown, d.SerialNum, p.Name, false, getServiceList(port))
1425 return
1426 }
1427/*
1428 if p.Type != VoltPortTypeNni {
1429 // Process port down indication
1430 indTask := cntlr.NewAddPortInd(p.Name, msgbus.PortDown, d.SerialNum, true, getServiceList(port))
1431 cntlr.GetController().PostIndication(device, indTask)
1432 }
1433*/
1434 for _, vpv := range vpvs.([]*VoltPortVnet) {
1435 vpv.VpvLock.Lock()
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05301436 vpv.PortDownInd(cntx, device, port, false)
Naveen Sampath04696f72022-06-13 15:19:14 +05301437 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301438 va.ReceiverDownInd(cntx, device, port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301439 }
1440 vpv.VpvLock.Unlock()
1441 }
1442}
1443
1444// PacketInInd :
1445// -----------------------------------------------------------------------
1446// PacketIn Processing
1447// Packet In Indication processing. It arrives with the identities of
1448// the device and port on which the packet is received. At first, the
1449// packet is decoded and the right processor is called. Currently, we
1450// plan to support only DHCP and IGMP. In future, we can add more
1451// capabilities as needed
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301452func (va *VoltApplication) PacketInInd(cntx context.Context, device string, port string, pkt []byte) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301453 // Decode the incoming packet
1454 packetSide := US
1455 if strings.Contains(port, NNI) {
1456 packetSide = DS
1457 }
1458
1459 logger.Debugw(ctx, "Received a Packet-In Indication", log.Fields{"Device": device, "Port": port})
1460
1461 gopkt := gopacket.NewPacket(pkt, layers.LayerTypeEthernet, gopacket.Default)
1462
1463 var dot1qFound = false
1464 for _, l := range gopkt.Layers() {
1465 if l.LayerType() == layers.LayerTypeDot1Q {
1466 dot1qFound = true
1467 break
1468 }
1469 }
1470
1471 if !dot1qFound {
1472 logger.Debugw(ctx, "Ignoring Received Packet-In Indication without Dot1Q Header",
1473 log.Fields{"Device": device, "Port": port})
1474 return
1475 }
1476
1477 logger.Debugw(ctx, "Received Southbound Packet In", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1478
1479 // Classify the packet into packet types that we support
1480 // The supported types are DHCP and IGMP. The DHCP packet is
1481 // identified by matching the L4 protocol to UDP. The IGMP packet
1482 // is identified by matching L3 protocol to IGMP
1483 arpl := gopkt.Layer(layers.LayerTypeARP)
1484 if arpl != nil {
1485 if callBack, ok := PacketHandlers[ARP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301486 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301487 } else {
1488 logger.Debugw(ctx, "ARP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1489 }
1490 return
1491 }
1492 ipv4l := gopkt.Layer(layers.LayerTypeIPv4)
1493 if ipv4l != nil {
1494 ip := ipv4l.(*layers.IPv4)
1495
1496 if ip.Protocol == layers.IPProtocolUDP {
1497 logger.Debugw(ctx, "Received Southbound UDP ipv4 packet in", log.Fields{"StreamSide": packetSide})
1498 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv4)
1499 if dhcpl != nil {
1500 if callBack, ok := PacketHandlers[DHCPv4]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301501 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301502 } else {
1503 logger.Debugw(ctx, "DHCPv4 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1504 }
1505 }
1506 } else if ip.Protocol == layers.IPProtocolIGMP {
1507 logger.Debugw(ctx, "Received Southbound IGMP packet in", log.Fields{"StreamSide": packetSide})
1508 if callBack, ok := PacketHandlers[IGMP]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301509 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301510 } else {
1511 logger.Debugw(ctx, "IGMP handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1512 }
1513 }
1514 return
1515 }
1516 ipv6l := gopkt.Layer(layers.LayerTypeIPv6)
1517 if ipv6l != nil {
1518 ip := ipv6l.(*layers.IPv6)
1519 if ip.NextHeader == layers.IPProtocolUDP {
1520 logger.Debug(ctx, "Received Southbound UDP ipv6 packet in")
1521 dhcpl := gopkt.Layer(layers.LayerTypeDHCPv6)
1522 if dhcpl != nil {
1523 if callBack, ok := PacketHandlers[DHCPv6]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301524 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301525 } else {
1526 logger.Debugw(ctx, "DHCPv6 handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1527 }
1528 }
1529 }
1530 return
1531 }
1532
1533 pppoel := gopkt.Layer(layers.LayerTypePPPoE)
1534 if pppoel != nil {
1535 logger.Debugw(ctx, "Received Southbound PPPoE packet in", log.Fields{"StreamSide": packetSide})
1536 if callBack, ok := PacketHandlers[PPPOE]; ok {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301537 callBack(cntx, device, port, gopkt)
Naveen Sampath04696f72022-06-13 15:19:14 +05301538 } else {
1539 logger.Debugw(ctx, "PPPoE handler is not registered, dropping the packet", log.Fields{"Pkt": hex.EncodeToString(gopkt.Data())})
1540 }
1541 }
1542}
1543
1544// GetVlans : This utility gets the VLANs from the packet. The VLANs are
1545// used to identify the right service that must process the incoming
1546// packet
1547func GetVlans(pkt gopacket.Packet) []of.VlanType {
1548 var vlans []of.VlanType
1549 for _, l := range pkt.Layers() {
1550 if l.LayerType() == layers.LayerTypeDot1Q {
1551 q, ok := l.(*layers.Dot1Q)
1552 if ok {
1553 vlans = append(vlans, of.VlanType(q.VLANIdentifier))
1554 }
1555 }
1556 }
1557 return vlans
1558}
1559
1560// GetPriority to get priority
1561func GetPriority(pkt gopacket.Packet) uint8 {
1562 for _, l := range pkt.Layers() {
1563 if l.LayerType() == layers.LayerTypeDot1Q {
1564 q, ok := l.(*layers.Dot1Q)
1565 if ok {
1566 return q.Priority
1567 }
1568 }
1569 }
1570 return PriorityNone
1571}
1572
1573// HandleFlowClearFlag to handle flow clear flag during reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301574func (va *VoltApplication) HandleFlowClearFlag(cntx context.Context, deviceID string, serialNum, southBoundID string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301575 logger.Warnw(ctx, "Clear All flags for Device", log.Fields{"Device": deviceID, "SerialNum": serialNum, "SBID": southBoundID})
1576 dev, ok := va.DevicesDisc.Load(deviceID)
1577 if ok && dev != nil {
1578 logger.Infow(ctx, "Clear Flags for device", log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1579 dev.(*VoltDevice).icmpv6GroupAdded = false
1580 logger.Infow(ctx, "Clearing DS Icmpv6 Map",
1581 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1582 dev.(*VoltDevice).ConfiguredVlanForDeviceFlows = util.NewConcurrentMap()
1583 logger.Infow(ctx, "Clearing DS IGMP Map",
1584 log.Fields{"voltDevice": dev.(*VoltDevice).Name})
1585 for k := range dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan {
1586 delete(dev.(*VoltDevice).IgmpDsFlowAppliedForMvlan, k)
1587 }
1588 //Delete group 1 - ICMPv6/ARP group
1589 if err := ProcessIcmpv6McGroup(deviceID, true); err != nil {
1590 logger.Errorw(ctx, "ProcessIcmpv6McGroup failed", log.Fields{"Device": deviceID, "Error": err})
1591 }
1592 } else {
1593 logger.Warnw(ctx, "VoltDevice not found for device ", log.Fields{"deviceID": deviceID})
1594 }
1595
1596 getVpvs := func(key interface{}, value interface{}) bool {
1597 vpvs := value.([]*VoltPortVnet)
1598 for _, vpv := range vpvs {
1599 if vpv.Device == deviceID {
1600 logger.Infow(ctx, "Clear Flags for vpv",
1601 log.Fields{"device": vpv.Device, "port": vpv.Port,
1602 "svlan": vpv.SVlan, "cvlan": vpv.CVlan, "univlan": vpv.UniVlan})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301603 vpv.ClearAllServiceFlags(cntx)
1604 vpv.ClearAllVpvFlags(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301605
1606 if vpv.IgmpEnabled {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301607 va.ReceiverDownInd(cntx, vpv.Device, vpv.Port)
Naveen Sampath04696f72022-06-13 15:19:14 +05301608 //Also clear service igmp stats
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301609 vpv.ClearServiceCounters(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301610 }
1611 }
1612 }
1613 return true
1614 }
1615 va.VnetsByPort.Range(getVpvs)
1616
1617 //Clear Static Group
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301618 va.ReceiverDownInd(cntx, deviceID, StaticPort)
Naveen Sampath04696f72022-06-13 15:19:14 +05301619
1620 logger.Warnw(ctx, "All flags cleared for device", log.Fields{"Device": deviceID})
1621
1622 //Reset pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301623 va.RemovePendingGroups(cntx, deviceID, true)
Naveen Sampath04696f72022-06-13 15:19:14 +05301624
1625 //Process all Migrate Service Request - force udpate all profiles since resources are already cleaned up
1626 if dev != nil {
1627 triggerForceUpdate := func(key, value interface{}) bool {
1628 msrList := value.(*util.ConcurrentMap)
1629 forceUpdateServices := func(key, value interface{}) bool {
1630 msr := value.(*MigrateServicesRequest)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301631 forceUpdateAllServices(cntx, msr)
Naveen Sampath04696f72022-06-13 15:19:14 +05301632 return true
1633 }
1634 msrList.Range(forceUpdateServices)
1635 return true
1636 }
1637 dev.(*VoltDevice).MigratingServices.Range(triggerForceUpdate)
1638 } else {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301639 va.FetchAndProcessAllMigrateServicesReq(cntx, deviceID, forceUpdateAllServices)
Naveen Sampath04696f72022-06-13 15:19:14 +05301640 }
1641}
1642
1643//GetPonPortIDFromUNIPort to get pon port id from uni port
1644func GetPonPortIDFromUNIPort(uniPortID uint32) uint32 {
1645 ponPortID := (uniPortID & 0x0FF00000) >> 20
1646 return ponPortID
1647}
1648
1649//ProcessFlowModResultIndication - Processes Flow mod operation indications from controller
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301650func (va *VoltApplication) ProcessFlowModResultIndication(cntx context.Context, flowStatus intf.FlowStatus) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301651
1652 d := va.GetDevice(flowStatus.Device)
1653 if d == nil {
1654 logger.Errorw(ctx, "Dropping Flow Mod Indication. Device not found", log.Fields{"Cookie": flowStatus.Cookie, "Device": flowStatus.Device})
1655 return
1656 }
1657
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301658 cookieExists := ExecuteFlowEvent(cntx, d, flowStatus.Cookie, flowStatus)
Naveen Sampath04696f72022-06-13 15:19:14 +05301659
1660 if flowStatus.Flow != nil {
1661 flowAdd := (flowStatus.FlowModType == of.CommandAdd)
1662 if !cookieExists && !isFlowStatusSuccess(flowStatus.Status, flowAdd) {
1663 pushFlowFailureNotif(flowStatus)
1664 }
1665 }
1666}
1667
1668func pushFlowFailureNotif(flowStatus intf.FlowStatus) {
1669 subFlow := flowStatus.Flow
1670 cookie := subFlow.Cookie
1671 uniPort := cookie >> 16 & 0xFFFFFFFF
1672 logger.Errorw(ctx, "Flow Failure Notification", log.Fields{"uniPort": uniPort, "Cookie": cookie})
1673/*
1674 device := flowStatus.Device
1675 priority := subFlow.Priority
1676 isIgmp := false
1677 var devSerialNum string
1678 var service *VoltService
1679
1680 if subFlow.Match.L4Protocol == of.IPProtocolIgmp {
1681 isIgmp = true
1682 } else if priority != of.HsiaFlowPriority {
1683 logger.Info(ctx, "Not HSIA flow, ignoring the failure notification")
1684 return
1685 }
1686
1687 cookie := subFlow.Cookie
1688 pbit := subFlow.Pbits
1689 uniPort := cookie >> 16 & 0xFFFFFFFF
1690 portName, _ := GetApplication().GetPortName(uint32(uniPort))
1691 portState := msgbus.PortDown
1692 logger.Errorw(ctx, "Construct Flow Failure Notification", log.Fields{"uniPort": uniPort, "Cookie": cookie, "Pbit": pbit, "isIgmp": isIgmp})
1693
1694 if isIgmp {
1695 cvlan := subFlow.TableMetadata & 0xFFFF
1696 service = GetApplication().GetMatchingMcastService(portName, device, of.VlanType(cvlan))
1697 } else {
1698 service = GetApplication().GetServiceNameFromCookie(cookie, portName, uint8(pbit), device, subFlow.TableMetadata)
1699 }
1700 var trigger infra.Reason
1701 if nil != service {
1702 logger.Errorw(ctx, "Sending Flow Failure Notification", log.Fields{"uniPort": uniPort, "Cookie": cookie, "Pbit": pbit, "Service": service.Name, "ErrorCode": flowStatus.Status})
1703 if vd := GetApplication().GetDevice(device); vd != nil {
1704 devSerialNum = vd.SerialNum
1705 if portSt, _ := GetApplication().GetPortState(service.Port); portSt == PortStateUp {
1706 portState = msgbus.PortUp
1707 }
1708 trigger = service.getSrvDeactTrigger(vd, portState)
1709 }
1710 msgbus.PostAccessConfigInd(msgbus.Failed, devSerialNum, msgbus.HSIA, service.Name, int(flowStatus.Status), subFlow.ErrorReason, trigger, portState)
1711 }
1712*/
1713}
1714
1715//UpdateMvlanProfilesForDevice to update mvlan profile for device
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301716func (va *VoltApplication) UpdateMvlanProfilesForDevice(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301717
1718 checkAndAddMvlanUpdateTask := func(key, value interface{}) bool {
1719 mvp := value.(*MvlanProfile)
1720 if mvp.IsUpdateInProgressForDevice(device) {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301721 mvp.UpdateProfile(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301722 }
1723 return true
1724 }
1725 va.MvlanProfilesByName.Range(checkAndAddMvlanUpdateTask)
1726}
1727
1728// TaskInfo structure that is used to store the task Info.
1729type TaskInfo struct {
1730 ID string
1731 Name string
1732 Timestamp string
1733}
1734
1735// GetTaskList to get task list information.
1736func (va *VoltApplication) GetTaskList(device string) map[int]*TaskInfo {
1737 taskList := cntlr.GetController().GetTaskList(device)
1738 taskMap := make(map[int]*TaskInfo)
1739 for i, task := range taskList {
1740 taskID := strconv.Itoa(int(task.TaskID()))
1741 name := task.Name()
1742 timestamp := task.Timestamp()
1743 taskInfo := &TaskInfo{ID: taskID, Name: name, Timestamp: timestamp}
1744 taskMap[i] = taskInfo
1745 }
1746 return taskMap
1747}
1748
1749// UpdateDeviceSerialNumberList to update the device serial number list after device serial number is updated for vnet and mvlan
1750func (va *VoltApplication) UpdateDeviceSerialNumberList(oldOltSlNo string, newOltSlNo string) {
1751
Tinoj Joseph50d722c2022-12-06 22:53:22 +05301752 voltDevice, _ := va.GetDeviceBySerialNo(oldOltSlNo)
Naveen Sampath04696f72022-06-13 15:19:14 +05301753
1754 if voltDevice != nil {
1755 // Device is present with old serial number ID
1756 logger.Errorw(ctx, "OLT Migration cannot be completed as there are dangling devices", log.Fields{"Serial Number": oldOltSlNo})
1757
1758 } else {
1759 logger.Infow(ctx, "No device present with old serial number", log.Fields{"Serial Number": oldOltSlNo})
1760
1761 // Add Serial Number to Blocked Devices List.
1762 cntlr.GetController().AddBlockedDevices(oldOltSlNo)
1763 cntlr.GetController().AddBlockedDevices(newOltSlNo)
1764
1765 updateSlNoForVnet := func(key, value interface{}) bool {
1766 vnet := value.(*VoltVnet)
1767 for i, deviceSlNo := range vnet.VnetConfig.DevicesList {
1768 if deviceSlNo == oldOltSlNo {
1769 vnet.VnetConfig.DevicesList[i] = newOltSlNo
1770 logger.Infow(ctx, "device serial number updated for vnet profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1771 break
1772 }
1773 }
1774 return true
1775 }
1776
1777 updateSlNoforMvlan := func(key interface{}, value interface{}) bool {
1778 mvProfile := value.(*MvlanProfile)
1779 for deviceSlNo := range mvProfile.DevicesList {
1780 if deviceSlNo == oldOltSlNo {
1781 mvProfile.DevicesList[newOltSlNo] = mvProfile.DevicesList[oldOltSlNo]
1782 delete(mvProfile.DevicesList, oldOltSlNo)
1783 logger.Infow(ctx, "device serial number updated for mvlan profile", log.Fields{"Updated Serial Number": deviceSlNo, "Previous Serial Number": oldOltSlNo})
1784 break
1785 }
1786 }
1787 return true
1788 }
1789
1790 va.VnetsByName.Range(updateSlNoForVnet)
1791 va.MvlanProfilesByName.Range(updateSlNoforMvlan)
1792
1793 // Clear the serial number from Blocked Devices List
1794 cntlr.GetController().DelBlockedDevices(oldOltSlNo)
1795 cntlr.GetController().DelBlockedDevices(newOltSlNo)
1796
1797 }
1798}
1799
1800// GetVpvsForDsPkt to get vpv for downstream packets
1801func (va *VoltApplication) GetVpvsForDsPkt(cvlan of.VlanType, svlan of.VlanType, clientMAC net.HardwareAddr,
1802 pbit uint8) ([]*VoltPortVnet, error) {
1803
1804 var matchVPVs []*VoltPortVnet
1805 findVpv := func(key, value interface{}) bool {
1806 vpvs := value.([]*VoltPortVnet)
1807 for _, vpv := range vpvs {
1808 if vpv.isVlanMatching(cvlan, svlan) && vpv.MatchesPriority(pbit) != nil {
1809 var subMac net.HardwareAddr
1810 if NonZeroMacAddress(vpv.MacAddr) {
1811 subMac = vpv.MacAddr
1812 } else if vpv.LearntMacAddr != nil && NonZeroMacAddress(vpv.LearntMacAddr) {
1813 subMac = vpv.LearntMacAddr
1814 } else {
1815 matchVPVs = append(matchVPVs, vpv)
1816 continue
1817 }
1818 if util.MacAddrsMatch(subMac, clientMAC) {
1819 matchVPVs = append([]*VoltPortVnet{}, vpv)
1820 logger.Infow(ctx, "Matching VPV found", log.Fields{"Port": vpv.Port, "SVLAN": vpv.SVlan, "CVLAN": vpv.CVlan, "UNIVlan": vpv.UniVlan, "MAC": clientMAC})
1821 return false
1822 }
1823 }
1824 }
1825 return true
1826 }
1827 va.VnetsByPort.Range(findVpv)
1828
1829 if len(matchVPVs) != 1 {
1830 logger.Infow(ctx, "No matching VPV found or multiple vpvs found", log.Fields{"Match VPVs": matchVPVs, "MAC": clientMAC})
1831 return nil, errors.New("No matching VPV found or multiple vpvs found")
1832 }
1833 return matchVPVs, nil
1834}
1835
1836// GetMacInPortMap to get PORT value based on MAC key
1837func (va *VoltApplication) GetMacInPortMap(macAddr net.HardwareAddr) string {
1838 if NonZeroMacAddress(macAddr) {
1839 va.macPortLock.Lock()
1840 defer va.macPortLock.Unlock()
1841 if port, ok := va.macPortMap[macAddr.String()]; ok {
1842 logger.Debugw(ctx, "found-entry-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1843 return port
1844 }
1845 }
1846 logger.Infow(ctx, "entry-not-found-macportmap", log.Fields{"MacAddr": macAddr.String()})
1847 return ""
1848}
1849
1850// UpdateMacInPortMap to update MAC PORT (key value) information in MacPortMap
1851func (va *VoltApplication) UpdateMacInPortMap(macAddr net.HardwareAddr, port string) {
1852 if NonZeroMacAddress(macAddr) {
1853 va.macPortLock.Lock()
1854 va.macPortMap[macAddr.String()] = port
1855 va.macPortLock.Unlock()
1856 logger.Debugw(ctx, "updated-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1857 }
1858}
1859
1860// DeleteMacInPortMap to remove MAC key from MacPortMap
1861func (va *VoltApplication) DeleteMacInPortMap(macAddr net.HardwareAddr) {
1862 if NonZeroMacAddress(macAddr) {
1863 port := va.GetMacInPortMap(macAddr)
1864 va.macPortLock.Lock()
1865 delete(va.macPortMap, macAddr.String())
1866 va.macPortLock.Unlock()
1867 logger.Debugw(ctx, "deleted-from-macportmap", log.Fields{"MacAddr": macAddr.String(), "Port": port})
1868 }
1869}
1870
1871//AddGroupToPendingPool - adds the IgmpGroup with active group table entry to global pending pool
1872func (va *VoltApplication) AddGroupToPendingPool(ig *IgmpGroup) {
1873 var grpMap map[*IgmpGroup]bool
1874 var ok bool
1875
1876 va.PendingPoolLock.Lock()
1877 defer va.PendingPoolLock.Unlock()
1878
1879 logger.Infow(ctx, "Adding IgmpGroup to Global Pending Pool", log.Fields{"GroupID": ig.GroupID, "GroupName": ig.GroupName, "GroupAddr": ig.GroupAddr, "PendingDevices": len(ig.Devices)})
1880 // Do Not Reset any current profile info since group table entry tied to mvlan profile
1881 // The PonVlan is part of set field in group installed
1882 // Hence, Group created is always tied to the same mvlan profile until deleted
1883
1884 for device := range ig.Devices {
1885 key := getPendingPoolKey(ig.Mvlan, device)
1886
1887 if grpMap, ok = va.IgmpPendingPool[key]; !ok {
1888 grpMap = make(map[*IgmpGroup]bool)
1889 }
1890 grpMap[ig] = true
1891
1892 //Add grpObj reference to all associated devices
1893 va.IgmpPendingPool[key] = grpMap
1894 }
1895}
1896
1897//RemoveGroupFromPendingPool - removes the group from global pending group pool
1898func (va *VoltApplication) RemoveGroupFromPendingPool(device string, ig *IgmpGroup) bool {
1899 GetApplication().PendingPoolLock.Lock()
1900 defer GetApplication().PendingPoolLock.Unlock()
1901
1902 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)})
1903
1904 key := getPendingPoolKey(ig.Mvlan, device)
1905 if _, ok := va.IgmpPendingPool[key]; ok {
1906 delete(va.IgmpPendingPool[key], ig)
1907 return true
1908 }
1909 return false
1910}
1911
1912//RemoveGroupsFromPendingPool - removes the group from global pending group pool
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301913func (va *VoltApplication) RemoveGroupsFromPendingPool(cntx context.Context, device string, mvlan of.VlanType) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301914 GetApplication().PendingPoolLock.Lock()
1915 defer GetApplication().PendingPoolLock.Unlock()
1916
1917 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool for given Deivce & Mvlan", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1918
1919 key := getPendingPoolKey(mvlan, device)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301920 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05301921}
1922
1923//RemoveGroupListFromPendingPool - removes the groups for provided key
1924// 1. Deletes the group from device
1925// 2. Delete the IgmpGroup obj and release the group ID to pool
1926// Note: Make sure to obtain PendingPoolLock lock before calling this func
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301927func (va *VoltApplication) RemoveGroupListFromPendingPool(cntx context.Context, key string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301928 if grpMap, ok := va.IgmpPendingPool[key]; ok {
1929 delete(va.IgmpPendingPool, key)
1930 for ig := range grpMap {
1931 for device := range ig.Devices {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301932 ig.DeleteIgmpGroupDevice(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05301933 }
1934 }
1935 }
1936}
1937
1938//RemoveGroupDevicesFromPendingPool - removes the group from global pending group pool
1939func (va *VoltApplication) RemoveGroupDevicesFromPendingPool(ig *IgmpGroup) {
1940
1941 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)})
1942 for device := range ig.PendingGroupForDevice {
1943 va.RemoveGroupFromPendingPool(device, ig)
1944 }
1945}
1946
1947//GetGroupFromPendingPool - Returns IgmpGroup obj from global pending pool
1948func (va *VoltApplication) GetGroupFromPendingPool(mvlan of.VlanType, device string) *IgmpGroup {
1949
1950 var ig *IgmpGroup
1951
1952 va.PendingPoolLock.Lock()
1953 defer va.PendingPoolLock.Unlock()
1954
1955 key := getPendingPoolKey(mvlan, device)
1956 logger.Infow(ctx, "Getting IgmpGroup from Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String(), "Key": key})
1957
1958 //Gets all IgmpGrp Obj for the device
1959 grpMap, ok := va.IgmpPendingPool[key]
1960 if !ok || len(grpMap) == 0 {
1961 logger.Infow(ctx, "Matching IgmpGroup not found in Global Pending Pool", log.Fields{"Device": device, "Mvlan": mvlan.String()})
1962 return nil
1963 }
1964
1965 //Gets a random obj from available grps
1966 for ig = range grpMap {
1967
1968 //Remove grp obj reference from all devices associated in pending pool
1969 for dev := range ig.Devices {
1970 key := getPendingPoolKey(mvlan, dev)
1971 delete(va.IgmpPendingPool[key], ig)
1972 }
1973
1974 //Safety check to avoid re-allocating group already in use
1975 if ig.NumDevicesActive() == 0 {
1976 return ig
1977 }
1978
1979 //Iteration will continue only if IG is not allocated
1980 }
1981 return nil
1982}
1983
1984//RemovePendingGroups - removes all pending groups for provided reference from global pending pool
1985// reference - mvlan/device ID
1986// isRefDevice - true - Device as reference
1987// false - Mvlan as reference
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301988func (va *VoltApplication) RemovePendingGroups(cntx context.Context, reference string, isRefDevice bool) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301989 va.PendingPoolLock.Lock()
1990 defer va.PendingPoolLock.Unlock()
1991
1992 logger.Infow(ctx, "Removing IgmpGroups from Global Pending Pool", log.Fields{"Reference": reference, "isRefDevice": isRefDevice})
1993
1994 //Pending Pool key: "<mvlan>_<DeviceID>""
1995 paramPosition := 0
1996 if isRefDevice {
1997 paramPosition = 1
1998 }
1999
2000 // 1.Remove the Entry from pending pool
2001 // 2.Deletes the group from device
2002 // 3.Delete the IgmpGroup obj and release the group ID to pool
2003 for key := range va.IgmpPendingPool {
2004 keyParams := strings.Split(key, "_")
2005 if keyParams[paramPosition] == reference {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302006 va.RemoveGroupListFromPendingPool(cntx, key)
Naveen Sampath04696f72022-06-13 15:19:14 +05302007 }
2008 }
2009}
2010
2011func getPendingPoolKey(mvlan of.VlanType, device string) string {
2012 return mvlan.String() + "_" + device
2013}
2014
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302015func (va *VoltApplication) removeExpiredGroups(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302016 logger.Debug(ctx, "Check for expired Igmp Groups")
2017 removeExpiredGroups := func(key interface{}, value interface{}) bool {
2018 ig := value.(*IgmpGroup)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302019 ig.removeExpiredGroupFromDevice(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302020 return true
2021 }
2022 va.IgmpGroups.Range(removeExpiredGroups)
2023}
2024
2025//TriggerPendingProfileDeleteReq - trigger pending profile delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302026func (va *VoltApplication) TriggerPendingProfileDeleteReq(cntx context.Context, device string) {
2027 va.TriggerPendingServiceDeleteReq(cntx, device)
2028 va.TriggerPendingVpvDeleteReq(cntx, device)
2029 va.TriggerPendingVnetDeleteReq(cntx, device)
Naveen Sampath04696f72022-06-13 15:19:14 +05302030 logger.Warnw(ctx, "All Pending Profile Delete triggered for device", log.Fields{"Device": device})
2031}
2032
2033//TriggerPendingServiceDeleteReq - trigger pending service delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302034func (va *VoltApplication) TriggerPendingServiceDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302035
2036 logger.Warnw(ctx, "Pending Services to be deleted", log.Fields{"Count": len(va.ServicesToDelete)})
2037 for serviceName := range va.ServicesToDelete {
2038 logger.Debugw(ctx, "Trigger Service Delete", log.Fields{"Service": serviceName})
2039 if vs := va.GetService(serviceName); vs != nil {
2040 if vs.Device == device {
2041 logger.Warnw(ctx, "Triggering Pending Service delete", log.Fields{"Service": vs.Name})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302042 vs.DelHsiaFlows(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302043 if vs.ForceDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302044 vs.DelFromDb(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05302045 /*
2046 portState := msgbus.PortDown
2047 if d, err := va.GetDeviceFromPort(vs.Port); d != nil {
2048
2049 if portSt, _ := GetApplication().GetPortState(vs.Port); portSt == PortStateUp {
2050 portState = msgbus.PortUp
2051 }
2052 indTask := cntlr.NewAddServiceIndTask(vs.Name, d.SerialNum, msgbus.DelHSIA, msgbus.Success, "", portState, infra.DelHSIAFromNB)
2053 cntlr.GetController().PostIndication(d.Name, indTask)
2054 } else {
2055 // Port Not found can occur during ONU movement. However, port delete had already handled flow deletion,
2056 // hence indication can be sent immediately
2057 var devSrNo string
2058 logger.Errorw(ctx, "Device/Port not found. Send indication directly", log.Fields{"serviceName": vs.Name, "error": err})
2059 if vd := va.GetDevice(vs.Device); vd != nil {
2060 devSrNo = vd.SerialNum
2061 }
2062 msgbus.PostAccessConfigInd(msgbus.Success, devSrNo, msgbus.DelHSIA, vs.Name, 0, "", infra.DelHSIAFromNB, portState)
2063 }*/
2064 }
2065 }
2066 } else {
2067 logger.Errorw(ctx, "Pending Service Not found", log.Fields{"Service": serviceName})
2068 }
2069 }
2070}
2071
2072//TriggerPendingVpvDeleteReq - trigger pending VPV delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302073func (va *VoltApplication) TriggerPendingVpvDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302074
2075 logger.Warnw(ctx, "Pending VPVs to be deleted", log.Fields{"Count": len(va.VoltPortVnetsToDelete)})
2076 for vpv := range va.VoltPortVnetsToDelete {
2077 if vpv.Device == device {
2078 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 +05302079 va.DelVnetFromPort(cntx, vpv.Port, vpv)
Naveen Sampath04696f72022-06-13 15:19:14 +05302080 }
2081 }
2082}
2083
2084//TriggerPendingVnetDeleteReq - trigger pending vnet delete request
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302085func (va *VoltApplication) TriggerPendingVnetDeleteReq(cntx context.Context, device string) {
Naveen Sampath04696f72022-06-13 15:19:14 +05302086
2087 logger.Warnw(ctx, "Pending Vnets to be deleted", log.Fields{"Count": len(va.VnetsToDelete)})
2088 for vnetName := range va.VnetsToDelete {
2089 if vnetIntf, _ := va.VnetsByName.Load(vnetName); vnetIntf != nil {
2090 vnet := vnetIntf.(*VoltVnet)
2091 logger.Warnw(ctx, "Triggering Pending Vnet flows delete", log.Fields{"Vnet": vnet.Name})
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302092 if d, _ := va.GetDeviceBySerialNo(vnet.PendingDeviceToDelete); d != nil && d.SerialNum == vnet.PendingDeviceToDelete {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05302093 va.DeleteDevFlowForVlanFromDevice(cntx, vnet, vnet.PendingDeviceToDelete)
Naveen Sampath04696f72022-06-13 15:19:14 +05302094 va.deleteVnetConfig(vnet)
2095 } else {
Tinoj Joseph1d108322022-07-13 10:07:39 +05302096 logger.Warnw(ctx, "Vnet Delete Failed : Device Not Found", log.Fields{"Vnet": vnet.Name, "Device": vnet.PendingDeviceToDelete})
Naveen Sampath04696f72022-06-13 15:19:14 +05302097 }
2098 }
2099 }
2100}
Tinoj Joseph4ead4e02023-01-30 03:12:44 +05302101
2102type OltFlowService struct {
2103 EnableDhcpOnNni bool `json:"enableDhcpOnNni"`
2104 DefaultTechProfileId int `json:"defaultTechProfileId"`
2105 EnableIgmpOnNni bool `json:"enableIgmpOnNni"`
2106 EnableEapol bool `json:"enableEapol"`
2107 EnableDhcpV6 bool `json:"enableDhcpV6"`
2108 EnableDhcpV4 bool `json:"enableDhcpV4"`
2109 RemoveFlowsOnDisable bool `json:"removeFlowsOnDisable"`
2110}
2111
2112func (va *VoltApplication) UpdateOltFlowService(cntx context.Context, oltFlowService OltFlowService) {
2113 logger.Infow(ctx, "UpdateOltFlowService", log.Fields{"oldValue": va.OltFlowServiceConfig, "newValue": oltFlowService})
2114 va.OltFlowServiceConfig = oltFlowService
2115 b, err := json.Marshal(va.OltFlowServiceConfig)
2116 if err != nil {
2117 logger.Warnw(ctx, "Failed to Marshal OltFlowServiceConfig", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2118 return
2119 }
2120 _ = db.PutOltFlowService(cntx, string(b))
2121}
2122// RestoreOltFlowService to read from the DB and restore olt flow service config
2123func (va *VoltApplication) RestoreOltFlowService(cntx context.Context) {
2124 oltflowService, err := db.GetOltFlowService(cntx)
2125 if err != nil {
2126 logger.Warnw(ctx, "Failed to Get OltFlowServiceConfig from DB", log.Fields{"Error": err})
2127 return
2128 }
2129 err = json.Unmarshal([]byte(oltflowService), &va.OltFlowServiceConfig)
2130 if err != nil {
2131 logger.Warn(ctx, "Unmarshal of oltflowService failed")
2132 return
2133 }
2134 logger.Infow(ctx, "updated OltFlowServiceConfig from DB", log.Fields{"OltFlowServiceConfig": va.OltFlowServiceConfig})
2135}
Tinoj Joseph50d722c2022-12-06 22:53:22 +05302136
2137type DeviceConfig struct {
2138 SerialNumber string
2139 UplinkPort int
2140 HardwareIdentifier string
2141 IPAddress net.IP
2142 NasID string
2143 NniDhcpTrapVid int
2144}
2145
2146func (va *VoltApplication) UpdateDeviceConfig(cntx context.Context, sn, mac, nasID string, port, dhcpVid int, ip net.IP) {
2147 if d, ok := va.DevicesConfig.Load(sn); ok {
2148 logger.Infow(ctx, "Device configuration already exists", log.Fields{"DeviceInfo": d})
2149 }
2150 d := DeviceConfig {
2151 SerialNumber : sn,
2152 UplinkPort : port,
2153 HardwareIdentifier : mac,
2154 IPAddress : ip,
2155 NasID : nasID,
2156 NniDhcpTrapVid : dhcpVid,
2157 }
2158 logger.Infow(ctx, "Added OLT configurations", log.Fields{"DeviceInfo": d})
2159 va.DevicesConfig.Store(sn, d)
2160 // If device is already discovered update the VoltDevice structure
2161 device, id := va.GetDeviceBySerialNo(sn)
2162 if device != nil {
2163 device.NniDhcpTrapVid = of.VlanType(dhcpVid)
2164 va.DevicesDisc.Store(id, device)
2165 }
2166}