blob: baff5756dd928c4909c5b2289f2b330a40caa313 [file] [log] [blame]
Takahiro Suzukid7bf8202020-12-17 20:21:59 +09001/*
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 ponresourcemanager
18
19import (
20 "context"
21 "encoding/base64"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "time"
26
27 bitmap "github.com/boljen/go-bitmap"
28 "github.com/opencord/voltha-lib-go/v3/pkg/db"
29 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
30 "github.com/opencord/voltha-lib-go/v3/pkg/log"
31 tp "github.com/opencord/voltha-lib-go/v3/pkg/techprofile"
32)
33
34const (
35 //Constants to identify resource pool
36 UNI_ID = "UNI_ID"
37 ONU_ID = "ONU_ID"
38 ALLOC_ID = "ALLOC_ID"
39 GEMPORT_ID = "GEMPORT_ID"
40 FLOW_ID = "FLOW_ID"
41
42 //Constants for passing command line arugments
43 OLT_MODEL_ARG = "--olt_model"
44 PATH_PREFIX = "service/voltha/resource_manager/{%s}"
45
46 /*The path under which configuration data is stored is defined as technology/device agnostic.
47 That means the path does not include any specific technology/device variable. Using technology/device
48 agnostic path also makes northbound applications, that need to write to this path,
49 technology/device agnostic.
50
51 Default kv client of PonResourceManager reads from/writes to PATH_PREFIX defined above.
52 That is why, an additional kv client (named KVStoreForConfig) is defined to read from the config path.
53 */
54 PATH_PREFIX_FOR_CONFIG = "service/voltha/resource_manager/config"
55 /*The resource ranges for a given device model should be placed
56 at 'resource_manager/<technology>/resource_ranges/<olt_model_type>'
57 path on the KV store.
58 If Resource Range parameters are to be read from the external KV store,
59 they are expected to be stored in the following format.
60 Note: All parameters are MANDATORY for now.
61 constants used as keys to reference the resource range parameters from
62 and external KV store.
63 */
64 UNI_ID_START_IDX = "uni_id_start"
65 UNI_ID_END_IDX = "uni_id_end"
66 ONU_ID_START_IDX = "onu_id_start"
67 ONU_ID_END_IDX = "onu_id_end"
68 ONU_ID_SHARED_IDX = "onu_id_shared"
69 ALLOC_ID_START_IDX = "alloc_id_start"
70 ALLOC_ID_END_IDX = "alloc_id_end"
71 ALLOC_ID_SHARED_IDX = "alloc_id_shared"
72 GEMPORT_ID_START_IDX = "gemport_id_start"
73 GEMPORT_ID_END_IDX = "gemport_id_end"
74 GEMPORT_ID_SHARED_IDX = "gemport_id_shared"
75 FLOW_ID_START_IDX = "flow_id_start"
76 FLOW_ID_END_IDX = "flow_id_end"
77 FLOW_ID_SHARED_IDX = "flow_id_shared"
78 NUM_OF_PON_PORT = "pon_ports"
79
80 /*
81 The KV store backend is initialized with a path prefix and we need to
82 provide only the suffix.
83 */
84 PON_RESOURCE_RANGE_CONFIG_PATH = "resource_ranges/%s"
85
86 //resource path suffix
87 //Path on the KV store for storing alloc id ranges and resource pool for a given interface
88 //Format: <device_id>/alloc_id_pool/<pon_intf_id>
89 ALLOC_ID_POOL_PATH = "{%s}/alloc_id_pool/{%d}"
90 //Path on the KV store for storing gemport id ranges and resource pool for a given interface
91 //Format: <device_id>/gemport_id_pool/<pon_intf_id>
92 GEMPORT_ID_POOL_PATH = "{%s}/gemport_id_pool/{%d}"
93 //Path on the KV store for storing onu id ranges and resource pool for a given interface
94 //Format: <device_id>/onu_id_pool/<pon_intf_id>
95 ONU_ID_POOL_PATH = "{%s}/onu_id_pool/{%d}"
96 //Path on the KV store for storing flow id ranges and resource pool for a given interface
97 //Format: <device_id>/flow_id_pool/<pon_intf_id>
98 FLOW_ID_POOL_PATH = "{%s}/flow_id_pool/{%d}"
99
100 //Path on the KV store for storing list of alloc IDs for a given ONU
101 //Format: <device_id>/<(pon_intf_id, onu_id)>/alloc_ids
102 ALLOC_ID_RESOURCE_MAP_PATH = "{%s}/{%s}/alloc_ids"
103
104 //Path on the KV store for storing list of gemport IDs for a given ONU
105 //Format: <device_id>/<(pon_intf_id, onu_id)>/gemport_ids
106 GEMPORT_ID_RESOURCE_MAP_PATH = "{%s}/{%s}/gemport_ids"
107
108 //Path on the KV store for storing list of Flow IDs for a given ONU
109 //Format: <device_id>/<(pon_intf_id, onu_id)>/flow_ids
110 FLOW_ID_RESOURCE_MAP_PATH = "{%s}/{%s}/flow_ids"
111
112 //Flow Id info: Use to store more metadata associated with the flow_id
113 //Format: <device_id>/<(pon_intf_id, onu_id)>/flow_id_info/<flow_id>
114 FLOW_ID_INFO_PATH = "{%s}/{%s}/flow_id_info/{%d}"
115
116 //path on the kvstore to store onugem info map
117 //format: <device-id>/onu_gem_info/<intfid>
118 ONU_GEM_INFO_PATH = "{%s}/onu_gem_info/{%d}" // onu_gem/<(intfid)>
119
120 //Constants for internal usage.
121 PON_INTF_ID = "pon_intf_id"
122 START_IDX = "start_idx"
123 END_IDX = "end_idx"
124 POOL = "pool"
125 NUM_OF_PON_INTF = 16
126
127 KVSTORE_RETRY_TIMEOUT = 5 * time.Second
128 //Path on the KV store for storing reserved gem ports
129 //Format: reserved_gemport_ids
130 RESERVED_GEMPORT_IDS_PATH = "reserved_gemport_ids"
131)
132
133//type ResourceTypeIndex string
134//type ResourceType string
135
136type PONResourceManager struct {
137 //Implements APIs to initialize/allocate/release alloc/gemport/onu IDs.
138 Technology string
139 DeviceType string
140 DeviceID string
141 Backend string // ETCD, or consul
142 Address string // address of the KV store
143 OLTModel string
144 KVStore *db.Backend
145 KVStoreForConfig *db.Backend
146 TechProfileMgr tp.TechProfileIf // create object of *tp.TechProfileMgr
147
148 // Below attribute, pon_resource_ranges, should be initialized
149 // by reading from KV store.
150 PonResourceRanges map[string]interface{}
151 SharedResourceMgrs map[string]*PONResourceManager
152 SharedIdxByType map[string]string
153 IntfIDs []uint32 // list of pon interface IDs
154 Globalorlocal string
155}
156
157func newKVClient(ctx context.Context, storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
158 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
159 switch storeType {
160 case "consul":
161 return kvstore.NewConsulClient(ctx, address, timeout)
162 case "etcd":
163 return kvstore.NewEtcdClient(ctx, address, timeout, log.WarnLevel)
164 }
165 return nil, errors.New("unsupported-kv-store")
166}
167
168func SetKVClient(ctx context.Context, Technology string, Backend string, Addr string, configClient bool) *db.Backend {
169 // TODO : Make sure direct call to NewBackend is working fine with backend , currently there is some
170 // issue between kv store and backend , core is not calling NewBackend directly
171 kvClient, err := newKVClient(ctx, Backend, Addr, KVSTORE_RETRY_TIMEOUT)
172 if err != nil {
173 logger.Fatalw(ctx, "Failed to init KV client\n", log.Fields{"err": err})
174 return nil
175 }
176
177 var pathPrefix string
178 if configClient {
179 pathPrefix = PATH_PREFIX_FOR_CONFIG
180 } else {
181 pathPrefix = fmt.Sprintf(PATH_PREFIX, Technology)
182 }
183
184 kvbackend := &db.Backend{
185 Client: kvClient,
186 StoreType: Backend,
187 Address: Addr,
188 Timeout: KVSTORE_RETRY_TIMEOUT,
189 PathPrefix: pathPrefix}
190
191 return kvbackend
192}
193
194// NewPONResourceManager creates a new PON resource manager.
195func NewPONResourceManager(ctx context.Context, Technology string, DeviceType string, DeviceID string, Backend string, Address string) (*PONResourceManager, error) {
196 var PONMgr PONResourceManager
197 PONMgr.Technology = Technology
198 PONMgr.DeviceType = DeviceType
199 PONMgr.DeviceID = DeviceID
200 PONMgr.Backend = Backend
201 PONMgr.Address = Address
202 PONMgr.KVStore = SetKVClient(ctx, Technology, Backend, Address, false)
203 if PONMgr.KVStore == nil {
204 logger.Error(ctx, "KV Client initilization failed")
205 return nil, errors.New("Failed to init KV client")
206 }
207 // init kv client to read from the config path
208 PONMgr.KVStoreForConfig = SetKVClient(ctx, Technology, Backend, Address, true)
209 if PONMgr.KVStoreForConfig == nil {
210 logger.Error(ctx, "KV Config Client initilization failed")
211 return nil, errors.New("Failed to init KV Config client")
212 }
213 // Initialize techprofile for this technology
214 if PONMgr.TechProfileMgr, _ = tp.NewTechProfile(ctx, &PONMgr, Backend, Address); PONMgr.TechProfileMgr == nil {
215 logger.Error(ctx, "Techprofile initialization failed")
216 return nil, errors.New("Failed to init tech profile")
217 }
218 PONMgr.PonResourceRanges = make(map[string]interface{})
219 PONMgr.SharedResourceMgrs = make(map[string]*PONResourceManager)
220 PONMgr.SharedIdxByType = make(map[string]string)
221 PONMgr.SharedIdxByType[ONU_ID] = ONU_ID_SHARED_IDX
222 PONMgr.SharedIdxByType[ALLOC_ID] = ALLOC_ID_SHARED_IDX
223 PONMgr.SharedIdxByType[GEMPORT_ID] = GEMPORT_ID_SHARED_IDX
224 PONMgr.SharedIdxByType[FLOW_ID] = FLOW_ID_SHARED_IDX
225 PONMgr.IntfIDs = make([]uint32, NUM_OF_PON_INTF)
226 PONMgr.OLTModel = DeviceType
227 return &PONMgr, nil
228}
229
230/*
231 Initialize PON resource ranges with config fetched from kv store.
232 return boolean: True if PON resource ranges initialized else false
233 Try to initialize the PON Resource Ranges from KV store based on the
234 OLT model key, if available
235*/
236
237func (PONRMgr *PONResourceManager) InitResourceRangesFromKVStore(ctx context.Context) bool {
238 //Initialize PON resource ranges with config fetched from kv store.
239 //:return boolean: True if PON resource ranges initialized else false
240 // Try to initialize the PON Resource Ranges from KV store based on the
241 // OLT model key, if available
242 if PONRMgr.OLTModel == "" {
243 logger.Error(ctx, "Failed to get OLT model")
244 return false
245 }
246 Path := fmt.Sprintf(PON_RESOURCE_RANGE_CONFIG_PATH, PONRMgr.OLTModel)
247 //get resource from kv store
248 Result, err := PONRMgr.KVStore.Get(ctx, Path)
249 if err != nil {
250 logger.Debugf(ctx, "Error in fetching resource %s from KV strore", Path)
251 return false
252 }
253 if Result == nil {
254 logger.Debug(ctx, "There may be no resources in the KV store in case of fresh bootup, return true")
255 return false
256 }
257 //update internal ranges from kv ranges. If there are missing
258 // values in the KV profile, continue to use the defaults
259 Value, err := ToByte(Result.Value)
260 if err != nil {
261 logger.Error(ctx, "Failed to convert kvpair to byte string")
262 return false
263 }
264 if err := json.Unmarshal(Value, &PONRMgr.PonResourceRanges); err != nil {
265 logger.Error(ctx, "Failed to Unmarshal json byte")
266 return false
267 }
268 logger.Debug(ctx, "Init resource ranges from kvstore success")
269 return true
270}
271
272func (PONRMgr *PONResourceManager) UpdateRanges(ctx context.Context, StartIDx string, StartID uint32, EndIDx string, EndID uint32,
273 SharedIDx string, SharedPoolID uint32, RMgr *PONResourceManager) {
274 /*
275 Update the ranges for all reosurce type in the intermnal maps
276 param: resource type start index
277 param: start ID
278 param: resource type end index
279 param: end ID
280 param: resource type shared index
281 param: shared pool id
282 param: global resource manager
283 */
284 logger.Debugf(ctx, "update ranges for %s, %d", StartIDx, StartID)
285
286 if StartID != 0 {
287 if (PONRMgr.PonResourceRanges[StartIDx] == nil) || (PONRMgr.PonResourceRanges[StartIDx].(uint32) < StartID) {
288 PONRMgr.PonResourceRanges[StartIDx] = StartID
289 }
290 }
291 if EndID != 0 {
292 if (PONRMgr.PonResourceRanges[EndIDx] == nil) || (PONRMgr.PonResourceRanges[EndIDx].(uint32) > EndID) {
293 PONRMgr.PonResourceRanges[EndIDx] = EndID
294 }
295 }
296 //if SharedPoolID != 0 {
297 PONRMgr.PonResourceRanges[SharedIDx] = SharedPoolID
298 //}
299 if RMgr != nil {
300 PONRMgr.SharedResourceMgrs[SharedIDx] = RMgr
301 }
302}
303
304func (PONRMgr *PONResourceManager) InitDefaultPONResourceRanges(ctx context.Context,
305 ONUIDStart uint32,
306 ONUIDEnd uint32,
307 ONUIDSharedPoolID uint32,
308 AllocIDStart uint32,
309 AllocIDEnd uint32,
310 AllocIDSharedPoolID uint32,
311 GEMPortIDStart uint32,
312 GEMPortIDEnd uint32,
313 GEMPortIDSharedPoolID uint32,
314 FlowIDStart uint32,
315 FlowIDEnd uint32,
316 FlowIDSharedPoolID uint32,
317 UNIIDStart uint32,
318 UNIIDEnd uint32,
319 NoOfPONPorts uint32,
320 IntfIDs []uint32) bool {
321
322 /*Initialize default PON resource ranges
323
324 :param onu_id_start_idx: onu id start index
325 :param onu_id_end_idx: onu id end index
326 :param onu_id_shared_pool_id: pool idx for id shared by all intfs or None for no sharing
327 :param alloc_id_start_idx: alloc id start index
328 :param alloc_id_end_idx: alloc id end index
329 :param alloc_id_shared_pool_id: pool idx for alloc id shared by all intfs or None for no sharing
330 :param gemport_id_start_idx: gemport id start index
331 :param gemport_id_end_idx: gemport id end index
332 :param gemport_id_shared_pool_id: pool idx for gemport id shared by all intfs or None for no sharing
333 :param flow_id_start_idx: flow id start index
334 :param flow_id_end_idx: flow id end index
335 :param flow_id_shared_pool_id: pool idx for flow id shared by all intfs or None for no sharing
336 :param num_of_pon_ports: number of PON ports
337 :param intf_ids: interfaces serviced by this manager
338 */
339 PONRMgr.UpdateRanges(ctx, ONU_ID_START_IDX, ONUIDStart, ONU_ID_END_IDX, ONUIDEnd, ONU_ID_SHARED_IDX, ONUIDSharedPoolID, nil)
340 PONRMgr.UpdateRanges(ctx, ALLOC_ID_START_IDX, AllocIDStart, ALLOC_ID_END_IDX, AllocIDEnd, ALLOC_ID_SHARED_IDX, AllocIDSharedPoolID, nil)
341 PONRMgr.UpdateRanges(ctx, GEMPORT_ID_START_IDX, GEMPortIDStart, GEMPORT_ID_END_IDX, GEMPortIDEnd, GEMPORT_ID_SHARED_IDX, GEMPortIDSharedPoolID, nil)
342 PONRMgr.UpdateRanges(ctx, FLOW_ID_START_IDX, FlowIDStart, FLOW_ID_END_IDX, FlowIDEnd, FLOW_ID_SHARED_IDX, FlowIDSharedPoolID, nil)
343 PONRMgr.UpdateRanges(ctx, UNI_ID_START_IDX, UNIIDStart, UNI_ID_END_IDX, UNIIDEnd, "", 0, nil)
344 logger.Debug(ctx, "Initialize default range values")
345 var i uint32
346 if IntfIDs == nil {
347 for i = 0; i < NoOfPONPorts; i++ {
348 PONRMgr.IntfIDs = append(PONRMgr.IntfIDs, i)
349 }
350 } else {
351 PONRMgr.IntfIDs = IntfIDs
352 }
353 return true
354}
355
356func (PONRMgr *PONResourceManager) InitDeviceResourcePool(ctx context.Context) error {
357
358 //Initialize resource pool for all PON ports.
359
360 logger.Debug(ctx, "Init resource ranges")
361
362 var err error
363 for _, Intf := range PONRMgr.IntfIDs {
364 SharedPoolID := PONRMgr.PonResourceRanges[ONU_ID_SHARED_IDX].(uint32)
365 if SharedPoolID != 0 {
366 Intf = SharedPoolID
367 }
368 if err = PONRMgr.InitResourceIDPool(ctx, Intf, ONU_ID,
369 PONRMgr.PonResourceRanges[ONU_ID_START_IDX].(uint32),
370 PONRMgr.PonResourceRanges[ONU_ID_END_IDX].(uint32)); err != nil {
371 logger.Error(ctx, "Failed to init ONU ID resource pool")
372 return err
373 }
374 if SharedPoolID != 0 {
375 break
376 }
377 }
378
379 for _, Intf := range PONRMgr.IntfIDs {
380 SharedPoolID := PONRMgr.PonResourceRanges[ALLOC_ID_SHARED_IDX].(uint32)
381 if SharedPoolID != 0 {
382 Intf = SharedPoolID
383 }
384 if err = PONRMgr.InitResourceIDPool(ctx, Intf, ALLOC_ID,
385 PONRMgr.PonResourceRanges[ALLOC_ID_START_IDX].(uint32),
386 PONRMgr.PonResourceRanges[ALLOC_ID_END_IDX].(uint32)); err != nil {
387 logger.Error(ctx, "Failed to init ALLOC ID resource pool ")
388 return err
389 }
390 if SharedPoolID != 0 {
391 break
392 }
393 }
394 for _, Intf := range PONRMgr.IntfIDs {
395 SharedPoolID := PONRMgr.PonResourceRanges[GEMPORT_ID_SHARED_IDX].(uint32)
396 if SharedPoolID != 0 {
397 Intf = SharedPoolID
398 }
399 if err = PONRMgr.InitResourceIDPool(ctx, Intf, GEMPORT_ID,
400 PONRMgr.PonResourceRanges[GEMPORT_ID_START_IDX].(uint32),
401 PONRMgr.PonResourceRanges[GEMPORT_ID_END_IDX].(uint32)); err != nil {
402 logger.Error(ctx, "Failed to init GEMPORT ID resource pool")
403 return err
404 }
405 if SharedPoolID != 0 {
406 break
407 }
408 }
409
410 for _, Intf := range PONRMgr.IntfIDs {
411 SharedPoolID := PONRMgr.PonResourceRanges[FLOW_ID_SHARED_IDX].(uint32)
412 if SharedPoolID != 0 {
413 Intf = SharedPoolID
414 }
415 if err = PONRMgr.InitResourceIDPool(ctx, Intf, FLOW_ID,
416 PONRMgr.PonResourceRanges[FLOW_ID_START_IDX].(uint32),
417 PONRMgr.PonResourceRanges[FLOW_ID_END_IDX].(uint32)); err != nil {
418 logger.Error(ctx, "Failed to init FLOW ID resource pool")
419 return err
420 }
421 if SharedPoolID != 0 {
422 break
423 }
424 }
425 return err
426}
427
428func (PONRMgr *PONResourceManager) ClearDeviceResourcePool(ctx context.Context) error {
429
430 //Clear resource pool for all PON ports.
431
432 logger.Debug(ctx, "Clear resource ranges")
433
434 for _, Intf := range PONRMgr.IntfIDs {
435 SharedPoolID := PONRMgr.PonResourceRanges[ONU_ID_SHARED_IDX].(uint32)
436 if SharedPoolID != 0 {
437 Intf = SharedPoolID
438 }
439 if status := PONRMgr.ClearResourceIDPool(ctx, Intf, ONU_ID); !status {
440 logger.Error(ctx, "Failed to clear ONU ID resource pool")
441 return errors.New("Failed to clear ONU ID resource pool")
442 }
443 if SharedPoolID != 0 {
444 break
445 }
446 }
447
448 for _, Intf := range PONRMgr.IntfIDs {
449 SharedPoolID := PONRMgr.PonResourceRanges[ALLOC_ID_SHARED_IDX].(uint32)
450 if SharedPoolID != 0 {
451 Intf = SharedPoolID
452 }
453 if status := PONRMgr.ClearResourceIDPool(ctx, Intf, ALLOC_ID); !status {
454 logger.Error(ctx, "Failed to clear ALLOC ID resource pool ")
455 return errors.New("Failed to clear ALLOC ID resource pool")
456 }
457 if SharedPoolID != 0 {
458 break
459 }
460 }
461 for _, Intf := range PONRMgr.IntfIDs {
462 SharedPoolID := PONRMgr.PonResourceRanges[GEMPORT_ID_SHARED_IDX].(uint32)
463 if SharedPoolID != 0 {
464 Intf = SharedPoolID
465 }
466 if status := PONRMgr.ClearResourceIDPool(ctx, Intf, GEMPORT_ID); !status {
467 logger.Error(ctx, "Failed to clear GEMPORT ID resource pool")
468 return errors.New("Failed to clear GEMPORT ID resource pool")
469 }
470 if SharedPoolID != 0 {
471 break
472 }
473 }
474
475 for _, Intf := range PONRMgr.IntfIDs {
476 SharedPoolID := PONRMgr.PonResourceRanges[FLOW_ID_SHARED_IDX].(uint32)
477 if SharedPoolID != 0 {
478 Intf = SharedPoolID
479 }
480 if status := PONRMgr.ClearResourceIDPool(ctx, Intf, FLOW_ID); !status {
481 logger.Error(ctx, "Failed to clear FLOW ID resource pool")
482 return errors.New("Failed to clear FLOW ID resource pool")
483 }
484 if SharedPoolID != 0 {
485 break
486 }
487 }
488 return nil
489}
490
491func (PONRMgr *PONResourceManager) InitResourceIDPool(ctx context.Context, Intf uint32, ResourceType string, StartID uint32, EndID uint32) error {
492
493 /*Initialize Resource ID pool for a given Resource Type on a given PON Port
494
495 :param pon_intf_id: OLT PON interface id
496 :param resource_type: String to identify type of resource
497 :param start_idx: start index for onu id pool
498 :param end_idx: end index for onu id pool
499 :return boolean: True if resource id pool initialized else false
500 */
501
502 // delegate to the master instance if sharing enabled across instances
503 SharedResourceMgr := PONRMgr.SharedResourceMgrs[PONRMgr.SharedIdxByType[ResourceType]]
504 if SharedResourceMgr != nil && PONRMgr != SharedResourceMgr {
505 return SharedResourceMgr.InitResourceIDPool(ctx, Intf, ResourceType, StartID, EndID)
506 }
507
508 Path := PONRMgr.GetPath(ctx, Intf, ResourceType)
509 if Path == "" {
510 logger.Errorf(ctx, "Failed to get path for resource type %s", ResourceType)
511 return fmt.Errorf("Failed to get path for resource type %s", ResourceType)
512 }
513
514 //In case of adapter reboot and reconciliation resource in kv store
515 //checked for its presence if not kv store update happens
516 Res, err := PONRMgr.GetResource(ctx, Path)
517 if (err == nil) && (Res != nil) {
518 logger.Debugf(ctx, "Resource %s already present in store ", Path)
519 return nil
520 } else {
521 var excluded []uint32
522 if ResourceType == GEMPORT_ID {
523 //get gem port ids defined in the KV store, if any, and exclude them from the gem port id pool
524 if reservedGemPortIds, defined := PONRMgr.getReservedGemPortIdsFromKVStore(ctx); defined {
525 excluded = reservedGemPortIds
526 logger.Debugw(ctx, "Excluding some ports from GEM port id pool", log.Fields{"excluded gem ports": excluded})
527 }
528 }
529 FormatResult, err := PONRMgr.FormatResource(ctx, Intf, StartID, EndID, excluded)
530 if err != nil {
531 logger.Errorf(ctx, "Failed to format resource")
532 return err
533 }
534 // Add resource as json in kv store.
535 err = PONRMgr.KVStore.Put(ctx, Path, FormatResult)
536 if err == nil {
537 logger.Debug(ctx, "Successfuly posted to kv store")
538 return err
539 }
540 }
541
542 logger.Debug(ctx, "Error initializing pool")
543
544 return err
545}
546
547func (PONRMgr *PONResourceManager) getReservedGemPortIdsFromKVStore(ctx context.Context) ([]uint32, bool) {
548 var reservedGemPortIds []uint32
549 // read reserved gem ports from the config path
550 KvPair, err := PONRMgr.KVStoreForConfig.Get(ctx, RESERVED_GEMPORT_IDS_PATH)
551 if err != nil {
552 logger.Errorw(ctx, "Unable to get reserved GEM port ids from the kv store", log.Fields{"err": err})
553 return reservedGemPortIds, false
554 }
555 if KvPair == nil || KvPair.Value == nil {
556 //no reserved gem port defined in the store
557 return reservedGemPortIds, false
558 }
559 Val, err := kvstore.ToByte(KvPair.Value)
560 if err != nil {
561 logger.Errorw(ctx, "Failed to convert reserved gem port ids into byte array", log.Fields{"err": err})
562 return reservedGemPortIds, false
563 }
564 if err = json.Unmarshal(Val, &reservedGemPortIds); err != nil {
565 logger.Errorw(ctx, "Failed to unmarshal reservedGemPortIds", log.Fields{"err": err})
566 return reservedGemPortIds, false
567 }
568 return reservedGemPortIds, true
569}
570
571func (PONRMgr *PONResourceManager) FormatResource(ctx context.Context, IntfID uint32, StartIDx uint32, EndIDx uint32,
572 Excluded []uint32) ([]byte, error) {
573 /*
574 Format resource as json.
575 :param pon_intf_id: OLT PON interface id
576 :param start_idx: start index for id pool
577 :param end_idx: end index for id pool
578 :Id values to be Excluded from the pool
579 :return dictionary: resource formatted as map
580 */
581 // Format resource as json to be stored in backend store
582 Resource := make(map[string]interface{})
583 Resource[PON_INTF_ID] = IntfID
584 Resource[START_IDX] = StartIDx
585 Resource[END_IDX] = EndIDx
586 /*
587 Resource pool stored in backend store as binary string.
588 Tracking the resource allocation will be done by setting the bits \
589 in the byte array. The index set will be the resource number allocated.
590 */
591 var TSData *bitmap.Threadsafe
592 if TSData = bitmap.NewTS(int(EndIDx)); TSData == nil {
593 logger.Error(ctx, "Failed to create a bitmap")
594 return nil, errors.New("Failed to create bitmap")
595 }
596 for _, excludedID := range Excluded {
597 if excludedID < StartIDx || excludedID > EndIDx {
598 logger.Warnf(ctx, "Cannot reserve %d. It must be in the range of [%d, %d]", excludedID,
599 StartIDx, EndIDx)
600 continue
601 }
602 PONRMgr.reserveID(ctx, TSData, StartIDx, excludedID)
603 }
604 Resource[POOL] = TSData.Data(false) //we pass false so as the TSData lib api does not do a copy of the data and return
605
606 Value, err := json.Marshal(Resource)
607 if err != nil {
608 logger.Errorf(ctx, "Failed to marshall resource")
609 return nil, err
610 }
611 return Value, err
612}
613func (PONRMgr *PONResourceManager) GetResource(ctx context.Context, Path string) (map[string]interface{}, error) {
614 /*
615 Get resource from kv store.
616
617 :param path: path to get resource
618 :return: resource if resource present in kv store else None
619 */
620 //get resource from kv store
621
622 var Value []byte
623 Result := make(map[string]interface{})
624 var Str string
625
626 Resource, err := PONRMgr.KVStore.Get(ctx, Path)
627 if (err != nil) || (Resource == nil) {
628 logger.Debugf(ctx, "Resource unavailable at %s", Path)
629 return nil, err
630 }
631
632 Value, err = ToByte(Resource.Value)
633 if err != nil {
634 return nil, err
635 }
636
637 // decode resource fetched from backend store to dictionary
638 err = json.Unmarshal(Value, &Result)
639 if err != nil {
640 logger.Error(ctx, "Failed to decode resource")
641 return Result, err
642 }
643 /*
644 resource pool in backend store stored as binary string whereas to
645 access the pool to generate/release IDs it need to be converted
646 as BitArray
647 */
648 Str, err = ToString(Result[POOL])
649 if err != nil {
650 logger.Error(ctx, "Failed to conver to kv pair to string")
651 return Result, err
652 }
653 Decode64, _ := base64.StdEncoding.DecodeString(Str)
654 Result[POOL], err = ToByte(Decode64)
655 if err != nil {
656 logger.Error(ctx, "Failed to convert resource pool to byte")
657 return Result, err
658 }
659
660 return Result, err
661}
662
663func (PONRMgr *PONResourceManager) GetPath(ctx context.Context, IntfID uint32, ResourceType string) string {
664 /*
665 Get path for given resource type.
666 :param pon_intf_id: OLT PON interface id
667 :param resource_type: String to identify type of resource
668 :return: path for given resource type
669 */
670
671 /*
672 Get the shared pool for the given resource type.
673 all the resource ranges and the shared resource maps are initialized during the init.
674 */
675 SharedPoolID := PONRMgr.PonResourceRanges[PONRMgr.SharedIdxByType[ResourceType]].(uint32)
676 if SharedPoolID != 0 {
677 IntfID = SharedPoolID
678 }
679 var Path string
680 if ResourceType == ONU_ID {
681 Path = fmt.Sprintf(ONU_ID_POOL_PATH, PONRMgr.DeviceID, IntfID)
682 } else if ResourceType == ALLOC_ID {
683 Path = fmt.Sprintf(ALLOC_ID_POOL_PATH, PONRMgr.DeviceID, IntfID)
684 } else if ResourceType == GEMPORT_ID {
685 Path = fmt.Sprintf(GEMPORT_ID_POOL_PATH, PONRMgr.DeviceID, IntfID)
686 } else if ResourceType == FLOW_ID {
687 Path = fmt.Sprintf(FLOW_ID_POOL_PATH, PONRMgr.DeviceID, IntfID)
688 } else {
689 logger.Error(ctx, "Invalid resource pool identifier")
690 }
691 return Path
692}
693
694func (PONRMgr *PONResourceManager) GetResourceID(ctx context.Context, IntfID uint32, ResourceType string, NumIDs uint32) ([]uint32, error) {
695 /*
696 Create alloc/gemport/onu/flow id for given OLT PON interface.
697 :param pon_intf_id: OLT PON interface id
698 :param resource_type: String to identify type of resource
699 :param num_of_id: required number of ids
700 :return list/uint32/None: list, uint32 or None if resource type is
701 alloc_id/gemport_id, onu_id or invalid type respectively
702 */
703 if NumIDs < 1 {
704 logger.Error(ctx, "Invalid number of resources requested")
705 return nil, fmt.Errorf("Invalid number of resources requested %d", NumIDs)
706 }
707 // delegate to the master instance if sharing enabled across instances
708
709 SharedResourceMgr := PONRMgr.SharedResourceMgrs[PONRMgr.SharedIdxByType[ResourceType]]
710 if SharedResourceMgr != nil && PONRMgr != SharedResourceMgr {
711 return SharedResourceMgr.GetResourceID(ctx, IntfID, ResourceType, NumIDs)
712 }
713 logger.Debugf(ctx, "Fetching resource from %s rsrc mgr for resource %s", PONRMgr.Globalorlocal, ResourceType)
714
715 Path := PONRMgr.GetPath(ctx, IntfID, ResourceType)
716 if Path == "" {
717 logger.Errorf(ctx, "Failed to get path for resource type %s", ResourceType)
718 return nil, fmt.Errorf("Failed to get path for resource type %s", ResourceType)
719 }
720 logger.Debugf(ctx, "Get resource for type %s on path %s", ResourceType, Path)
721 var Result []uint32
722 var NextID uint32
723 Resource, err := PONRMgr.GetResource(ctx, Path)
724 if (err == nil) && (ResourceType == ONU_ID) || (ResourceType == FLOW_ID) {
725 if NextID, err = PONRMgr.GenerateNextID(ctx, Resource); err != nil {
726 logger.Error(ctx, "Failed to Generate ID")
727 return Result, err
728 }
729 Result = append(Result, NextID)
730 } else if (err == nil) && ((ResourceType == GEMPORT_ID) || (ResourceType == ALLOC_ID)) {
731 if NumIDs == 1 {
732 if NextID, err = PONRMgr.GenerateNextID(ctx, Resource); err != nil {
733 logger.Error(ctx, "Failed to Generate ID")
734 return Result, err
735 }
736 Result = append(Result, NextID)
737 } else {
738 for NumIDs > 0 {
739 if NextID, err = PONRMgr.GenerateNextID(ctx, Resource); err != nil {
740 logger.Error(ctx, "Failed to Generate ID")
741 return Result, err
742 }
743 Result = append(Result, NextID)
744 NumIDs--
745 }
746 }
747 } else {
748 logger.Error(ctx, "get resource failed")
749 return Result, err
750 }
751
752 //Update resource in kv store
753 if PONRMgr.UpdateResource(ctx, Path, Resource) != nil {
754 logger.Errorf(ctx, "Failed to update resource %s", Path)
755 return nil, fmt.Errorf("Failed to update resource %s", Path)
756 }
757 return Result, nil
758}
759
760func checkValidResourceType(ResourceType string) bool {
761 KnownResourceTypes := []string{ONU_ID, ALLOC_ID, GEMPORT_ID, FLOW_ID}
762
763 for _, v := range KnownResourceTypes {
764 if v == ResourceType {
765 return true
766 }
767 }
768 return false
769}
770
771func (PONRMgr *PONResourceManager) FreeResourceID(ctx context.Context, IntfID uint32, ResourceType string, ReleaseContent []uint32) bool {
772 /*
773 Release alloc/gemport/onu/flow id for given OLT PON interface.
774 :param pon_intf_id: OLT PON interface id
775 :param resource_type: String to identify type of resource
776 :param release_content: required number of ids
777 :return boolean: True if all IDs in given release_content release else False
778 */
779 if !checkValidResourceType(ResourceType) {
780 logger.Error(ctx, "Invalid resource type")
781 return false
782 }
783 if ReleaseContent == nil {
784 logger.Debug(ctx, "Nothing to release")
785 return true
786 }
787 // delegate to the master instance if sharing enabled across instances
788 SharedResourceMgr := PONRMgr.SharedResourceMgrs[PONRMgr.SharedIdxByType[ResourceType]]
789 if SharedResourceMgr != nil && PONRMgr != SharedResourceMgr {
790 return SharedResourceMgr.FreeResourceID(ctx, IntfID, ResourceType, ReleaseContent)
791 }
792 Path := PONRMgr.GetPath(ctx, IntfID, ResourceType)
793 if Path == "" {
794 logger.Error(ctx, "Failed to get path")
795 return false
796 }
797 Resource, err := PONRMgr.GetResource(ctx, Path)
798 if err != nil {
799 logger.Error(ctx, "Failed to get resource")
800 return false
801 }
802 for _, Val := range ReleaseContent {
803 PONRMgr.ReleaseID(ctx, Resource, Val)
804 }
805 if PONRMgr.UpdateResource(ctx, Path, Resource) != nil {
806 logger.Errorf(ctx, "Free resource for %s failed", Path)
807 return false
808 }
809 return true
810}
811
812func (PONRMgr *PONResourceManager) UpdateResource(ctx context.Context, Path string, Resource map[string]interface{}) error {
813 /*
814 Update resource in resource kv store.
815 :param path: path to update resource
816 :param resource: resource need to be updated
817 :return boolean: True if resource updated in kv store else False
818 */
819 // TODO resource[POOL] = resource[POOL].bin
820 Value, err := json.Marshal(Resource)
821 if err != nil {
822 logger.Error(ctx, "failed to Marshal")
823 return err
824 }
825 err = PONRMgr.KVStore.Put(ctx, Path, Value)
826 if err != nil {
827 logger.Error(ctx, "failed to put data to kv store %s", Path)
828 return err
829 }
830 return nil
831}
832
833func (PONRMgr *PONResourceManager) ClearResourceIDPool(ctx context.Context, contIntfID uint32, ResourceType string) bool {
834 /*
835 Clear Resource Pool for a given Resource Type on a given PON Port.
836 :return boolean: True if removed else False
837 */
838
839 // delegate to the master instance if sharing enabled across instances
840 SharedResourceMgr := PONRMgr.SharedResourceMgrs[PONRMgr.SharedIdxByType[ResourceType]]
841 if SharedResourceMgr != nil && PONRMgr != SharedResourceMgr {
842 return SharedResourceMgr.ClearResourceIDPool(ctx, contIntfID, ResourceType)
843 }
844 Path := PONRMgr.GetPath(ctx, contIntfID, ResourceType)
845 if Path == "" {
846 logger.Error(ctx, "Failed to get path")
847 return false
848 }
849
850 if err := PONRMgr.KVStore.Delete(ctx, Path); err != nil {
851 logger.Errorf(ctx, "Failed to delete resource %s", Path)
852 return false
853 }
854 logger.Debugf(ctx, "Cleared resource %s", Path)
855 return true
856}
857
858func (PONRMgr PONResourceManager) InitResourceMap(ctx context.Context, PONIntfONUID string) {
859 /*
860 Initialize resource map
861 :param pon_intf_onu_id: reference of PON interface id and onu id
862 */
863 // initialize pon_intf_onu_id tuple to alloc_ids map
864 AllocIDPath := fmt.Sprintf(ALLOC_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, PONIntfONUID)
865 var AllocIDs []byte
866 Result := PONRMgr.KVStore.Put(ctx, AllocIDPath, AllocIDs)
867 if Result != nil {
868 logger.Error(ctx, "Failed to update the KV store")
869 return
870 }
871 // initialize pon_intf_onu_id tuple to gemport_ids map
872 GEMPortIDPath := fmt.Sprintf(GEMPORT_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, PONIntfONUID)
873 var GEMPortIDs []byte
874 Result = PONRMgr.KVStore.Put(ctx, GEMPortIDPath, GEMPortIDs)
875 if Result != nil {
876 logger.Error(ctx, "Failed to update the KV store")
877 return
878 }
879}
880
881func (PONRMgr PONResourceManager) RemoveResourceMap(ctx context.Context, PONIntfONUID string) bool {
882 /*
883 Remove resource map
884 :param pon_intf_onu_id: reference of PON interface id and onu id
885 */
886 // remove pon_intf_onu_id tuple to alloc_ids map
887 var err error
888 AllocIDPath := fmt.Sprintf(ALLOC_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, PONIntfONUID)
889 if err = PONRMgr.KVStore.Delete(ctx, AllocIDPath); err != nil {
890 logger.Errorf(ctx, "Failed to remove resource %s", AllocIDPath)
891 return false
892 }
893 // remove pon_intf_onu_id tuple to gemport_ids map
894 GEMPortIDPath := fmt.Sprintf(GEMPORT_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, PONIntfONUID)
895 err = PONRMgr.KVStore.Delete(ctx, GEMPortIDPath)
896 if err != nil {
897 logger.Errorf(ctx, "Failed to remove resource %s", GEMPortIDPath)
898 return false
899 }
900
901 FlowIDPath := fmt.Sprintf(FLOW_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, PONIntfONUID)
902 if FlowIDs, err := PONRMgr.KVStore.List(ctx, FlowIDPath); err != nil {
903 for _, Flow := range FlowIDs {
904 FlowIDInfoPath := fmt.Sprintf(FLOW_ID_INFO_PATH, PONRMgr.DeviceID, PONIntfONUID, Flow.Value)
905 if err = PONRMgr.KVStore.Delete(ctx, FlowIDInfoPath); err != nil {
906 logger.Errorf(ctx, "Failed to remove resource %s", FlowIDInfoPath)
907 return false
908 }
909 }
910 }
911
912 if err = PONRMgr.KVStore.Delete(ctx, FlowIDPath); err != nil {
913 logger.Errorf(ctx, "Failed to remove resource %s", FlowIDPath)
914 return false
915 }
916
917 return true
918}
919
920func (PONRMgr *PONResourceManager) GetCurrentAllocIDForOnu(ctx context.Context, IntfONUID string) []uint32 {
921 /*
922 Get currently configured alloc ids for given pon_intf_onu_id
923 :param pon_intf_onu_id: reference of PON interface id and onu id
924 :return list: List of alloc_ids if available, else None
925 */
926 Path := fmt.Sprintf(ALLOC_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
927
928 var Data []uint32
929 Value, err := PONRMgr.KVStore.Get(ctx, Path)
930 if err == nil {
931 if Value != nil {
932 Val, err := ToByte(Value.Value)
933 if err != nil {
934 logger.Errorw(ctx, "Failed to convert into byte array", log.Fields{"error": err})
935 return Data
936 }
937 if err = json.Unmarshal(Val, &Data); err != nil {
938 logger.Error(ctx, "Failed to unmarshal", log.Fields{"error": err})
939 return Data
940 }
941 }
942 }
943 return Data
944}
945
946func (PONRMgr *PONResourceManager) GetCurrentGEMPortIDsForOnu(ctx context.Context, IntfONUID string) []uint32 {
947 /*
948 Get currently configured gemport ids for given pon_intf_onu_id
949 :param pon_intf_onu_id: reference of PON interface id and onu id
950 :return list: List of gemport IDs if available, else None
951 */
952
953 Path := fmt.Sprintf(GEMPORT_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
954 logger.Debugf(ctx, "Getting current gemports for %s", Path)
955 var Data []uint32
956 Value, err := PONRMgr.KVStore.Get(ctx, Path)
957 if err == nil {
958 if Value != nil {
959 Val, _ := ToByte(Value.Value)
960 if err = json.Unmarshal(Val, &Data); err != nil {
961 logger.Errorw(ctx, "Failed to unmarshal", log.Fields{"error": err})
962 return Data
963 }
964 }
965 } else {
966 logger.Errorf(ctx, "Failed to get data from kvstore for %s", Path)
967 }
968 return Data
969}
970
971func (PONRMgr *PONResourceManager) GetCurrentFlowIDsForOnu(ctx context.Context, IntfONUID string) []uint32 {
972 /*
973 Get currently configured flow ids for given pon_intf_onu_id
974 :param pon_intf_onu_id: reference of PON interface id and onu id
975 :return list: List of Flow IDs if available, else None
976 */
977
978 Path := fmt.Sprintf(FLOW_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
979
980 var Data []uint32
981 Value, err := PONRMgr.KVStore.Get(ctx, Path)
982 if err == nil {
983 if Value != nil {
984 Val, _ := ToByte(Value.Value)
985 if err = json.Unmarshal(Val, &Data); err != nil {
986 logger.Error(ctx, "Failed to unmarshal")
987 return Data
988 }
989 }
990 }
991 return Data
992}
993
994func (PONRMgr *PONResourceManager) GetFlowIDInfo(ctx context.Context, IntfONUID string, FlowID uint32, Data interface{}) error {
995 /*
996 Get flow details configured for the ONU.
997 :param pon_intf_onu_id: reference of PON interface id and onu id
998 :param flow_id: Flow Id reference
999 :param Data: Result
1000 :return error: nil if no error in getting from KV store
1001 */
1002
1003 Path := fmt.Sprintf(FLOW_ID_INFO_PATH, PONRMgr.DeviceID, IntfONUID, FlowID)
1004
1005 Value, err := PONRMgr.KVStore.Get(ctx, Path)
1006 if err == nil {
1007 if Value != nil {
1008 Val, err := ToByte(Value.Value)
1009 if err != nil {
1010 logger.Errorw(ctx, "Failed to convert flowinfo into byte array", log.Fields{"error": err})
1011 return err
1012 }
1013 if err = json.Unmarshal(Val, Data); err != nil {
1014 logger.Errorw(ctx, "Failed to unmarshal", log.Fields{"error": err})
1015 return err
1016 }
1017 }
1018 }
1019 return err
1020}
1021
1022func (PONRMgr *PONResourceManager) RemoveFlowIDInfo(ctx context.Context, IntfONUID string, FlowID uint32) bool {
1023 /*
1024 Get flow_id details configured for the ONU.
1025 :param pon_intf_onu_id: reference of PON interface id and onu id
1026 :param flow_id: Flow Id reference
1027 */
1028 Path := fmt.Sprintf(FLOW_ID_INFO_PATH, PONRMgr.DeviceID, IntfONUID, FlowID)
1029
1030 if err := PONRMgr.KVStore.Delete(ctx, Path); err != nil {
1031 logger.Errorf(ctx, "Falied to remove resource %s", Path)
1032 return false
1033 }
1034 return true
1035}
1036
1037func (PONRMgr *PONResourceManager) UpdateAllocIdsForOnu(ctx context.Context, IntfONUID string, AllocIDs []uint32) error {
1038 /*
1039 Update currently configured alloc ids for given pon_intf_onu_id
1040 :param pon_intf_onu_id: reference of PON interface id and onu id
1041 :param alloc_ids: list of alloc ids
1042 */
1043 var Value []byte
1044 var err error
1045 Path := fmt.Sprintf(ALLOC_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
1046 Value, err = json.Marshal(AllocIDs)
1047 if err != nil {
1048 logger.Error(ctx, "failed to Marshal")
1049 return err
1050 }
1051
1052 if err = PONRMgr.KVStore.Put(ctx, Path, Value); err != nil {
1053 logger.Errorf(ctx, "Failed to update resource %s", Path)
1054 return err
1055 }
1056 return err
1057}
1058
1059func (PONRMgr *PONResourceManager) UpdateGEMPortIDsForOnu(ctx context.Context, IntfONUID string, GEMPortIDs []uint32) error {
1060 /*
1061 Update currently configured gemport ids for given pon_intf_onu_id
1062 :param pon_intf_onu_id: reference of PON interface id and onu id
1063 :param gemport_ids: list of gem port ids
1064 */
1065
1066 var Value []byte
1067 var err error
1068 Path := fmt.Sprintf(GEMPORT_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
1069 logger.Debugf(ctx, "Updating gemport ids for %s", Path)
1070 Value, err = json.Marshal(GEMPortIDs)
1071 if err != nil {
1072 logger.Error(ctx, "failed to Marshal")
1073 return err
1074 }
1075
1076 if err = PONRMgr.KVStore.Put(ctx, Path, Value); err != nil {
1077 logger.Errorf(ctx, "Failed to update resource %s", Path)
1078 return err
1079 }
1080 return err
1081}
1082
1083func checkForFlowIDInList(FlowIDList []uint32, FlowID uint32) (bool, uint32) {
1084 /*
1085 Check for a flow id in a given list of flow IDs.
1086 :param FLowIDList: List of Flow IDs
1087 :param FlowID: Flowd to check in the list
1088 : return true and the index if present false otherwise.
1089 */
1090
1091 for idx := range FlowIDList {
1092 if FlowID == FlowIDList[idx] {
1093 return true, uint32(idx)
1094 }
1095 }
1096 return false, 0
1097}
1098
1099func (PONRMgr *PONResourceManager) UpdateFlowIDForOnu(ctx context.Context, IntfONUID string, FlowID uint32, Add bool) error {
1100 /*
1101 Update the flow_id list of the ONU (add or remove flow_id from the list)
1102 :param pon_intf_onu_id: reference of PON interface id and onu id
1103 :param flow_id: flow ID
1104 :param add: Boolean flag to indicate whether the flow_id should be
1105 added or removed from the list. Defaults to adding the flow.
1106 */
1107 var Value []byte
1108 var err error
1109 var RetVal bool
1110 var IDx uint32
1111 Path := fmt.Sprintf(FLOW_ID_RESOURCE_MAP_PATH, PONRMgr.DeviceID, IntfONUID)
1112 FlowIDs := PONRMgr.GetCurrentFlowIDsForOnu(ctx, IntfONUID)
1113
1114 if Add {
1115 if RetVal, _ = checkForFlowIDInList(FlowIDs, FlowID); RetVal {
1116 return nil
1117 }
1118 FlowIDs = append(FlowIDs, FlowID)
1119 } else {
1120 if RetVal, IDx = checkForFlowIDInList(FlowIDs, FlowID); !RetVal {
1121 return nil
1122 }
1123 // delete the index and shift
1124 FlowIDs = append(FlowIDs[:IDx], FlowIDs[IDx+1:]...)
1125 }
1126 Value, err = json.Marshal(FlowIDs)
1127 if err != nil {
1128 logger.Error(ctx, "Failed to Marshal")
1129 return err
1130 }
1131
1132 if err = PONRMgr.KVStore.Put(ctx, Path, Value); err != nil {
1133 logger.Errorf(ctx, "Failed to update resource %s", Path)
1134 return err
1135 }
1136 return err
1137}
1138
1139func (PONRMgr *PONResourceManager) UpdateFlowIDInfoForOnu(ctx context.Context, IntfONUID string, FlowID uint32, FlowData interface{}) error {
1140 /*
1141 Update any metadata associated with the flow_id. The flow_data could be json
1142 or any of other data structure. The resource manager doesnt care
1143 :param pon_intf_onu_id: reference of PON interface id and onu id
1144 :param flow_id: Flow ID
1145 :param flow_data: Flow data blob
1146 */
1147 var Value []byte
1148 var err error
1149 Path := fmt.Sprintf(FLOW_ID_INFO_PATH, PONRMgr.DeviceID, IntfONUID, FlowID)
1150 Value, err = json.Marshal(FlowData)
1151 if err != nil {
1152 logger.Error(ctx, "failed to Marshal")
1153 return err
1154 }
1155
1156 if err = PONRMgr.KVStore.Put(ctx, Path, Value); err != nil {
1157 logger.Errorf(ctx, "Failed to update resource %s", Path)
1158 return err
1159 }
1160 return err
1161}
1162
1163func (PONRMgr *PONResourceManager) GenerateNextID(ctx context.Context, Resource map[string]interface{}) (uint32, error) {
1164 /*
1165 Generate unique id having OFFSET as start
1166 :param resource: resource used to generate ID
1167 :return uint32: generated id
1168 */
1169 ByteArray, err := ToByte(Resource[POOL])
1170 if err != nil {
1171 logger.Error(ctx, "Failed to convert resource to byte array")
1172 return 0, err
1173 }
1174 Data := bitmap.TSFromData(ByteArray, false)
1175 if Data == nil {
1176 logger.Error(ctx, "Failed to get data from byte array")
1177 return 0, errors.New("Failed to get data from byte array")
1178 }
1179
1180 Len := Data.Len()
1181 var Idx int
1182 for Idx = 0; Idx < Len; Idx++ {
1183 if !Data.Get(Idx) {
1184 break
1185 }
1186 }
1187 Data.Set(Idx, true)
1188 res := uint32(Resource[START_IDX].(float64))
1189 Resource[POOL] = Data.Data(false)
1190 logger.Debugf(ctx, "Generated ID for %d", (uint32(Idx) + res))
1191 return (uint32(Idx) + res), err
1192}
1193
1194func (PONRMgr *PONResourceManager) ReleaseID(ctx context.Context, Resource map[string]interface{}, Id uint32) bool {
1195 /*
1196 Release unique id having OFFSET as start index.
1197 :param resource: resource used to release ID
1198 :param unique_id: id need to be released
1199 */
1200 ByteArray, err := ToByte(Resource[POOL])
1201 if err != nil {
1202 logger.Error(ctx, "Failed to convert resource to byte array")
1203 return false
1204 }
1205 Data := bitmap.TSFromData(ByteArray, false)
1206 if Data == nil {
1207 logger.Error(ctx, "Failed to get resource pool")
1208 return false
1209 }
1210 Idx := Id - uint32(Resource[START_IDX].(float64))
1211 Data.Set(int(Idx), false)
1212 Resource[POOL] = Data.Data(false)
1213
1214 return true
1215}
1216
1217/* Reserves a unique id in the specified resource pool.
1218:param Resource: resource used to reserve ID
1219:param Id: ID to be reserved
1220*/
1221func (PONRMgr *PONResourceManager) reserveID(ctx context.Context, TSData *bitmap.Threadsafe, StartIndex uint32, Id uint32) bool {
1222 Data := bitmap.TSFromData(TSData.Data(false), false)
1223 if Data == nil {
1224 logger.Error(ctx, "Failed to get resource pool")
1225 return false
1226 }
1227 Idx := Id - StartIndex
1228 Data.Set(int(Idx), true)
1229 return true
1230}
1231
1232func (PONRMgr *PONResourceManager) GetTechnology() string {
1233 return PONRMgr.Technology
1234}
1235
1236func (PONRMgr *PONResourceManager) GetResourceTypeAllocID() string {
1237 return ALLOC_ID
1238}
1239
1240func (PONRMgr *PONResourceManager) GetResourceTypeGemPortID() string {
1241 return GEMPORT_ID
1242}
1243
1244// ToByte converts an interface value to a []byte. The interface should either be of
1245// a string type or []byte. Otherwise, an error is returned.
1246func ToByte(value interface{}) ([]byte, error) {
1247 switch t := value.(type) {
1248 case []byte:
1249 return value.([]byte), nil
1250 case string:
1251 return []byte(value.(string)), nil
1252 default:
1253 return nil, fmt.Errorf("unexpected-type-%T", t)
1254 }
1255}
1256
1257// ToString converts an interface value to a string. The interface should either be of
1258// a string type or []byte. Otherwise, an error is returned.
1259func ToString(value interface{}) (string, error) {
1260 switch t := value.(type) {
1261 case []byte:
1262 return string(value.([]byte)), nil
1263 case string:
1264 return value.(string), nil
1265 default:
1266 return "", fmt.Errorf("unexpected-type-%T", t)
1267 }
1268}
1269
1270func (PONRMgr *PONResourceManager) AddOnuGemInfo(ctx context.Context, intfID uint32, onuGemData interface{}) error {
1271 /*
1272 Update onugem info map,
1273 :param pon_intf_id: reference of PON interface id
1274 :param onuegmdata: onugem info map
1275 */
1276 var Value []byte
1277 var err error
1278 Path := fmt.Sprintf(ONU_GEM_INFO_PATH, PONRMgr.DeviceID, intfID)
1279 Value, err = json.Marshal(onuGemData)
1280 if err != nil {
1281 logger.Error(ctx, "failed to Marshal")
1282 return err
1283 }
1284
1285 if err = PONRMgr.KVStore.Put(ctx, Path, Value); err != nil {
1286 logger.Errorf(ctx, "Failed to update resource %s", Path)
1287 return err
1288 }
1289 return err
1290}
1291
1292func (PONRMgr *PONResourceManager) GetOnuGemInfo(ctx context.Context, IntfId uint32, onuGemInfo interface{}) error {
1293 /*
1294 Get onugeminfo map from kvstore
1295 :param intfid: refremce pon intfid
1296 :param onuGemInfo: onugem info to return from kv strore.
1297 */
1298 var Val []byte
1299
1300 path := fmt.Sprintf(ONU_GEM_INFO_PATH, PONRMgr.DeviceID, IntfId)
1301 value, err := PONRMgr.KVStore.Get(ctx, path)
1302 if err != nil {
1303 logger.Errorw(ctx, "Failed to get from kv store", log.Fields{"path": path})
1304 return err
1305 } else if value == nil {
1306 logger.Debug(ctx, "No onuinfo for path", log.Fields{"path": path})
1307 return nil // returning nil as this could happen if there are no onus for the interface yet
1308 }
1309 if Val, err = kvstore.ToByte(value.Value); err != nil {
1310 logger.Error(ctx, "Failed to convert to byte array")
1311 return err
1312 }
1313
1314 if err = json.Unmarshal(Val, &onuGemInfo); err != nil {
1315 logger.Error(ctx, "Failed to unmarshall")
1316 return err
1317 }
1318 logger.Debugw(ctx, "found onuinfo from path", log.Fields{"path": path, "onuinfo": onuGemInfo})
1319 return err
1320}
1321
1322func (PONRMgr *PONResourceManager) DelOnuGemInfoForIntf(ctx context.Context, intfId uint32) error {
1323 /*
1324 delete onugem info for an interface from kvstore
1325 :param intfid: refremce pon intfid
1326 */
1327
1328 path := fmt.Sprintf(ONU_GEM_INFO_PATH, PONRMgr.DeviceID, intfId)
1329 if err := PONRMgr.KVStore.Delete(ctx, path); err != nil {
1330 logger.Errorf(ctx, "Falied to remove resource %s", path)
1331 return err
1332 }
1333 return nil
1334}