blob: 8d185a3d5ae8c886249e84980f8fd6f6ac0ce866 [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 controller
17
18import (
19 "context"
20 "encoding/json"
21 "errors"
Tinoj Joseph429b9d92022-11-16 18:51:05 +053022 "fmt"
Naveen Sampath04696f72022-06-13 15:19:14 +053023 infraerror "voltha-go-controller/internal/pkg/errorcodes"
24 "strconv"
Tinoj Joseph429b9d92022-11-16 18:51:05 +053025 "strings"
Naveen Sampath04696f72022-06-13 15:19:14 +053026 "sync"
27 "time"
28
29 "voltha-go-controller/database"
30 "voltha-go-controller/internal/pkg/holder"
31 "voltha-go-controller/internal/pkg/intf"
32 "voltha-go-controller/internal/pkg/of"
33 //"voltha-go-controller/internal/pkg/vpagent"
34 "voltha-go-controller/internal/pkg/tasks"
35 "voltha-go-controller/internal/pkg/util"
Tinoj Joseph1d108322022-07-13 10:07:39 +053036 "voltha-go-controller/log"
Naveen Sampath04696f72022-06-13 15:19:14 +053037 ofp "github.com/opencord/voltha-protos/v5/go/openflow_13"
38 "github.com/opencord/voltha-protos/v5/go/voltha"
39)
40
41// PortState type
42type PortState string
43
44const (
45 // PortStateDown constant
46 PortStateDown PortState = "DOWN"
47 // PortStateUp constant
48 PortStateUp PortState = "UP"
49 // DefaultMaxFlowQueues constant
50 DefaultMaxFlowQueues = 67
51 //ErrDuplicateFlow - indicates flow already exists in DB
52 ErrDuplicateFlow string = "Duplicate Flow"
53)
54
55// DevicePort structure
56type DevicePort struct {
57 tasks.Tasks
Tinoj Joseph429b9d92022-11-16 18:51:05 +053058 Name string
59 ID uint32
60 State PortState
61 Version string
62 HwAddr string
63 CurrSpeed uint32
64 MaxSpeed uint32
Naveen Sampath04696f72022-06-13 15:19:14 +053065}
66
67// NewDevicePort is the constructor for DevicePort
Tinoj Joseph429b9d92022-11-16 18:51:05 +053068func NewDevicePort(mp *ofp.OfpPort) *DevicePort {
Naveen Sampath04696f72022-06-13 15:19:14 +053069 var port DevicePort
70
Tinoj Joseph429b9d92022-11-16 18:51:05 +053071 port.ID = mp.PortNo
72 port.Name = mp.Name
73
74 //port.HwAddr = strings.Trim(strings.Join(strings.Fields(fmt.Sprint("%02x", mp.HwAddr)), ":"), "[]")
75 port.HwAddr = strings.Trim(strings.ReplaceAll(fmt.Sprintf("%02x", mp.HwAddr), " ", ":"), "[]")
76 port.CurrSpeed = mp.CurrSpeed
77 port.MaxSpeed = mp.MaxSpeed
Naveen Sampath04696f72022-06-13 15:19:14 +053078 port.State = PortStateDown
79 return &port
80}
81
82// UniIDFlowQueue structure which maintains flows in queue.
83type UniIDFlowQueue struct {
84 tasks.Tasks
85 ID uint32
86}
87
88// NewUniIDFlowQueue is the constructor for UniIDFlowQueue.
89func NewUniIDFlowQueue(id uint32) *UniIDFlowQueue {
90 var flowQueue UniIDFlowQueue
91 flowQueue.ID = id
92 return &flowQueue
93}
94
95// DeviceState type
96type DeviceState string
97
98const (
99
100 // DeviceStateUNKNOWN constant
101 DeviceStateUNKNOWN DeviceState = "UNKNOWN"
102 // DeviceStateINIT constant
103 DeviceStateINIT DeviceState = "INIT"
104 // DeviceStateUP constant
105 DeviceStateUP DeviceState = "UP"
106 // DeviceStateDOWN constant
107 DeviceStateDOWN DeviceState = "DOWN"
108 // DeviceStateREBOOTED constant
109 DeviceStateREBOOTED DeviceState = "REBOOTED"
110 // DeviceStateDISABLED constant
111 DeviceStateDISABLED DeviceState = "DISABLED"
112 // DeviceStateDELETED constant
113 DeviceStateDELETED DeviceState = "DELETED"
114)
115
116// Device structure
117type Device struct {
118 tasks.Tasks
119 ID string
120 SerialNum string
121 State DeviceState
122 PortsByID map[uint32]*DevicePort
123 PortsByName map[string]*DevicePort
124 portLock sync.RWMutex
125 vclientHolder *holder.VolthaServiceClientHolder
126 ctx context.Context
127 cancel context.CancelFunc
128 packetOutChannel chan *ofp.PacketOut
129 flows map[uint64]*of.VoltSubFlow
130 flowLock sync.RWMutex
131 meters map[uint32]*of.Meter
132 meterLock sync.RWMutex
133 groups sync.Map //map[uint32]*of.Group -> [GroupId : Group]
134 auditInProgress bool
135 flowQueueLock sync.RWMutex
136 flowHash uint32
137 flowQueue map[uint32]*UniIDFlowQueue // key is hash ID generated and value is UniIDFlowQueue.
138 deviceAuditInProgress bool
139 SouthBoundID string
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530140 MfrDesc string
141 HwDesc string
142 SwDesc string
143 TimeStamp time.Time
Naveen Sampath04696f72022-06-13 15:19:14 +0530144}
145
146// NewDevice is the constructor for Device
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530147func NewDevice(cntx context.Context, id string, slno string, vclientHldr *holder.VolthaServiceClientHolder, southBoundID, mfr, hwDesc, swDesc string) *Device {
Naveen Sampath04696f72022-06-13 15:19:14 +0530148 var device Device
149 device.ID = id
150 device.SerialNum = slno
151 device.State = DeviceStateDOWN
152 device.PortsByID = make(map[uint32]*DevicePort)
153 device.PortsByName = make(map[string]*DevicePort)
154 device.vclientHolder = vclientHldr
155 device.flows = make(map[uint64]*of.VoltSubFlow)
156 device.meters = make(map[uint32]*of.Meter)
157 device.flowQueue = make(map[uint32]*UniIDFlowQueue)
158 //Get the flowhash from db and update the flowhash variable in the device.
159 device.SouthBoundID = southBoundID
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530160 device.MfrDesc = mfr
161 device.HwDesc = hwDesc
162 device.SwDesc = swDesc
163 device.TimeStamp = time.Now()
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530164 flowHash, err := db.GetFlowHash(cntx, id)
Naveen Sampath04696f72022-06-13 15:19:14 +0530165 if err != nil {
166 device.flowHash = DefaultMaxFlowQueues
167 } else {
168 var hash uint32
169 err = json.Unmarshal([]byte(flowHash), &hash)
170 if err != nil {
171 logger.Error(ctx, "Failed to unmarshall flowhash")
172 } else {
173 device.flowHash = hash
174 }
175 }
176 logger.Infow(ctx, "Flow hash for device", log.Fields{"Deviceid": id, "hash": device.flowHash})
177 return &device
178}
179
180// ResetCache to reset cache
181func (d *Device) ResetCache() {
182 logger.Warnw(ctx, "Resetting flows, meters and groups cache", log.Fields{"Device": d.ID})
183 d.flows = make(map[uint64]*of.VoltSubFlow)
184 d.meters = make(map[uint32]*of.Meter)
185 d.groups = sync.Map{}
186}
187
188// GetFlow - Get the flow from device obj
189func (d *Device) GetFlow(cookie uint64) (*of.VoltSubFlow, bool) {
190 d.flowLock.RLock()
191 defer d.flowLock.RUnlock()
192 logger.Infow(ctx, "Get Flow", log.Fields{"Cookie": cookie})
193 flow, ok := d.flows[cookie]
194 return flow, ok
195}
196
Tinoj Josephec742f62022-09-29 19:11:10 +0530197// GetAllFlows - Get the flow from device obj
198func (d *Device) GetAllFlows() ([]*of.VoltSubFlow) {
199 d.flowLock.RLock()
200 defer d.flowLock.RUnlock()
201 var flows []*of.VoltSubFlow
202 logger.Infow(ctx, "Get All Flows", log.Fields{"deviceID": d.ID})
203 for _, f := range d.flows {
204 flows = append(flows, f)
205 }
206 return flows
207}
208
209// GetAllPendingFlows - Get the flow from device obj
210func (d *Device) GetAllPendingFlows() ([]*of.VoltSubFlow) {
211 d.flowLock.RLock()
212 defer d.flowLock.RUnlock()
213 var flows []*of.VoltSubFlow
214 logger.Infow(ctx, "Get All Pending Flows", log.Fields{"deviceID": d.ID})
215 for _, f := range d.flows {
216 if f.State == of.FlowAddPending {
217 flows = append(flows, f)
218 }
219 }
220 return flows
221}
222
Naveen Sampath04696f72022-06-13 15:19:14 +0530223// AddFlow - Adds the flow to the device and also to the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530224func (d *Device) AddFlow(cntx context.Context, flow *of.VoltSubFlow) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530225 d.flowLock.Lock()
226 defer d.flowLock.Unlock()
227 logger.Infow(ctx, "AddFlow to device", log.Fields{"Cookie": flow.Cookie})
228 if _, ok := d.flows[flow.Cookie]; ok {
229 return errors.New(ErrDuplicateFlow)
230 }
231 d.flows[flow.Cookie] = flow
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530232 d.AddFlowToDb(cntx, flow)
Naveen Sampath04696f72022-06-13 15:19:14 +0530233 return nil
234}
235
236// AddFlowToDb is the utility to add the flow to the device
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530237func (d *Device) AddFlowToDb(cntx context.Context, flow *of.VoltSubFlow) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530238 if b, err := json.Marshal(flow); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530239 if err = db.PutFlow(cntx, d.ID, flow.Cookie, string(b)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530240 logger.Errorw(ctx, "Write Flow to DB failed", log.Fields{"device": d.ID, "cookie": flow.Cookie, "Reason": err})
241 }
242 }
243}
244
245// DelFlow - Deletes the flow from the device and the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530246func (d *Device) DelFlow(cntx context.Context, flow *of.VoltSubFlow) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530247 d.flowLock.Lock()
248 defer d.flowLock.Unlock()
249 if _, ok := d.flows[flow.Cookie]; ok {
250 delete(d.flows, flow.Cookie)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530251 d.DelFlowFromDb(cntx, flow.Cookie)
Naveen Sampath04696f72022-06-13 15:19:14 +0530252 return nil
253 }
254 return errors.New("Flow does not Exist")
255}
256
257// DelFlowFromDb is utility to delete the flow from the device
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530258func (d *Device) DelFlowFromDb(cntx context.Context, flowID uint64) {
259 _ = db.DelFlow(cntx, d.ID, flowID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530260}
261
262// IsFlowPresentWithOldCookie is to check whether there is any flow with old cookie.
263func (d *Device) IsFlowPresentWithOldCookie(flow *of.VoltSubFlow) bool {
264 d.flowLock.RLock()
265 defer d.flowLock.RUnlock()
266 if _, ok := d.flows[flow.Cookie]; ok {
267 return false
268 } else if flow.OldCookie != 0 && flow.Cookie != flow.OldCookie {
269 if _, ok := d.flows[flow.OldCookie]; ok {
270 logger.Infow(ctx, "Flow present with old cookie", log.Fields{"OldCookie": flow.OldCookie})
271 return true
272 }
273 }
274 return false
275}
276
277// DelFlowWithOldCookie is to delete flow with old cookie.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530278func (d *Device) DelFlowWithOldCookie(cntx context.Context, flow *of.VoltSubFlow) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530279 d.flowLock.Lock()
280 defer d.flowLock.Unlock()
281 if _, ok := d.flows[flow.OldCookie]; ok {
282 logger.Infow(ctx, "Flow was added before vgc upgrade. Trying to delete with old cookie",
283 log.Fields{"OldCookie": flow.OldCookie})
284 delete(d.flows, flow.OldCookie)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530285 d.DelFlowFromDb(cntx, flow.OldCookie)
Naveen Sampath04696f72022-06-13 15:19:14 +0530286 return nil
287 }
288 return errors.New("Flow does not Exist")
289}
290
291// RestoreFlowsFromDb to restore flows from database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530292func (d *Device) RestoreFlowsFromDb(cntx context.Context) {
293 flows, _ := db.GetFlows(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530294 for _, flow := range flows {
295 b, ok := flow.Value.([]byte)
296 if !ok {
297 logger.Warn(ctx, "The value type is not []byte")
298 continue
299 }
300 d.CreateFlowFromString(b)
301 }
302}
303
304// CreateFlowFromString to create flow from string
305func (d *Device) CreateFlowFromString(b []byte) {
306 var flow of.VoltSubFlow
307 if err := json.Unmarshal(b, &flow); err == nil {
308 if _, ok := d.flows[flow.Cookie]; !ok {
309 logger.Debugw(ctx, "Adding Flow From Db", log.Fields{"Cookie": flow.Cookie})
310 d.flows[flow.Cookie] = &flow
311 } else {
312 logger.Warnw(ctx, "Duplicate Flow", log.Fields{"Cookie": flow.Cookie})
313 }
314 } else {
315 logger.Warn(ctx, "Unmarshal failed")
316 }
317}
318
319// ----------------------------------------------------------
320// Database related functionality
321// Group operations at the device which include update and delete
322
323// UpdateGroupEntry - Adds/Updates the group to the device and also to the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530324func (d *Device) UpdateGroupEntry(cntx context.Context, group *of.Group) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530325
326 logger.Infow(ctx, "Update Group to device", log.Fields{"ID": group.GroupID})
327 d.groups.Store(group.GroupID, group)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530328 d.AddGroupToDb(cntx, group)
Naveen Sampath04696f72022-06-13 15:19:14 +0530329}
330
331// AddGroupToDb - Utility to add the group to the device DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530332func (d *Device) AddGroupToDb(cntx context.Context, group *of.Group) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530333 if b, err := json.Marshal(group); err == nil {
334 logger.Infow(ctx, "Adding Group to DB", log.Fields{"grp": group, "Json": string(b)})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530335 if err = db.PutGroup(cntx, d.ID, group.GroupID, string(b)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530336 logger.Errorw(ctx, "Write Group to DB failed", log.Fields{"device": d.ID, "groupID": group.GroupID, "Reason": err})
337 }
338 }
339}
340
341// DelGroupEntry - Deletes the group from the device and the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530342func (d *Device) DelGroupEntry(cntx context.Context, group *of.Group) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530343
344 if _, ok := d.groups.Load(group.GroupID); ok {
345 d.groups.Delete(group.GroupID)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530346 d.DelGroupFromDb(cntx, group.GroupID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530347 }
348}
349
350// DelGroupFromDb - Utility to delete the Group from the device
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530351func (d *Device) DelGroupFromDb(cntx context.Context, groupID uint32) {
352 _ = db.DelGroup(cntx, d.ID, groupID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530353}
354
355//RestoreGroupsFromDb - restores all groups from DB
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530356func (d *Device) RestoreGroupsFromDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530357 logger.Info(ctx, "Restoring Groups")
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530358 groups, _ := db.GetGroups(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530359 for _, group := range groups {
360 b, ok := group.Value.([]byte)
361 if !ok {
362 logger.Warn(ctx, "The value type is not []byte")
363 continue
364 }
365 d.CreateGroupFromString(b)
366 }
367}
368
369//CreateGroupFromString - Forms group struct from json string
370func (d *Device) CreateGroupFromString(b []byte) {
371 var group of.Group
372 if err := json.Unmarshal(b, &group); err == nil {
373 if _, ok := d.groups.Load(group.GroupID); !ok {
374 logger.Debugw(ctx, "Adding Group From Db", log.Fields{"GroupId": group.GroupID})
375 d.groups.Store(group.GroupID, &group)
376 } else {
377 logger.Warnw(ctx, "Duplicate Group", log.Fields{"GroupId": group.GroupID})
378 }
379 } else {
380 logger.Warn(ctx, "Unmarshal failed")
381 }
382}
383
384// AddMeter to add meter
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530385func (d *Device) AddMeter(cntx context.Context, meter *of.Meter) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530386 d.meterLock.Lock()
387 defer d.meterLock.Unlock()
388 if _, ok := d.meters[meter.ID]; ok {
389 return errors.New("Duplicate Meter")
390 }
391 d.meters[meter.ID] = meter
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530392 go d.AddMeterToDb(cntx, meter)
Naveen Sampath04696f72022-06-13 15:19:14 +0530393 return nil
394}
395
396// GetMeter to get meter
397func (d *Device) GetMeter(id uint32) (*of.Meter, error) {
398 d.meterLock.RLock()
399 defer d.meterLock.RUnlock()
400 if m, ok := d.meters[id]; ok {
401 return m, nil
402 }
403 return nil, errors.New("Meter Not Found")
404}
405
406// DelMeter to delete meter
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530407func (d *Device) DelMeter(cntx context.Context, meter *of.Meter) bool {
Naveen Sampath04696f72022-06-13 15:19:14 +0530408 d.meterLock.Lock()
409 defer d.meterLock.Unlock()
410 if _, ok := d.meters[meter.ID]; ok {
411 delete(d.meters, meter.ID)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530412 go d.DelMeterFromDb(cntx, meter.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530413 return true
414 }
415 return false
416}
417
418// AddMeterToDb is utility to add the Group to the device
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530419func (d *Device) AddMeterToDb(cntx context.Context, meter *of.Meter) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530420 if b, err := json.Marshal(meter); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530421 if err = db.PutDeviceMeter(cntx, d.ID, meter.ID, string(b)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530422 logger.Errorw(ctx, "Write Meter to DB failed", log.Fields{"device": d.ID, "meterID": meter.ID, "Reason": err})
423 }
424 }
425}
426
427// DelMeterFromDb to delete meter from db
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530428func (d *Device) DelMeterFromDb(cntx context.Context, id uint32) {
429 _ = db.DelDeviceMeter(cntx, d.ID, id)
Naveen Sampath04696f72022-06-13 15:19:14 +0530430}
431
432// RestoreMetersFromDb to restore meters from db
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530433func (d *Device) RestoreMetersFromDb(cntx context.Context) {
434 meters, _ := db.GetDeviceMeters(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530435 for _, meter := range meters {
436 b, ok := meter.Value.([]byte)
437 if !ok {
438 logger.Warn(ctx, "The value type is not []byte")
439 continue
440 }
441 d.CreateMeterFromString(b)
442 }
443}
444
445// CreateMeterFromString to create meter from string
446func (d *Device) CreateMeterFromString(b []byte) {
447 var meter of.Meter
448 if err := json.Unmarshal(b, &meter); err == nil {
449 if _, ok := d.meters[meter.ID]; !ok {
450 logger.Debugw(ctx, "Adding Meter From Db", log.Fields{"ID": meter.ID})
451 d.meters[meter.ID] = &meter
452 } else {
453 logger.Warnw(ctx, "Duplicate Meter", log.Fields{"ID": meter.ID})
454 }
455 } else {
456 logger.Warn(ctx, "Unmarshal failed")
457 }
458}
459
460// VolthaClient to get voltha client
461func (d *Device) VolthaClient() voltha.VolthaServiceClient {
462 return d.vclientHolder.Get()
463}
464
465// AddPort to add the port as requested by the device/VOLTHA
466// Inform the application if the port is successfully added
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530467func (d *Device) AddPort(cntx context.Context, mp *ofp.OfpPort) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530468 d.portLock.Lock()
469 defer d.portLock.Unlock()
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530470 id := mp.PortNo
471 name := mp.Name
Naveen Sampath04696f72022-06-13 15:19:14 +0530472 if _, ok := d.PortsByID[id]; ok {
473 return errors.New("Duplicate port")
474 }
475 if _, ok := d.PortsByName[name]; ok {
476 return errors.New("Duplicate port")
477 }
478
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530479 p := NewDevicePort(mp)
Naveen Sampath04696f72022-06-13 15:19:14 +0530480 d.PortsByID[id] = p
481 d.PortsByName[name] = p
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530482 d.WritePortToDb(cntx, p)
483 GetController().PortAddInd(cntx, d.ID, p.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530484 logger.Infow(ctx, "Added Port", log.Fields{"Device": d.ID, "Port": id})
485 return nil
486}
487
488// DelPort to delete the port as requested by the device/VOLTHA
489// Inform the application if the port is successfully deleted
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530490func (d *Device) DelPort(cntx context.Context, id uint32) error {
Naveen Sampath04696f72022-06-13 15:19:14 +0530491
492 p := d.GetPortByID(id)
493 if p == nil {
494 return errors.New("Unknown Port")
495 }
496 if p.State == PortStateUp {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530497 GetController().PortDownInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530498 }
Tinoj Joseph4ead4e02023-01-30 03:12:44 +0530499 GetController().PortDelInd(cntx, d.ID, p.Name)
500
Naveen Sampath04696f72022-06-13 15:19:14 +0530501 d.portLock.Lock()
502 defer d.portLock.Unlock()
503
Naveen Sampath04696f72022-06-13 15:19:14 +0530504 delete(d.PortsByID, p.ID)
505 delete(d.PortsByName, p.Name)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530506 d.DelPortFromDb(cntx, p.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530507 logger.Infow(ctx, "Deleted Port", log.Fields{"Device": d.ID, "Port": id})
508 return nil
509}
510
511// UpdatePortByName is utility to update the port by Name
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530512func (d *Device) UpdatePortByName(cntx context.Context, name string, port uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530513 d.portLock.Lock()
514 defer d.portLock.Unlock()
515
516 p, ok := d.PortsByName[name]
517 if !ok {
518 return
519 }
520 delete(d.PortsByID, p.ID)
521 p.ID = port
522 d.PortsByID[port] = p
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530523 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530524 GetController().PortUpdateInd(d.ID, p.Name, p.ID)
525 logger.Infow(ctx, "Updated Port", log.Fields{"Device": d.ID, "Port": p.ID, "PortName": name})
526}
527
528// GetPortName to get the name of the port by its id
529func (d *Device) GetPortName(id uint32) (string, error) {
530 d.portLock.RLock()
531 defer d.portLock.RUnlock()
532
533 if p, ok := d.PortsByID[id]; ok {
534 return p.Name, nil
535 }
536 logger.Errorw(ctx, "Port not found", log.Fields{"port": id})
537 return "", errors.New("Unknown Port ID")
538}
539
540// GetPortByID is utility to retrieve the port by ID
541func (d *Device) GetPortByID(id uint32) *DevicePort {
542 d.portLock.RLock()
543 defer d.portLock.RUnlock()
544
545 p, ok := d.PortsByID[id]
546 if ok {
547 return p
548 }
549 return nil
550}
551
552// GetPortByName is utility to retrieve the port by Name
553func (d *Device) GetPortByName(name string) *DevicePort {
554 d.portLock.RLock()
555 defer d.portLock.RUnlock()
556
557 p, ok := d.PortsByName[name]
558 if ok {
559 return p
560 }
561 return nil
562}
563
564// GetPortState to get the state of the port by name
565func (d *Device) GetPortState(name string) (PortState, error) {
566 d.portLock.RLock()
567 defer d.portLock.RUnlock()
568
569 if p, ok := d.PortsByName[name]; ok {
570 return p.State, nil
571 }
572 return PortStateDown, errors.New("Unknown Port ID")
573}
574
575// GetPortID to get the port-id by the port name
576func (d *Device) GetPortID(name string) (uint32, error) {
577 d.portLock.RLock()
578 defer d.portLock.RUnlock()
579
580 if p, ok := d.PortsByName[name]; ok {
581 return p.ID, nil
582 }
583 return 0, errors.New("Unknown Port ID")
584
585}
586
587// WritePortToDb to add the port to the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530588func (d *Device) WritePortToDb(ctx context.Context, port *DevicePort) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530589 port.Version = database.PresentVersionMap[database.DevicePortPath]
590 if b, err := json.Marshal(port); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530591 if err = db.PutPort(ctx, d.ID, port.ID, string(b)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530592 logger.Errorw(ctx, "Write port to DB failed", log.Fields{"device": d.ID, "port": port.ID, "Reason": err})
593 }
594 }
595}
596
597// DelPortFromDb to delete port from database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530598func (d *Device) DelPortFromDb(cntx context.Context, id uint32) {
599 _ = db.DelPort(cntx, d.ID, id)
Naveen Sampath04696f72022-06-13 15:19:14 +0530600}
601
602// RestorePortsFromDb to restore ports from database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530603func (d *Device) RestorePortsFromDb(cntx context.Context) {
604 ports, _ := db.GetPorts(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530605 for _, port := range ports {
606 b, ok := port.Value.([]byte)
607 if !ok {
608 logger.Warn(ctx, "The value type is not []byte")
609 continue
610 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530611 d.CreatePortFromString(cntx, b)
Naveen Sampath04696f72022-06-13 15:19:14 +0530612 }
613}
614
615// CreatePortFromString to create port from string
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530616func (d *Device) CreatePortFromString(cntx context.Context, b []byte) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530617 var port DevicePort
618 if err := json.Unmarshal(b, &port); err == nil {
619 if _, ok := d.PortsByID[port.ID]; !ok {
620 logger.Debugw(ctx, "Adding Port From Db", log.Fields{"ID": port.ID})
621 d.PortsByID[port.ID] = &port
622 d.PortsByName[port.Name] = &port
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530623 GetController().PortAddInd(cntx, d.ID, port.ID, port.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530624 } else {
625 logger.Warnw(ctx, "Duplicate Port", log.Fields{"ID": port.ID})
626 }
627 } else {
628 logger.Warn(ctx, "Unmarshal failed")
629 }
630}
631
632// Delete : OLT Delete functionality yet to be implemented. IDeally all of the
633// resources should have been removed by this time. It is an error
634// scenario if the OLT has resources associated with it.
635func (d *Device) Delete() {
636 d.StopAll()
637}
638
639// Stop to stop the task
640func (d *Device) Stop() {
641}
642
643// ConnectInd is called when the connection between VGC and the VOLTHA is
644// restored. This will perform audit of the device post reconnection
645func (d *Device) ConnectInd(ctx context.Context, discType intf.DiscoveryType) {
646 logger.Warnw(ctx, "Audit Upon Connection Establishment", log.Fields{"Device": d.ID, "State": d.State})
647 ctx1, cancel := context.WithCancel(ctx)
648 d.cancel = cancel
649 d.ctx = ctx1
650 d.Tasks.Initialize(ctx1)
651
652 logger.Warnw(ctx, "Device State change Ind: UP", log.Fields{"Device": d.ID})
653 d.State = DeviceStateUP
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530654 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530655 GetController().DeviceUpInd(d.ID)
656
657 logger.Warnw(ctx, "Device State change Ind: UP, trigger Audit Tasks", log.Fields{"Device": d.ID})
658 t := NewAuditDevice(d, AuditEventDeviceDisc)
659 d.Tasks.AddTask(t)
660
661 t1 := NewAuditTablesTask(d)
662 d.Tasks.AddTask(t1)
663
664 t2 := NewPendingProfilesTask(d)
665 d.Tasks.AddTask(t2)
666
667 go d.synchronizeDeviceTables()
668}
669
670func (d *Device) synchronizeDeviceTables() {
671
Tinoj Josephaf37ce82022-12-28 11:59:43 +0530672 tick := time.NewTicker(GetController().GetDeviceTableSyncDuration())
Naveen Sampath04696f72022-06-13 15:19:14 +0530673loop:
674 for {
675 select {
676 case <-d.ctx.Done():
677 logger.Warnw(d.ctx, "Context Done. Cancelling Periodic Audit", log.Fields{"Context": ctx, "Device": d.ID, "DeviceSerialNum": d.SerialNum})
678 break loop
679 case <-tick.C:
680 t1 := NewAuditTablesTask(d)
681 d.Tasks.AddTask(t1)
682 }
683 }
684 tick.Stop()
685}
686
687// DeviceUpInd is called when the logical device state changes to UP. This will perform audit of the device post reconnection
688func (d *Device) DeviceUpInd() {
689 logger.Warnw(ctx, "Device State change Ind: UP", log.Fields{"Device": d.ID})
690 d.State = DeviceStateUP
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530691 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530692 GetController().DeviceUpInd(d.ID)
693
694 logger.Warnw(ctx, "Device State change Ind: UP, trigger Audit Tasks", log.Fields{"Device": d.ID})
695 t := NewAuditDevice(d, AuditEventDeviceDisc)
696 d.Tasks.AddTask(t)
697
698 t1 := NewAuditTablesTask(d)
699 d.Tasks.AddTask(t1)
700
701 t2 := NewPendingProfilesTask(d)
702 d.Tasks.AddTask(t2)
703}
704
705// DeviceDownInd is called when the logical device state changes to Down.
706func (d *Device) DeviceDownInd() {
707 logger.Warnw(ctx, "Device State change Ind: Down", log.Fields{"Device": d.ID})
708 d.State = DeviceStateDOWN
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530709 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530710 GetController().DeviceDownInd(d.ID)
711}
712
713// DeviceRebootInd is called when the logical device is rebooted.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530714func (d *Device) DeviceRebootInd(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530715 logger.Warnw(ctx, "Device State change Ind: Rebooted", log.Fields{"Device": d.ID})
716
717 if d.State == DeviceStateREBOOTED {
718 d.State = DeviceStateREBOOTED
719 logger.Warnw(ctx, "Ignoring Device State change Ind: REBOOT, Device Already in REBOOT state", log.Fields{"Device": d.ID, "SeralNo": d.SerialNum})
720 return
721 }
722
723 d.State = DeviceStateREBOOTED
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530724 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530725 GetController().SetRebootInProgressForDevice(d.ID)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530726 GetController().DeviceRebootInd(cntx, d.ID, d.SerialNum, d.SouthBoundID)
727 d.ReSetAllPortStates(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530728}
729
730// DeviceDisabledInd is called when the logical device is disabled
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530731func (d *Device) DeviceDisabledInd(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530732 logger.Warnw(ctx, "Device State change Ind: Disabled", log.Fields{"Device": d.ID})
733 d.State = DeviceStateDISABLED
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530734 d.TimeStamp = time.Now()
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530735 GetController().DeviceDisableInd(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530736}
737
738//ReSetAllPortStates - Set all logical device port status to DOWN
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530739func (d *Device) ReSetAllPortStates(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530740 logger.Warnw(ctx, "Resetting all Ports State to DOWN", log.Fields{"Device": d.ID, "State": d.State})
741
742 d.portLock.Lock()
743 defer d.portLock.Unlock()
744
745 for _, port := range d.PortsByID {
746 if port.State != PortStateDown {
747 logger.Infow(ctx, "Resetting Port State to DOWN", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530748 GetController().PortDownInd(cntx, d.ID, port.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530749 port.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530750 d.WritePortToDb(cntx, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530751 }
752 }
753}
754
755//ReSetAllPortStatesInDb - Set all logical device port status to DOWN in DB and skip indication to application
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530756func (d *Device) ReSetAllPortStatesInDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530757 logger.Warnw(ctx, "Resetting all Ports State to DOWN In DB", log.Fields{"Device": d.ID, "State": d.State})
758
759 d.portLock.Lock()
760 defer d.portLock.Unlock()
761
762 for _, port := range d.PortsByID {
763 if port.State != PortStateDown {
764 logger.Infow(ctx, "Resetting Port State to DOWN and Write to DB", log.Fields{"Device": d.ID, "Port": port})
765 port.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530766 d.WritePortToDb(cntx, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530767 }
768 }
769}
770
771// ProcessPortUpdate deals with the change in port id (ONU movement) and taking action
772// to update only when the port state is DOWN
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530773func (d *Device) ProcessPortUpdate(cntx context.Context, portName string, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530774 if p := d.GetPortByName(portName); p != nil {
775 if p.ID != port {
776 logger.Infow(ctx, "Port ID update indication", log.Fields{"Port": p.Name, "Old PortID": p.ID, "New Port ID": port})
777 if p.State != PortStateDown {
778 logger.Errorw(ctx, "Port ID update failed. Port State UP", log.Fields{"Port": p})
779 return
780 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530781 d.UpdatePortByName(cntx, portName, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530782 logger.Errorw(ctx, "Port ID Updated", log.Fields{"Port": p})
783 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530784 d.ProcessPortState(cntx, port, state)
Naveen Sampath04696f72022-06-13 15:19:14 +0530785 }
786}
787
788// ***Operations Performed on Port state Transitions***
789//
790// |-----------------------------------------------------------------------------|
791// | State | Action |
792// |--------------------|--------------------------------------------------------|
793// | UP | UNI - Trigger Flow addition for service configured |
794// | | NNI - Trigger Flow addition for vnets & mvlan profiles |
795// | | |
796// | DOWN | UNI - Trigger Flow deletion for service configured |
797// | | NNI - Trigger Flow deletion for vnets & mvlan profiles |
798// | | |
799// |-----------------------------------------------------------------------------|
800//
801
802// ProcessPortState deals with the change in port status and taking action
803// based on the new state and the old state
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530804func (d *Device) ProcessPortState(cntx context.Context, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530805 if d.State != DeviceStateUP && !util.IsNniPort(port) {
806 logger.Warnw(ctx, "Ignore Port State Processing - Device not UP", log.Fields{"Device": d.ID, "Port": port, "DeviceState": d.State})
807 return
808 }
809 if p := d.GetPortByID(port); p != nil {
810 logger.Infow(ctx, "Port State Processing", log.Fields{"Received": state, "Current": p.State})
811
812 // Avoid blind initialization as the current tasks in the queue will be lost
813 // Eg: Service Del followed by Port Down - The flows will be dangling
814 // Eg: NNI Down followed by NNI UP - Mcast data flows will be dangling
815 p.Tasks.CheckAndInitialize(d.ctx)
816 if state == uint32(ofp.OfpPortState_OFPPS_LIVE) && p.State == PortStateDown {
817 // Transition from DOWN to UP
818 logger.Infow(ctx, "Port State Change to UP", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530819 GetController().PortUpInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530820 p.State = PortStateUp
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530821 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530822 } else if (state != uint32(ofp.OfpPortState_OFPPS_LIVE)) && (p.State != PortStateDown) {
823 // Transition from UP to Down
824 logger.Infow(ctx, "Port State Change to Down", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530825 GetController().PortDownInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530826 p.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530827 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530828 } else {
829 logger.Warnw(ctx, "Dropping Port Ind: No Change in Port State", log.Fields{"PortName": p.Name, "ID": port, "Device": d.ID, "PortState": p.State, "IncomingState": state})
830 }
831 }
832}
833
834// ProcessPortStateAfterReboot - triggers the port state indication to sort out configu mismatch due to reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530835func (d *Device) ProcessPortStateAfterReboot(cntx context.Context, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530836 if d.State != DeviceStateUP && !util.IsNniPort(port) {
837 logger.Warnw(ctx, "Ignore Port State Processing - Device not UP", log.Fields{"Device": d.ID, "Port": port, "DeviceState": d.State})
838 return
839 }
840 if p := d.GetPortByID(port); p != nil {
841 logger.Infow(ctx, "Port State Processing after Reboot", log.Fields{"Received": state, "Current": p.State})
842 p.Tasks.Initialize(d.ctx)
843 if p.State == PortStateUp {
844 logger.Infow(ctx, "Port State: UP", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530845 GetController().PortUpInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530846 } else if p.State == PortStateDown {
847 logger.Infow(ctx, "Port State: Down", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530848 GetController().PortDownInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530849 }
850 }
851}
852
853// ChangeEvent : Change event brings in ports related changes such as addition/deletion
854// or modification where the port status change up/down is indicated to the
855// controller
856func (d *Device) ChangeEvent(event *ofp.ChangeEvent) error {
857 cet := NewChangeEventTask(d.ctx, event, d)
858 d.AddTask(cet)
859 return nil
860}
861
862// PacketIn handle the incoming packet-in and deliver to the application for the
863// actual processing
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530864func (d *Device) PacketIn(cntx context.Context, pkt *ofp.PacketIn) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530865 logger.Debugw(ctx, "Received a Packet-In", log.Fields{"Device": d.ID})
866 if pkt.PacketIn.Reason != ofp.OfpPacketInReason_OFPR_ACTION {
867 logger.Warnw(ctx, "Unsupported PacketIn Reason", log.Fields{"Reason": pkt.PacketIn.Reason})
868 return
869 }
870 data := pkt.PacketIn.Data
871 port := PacketInGetPort(pkt.PacketIn)
872 if pName, err := d.GetPortName(port); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530873 GetController().PacketInInd(cntx, d.ID, pName, data)
Naveen Sampath04696f72022-06-13 15:19:14 +0530874 } else {
875 logger.Warnw(ctx, "Unknown Port", log.Fields{"Reason": err.Error()})
876 }
877}
878
879// PacketInGetPort to get the port on which the packet-in is reported
880func PacketInGetPort(pkt *ofp.OfpPacketIn) uint32 {
881 for _, field := range pkt.Match.OxmFields {
882 if field.OxmClass == ofp.OfpOxmClass_OFPXMC_OPENFLOW_BASIC {
883 if ofbField, ok := field.Field.(*ofp.OfpOxmField_OfbField); ok {
884 if ofbField.OfbField.Type == ofp.OxmOfbFieldTypes_OFPXMT_OFB_IN_PORT {
885 if port, ok := ofbField.OfbField.Value.(*ofp.OfpOxmOfbField_Port); ok {
886 return port.Port
887 }
888 }
889 }
890 }
891 }
892 return 0
893}
894
895// PacketOutReq receives the packet out request from the application via the
896// controller. The interface from the application uses name as the identity.
897func (d *Device) PacketOutReq(outport string, inport string, data []byte, isCustomPkt bool) error {
898 inp, err := d.GetPortID(inport)
899 if err != nil {
900 return errors.New("Unknown inport")
901 }
902 outp, err1 := d.GetPortID(outport)
903 if err1 != nil {
904 return errors.New("Unknown outport")
905 }
906 logger.Debugw(ctx, "Sending packet out", log.Fields{"Device": d.ID, "Inport": inport, "Outport": outport})
907 return d.SendPacketOut(outp, inp, data, isCustomPkt)
908}
909
910// SendPacketOut is responsible for building the OF structure and send the
911// packet-out to the VOLTHA
912func (d *Device) SendPacketOut(outport uint32, inport uint32, data []byte, isCustomPkt bool) error {
913 pout := &ofp.PacketOut{}
914 pout.Id = d.ID
915 opout := &ofp.OfpPacketOut{}
916 pout.PacketOut = opout
917 opout.InPort = inport
918 opout.Data = data
919 opout.Actions = []*ofp.OfpAction{
920 {
921 Type: ofp.OfpActionType_OFPAT_OUTPUT,
922 Action: &ofp.OfpAction_Output{
923 Output: &ofp.OfpActionOutput{
924 Port: outport,
925 MaxLen: 65535,
926 },
927 },
928 },
929 }
930 d.packetOutChannel <- pout
931 return nil
932}
933
934// UpdateFlows receives the flows in the form that is implemented
935// in the VGC and transforms them to the OF format. This is handled
936// as a port of the task that is enqueued to do the same.
937func (d *Device) UpdateFlows(flow *of.VoltFlow, devPort *DevicePort) {
938 t := NewAddFlowsTask(d.ctx, flow, d)
939 logger.Debugw(ctx, "Port Context", log.Fields{"Ctx": devPort.GetContext()})
940 // check if port isNni , if yes flows will be added to device port queues.
941 if util.IsNniPort(devPort.ID) {
942 // Adding the flows to device port queues.
943 devPort.AddTask(t)
944 return
945 }
946 // If the flowHash is enabled then add the flows to the flowhash generated queues.
947 flowQueue := d.getAndAddFlowQueueForUniID(uint32(devPort.ID))
948 if flowQueue != nil {
949 logger.Debugw(ctx, "flowHashQId", log.Fields{"uniid": devPort.ID, "flowhash": flowQueue.ID})
950 flowQueue.AddTask(t)
951 logger.Debugw(ctx, "Tasks Info", log.Fields{"uniid": devPort.ID, "flowhash": flowQueue.ID, "Total": flowQueue.TotalTasks(), "Pending": flowQueue.NumPendingTasks()})
952 } else {
953 //FlowThrotling disabled, add to the device port queue
954 devPort.AddTask(t)
955 return
956 }
957}
958
959// UpdateGroup to update group info
960func (d *Device) UpdateGroup(group *of.Group, devPort *DevicePort) {
961 task := NewModGroupTask(d.ctx, group, d)
962 logger.Debugw(ctx, "NNI Port Context", log.Fields{"Ctx": devPort.GetContext()})
963 devPort.AddTask(task)
964}
965
966// ModMeter for mod meter task
967func (d *Device) ModMeter(command of.MeterCommand, meter *of.Meter, devPort *DevicePort) {
968 if command == of.MeterCommandAdd {
969 if _, err := d.GetMeter(meter.ID); err == nil {
970 logger.Debugw(ctx, "Meter already added", log.Fields{"ID": meter.ID})
971 return
972 }
973 }
974 t := NewModMeterTask(d.ctx, command, meter, d)
975 devPort.AddTask(t)
976}
977
978func (d *Device) getAndAddFlowQueueForUniID(id uint32) *UniIDFlowQueue {
979 d.flowQueueLock.RLock()
980 //If flowhash is 0 that means flowhash throttling is disabled, return nil
981 if d.flowHash == 0 {
982 d.flowQueueLock.RUnlock()
983 return nil
984 }
985 flowHashID := id % uint32(d.flowHash)
986 if value, found := d.flowQueue[uint32(flowHashID)]; found {
987 d.flowQueueLock.RUnlock()
988 return value
989 }
990 d.flowQueueLock.RUnlock()
991 logger.Debugw(ctx, "Flow queue not found creating one", log.Fields{"uniid": id, "hash": flowHashID})
992
993 return d.addFlowQueueForUniID(id)
994}
995
996func (d *Device) addFlowQueueForUniID(id uint32) *UniIDFlowQueue {
997
998 d.flowQueueLock.Lock()
999 defer d.flowQueueLock.Unlock()
1000 flowHashID := id % uint32(d.flowHash)
1001 flowQueue := NewUniIDFlowQueue(uint32(flowHashID))
1002 flowQueue.Tasks.Initialize(d.ctx)
1003 d.flowQueue[flowHashID] = flowQueue
1004 return flowQueue
1005}
1006
1007// SetFlowHash sets the device flow hash and writes to the DB.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301008func (d *Device) SetFlowHash(cntx context.Context, hash uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301009 d.flowQueueLock.Lock()
1010 defer d.flowQueueLock.Unlock()
1011
1012 d.flowHash = hash
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301013 d.writeFlowHashToDB(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301014}
1015
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301016func (d *Device) writeFlowHashToDB(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301017 hash, err := json.Marshal(d.flowHash)
1018 if err != nil {
1019 logger.Errorw(ctx, "failed to marshal flow hash", log.Fields{"hash": d.flowHash})
1020 return
1021 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301022 if err := db.PutFlowHash(cntx, d.ID, string(hash)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +05301023 logger.Errorw(ctx, "Failed to add flow hash to DB", log.Fields{"device": d.ID, "hash": d.flowHash})
1024 }
1025}
1026
1027//isSBOperAllowed - determins if the SB operation is allowed based on device state & force flag
1028func (d *Device) isSBOperAllowed(forceAction bool) bool {
1029
1030 if d.State == DeviceStateUP {
1031 return true
1032 }
1033
1034 if d.State == DeviceStateDISABLED && forceAction {
1035 return true
1036 }
1037
1038 return false
1039}
1040
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301041func (d *Device) triggerFlowNotification(cntx context.Context, cookie uint64, oper of.Command, bwDetails of.BwAvailDetails, err error) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301042 flow, _ := d.GetFlow(cookie)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301043 d.triggerFlowResultNotification(cntx, cookie, flow, oper, bwDetails, err)
Naveen Sampath04696f72022-06-13 15:19:14 +05301044}
1045
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301046func (d *Device) triggerFlowResultNotification(cntx context.Context, cookie uint64, flow *of.VoltSubFlow, oper of.Command, bwDetails of.BwAvailDetails, err error) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301047
1048 statusCode, statusMsg := infraerror.GetErrorInfo(err)
1049 success := isFlowOperSuccess(statusCode, oper)
1050
1051 updateFlow := func(cookie uint64, state int, reason string) {
1052 if dbFlow, ok := d.GetFlow(cookie); ok {
1053 dbFlow.State = uint8(state)
1054 dbFlow.ErrorReason = reason
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301055 d.AddFlowToDb(cntx, dbFlow)
Naveen Sampath04696f72022-06-13 15:19:14 +05301056 }
1057 }
1058
1059 //Update flow results
1060 // Add - Update Success or Failure status with reason
1061 // Del - Delete entry from DB on success else update error reason
1062 if oper == of.CommandAdd {
1063 state := of.FlowAddSuccess
1064 reason := ""
1065 if !success {
1066 state = of.FlowAddFailure
1067 reason = statusMsg
1068 }
1069 updateFlow(cookie, state, reason)
1070 logger.Debugw(ctx, "Updated Flow to DB", log.Fields{"Cookie": cookie, "State": state})
1071 } else {
1072 if success && flow != nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301073 if err := d.DelFlow(cntx, flow); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +05301074 logger.Warnw(ctx, "Delete Flow Error", log.Fields{"Cookie": flow.Cookie, "Reason": err.Error()})
1075 }
1076 } else if !success {
1077 updateFlow(cookie, of.FlowDelFailure, statusMsg)
1078 }
1079 }
1080
1081 flowResult := intf.FlowStatus{
1082 Cookie: strconv.FormatUint(cookie, 10),
1083 Device: d.ID,
1084 FlowModType: oper,
1085 Flow: flow,
1086 Status: statusCode,
1087 Reason: statusMsg,
1088 AdditionalData: bwDetails,
1089 }
1090
1091 logger.Infow(ctx, "Sending Flow Notification", log.Fields{"Cookie": cookie, "Error Code": statusCode, "FlowOp": oper})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301092 GetController().ProcessFlowModResultIndication(cntx, flowResult)
Naveen Sampath04696f72022-06-13 15:19:14 +05301093}