blob: 8d391eb51d3da95ea7c1177c148a564723ab4e78 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
2 * Copyright 2019-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package techprofile
18
19import (
20 "encoding/json"
21 "errors"
22 "fmt"
Girish Gowdra9447baf2019-11-05 16:42:37 +053023 "regexp"
Scott Baker2c1c4822019-10-16 11:02:41 -070024 "strconv"
25
sbarbari1e3e29c2019-11-05 10:06:50 -050026 "github.com/opencord/voltha-lib-go/v2/pkg/db"
Scott Bakerce767002019-10-23 13:30:24 -070027 "github.com/opencord/voltha-lib-go/v2/pkg/db/kvstore"
Scott Bakerce767002019-10-23 13:30:24 -070028 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Bakerf1b096c2019-11-01 12:36:30 -070029 tp_pb "github.com/opencord/voltha-protos/v2/go/tech_profile"
Scott Baker2c1c4822019-10-16 11:02:41 -070030)
31
32// Interface to pon resource manager APIs
33type iPonResourceMgr interface {
34 GetResourceID(IntfID uint32, ResourceType string, NumIDs uint32) ([]uint32, error)
35 GetResourceTypeAllocID() string
36 GetResourceTypeGemPortID() string
37 GetTechnology() string
38}
39
40type Direction int32
41
42const (
43 Direction_UPSTREAM Direction = 0
44 Direction_DOWNSTREAM Direction = 1
45 Direction_BIDIRECTIONAL Direction = 2
46)
47
48var Direction_name = map[Direction]string{
49 0: "UPSTREAM",
50 1: "DOWNSTREAM",
51 2: "BIDIRECTIONAL",
52}
53
54type SchedulingPolicy int32
55
56const (
57 SchedulingPolicy_WRR SchedulingPolicy = 0
58 SchedulingPolicy_StrictPriority SchedulingPolicy = 1
59 SchedulingPolicy_Hybrid SchedulingPolicy = 2
60)
61
62var SchedulingPolicy_name = map[SchedulingPolicy]string{
63 0: "WRR",
64 1: "StrictPriority",
65 2: "Hybrid",
66}
67
68type AdditionalBW int32
69
70const (
71 AdditionalBW_AdditionalBW_None AdditionalBW = 0
72 AdditionalBW_AdditionalBW_NA AdditionalBW = 1
73 AdditionalBW_AdditionalBW_BestEffort AdditionalBW = 2
74 AdditionalBW_AdditionalBW_Auto AdditionalBW = 3
75)
76
77var AdditionalBW_name = map[AdditionalBW]string{
78 0: "AdditionalBW_None",
79 1: "AdditionalBW_NA",
80 2: "AdditionalBW_BestEffort",
81 3: "AdditionalBW_Auto",
82}
83
84type DiscardPolicy int32
85
86const (
87 DiscardPolicy_TailDrop DiscardPolicy = 0
88 DiscardPolicy_WTailDrop DiscardPolicy = 1
89 DiscardPolicy_Red DiscardPolicy = 2
90 DiscardPolicy_WRed DiscardPolicy = 3
91)
92
93var DiscardPolicy_name = map[DiscardPolicy]string{
94 0: "TailDrop",
95 1: "WTailDrop",
96 2: "Red",
97 3: "WRed",
98}
99
Girish Gowdra9447baf2019-11-05 16:42:37 +0530100// Required uniPortName format
101var uniPortNameFormat = regexp.MustCompile(`^pon-{[0-9]+}/onu-{[0-9]+}/uni-{[0-9]+}$`)
102
Scott Baker2c1c4822019-10-16 11:02:41 -0700103/*
104type InferredAdditionBWIndication int32
105
106const (
107 InferredAdditionBWIndication_InferredAdditionBWIndication_None InferredAdditionBWIndication = 0
108 InferredAdditionBWIndication_InferredAdditionBWIndication_Assured InferredAdditionBWIndication = 1
109 InferredAdditionBWIndication_InferredAdditionBWIndication_BestEffort InferredAdditionBWIndication = 2
110)
111
112var InferredAdditionBWIndication_name = map[int32]string{
113 0: "InferredAdditionBWIndication_None",
114 1: "InferredAdditionBWIndication_Assured",
115 2: "InferredAdditionBWIndication_BestEffort",
116}
117*/
118// instance control defaults
119const (
120 defaultOnuInstance = "multi-instance"
121 defaultUniInstance = "single-instance"
122 defaultNumGemPorts = 1
123 defaultGemPayloadSize = "auto"
124)
125
126const MAX_GEM_PAYLOAD = "max_gem_payload_size"
127
128type InstanceControl struct {
129 Onu string `json:"ONU"`
130 Uni string `json:"uni"`
131 MaxGemPayloadSize string `json:"max_gem_payload_size"`
132}
133
134// default discard config constants
135const (
136 defaultMinThreshold = 0
137 defaultMaxThreshold = 0
138 defaultMaxProbability = 0
139)
140
141type DiscardConfig struct {
142 MinThreshold int `json:"min_threshold"`
143 MaxThreshold int `json:"max_threshold"`
144 MaxProbability int `json:"max_probability"`
145}
146
147// default scheduler contants
148const (
149 defaultAdditionalBw = AdditionalBW_AdditionalBW_BestEffort
150 defaultPriority = 0
151 defaultWeight = 0
152 defaultQueueSchedPolicy = SchedulingPolicy_Hybrid
153)
154
155type Scheduler struct {
156 Direction string `json:"direction"`
157 AdditionalBw string `json:"additional_bw"`
158 Priority uint32 `json:"priority"`
159 Weight uint32 `json:"weight"`
160 QSchedPolicy string `json:"q_sched_policy"`
161}
162
163// default GEM attribute constants
164const (
165 defaultAESEncryption = "True"
166 defaultPriorityQueue = 0
167 defaultQueueWeight = 0
168 defaultMaxQueueSize = "auto"
169 defaultdropPolicy = DiscardPolicy_TailDrop
170 defaultSchedulePolicy = SchedulingPolicy_WRR
171)
172
173type GemPortAttribute struct {
174 MaxQueueSize string `json:"max_q_size"`
175 PbitMap string `json:"pbit_map"`
176 AesEncryption string `json:"aes_encryption"`
177 SchedulingPolicy string `json:"scheduling_policy"`
178 PriorityQueue uint32 `json:"priority_q"`
179 Weight uint32 `json:"weight"`
180 DiscardPolicy string `json:"discard_policy"`
181 DiscardConfig DiscardConfig `json:"discard_config"`
182}
183
184type iScheduler struct {
185 AllocID uint32 `json:"alloc_id"`
186 Direction string `json:"direction"`
187 AdditionalBw string `json:"additional_bw"`
188 Priority uint32 `json:"priority"`
189 Weight uint32 `json:"weight"`
190 QSchedPolicy string `json:"q_sched_policy"`
191}
192type iGemPortAttribute struct {
193 GemportID uint32 `json:"gemport_id"`
194 MaxQueueSize string `json:"max_q_size"`
195 PbitMap string `json:"pbit_map"`
196 AesEncryption string `json:"aes_encryption"`
197 SchedulingPolicy string `json:"scheduling_policy"`
198 PriorityQueue uint32 `json:"priority_q"`
199 Weight uint32 `json:"weight"`
200 DiscardPolicy string `json:"discard_policy"`
201 DiscardConfig DiscardConfig `json:"discard_config"`
202}
203
204type TechProfileMgr struct {
205 config *TechProfileFlags
206 resourceMgr iPonResourceMgr
207}
208type DefaultTechProfile struct {
209 Name string `json:"name"`
210 ProfileType string `json:"profile_type"`
211 Version int `json:"version"`
212 NumGemPorts uint32 `json:"num_gem_ports"`
213 InstanceCtrl InstanceControl `json:"instance_control"`
214 UsScheduler Scheduler `json:"us_scheduler"`
215 DsScheduler Scheduler `json:"ds_scheduler"`
216 UpstreamGemPortAttributeList []GemPortAttribute `json:"upstream_gem_port_attribute_list"`
217 DownstreamGemPortAttributeList []GemPortAttribute `json:"downstream_gem_port_attribute_list"`
218}
219type TechProfile struct {
220 Name string `json:"name"`
221 SubscriberIdentifier string `json:"subscriber_identifier"`
222 ProfileType string `json:"profile_type"`
223 Version int `json:"version"`
224 NumGemPorts uint32 `json:"num_gem_ports"`
Scott Baker2c1c4822019-10-16 11:02:41 -0700225 InstanceCtrl InstanceControl `json:"instance_control"`
226 UsScheduler iScheduler `json:"us_scheduler"`
227 DsScheduler iScheduler `json:"ds_scheduler"`
228 UpstreamGemPortAttributeList []iGemPortAttribute `json:"upstream_gem_port_attribute_list"`
229 DownstreamGemPortAttributeList []iGemPortAttribute `json:"downstream_gem_port_attribute_list"`
230}
231
sbarbari1e3e29c2019-11-05 10:06:50 -0500232func (t *TechProfileMgr) SetKVClient() *db.Backend {
Scott Baker2c1c4822019-10-16 11:02:41 -0700233 addr := t.config.KVStoreHost + ":" + strconv.Itoa(t.config.KVStorePort)
234 kvClient, err := newKVClient(t.config.KVStoreType, addr, t.config.KVStoreTimeout)
235 if err != nil {
236 log.Errorw("failed-to-create-kv-client",
237 log.Fields{
238 "type": t.config.KVStoreType, "host": t.config.KVStoreHost, "port": t.config.KVStorePort,
239 "timeout": t.config.KVStoreTimeout, "prefix": t.config.TPKVPathPrefix,
240 "error": err.Error(),
241 })
242 return nil
243 }
sbarbari1e3e29c2019-11-05 10:06:50 -0500244 return &db.Backend{
Scott Baker2c1c4822019-10-16 11:02:41 -0700245 Client: kvClient,
246 StoreType: t.config.KVStoreType,
247 Host: t.config.KVStoreHost,
248 Port: t.config.KVStorePort,
249 Timeout: t.config.KVStoreTimeout,
250 PathPrefix: t.config.TPKVPathPrefix}
251
252 /* TODO : Make sure direct call to NewBackend is working fine with backend , currently there is some
253 issue between kv store and backend , core is not calling NewBackend directly
254 kv := model.NewBackend(t.config.KVStoreType, t.config.KVStoreHost, t.config.KVStorePort,
255 t.config.KVStoreTimeout, kvStoreTechProfilePathPrefix)
256 */
257}
258
259func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
260
261 log.Infow("kv-store", log.Fields{"storeType": storeType, "address": address})
262 switch storeType {
263 case "consul":
264 return kvstore.NewConsulClient(address, timeout)
265 case "etcd":
266 return kvstore.NewEtcdClient(address, timeout)
267 }
268 return nil, errors.New("unsupported-kv-store")
269}
270
271func NewTechProfile(resourceMgr iPonResourceMgr, KVStoreType string, KVStoreHost string, KVStorePort int) (*TechProfileMgr, error) {
272 var techprofileObj TechProfileMgr
273 log.Debug("Initializing techprofile Manager")
274 techprofileObj.config = NewTechProfileFlags(KVStoreType, KVStoreHost, KVStorePort)
275 techprofileObj.config.KVBackend = techprofileObj.SetKVClient()
276 if techprofileObj.config.KVBackend == nil {
277 log.Error("Failed to initialize KV backend\n")
278 return nil, errors.New("KV backend init failed")
279 }
280 techprofileObj.resourceMgr = resourceMgr
281 log.Debug("Initializing techprofile object instance success")
282 return &techprofileObj, nil
283}
284
285func (t *TechProfileMgr) GetTechProfileInstanceKVPath(techProfiletblID uint32, uniPortName string) string {
286 return fmt.Sprintf(t.config.TPInstanceKVPath, t.resourceMgr.GetTechnology(), techProfiletblID, uniPortName)
287}
288
289func (t *TechProfileMgr) GetTPInstanceFromKVStore(techProfiletblID uint32, path string) (*TechProfile, error) {
290 var KvTpIns TechProfile
291 var resPtr *TechProfile = &KvTpIns
292 var err error
Girish Gowdra9447baf2019-11-05 16:42:37 +0530293 var tp *DefaultTechProfile = nil
294 var kvResult *kvstore.KVPair
295 if tp = t.getTPFromKVStore(techProfiletblID); tp != nil {
296 if err := t.validateInstanceControlAttr(tp.InstanceCtrl); err != nil {
297 return nil, errors.New("invalid-instance-ctl-attr")
298 }
299 } else {
300 return nil, errors.New("tp-not-found-on-kv-store")
301 }
302 if tp.InstanceCtrl.Onu == "multi-instance" {
303 // When InstanceCtrl.Onu is "multi-instance" there can be multiple instance of the same
304 // TP across different UNIs. We either find a pre-existing TP Instance on that UNI or
305 // create a new one.
306 log.Infow("Getting tech profile instance from KV store", log.Fields{"path": path})
307 kvResult, err = t.config.KVBackend.Get(path)
308 } else { // "single-instance"
309 // When InstanceCtrl.Onu is "single-instance" there can be only one instance of the
310 // TP across all UNIs. The TP instances for the given TP ID will have the same alloc_id,
311 // but different gemport-ids (per UNI).
312 // We do the following
313 // 1. Find a pre-existing TP Instance for the given TP ID and on the given UNI.
314 // If exists, return, else step 2.
315 // 2. Find TP instance for the given TP ID and on any other UNI on that ONU.
316 // If exists, make a copy of the TP instance, replace the gem-port IDs, place it
317 // in the the current UNIs TP instance path.
318 // If no other UNI have TP instance too, then return nil (a new TP instance will
319 // get created for the given TP ID).
320 kvResult, err = t.config.KVBackend.Get(path)
321 if kvResult == nil {
322 if resPtr, err = t.findAndAssignTpInstance(path); resPtr != nil {
323 log.Infow("successfully-found-and-assigned-tp-instance", log.Fields{"tpPath": path})
324 return resPtr, err
325 }
326 }
327 }
328
Scott Baker2c1c4822019-10-16 11:02:41 -0700329 if err != nil {
330 log.Errorw("Error while fetching tech-profile instance from KV backend", log.Fields{"key": path})
331 return nil, err
332 }
Girish Gowdra9447baf2019-11-05 16:42:37 +0530333 if kvResult == nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700334 log.Infow("Tech profile does not exist in KV store", log.Fields{"key": path})
335 resPtr = nil
336 } else {
Girish Gowdra9447baf2019-11-05 16:42:37 +0530337 if value, err := kvstore.ToByte(kvResult.Value); err == nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700338 if err = json.Unmarshal(value, resPtr); err != nil {
339 log.Errorw("Error while unmarshal KV result", log.Fields{"key": path, "value": value})
340 }
341 }
342 }
343 return resPtr, err
344}
345
346func (t *TechProfileMgr) addTechProfInstanceToKVStore(techProfiletblID uint32, uniPortName string, tpInstance *TechProfile) error {
347 path := t.GetTechProfileInstanceKVPath(techProfiletblID, uniPortName)
348 log.Debugw("Adding techprof instance to kvstore", log.Fields{"key": path, "tpinstance": tpInstance})
349 tpInstanceJson, err := json.Marshal(*tpInstance)
350 if err == nil {
351 // Backend will convert JSON byte array into string format
352 log.Debugw("Storing tech profile instance to KV Store", log.Fields{"key": path, "val": tpInstanceJson})
353 err = t.config.KVBackend.Put(path, tpInstanceJson)
354 } else {
355 log.Errorw("Error in marshaling into Json format", log.Fields{"key": path, "tpinstance": tpInstance})
356 }
357 return err
358}
359func (t *TechProfileMgr) getTPFromKVStore(techProfiletblID uint32) *DefaultTechProfile {
360 var kvtechprofile DefaultTechProfile
361 key := fmt.Sprintf(t.config.TPFileKVPath, t.resourceMgr.GetTechnology(), techProfiletblID)
362 log.Debugw("Getting techprofile from KV store", log.Fields{"techProfiletblID": techProfiletblID, "Key": key})
363 kvresult, err := t.config.KVBackend.Get(key)
364 if err != nil {
365 log.Errorw("Error while fetching value from KV store", log.Fields{"key": key})
366 return nil
367 }
368 if kvresult != nil {
369 /* Backend will return Value in string format,needs to be converted to []byte before unmarshal*/
370 if value, err := kvstore.ToByte(kvresult.Value); err == nil {
371 if err = json.Unmarshal(value, &kvtechprofile); err == nil {
372 log.Debugw("Success fetched techprofile from KV store", log.Fields{"techProfiletblID": techProfiletblID, "value": kvtechprofile})
373 return &kvtechprofile
374 }
375 }
376 }
377 return nil
378}
379func (t *TechProfileMgr) CreateTechProfInstance(techProfiletblID uint32, uniPortName string, intfId uint32) *TechProfile {
380 var tpInstance *TechProfile
381 log.Infow("Creating tech profile instance ", log.Fields{"tableid": techProfiletblID, "uni": uniPortName, "intId": intfId})
Girish Gowdra9447baf2019-11-05 16:42:37 +0530382
383 // Make sure the uniPortName is as per format pon-{[0-9]+}/onu-{[0-9]+}/uni-{[0-9]+}
384 if !uniPortNameFormat.Match([]byte(uniPortName)) {
385 log.Errorw("uni-port-name-not-confirming-to-format", log.Fields{"uniPortName": uniPortName})
386 return nil
387 }
388
Scott Baker2c1c4822019-10-16 11:02:41 -0700389 tp := t.getTPFromKVStore(techProfiletblID)
390 if tp != nil {
391 log.Infow("Creating tech profile instance with profile from KV store", log.Fields{"tpid": techProfiletblID})
392 } else {
393 tp = t.getDefaultTechProfile()
394 log.Infow("Creating tech profile instance with default values", log.Fields{"tpid": techProfiletblID})
395 }
Girish Gowdra9447baf2019-11-05 16:42:37 +0530396 tpInstance = t.allocateTPInstance(uniPortName, tp, intfId)
Scott Baker2c1c4822019-10-16 11:02:41 -0700397 if err := t.addTechProfInstanceToKVStore(techProfiletblID, uniPortName, tpInstance); err != nil {
398 log.Errorw("Error in adding tech profile instance to KV ", log.Fields{"tableid": techProfiletblID, "uni": uniPortName})
399 return nil
400 }
401 log.Infow("Added tech profile instance to KV store successfully ",
402 log.Fields{"tpid": techProfiletblID, "uni": uniPortName, "intfId": intfId})
403 return tpInstance
404}
405
406func (t *TechProfileMgr) DeleteTechProfileInstance(techProfiletblID uint32, uniPortName string) error {
407 path := t.GetTechProfileInstanceKVPath(techProfiletblID, uniPortName)
408 return t.config.KVBackend.Delete(path)
409}
410
Girish Gowdra9447baf2019-11-05 16:42:37 +0530411func (t *TechProfileMgr) validateInstanceControlAttr(instCtl InstanceControl) error {
412 if instCtl.Onu != "single-instance" && instCtl.Onu != "multi-instance" {
413 log.Errorw("invalid-onu-instance-control-attribute", log.Fields{"onu-inst": instCtl.Onu})
414 return errors.New("invalid-onu-instance-ctl-attr")
415 }
416
417 if instCtl.Uni != "single-instance" && instCtl.Uni != "multi-instance" {
418 log.Errorw("invalid-uni-instance-control-attribute", log.Fields{"uni-inst": instCtl.Uni})
419 return errors.New("invalid-uni-instance-ctl-attr")
420 }
421
422 if instCtl.Uni == "multi-instance" {
423 log.Error("uni-multi-instance-tp-not-supported")
424 return errors.New("uni-multi-instance-tp-not-supported")
425 }
426
427 return nil
428}
429
430func (t *TechProfileMgr) allocateTPInstance(uniPortName string, tp *DefaultTechProfile, intfId uint32) *TechProfile {
Scott Baker2c1c4822019-10-16 11:02:41 -0700431
432 var usGemPortAttributeList []iGemPortAttribute
433 var dsGemPortAttributeList []iGemPortAttribute
434 var tcontIDs []uint32
435 var gemPorts []uint32
436 var err error
437
Girish Gowdra9447baf2019-11-05 16:42:37 +0530438 log.Infow("Allocating TechProfileMgr instance from techprofile template", log.Fields{"uniPortName": uniPortName, "intfId": intfId, "numGem": tp.NumGemPorts})
439
440 err = t.validateInstanceControlAttr(tp.InstanceCtrl)
441 if err != nil {
442 log.Error("invalid-tp-instance-control-attributes")
Scott Baker2c1c4822019-10-16 11:02:41 -0700443 return nil
444 }
Girish Gowdra9447baf2019-11-05 16:42:37 +0530445
446 if tcontIDs, err = t.resourceMgr.GetResourceID(intfId, t.resourceMgr.GetResourceTypeAllocID(), 1); err != nil {
447 log.Errorw("Error getting alloc id from rsrcrMgr", log.Fields{"intfId": intfId})
Scott Baker2c1c4822019-10-16 11:02:41 -0700448 return nil
449 }
450 log.Debugw("Num GEM ports in TP:", log.Fields{"NumGemPorts": tp.NumGemPorts})
451 if gemPorts, err = t.resourceMgr.GetResourceID(intfId, t.resourceMgr.GetResourceTypeGemPortID(), tp.NumGemPorts); err != nil {
452 log.Errorw("Error getting gemport ids from rsrcrMgr", log.Fields{"intfId": intfId, "numGemports": tp.NumGemPorts})
453 return nil
454 }
455 log.Infow("Allocated tconts and GEM ports successfully", log.Fields{"tconts": tcontIDs, "gemports": gemPorts})
456 for index := 0; index < int(tp.NumGemPorts); index++ {
457 usGemPortAttributeList = append(usGemPortAttributeList,
458 iGemPortAttribute{GemportID: gemPorts[index],
459 MaxQueueSize: tp.UpstreamGemPortAttributeList[index].MaxQueueSize,
460 PbitMap: tp.UpstreamGemPortAttributeList[index].PbitMap,
461 AesEncryption: tp.UpstreamGemPortAttributeList[index].AesEncryption,
462 SchedulingPolicy: tp.UpstreamGemPortAttributeList[index].SchedulingPolicy,
463 PriorityQueue: tp.UpstreamGemPortAttributeList[index].PriorityQueue,
464 Weight: tp.UpstreamGemPortAttributeList[index].Weight,
465 DiscardPolicy: tp.UpstreamGemPortAttributeList[index].DiscardPolicy,
466 DiscardConfig: tp.UpstreamGemPortAttributeList[index].DiscardConfig})
467 dsGemPortAttributeList = append(dsGemPortAttributeList,
468 iGemPortAttribute{GemportID: gemPorts[index],
469 MaxQueueSize: tp.DownstreamGemPortAttributeList[index].MaxQueueSize,
470 PbitMap: tp.DownstreamGemPortAttributeList[index].PbitMap,
471 AesEncryption: tp.DownstreamGemPortAttributeList[index].AesEncryption,
472 SchedulingPolicy: tp.DownstreamGemPortAttributeList[index].SchedulingPolicy,
473 PriorityQueue: tp.DownstreamGemPortAttributeList[index].PriorityQueue,
474 Weight: tp.DownstreamGemPortAttributeList[index].Weight,
475 DiscardPolicy: tp.DownstreamGemPortAttributeList[index].DiscardPolicy,
476 DiscardConfig: tp.DownstreamGemPortAttributeList[index].DiscardConfig})
477 }
478 return &TechProfile{
479 SubscriberIdentifier: uniPortName,
480 Name: tp.Name,
481 ProfileType: tp.ProfileType,
482 Version: tp.Version,
483 NumGemPorts: tp.NumGemPorts,
Scott Baker2c1c4822019-10-16 11:02:41 -0700484 InstanceCtrl: tp.InstanceCtrl,
485 UsScheduler: iScheduler{
486 AllocID: tcontIDs[0],
487 Direction: tp.UsScheduler.Direction,
488 AdditionalBw: tp.UsScheduler.AdditionalBw,
489 Priority: tp.UsScheduler.Priority,
490 Weight: tp.UsScheduler.Weight,
491 QSchedPolicy: tp.UsScheduler.QSchedPolicy},
492 DsScheduler: iScheduler{
493 AllocID: tcontIDs[0],
494 Direction: tp.DsScheduler.Direction,
495 AdditionalBw: tp.DsScheduler.AdditionalBw,
496 Priority: tp.DsScheduler.Priority,
497 Weight: tp.DsScheduler.Weight,
498 QSchedPolicy: tp.DsScheduler.QSchedPolicy},
499 UpstreamGemPortAttributeList: usGemPortAttributeList,
500 DownstreamGemPortAttributeList: dsGemPortAttributeList}
501}
502
Girish Gowdra9447baf2019-11-05 16:42:37 +0530503// findAndAssignTpInstance finds out if there is another TpInstance for an ONU on a different
504// uni port for the same TP ID.
505// If it finds one:
506// 1. It will make a copy of the TpInstance
507// 2. Retain the AllocID
508// 3. Replace the GemPort IDs
509// 4. Copy the new TpInstance on the given tpPath
510// ** NOTE ** : This is to be used only when the instance control attribute is as below
511// uni: single-instance, onu: single-instance
512func (t *TechProfileMgr) findAndAssignTpInstance(tpPath string) (*TechProfile, error) {
513 var tpInst TechProfile
514 var foundValidTpInst = false
515 var gemPortIDs []uint32
516 var intfID uint64
517 var err error
518
519 // For example:
520 // tpPath like "service/voltha/technology_profiles/xgspon/64/pon-{0}/onu-{1}/uni-{1}"
521 // is broken into ["service/voltha/technology_profiles/xgspon/64/pon-{0}/onu-{1}" ""]
522 uniPathSlice := regexp.MustCompile(`/uni-{[0-9]+}$`).Split(tpPath, 2)
523 kvPairs, _ := t.config.KVBackend.List(uniPathSlice[0])
524
525 // Find the PON interface ID from the TP Path
526 var tpPathRgx = regexp.MustCompile(`pon-{([0-9]+)}`)
527 intfStrMatch := tpPathRgx.FindStringSubmatch(tpPath)
528 if intfStrMatch == nil {
529 log.Error("could-not-find-pon-intf-id-in-tp-path")
530 return nil, errors.New("could-not-find-pon-intf-id-in-tp-path")
531 } else {
532 if intfID, err = strconv.ParseUint(intfStrMatch[1], 10, 64); err != nil {
533 log.Errorw("error-converting-pon-intfid-str-to-unint", log.Fields{"intfIdStr": intfStrMatch[1]})
534 return nil, errors.New("error-converting-pon-intfid-str-to-unint")
535 }
536 }
537
538 // Find a valid TP Instance among all the UNIs of that ONU for the given TP ID
539 for keyPath, kvPair := range kvPairs {
540 if value, err := kvstore.ToByte(kvPair.Value); err == nil {
541 if err = json.Unmarshal(value, &tpInst); err != nil {
542 log.Errorw("error-unmarshal-kv-pair", log.Fields{"keyPath": keyPath, "value": value})
543 return nil, errors.New("error-unmarshal-kv-pair")
544 } else {
545 log.Debugw("found-valid-tp-instance-on-another-uni", log.Fields{"keyPath": keyPath})
546 foundValidTpInst = true
547 break
548 }
549 }
550 }
551 if foundValidTpInst {
552 // Get new GemPort IDs
553 if gemPortIDs, err = t.resourceMgr.GetResourceID(uint32(intfID), t.resourceMgr.GetResourceTypeGemPortID(), tpInst.NumGemPorts); err != nil {
554 log.Errorw("gem-port-assignment-failed", log.Fields{"intfId": intfID, "numGemports": tpInst.NumGemPorts})
555 return nil, errors.New("gem-port-assignment-failed")
556 }
557 // Update the new GemPort IDs to the TpInstance
558 for i := 0; i < int(tpInst.NumGemPorts); i++ {
559 tpInst.DownstreamGemPortAttributeList[i].GemportID = gemPortIDs[i]
560 tpInst.UpstreamGemPortAttributeList[i].GemportID = gemPortIDs[i]
561 }
562
563 tpInstanceJson, err := json.Marshal(tpInst)
564 if err == nil {
565 // Backend will convert JSON byte array into string format
566 log.Debugw("store-tp-instance", log.Fields{"tpPath": tpPath, "val": tpInstanceJson})
567 if err = t.config.KVBackend.Put(tpPath, tpInstanceJson); err != nil {
568 return nil, errors.New("error-store-instance-on-kv")
569 }
570 // We have succesfully placed the new TP Instance if we land here.
571 log.Debugw("successfully-placed-single-instance-tp-for-tp-path", log.Fields{"tpPath": tpPath})
572 return &tpInst, nil
573 } else {
574 log.Errorw("error-marshal-tp-to-json", log.Fields{"tpPath": tpPath, "tpInstance": tpInst})
575 return nil, errors.New("error-marshal-tp-to-json")
576 }
577 }
578 log.Debug("no-pre-existing-tp-instance-found-on-another-uni")
579 return nil, nil
580}
581
Scott Baker2c1c4822019-10-16 11:02:41 -0700582func (t *TechProfileMgr) getDefaultTechProfile() *DefaultTechProfile {
583
584 var usGemPortAttributeList []GemPortAttribute
585 var dsGemPortAttributeList []GemPortAttribute
586
587 for _, pbit := range t.config.DefaultPbits {
588 log.Debugw("Creating GEM port", log.Fields{"pbit": pbit})
589 usGemPortAttributeList = append(usGemPortAttributeList,
590 GemPortAttribute{
591 MaxQueueSize: defaultMaxQueueSize,
592 PbitMap: pbit,
593 AesEncryption: defaultAESEncryption,
594 SchedulingPolicy: SchedulingPolicy_name[defaultSchedulePolicy],
595 PriorityQueue: defaultPriorityQueue,
596 Weight: defaultQueueWeight,
597 DiscardPolicy: DiscardPolicy_name[defaultdropPolicy],
598 DiscardConfig: DiscardConfig{
599 MinThreshold: defaultMinThreshold,
600 MaxThreshold: defaultMaxThreshold,
601 MaxProbability: defaultMaxProbability}})
602 dsGemPortAttributeList = append(dsGemPortAttributeList,
603 GemPortAttribute{
604 MaxQueueSize: defaultMaxQueueSize,
605 PbitMap: pbit,
606 AesEncryption: defaultAESEncryption,
607 SchedulingPolicy: SchedulingPolicy_name[defaultSchedulePolicy],
608 PriorityQueue: defaultPriorityQueue,
609 Weight: defaultQueueWeight,
610 DiscardPolicy: DiscardPolicy_name[defaultdropPolicy],
611 DiscardConfig: DiscardConfig{
612 MinThreshold: defaultMinThreshold,
613 MaxThreshold: defaultMaxThreshold,
614 MaxProbability: defaultMaxProbability}})
615 }
616 return &DefaultTechProfile{
617 Name: t.config.DefaultTPName,
618 ProfileType: t.resourceMgr.GetTechnology(),
619 Version: t.config.TPVersion,
620 NumGemPorts: uint32(len(usGemPortAttributeList)),
621 InstanceCtrl: InstanceControl{
622 Onu: defaultOnuInstance,
623 Uni: defaultUniInstance,
624 MaxGemPayloadSize: defaultGemPayloadSize},
625 UsScheduler: Scheduler{
626 Direction: Direction_name[Direction_UPSTREAM],
627 AdditionalBw: AdditionalBW_name[defaultAdditionalBw],
628 Priority: defaultPriority,
629 Weight: defaultWeight,
630 QSchedPolicy: SchedulingPolicy_name[defaultQueueSchedPolicy]},
631 DsScheduler: Scheduler{
632 Direction: Direction_name[Direction_DOWNSTREAM],
633 AdditionalBw: AdditionalBW_name[defaultAdditionalBw],
634 Priority: defaultPriority,
635 Weight: defaultWeight,
636 QSchedPolicy: SchedulingPolicy_name[defaultQueueSchedPolicy]},
637 UpstreamGemPortAttributeList: usGemPortAttributeList,
638 DownstreamGemPortAttributeList: dsGemPortAttributeList}
639}
640
641func (t *TechProfileMgr) GetprotoBufParamValue(paramType string, paramKey string) int32 {
642 var result int32 = -1
643
644 if paramType == "direction" {
645 for key, val := range tp_pb.Direction_value {
646 if key == paramKey {
647 result = val
648 }
649 }
650 } else if paramType == "discard_policy" {
651 for key, val := range tp_pb.DiscardPolicy_value {
652 if key == paramKey {
653 result = val
654 }
655 }
656 } else if paramType == "sched_policy" {
657 for key, val := range tp_pb.SchedulingPolicy_value {
658 if key == paramKey {
659 log.Debugw("Got value in proto", log.Fields{"key": key, "value": val})
660 result = val
661 }
662 }
663 } else if paramType == "additional_bw" {
664 for key, val := range tp_pb.AdditionalBW_value {
665 if key == paramKey {
666 result = val
667 }
668 }
669 } else {
670 log.Error("Could not find proto parameter", log.Fields{"paramType": paramType, "key": paramKey})
671 return -1
672 }
673 log.Debugw("Got value in proto", log.Fields{"key": paramKey, "value": result})
674 return result
675}
676
677func (t *TechProfileMgr) GetUsScheduler(tpInstance *TechProfile) *tp_pb.SchedulerConfig {
678 dir := tp_pb.Direction(t.GetprotoBufParamValue("direction", tpInstance.UsScheduler.Direction))
679 if dir == -1 {
680 log.Fatal("Error in getting Proto for direction for upstream scheduler")
681 return nil
682 }
683 bw := tp_pb.AdditionalBW(t.GetprotoBufParamValue("additional_bw", tpInstance.UsScheduler.AdditionalBw))
684 if bw == -1 {
685 log.Fatal("Error in getting Proto for bandwidth for upstream scheduler")
686 return nil
687 }
688 policy := tp_pb.SchedulingPolicy(t.GetprotoBufParamValue("sched_policy", tpInstance.UsScheduler.QSchedPolicy))
689 if policy == -1 {
690 log.Fatal("Error in getting Proto for scheduling policy for upstream scheduler")
691 return nil
692 }
693 return &tp_pb.SchedulerConfig{
694 Direction: dir,
695 AdditionalBw: bw,
696 Priority: tpInstance.UsScheduler.Priority,
697 Weight: tpInstance.UsScheduler.Weight,
698 SchedPolicy: policy}
699}
700
701func (t *TechProfileMgr) GetDsScheduler(tpInstance *TechProfile) *tp_pb.SchedulerConfig {
702
703 dir := tp_pb.Direction(t.GetprotoBufParamValue("direction", tpInstance.DsScheduler.Direction))
704 if dir == -1 {
705 log.Fatal("Error in getting Proto for direction for downstream scheduler")
706 return nil
707 }
708 bw := tp_pb.AdditionalBW(t.GetprotoBufParamValue("additional_bw", tpInstance.DsScheduler.AdditionalBw))
709 if bw == -1 {
710 log.Fatal("Error in getting Proto for bandwidth for downstream scheduler")
711 return nil
712 }
713 policy := tp_pb.SchedulingPolicy(t.GetprotoBufParamValue("sched_policy", tpInstance.DsScheduler.QSchedPolicy))
714 if policy == -1 {
715 log.Fatal("Error in getting Proto for scheduling policy for downstream scheduler")
716 return nil
717 }
718
719 return &tp_pb.SchedulerConfig{
720 Direction: dir,
721 AdditionalBw: bw,
722 Priority: tpInstance.DsScheduler.Priority,
723 Weight: tpInstance.DsScheduler.Weight,
724 SchedPolicy: policy}
725}
726
727func (t *TechProfileMgr) GetTrafficScheduler(tpInstance *TechProfile, SchedCfg *tp_pb.SchedulerConfig,
728 ShapingCfg *tp_pb.TrafficShapingInfo) *tp_pb.TrafficScheduler {
729
730 tSched := &tp_pb.TrafficScheduler{
731 Direction: SchedCfg.Direction,
732 AllocId: tpInstance.UsScheduler.AllocID,
733 TrafficShapingInfo: ShapingCfg,
734 Scheduler: SchedCfg}
735
736 return tSched
737}
738
739func (tpm *TechProfileMgr) GetTrafficQueues(tp *TechProfile, Dir tp_pb.Direction) []*tp_pb.TrafficQueue {
740
741 var encryp bool
742 if Dir == tp_pb.Direction_UPSTREAM {
743 // upstream GEM ports
744 NumGemPorts := len(tp.UpstreamGemPortAttributeList)
745 GemPorts := make([]*tp_pb.TrafficQueue, 0)
746 for Count := 0; Count < NumGemPorts; Count++ {
747 if tp.UpstreamGemPortAttributeList[Count].AesEncryption == "True" {
748 encryp = true
749 } else {
750 encryp = false
751 }
752 GemPorts = append(GemPorts, &tp_pb.TrafficQueue{
753 Direction: tp_pb.Direction(tpm.GetprotoBufParamValue("direction", tp.UsScheduler.Direction)),
754 GemportId: tp.UpstreamGemPortAttributeList[Count].GemportID,
755 PbitMap: tp.UpstreamGemPortAttributeList[Count].PbitMap,
756 AesEncryption: encryp,
757 SchedPolicy: tp_pb.SchedulingPolicy(tpm.GetprotoBufParamValue("sched_policy", tp.UpstreamGemPortAttributeList[Count].SchedulingPolicy)),
758 Priority: tp.UpstreamGemPortAttributeList[Count].PriorityQueue,
759 Weight: tp.UpstreamGemPortAttributeList[Count].Weight,
760 DiscardPolicy: tp_pb.DiscardPolicy(tpm.GetprotoBufParamValue("discard_policy", tp.UpstreamGemPortAttributeList[Count].DiscardPolicy)),
761 })
762 }
763 log.Debugw("Upstream Traffic queue list ", log.Fields{"queuelist": GemPorts})
764 return GemPorts
765 } else if Dir == tp_pb.Direction_DOWNSTREAM {
766 //downstream GEM ports
767 NumGemPorts := len(tp.DownstreamGemPortAttributeList)
768 GemPorts := make([]*tp_pb.TrafficQueue, 0)
769 for Count := 0; Count < NumGemPorts; Count++ {
770 if tp.DownstreamGemPortAttributeList[Count].AesEncryption == "True" {
771 encryp = true
772 } else {
773 encryp = false
774 }
775 GemPorts = append(GemPorts, &tp_pb.TrafficQueue{
776 Direction: tp_pb.Direction(tpm.GetprotoBufParamValue("direction", tp.DsScheduler.Direction)),
777 GemportId: tp.DownstreamGemPortAttributeList[Count].GemportID,
778 PbitMap: tp.DownstreamGemPortAttributeList[Count].PbitMap,
779 AesEncryption: encryp,
780 SchedPolicy: tp_pb.SchedulingPolicy(tpm.GetprotoBufParamValue("sched_policy", tp.DownstreamGemPortAttributeList[Count].SchedulingPolicy)),
781 Priority: tp.DownstreamGemPortAttributeList[Count].PriorityQueue,
782 Weight: tp.DownstreamGemPortAttributeList[Count].Weight,
783 DiscardPolicy: tp_pb.DiscardPolicy(tpm.GetprotoBufParamValue("discard_policy", tp.DownstreamGemPortAttributeList[Count].DiscardPolicy)),
784 })
785 }
786 log.Debugw("Downstream Traffic queue list ", log.Fields{"queuelist": GemPorts})
787 return GemPorts
788 }
789 return nil
790}
791
792func (tpm *TechProfileMgr) GetUsTrafficScheduler(tp *TechProfile) *tp_pb.TrafficScheduler {
793 UsScheduler := tpm.GetUsScheduler(tp)
794
795 return &tp_pb.TrafficScheduler{Direction: UsScheduler.Direction,
796 AllocId: tp.UsScheduler.AllocID,
797 Scheduler: UsScheduler}
798}
799
800func (t *TechProfileMgr) GetGemportIDForPbit(tp *TechProfile, Dir tp_pb.Direction, pbit uint32) uint32 {
801 /*
802 Function to get the Gemport ID mapped to a pbit.
803 */
804 if Dir == tp_pb.Direction_UPSTREAM {
805 // upstream GEM ports
806 NumGemPorts := len(tp.UpstreamGemPortAttributeList)
807 for Count := 0; Count < NumGemPorts; Count++ {
808 NumPbitMaps := len(tp.UpstreamGemPortAttributeList[Count].PbitMap)
809 for ICount := 2; ICount < NumPbitMaps; ICount++ {
810 if p, err := strconv.Atoi(string(tp.UpstreamGemPortAttributeList[Count].PbitMap[ICount])); err == nil {
811 if uint32(ICount-2) == pbit && p == 1 { // Check this p-bit is set
812 log.Debugw("Found-US-GEMport-for-Pcp", log.Fields{"pbit": pbit, "GEMport": tp.UpstreamGemPortAttributeList[Count].GemportID})
813 return tp.UpstreamGemPortAttributeList[Count].GemportID
814 }
815 }
816 }
817 }
818 } else if Dir == tp_pb.Direction_DOWNSTREAM {
819 //downstream GEM ports
820 NumGemPorts := len(tp.DownstreamGemPortAttributeList)
821 for Count := 0; Count < NumGemPorts; Count++ {
822 NumPbitMaps := len(tp.DownstreamGemPortAttributeList[Count].PbitMap)
823 for ICount := 2; ICount < NumPbitMaps; ICount++ {
824 if p, err := strconv.Atoi(string(tp.DownstreamGemPortAttributeList[Count].PbitMap[ICount])); err == nil {
825 if uint32(ICount-2) == pbit && p == 1 { // Check this p-bit is set
826 log.Debugw("Found-DS-GEMport-for-Pcp", log.Fields{"pbit": pbit, "GEMport": tp.DownstreamGemPortAttributeList[Count].GemportID})
827 return tp.DownstreamGemPortAttributeList[Count].GemportID
828 }
829 }
830 }
831 }
832 }
833 log.Errorw("No-GemportId-Found-For-Pcp", log.Fields{"pcpVlan": pbit})
834 return 0
835}
Girish Gowdra9447baf2019-11-05 16:42:37 +0530836
837// FindAllTpInstances returns all TechProfile instances for a given TechProfile table-id, pon interface ID and onu ID.
838func (t *TechProfileMgr) FindAllTpInstances(techProfiletblID uint32, ponIntf uint32, onuID uint32) []TechProfile {
839 var tp TechProfile
840 onuTpInstancePath := fmt.Sprintf("%d/%s/pon-{%d}/onu-{%d}", techProfiletblID, t.resourceMgr.GetTechnology(), ponIntf, onuID)
841
842 if kvPairs, _ := t.config.KVBackend.List(onuTpInstancePath); kvPairs != nil {
843 tpInstances := make([]TechProfile, 0, len(kvPairs))
844 for kvPath, kvPair := range kvPairs {
845 if value, err := kvstore.ToByte(kvPair.Value); err == nil {
846 if err = json.Unmarshal(value, &tp); err != nil {
847 log.Errorw("error-unmarshal-kv-pair", log.Fields{"kvPath": kvPath, "value": value})
848 continue
849 } else {
850 tpInstances = append(tpInstances, tp)
851 }
852 }
853 }
854 return tpInstances
855 }
856 return nil
857}