blob: ea4ccb35b32bd0c6be7ac423a76bdbe36a4f1921 [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 }
499 d.portLock.Lock()
500 defer d.portLock.Unlock()
501
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530502 GetController().PortDelInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530503 delete(d.PortsByID, p.ID)
504 delete(d.PortsByName, p.Name)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530505 d.DelPortFromDb(cntx, p.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530506 logger.Infow(ctx, "Deleted Port", log.Fields{"Device": d.ID, "Port": id})
507 return nil
508}
509
510// UpdatePortByName is utility to update the port by Name
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530511func (d *Device) UpdatePortByName(cntx context.Context, name string, port uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530512 d.portLock.Lock()
513 defer d.portLock.Unlock()
514
515 p, ok := d.PortsByName[name]
516 if !ok {
517 return
518 }
519 delete(d.PortsByID, p.ID)
520 p.ID = port
521 d.PortsByID[port] = p
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530522 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530523 GetController().PortUpdateInd(d.ID, p.Name, p.ID)
524 logger.Infow(ctx, "Updated Port", log.Fields{"Device": d.ID, "Port": p.ID, "PortName": name})
525}
526
527// GetPortName to get the name of the port by its id
528func (d *Device) GetPortName(id uint32) (string, error) {
529 d.portLock.RLock()
530 defer d.portLock.RUnlock()
531
532 if p, ok := d.PortsByID[id]; ok {
533 return p.Name, nil
534 }
535 logger.Errorw(ctx, "Port not found", log.Fields{"port": id})
536 return "", errors.New("Unknown Port ID")
537}
538
539// GetPortByID is utility to retrieve the port by ID
540func (d *Device) GetPortByID(id uint32) *DevicePort {
541 d.portLock.RLock()
542 defer d.portLock.RUnlock()
543
544 p, ok := d.PortsByID[id]
545 if ok {
546 return p
547 }
548 return nil
549}
550
551// GetPortByName is utility to retrieve the port by Name
552func (d *Device) GetPortByName(name string) *DevicePort {
553 d.portLock.RLock()
554 defer d.portLock.RUnlock()
555
556 p, ok := d.PortsByName[name]
557 if ok {
558 return p
559 }
560 return nil
561}
562
563// GetPortState to get the state of the port by name
564func (d *Device) GetPortState(name string) (PortState, error) {
565 d.portLock.RLock()
566 defer d.portLock.RUnlock()
567
568 if p, ok := d.PortsByName[name]; ok {
569 return p.State, nil
570 }
571 return PortStateDown, errors.New("Unknown Port ID")
572}
573
574// GetPortID to get the port-id by the port name
575func (d *Device) GetPortID(name string) (uint32, error) {
576 d.portLock.RLock()
577 defer d.portLock.RUnlock()
578
579 if p, ok := d.PortsByName[name]; ok {
580 return p.ID, nil
581 }
582 return 0, errors.New("Unknown Port ID")
583
584}
585
586// WritePortToDb to add the port to the database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530587func (d *Device) WritePortToDb(ctx context.Context, port *DevicePort) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530588 port.Version = database.PresentVersionMap[database.DevicePortPath]
589 if b, err := json.Marshal(port); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530590 if err = db.PutPort(ctx, d.ID, port.ID, string(b)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +0530591 logger.Errorw(ctx, "Write port to DB failed", log.Fields{"device": d.ID, "port": port.ID, "Reason": err})
592 }
593 }
594}
595
596// DelPortFromDb to delete port from database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530597func (d *Device) DelPortFromDb(cntx context.Context, id uint32) {
598 _ = db.DelPort(cntx, d.ID, id)
Naveen Sampath04696f72022-06-13 15:19:14 +0530599}
600
601// RestorePortsFromDb to restore ports from database
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530602func (d *Device) RestorePortsFromDb(cntx context.Context) {
603 ports, _ := db.GetPorts(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530604 for _, port := range ports {
605 b, ok := port.Value.([]byte)
606 if !ok {
607 logger.Warn(ctx, "The value type is not []byte")
608 continue
609 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530610 d.CreatePortFromString(cntx, b)
Naveen Sampath04696f72022-06-13 15:19:14 +0530611 }
612}
613
614// CreatePortFromString to create port from string
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530615func (d *Device) CreatePortFromString(cntx context.Context, b []byte) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530616 var port DevicePort
617 if err := json.Unmarshal(b, &port); err == nil {
618 if _, ok := d.PortsByID[port.ID]; !ok {
619 logger.Debugw(ctx, "Adding Port From Db", log.Fields{"ID": port.ID})
620 d.PortsByID[port.ID] = &port
621 d.PortsByName[port.Name] = &port
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530622 GetController().PortAddInd(cntx, d.ID, port.ID, port.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530623 } else {
624 logger.Warnw(ctx, "Duplicate Port", log.Fields{"ID": port.ID})
625 }
626 } else {
627 logger.Warn(ctx, "Unmarshal failed")
628 }
629}
630
631// Delete : OLT Delete functionality yet to be implemented. IDeally all of the
632// resources should have been removed by this time. It is an error
633// scenario if the OLT has resources associated with it.
634func (d *Device) Delete() {
635 d.StopAll()
636}
637
638// Stop to stop the task
639func (d *Device) Stop() {
640}
641
642// ConnectInd is called when the connection between VGC and the VOLTHA is
643// restored. This will perform audit of the device post reconnection
644func (d *Device) ConnectInd(ctx context.Context, discType intf.DiscoveryType) {
645 logger.Warnw(ctx, "Audit Upon Connection Establishment", log.Fields{"Device": d.ID, "State": d.State})
646 ctx1, cancel := context.WithCancel(ctx)
647 d.cancel = cancel
648 d.ctx = ctx1
649 d.Tasks.Initialize(ctx1)
650
651 logger.Warnw(ctx, "Device State change Ind: UP", log.Fields{"Device": d.ID})
652 d.State = DeviceStateUP
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530653 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530654 GetController().DeviceUpInd(d.ID)
655
656 logger.Warnw(ctx, "Device State change Ind: UP, trigger Audit Tasks", log.Fields{"Device": d.ID})
657 t := NewAuditDevice(d, AuditEventDeviceDisc)
658 d.Tasks.AddTask(t)
659
660 t1 := NewAuditTablesTask(d)
661 d.Tasks.AddTask(t1)
662
663 t2 := NewPendingProfilesTask(d)
664 d.Tasks.AddTask(t2)
665
666 go d.synchronizeDeviceTables()
667}
668
669func (d *Device) synchronizeDeviceTables() {
670
Tinoj Josephaf37ce82022-12-28 11:59:43 +0530671 tick := time.NewTicker(GetController().GetDeviceTableSyncDuration())
Naveen Sampath04696f72022-06-13 15:19:14 +0530672loop:
673 for {
674 select {
675 case <-d.ctx.Done():
676 logger.Warnw(d.ctx, "Context Done. Cancelling Periodic Audit", log.Fields{"Context": ctx, "Device": d.ID, "DeviceSerialNum": d.SerialNum})
677 break loop
678 case <-tick.C:
679 t1 := NewAuditTablesTask(d)
680 d.Tasks.AddTask(t1)
681 }
682 }
683 tick.Stop()
684}
685
686// DeviceUpInd is called when the logical device state changes to UP. This will perform audit of the device post reconnection
687func (d *Device) DeviceUpInd() {
688 logger.Warnw(ctx, "Device State change Ind: UP", log.Fields{"Device": d.ID})
689 d.State = DeviceStateUP
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530690 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530691 GetController().DeviceUpInd(d.ID)
692
693 logger.Warnw(ctx, "Device State change Ind: UP, trigger Audit Tasks", log.Fields{"Device": d.ID})
694 t := NewAuditDevice(d, AuditEventDeviceDisc)
695 d.Tasks.AddTask(t)
696
697 t1 := NewAuditTablesTask(d)
698 d.Tasks.AddTask(t1)
699
700 t2 := NewPendingProfilesTask(d)
701 d.Tasks.AddTask(t2)
702}
703
704// DeviceDownInd is called when the logical device state changes to Down.
705func (d *Device) DeviceDownInd() {
706 logger.Warnw(ctx, "Device State change Ind: Down", log.Fields{"Device": d.ID})
707 d.State = DeviceStateDOWN
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530708 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530709 GetController().DeviceDownInd(d.ID)
710}
711
712// DeviceRebootInd is called when the logical device is rebooted.
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530713func (d *Device) DeviceRebootInd(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530714 logger.Warnw(ctx, "Device State change Ind: Rebooted", log.Fields{"Device": d.ID})
715
716 if d.State == DeviceStateREBOOTED {
717 d.State = DeviceStateREBOOTED
718 logger.Warnw(ctx, "Ignoring Device State change Ind: REBOOT, Device Already in REBOOT state", log.Fields{"Device": d.ID, "SeralNo": d.SerialNum})
719 return
720 }
721
722 d.State = DeviceStateREBOOTED
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530723 d.TimeStamp = time.Now()
Naveen Sampath04696f72022-06-13 15:19:14 +0530724 GetController().SetRebootInProgressForDevice(d.ID)
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530725 GetController().DeviceRebootInd(cntx, d.ID, d.SerialNum, d.SouthBoundID)
726 d.ReSetAllPortStates(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +0530727}
728
729// DeviceDisabledInd is called when the logical device is disabled
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530730func (d *Device) DeviceDisabledInd(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530731 logger.Warnw(ctx, "Device State change Ind: Disabled", log.Fields{"Device": d.ID})
732 d.State = DeviceStateDISABLED
Tinoj Joseph429b9d92022-11-16 18:51:05 +0530733 d.TimeStamp = time.Now()
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530734 GetController().DeviceDisableInd(cntx, d.ID)
Naveen Sampath04696f72022-06-13 15:19:14 +0530735}
736
737//ReSetAllPortStates - Set all logical device port status to DOWN
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530738func (d *Device) ReSetAllPortStates(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530739 logger.Warnw(ctx, "Resetting all Ports State to DOWN", log.Fields{"Device": d.ID, "State": d.State})
740
741 d.portLock.Lock()
742 defer d.portLock.Unlock()
743
744 for _, port := range d.PortsByID {
745 if port.State != PortStateDown {
746 logger.Infow(ctx, "Resetting Port State to DOWN", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530747 GetController().PortDownInd(cntx, d.ID, port.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530748 port.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530749 d.WritePortToDb(cntx, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530750 }
751 }
752}
753
754//ReSetAllPortStatesInDb - Set all logical device port status to DOWN in DB and skip indication to application
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530755func (d *Device) ReSetAllPortStatesInDb(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530756 logger.Warnw(ctx, "Resetting all Ports State to DOWN In DB", log.Fields{"Device": d.ID, "State": d.State})
757
758 d.portLock.Lock()
759 defer d.portLock.Unlock()
760
761 for _, port := range d.PortsByID {
762 if port.State != PortStateDown {
763 logger.Infow(ctx, "Resetting Port State to DOWN and Write to DB", log.Fields{"Device": d.ID, "Port": port})
764 port.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530765 d.WritePortToDb(cntx, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530766 }
767 }
768}
769
770// ProcessPortUpdate deals with the change in port id (ONU movement) and taking action
771// to update only when the port state is DOWN
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530772func (d *Device) ProcessPortUpdate(cntx context.Context, portName string, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530773 if p := d.GetPortByName(portName); p != nil {
774 if p.ID != port {
775 logger.Infow(ctx, "Port ID update indication", log.Fields{"Port": p.Name, "Old PortID": p.ID, "New Port ID": port})
776 if p.State != PortStateDown {
777 logger.Errorw(ctx, "Port ID update failed. Port State UP", log.Fields{"Port": p})
778 return
779 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530780 d.UpdatePortByName(cntx, portName, port)
Naveen Sampath04696f72022-06-13 15:19:14 +0530781 logger.Errorw(ctx, "Port ID Updated", log.Fields{"Port": p})
782 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530783 d.ProcessPortState(cntx, port, state)
Naveen Sampath04696f72022-06-13 15:19:14 +0530784 }
785}
786
787// ***Operations Performed on Port state Transitions***
788//
789// |-----------------------------------------------------------------------------|
790// | State | Action |
791// |--------------------|--------------------------------------------------------|
792// | UP | UNI - Trigger Flow addition for service configured |
793// | | NNI - Trigger Flow addition for vnets & mvlan profiles |
794// | | |
795// | DOWN | UNI - Trigger Flow deletion for service configured |
796// | | NNI - Trigger Flow deletion for vnets & mvlan profiles |
797// | | |
798// |-----------------------------------------------------------------------------|
799//
800
801// ProcessPortState deals with the change in port status and taking action
802// based on the new state and the old state
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530803func (d *Device) ProcessPortState(cntx context.Context, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530804 if d.State != DeviceStateUP && !util.IsNniPort(port) {
805 logger.Warnw(ctx, "Ignore Port State Processing - Device not UP", log.Fields{"Device": d.ID, "Port": port, "DeviceState": d.State})
806 return
807 }
808 if p := d.GetPortByID(port); p != nil {
809 logger.Infow(ctx, "Port State Processing", log.Fields{"Received": state, "Current": p.State})
810
811 // Avoid blind initialization as the current tasks in the queue will be lost
812 // Eg: Service Del followed by Port Down - The flows will be dangling
813 // Eg: NNI Down followed by NNI UP - Mcast data flows will be dangling
814 p.Tasks.CheckAndInitialize(d.ctx)
815 if state == uint32(ofp.OfpPortState_OFPPS_LIVE) && p.State == PortStateDown {
816 // Transition from DOWN to UP
817 logger.Infow(ctx, "Port State Change to UP", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530818 GetController().PortUpInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530819 p.State = PortStateUp
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530820 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530821 } else if (state != uint32(ofp.OfpPortState_OFPPS_LIVE)) && (p.State != PortStateDown) {
822 // Transition from UP to Down
823 logger.Infow(ctx, "Port State Change to Down", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530824 GetController().PortDownInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530825 p.State = PortStateDown
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530826 d.WritePortToDb(cntx, p)
Naveen Sampath04696f72022-06-13 15:19:14 +0530827 } else {
828 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})
829 }
830 }
831}
832
833// ProcessPortStateAfterReboot - triggers the port state indication to sort out configu mismatch due to reboot
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530834func (d *Device) ProcessPortStateAfterReboot(cntx context.Context, port uint32, state uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530835 if d.State != DeviceStateUP && !util.IsNniPort(port) {
836 logger.Warnw(ctx, "Ignore Port State Processing - Device not UP", log.Fields{"Device": d.ID, "Port": port, "DeviceState": d.State})
837 return
838 }
839 if p := d.GetPortByID(port); p != nil {
840 logger.Infow(ctx, "Port State Processing after Reboot", log.Fields{"Received": state, "Current": p.State})
841 p.Tasks.Initialize(d.ctx)
842 if p.State == PortStateUp {
843 logger.Infow(ctx, "Port State: UP", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530844 GetController().PortUpInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530845 } else if p.State == PortStateDown {
846 logger.Infow(ctx, "Port State: Down", log.Fields{"Device": d.ID, "Port": port})
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530847 GetController().PortDownInd(cntx, d.ID, p.Name)
Naveen Sampath04696f72022-06-13 15:19:14 +0530848 }
849 }
850}
851
852// ChangeEvent : Change event brings in ports related changes such as addition/deletion
853// or modification where the port status change up/down is indicated to the
854// controller
855func (d *Device) ChangeEvent(event *ofp.ChangeEvent) error {
856 cet := NewChangeEventTask(d.ctx, event, d)
857 d.AddTask(cet)
858 return nil
859}
860
861// PacketIn handle the incoming packet-in and deliver to the application for the
862// actual processing
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530863func (d *Device) PacketIn(cntx context.Context, pkt *ofp.PacketIn) {
Naveen Sampath04696f72022-06-13 15:19:14 +0530864 logger.Debugw(ctx, "Received a Packet-In", log.Fields{"Device": d.ID})
865 if pkt.PacketIn.Reason != ofp.OfpPacketInReason_OFPR_ACTION {
866 logger.Warnw(ctx, "Unsupported PacketIn Reason", log.Fields{"Reason": pkt.PacketIn.Reason})
867 return
868 }
869 data := pkt.PacketIn.Data
870 port := PacketInGetPort(pkt.PacketIn)
871 if pName, err := d.GetPortName(port); err == nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +0530872 GetController().PacketInInd(cntx, d.ID, pName, data)
Naveen Sampath04696f72022-06-13 15:19:14 +0530873 } else {
874 logger.Warnw(ctx, "Unknown Port", log.Fields{"Reason": err.Error()})
875 }
876}
877
878// PacketInGetPort to get the port on which the packet-in is reported
879func PacketInGetPort(pkt *ofp.OfpPacketIn) uint32 {
880 for _, field := range pkt.Match.OxmFields {
881 if field.OxmClass == ofp.OfpOxmClass_OFPXMC_OPENFLOW_BASIC {
882 if ofbField, ok := field.Field.(*ofp.OfpOxmField_OfbField); ok {
883 if ofbField.OfbField.Type == ofp.OxmOfbFieldTypes_OFPXMT_OFB_IN_PORT {
884 if port, ok := ofbField.OfbField.Value.(*ofp.OfpOxmOfbField_Port); ok {
885 return port.Port
886 }
887 }
888 }
889 }
890 }
891 return 0
892}
893
894// PacketOutReq receives the packet out request from the application via the
895// controller. The interface from the application uses name as the identity.
896func (d *Device) PacketOutReq(outport string, inport string, data []byte, isCustomPkt bool) error {
897 inp, err := d.GetPortID(inport)
898 if err != nil {
899 return errors.New("Unknown inport")
900 }
901 outp, err1 := d.GetPortID(outport)
902 if err1 != nil {
903 return errors.New("Unknown outport")
904 }
905 logger.Debugw(ctx, "Sending packet out", log.Fields{"Device": d.ID, "Inport": inport, "Outport": outport})
906 return d.SendPacketOut(outp, inp, data, isCustomPkt)
907}
908
909// SendPacketOut is responsible for building the OF structure and send the
910// packet-out to the VOLTHA
911func (d *Device) SendPacketOut(outport uint32, inport uint32, data []byte, isCustomPkt bool) error {
912 pout := &ofp.PacketOut{}
913 pout.Id = d.ID
914 opout := &ofp.OfpPacketOut{}
915 pout.PacketOut = opout
916 opout.InPort = inport
917 opout.Data = data
918 opout.Actions = []*ofp.OfpAction{
919 {
920 Type: ofp.OfpActionType_OFPAT_OUTPUT,
921 Action: &ofp.OfpAction_Output{
922 Output: &ofp.OfpActionOutput{
923 Port: outport,
924 MaxLen: 65535,
925 },
926 },
927 },
928 }
929 d.packetOutChannel <- pout
930 return nil
931}
932
933// UpdateFlows receives the flows in the form that is implemented
934// in the VGC and transforms them to the OF format. This is handled
935// as a port of the task that is enqueued to do the same.
936func (d *Device) UpdateFlows(flow *of.VoltFlow, devPort *DevicePort) {
937 t := NewAddFlowsTask(d.ctx, flow, d)
938 logger.Debugw(ctx, "Port Context", log.Fields{"Ctx": devPort.GetContext()})
939 // check if port isNni , if yes flows will be added to device port queues.
940 if util.IsNniPort(devPort.ID) {
941 // Adding the flows to device port queues.
942 devPort.AddTask(t)
943 return
944 }
945 // If the flowHash is enabled then add the flows to the flowhash generated queues.
946 flowQueue := d.getAndAddFlowQueueForUniID(uint32(devPort.ID))
947 if flowQueue != nil {
948 logger.Debugw(ctx, "flowHashQId", log.Fields{"uniid": devPort.ID, "flowhash": flowQueue.ID})
949 flowQueue.AddTask(t)
950 logger.Debugw(ctx, "Tasks Info", log.Fields{"uniid": devPort.ID, "flowhash": flowQueue.ID, "Total": flowQueue.TotalTasks(), "Pending": flowQueue.NumPendingTasks()})
951 } else {
952 //FlowThrotling disabled, add to the device port queue
953 devPort.AddTask(t)
954 return
955 }
956}
957
958// UpdateGroup to update group info
959func (d *Device) UpdateGroup(group *of.Group, devPort *DevicePort) {
960 task := NewModGroupTask(d.ctx, group, d)
961 logger.Debugw(ctx, "NNI Port Context", log.Fields{"Ctx": devPort.GetContext()})
962 devPort.AddTask(task)
963}
964
965// ModMeter for mod meter task
966func (d *Device) ModMeter(command of.MeterCommand, meter *of.Meter, devPort *DevicePort) {
967 if command == of.MeterCommandAdd {
968 if _, err := d.GetMeter(meter.ID); err == nil {
969 logger.Debugw(ctx, "Meter already added", log.Fields{"ID": meter.ID})
970 return
971 }
972 }
973 t := NewModMeterTask(d.ctx, command, meter, d)
974 devPort.AddTask(t)
975}
976
977func (d *Device) getAndAddFlowQueueForUniID(id uint32) *UniIDFlowQueue {
978 d.flowQueueLock.RLock()
979 //If flowhash is 0 that means flowhash throttling is disabled, return nil
980 if d.flowHash == 0 {
981 d.flowQueueLock.RUnlock()
982 return nil
983 }
984 flowHashID := id % uint32(d.flowHash)
985 if value, found := d.flowQueue[uint32(flowHashID)]; found {
986 d.flowQueueLock.RUnlock()
987 return value
988 }
989 d.flowQueueLock.RUnlock()
990 logger.Debugw(ctx, "Flow queue not found creating one", log.Fields{"uniid": id, "hash": flowHashID})
991
992 return d.addFlowQueueForUniID(id)
993}
994
995func (d *Device) addFlowQueueForUniID(id uint32) *UniIDFlowQueue {
996
997 d.flowQueueLock.Lock()
998 defer d.flowQueueLock.Unlock()
999 flowHashID := id % uint32(d.flowHash)
1000 flowQueue := NewUniIDFlowQueue(uint32(flowHashID))
1001 flowQueue.Tasks.Initialize(d.ctx)
1002 d.flowQueue[flowHashID] = flowQueue
1003 return flowQueue
1004}
1005
1006// SetFlowHash sets the device flow hash and writes to the DB.
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301007func (d *Device) SetFlowHash(cntx context.Context, hash uint32) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301008 d.flowQueueLock.Lock()
1009 defer d.flowQueueLock.Unlock()
1010
1011 d.flowHash = hash
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301012 d.writeFlowHashToDB(cntx)
Naveen Sampath04696f72022-06-13 15:19:14 +05301013}
1014
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301015func (d *Device) writeFlowHashToDB(cntx context.Context) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301016 hash, err := json.Marshal(d.flowHash)
1017 if err != nil {
1018 logger.Errorw(ctx, "failed to marshal flow hash", log.Fields{"hash": d.flowHash})
1019 return
1020 }
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301021 if err := db.PutFlowHash(cntx, d.ID, string(hash)); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +05301022 logger.Errorw(ctx, "Failed to add flow hash to DB", log.Fields{"device": d.ID, "hash": d.flowHash})
1023 }
1024}
1025
1026//isSBOperAllowed - determins if the SB operation is allowed based on device state & force flag
1027func (d *Device) isSBOperAllowed(forceAction bool) bool {
1028
1029 if d.State == DeviceStateUP {
1030 return true
1031 }
1032
1033 if d.State == DeviceStateDISABLED && forceAction {
1034 return true
1035 }
1036
1037 return false
1038}
1039
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301040func (d *Device) triggerFlowNotification(cntx context.Context, cookie uint64, oper of.Command, bwDetails of.BwAvailDetails, err error) {
Naveen Sampath04696f72022-06-13 15:19:14 +05301041 flow, _ := d.GetFlow(cookie)
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301042 d.triggerFlowResultNotification(cntx, cookie, flow, oper, bwDetails, err)
Naveen Sampath04696f72022-06-13 15:19:14 +05301043}
1044
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301045func (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 +05301046
1047 statusCode, statusMsg := infraerror.GetErrorInfo(err)
1048 success := isFlowOperSuccess(statusCode, oper)
1049
1050 updateFlow := func(cookie uint64, state int, reason string) {
1051 if dbFlow, ok := d.GetFlow(cookie); ok {
1052 dbFlow.State = uint8(state)
1053 dbFlow.ErrorReason = reason
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301054 d.AddFlowToDb(cntx, dbFlow)
Naveen Sampath04696f72022-06-13 15:19:14 +05301055 }
1056 }
1057
1058 //Update flow results
1059 // Add - Update Success or Failure status with reason
1060 // Del - Delete entry from DB on success else update error reason
1061 if oper == of.CommandAdd {
1062 state := of.FlowAddSuccess
1063 reason := ""
1064 if !success {
1065 state = of.FlowAddFailure
1066 reason = statusMsg
1067 }
1068 updateFlow(cookie, state, reason)
1069 logger.Debugw(ctx, "Updated Flow to DB", log.Fields{"Cookie": cookie, "State": state})
1070 } else {
1071 if success && flow != nil {
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301072 if err := d.DelFlow(cntx, flow); err != nil {
Naveen Sampath04696f72022-06-13 15:19:14 +05301073 logger.Warnw(ctx, "Delete Flow Error", log.Fields{"Cookie": flow.Cookie, "Reason": err.Error()})
1074 }
1075 } else if !success {
1076 updateFlow(cookie, of.FlowDelFailure, statusMsg)
1077 }
1078 }
1079
1080 flowResult := intf.FlowStatus{
1081 Cookie: strconv.FormatUint(cookie, 10),
1082 Device: d.ID,
1083 FlowModType: oper,
1084 Flow: flow,
1085 Status: statusCode,
1086 Reason: statusMsg,
1087 AdditionalData: bwDetails,
1088 }
1089
1090 logger.Infow(ctx, "Sending Flow Notification", log.Fields{"Cookie": cookie, "Error Code": statusCode, "FlowOp": oper})
Tinoj Joseph07cc5372022-07-18 22:53:51 +05301091 GetController().ProcessFlowModResultIndication(cntx, flowResult)
Naveen Sampath04696f72022-06-13 15:19:14 +05301092}