Prince Pereira | c1c21d6 | 2021-04-22 08:38:15 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2020-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 | |
| 17 | // Package config Common Logger initialization |
| 18 | package config |
| 19 | |
| 20 | import ( |
| 21 | "context" |
| 22 | "fmt" |
| 23 | |
| 24 | "github.com/google/uuid" |
| 25 | ) |
| 26 | |
| 27 | var ctxGlobal context.Context |
| 28 | |
| 29 | // Core represent read,write core attributes |
| 30 | type Core struct { |
| 31 | Ctx context.Context |
| 32 | Cancel context.CancelFunc |
| 33 | Stopped chan struct{} |
| 34 | } |
| 35 | |
| 36 | // NewCoreConfig will give the new core configuration |
| 37 | func NewCoreConfig() *Core { |
| 38 | ctx, cancelCtx := context.WithCancel(context.Background()) |
| 39 | core := &Core{Ctx: ctx, Cancel: cancelCtx, Stopped: make(chan struct{})} |
| 40 | ctxGlobal = ctx |
| 41 | return core |
| 42 | } |
| 43 | |
| 44 | // GetContext returns global context |
| 45 | func GetContext() context.Context { |
| 46 | return ctxGlobal |
| 47 | } |
| 48 | |
| 49 | func retConstructedContxt(ctx context.Context, msg string) context.Context { |
| 50 | id, _ := uuid.NewRandom() |
| 51 | var reqID string |
| 52 | if msg != "" { |
| 53 | reqID = fmt.Sprintf("%s-%v", msg, id) |
| 54 | } else { |
| 55 | reqID = fmt.Sprintf("%v", id) |
| 56 | } |
| 57 | ctx2 := context.WithValue(ctx, RequestIdKey, reqID) |
| 58 | return ctx2 |
| 59 | } |
| 60 | |
| 61 | // GetNewContextFromGlobalContxt returns context from global context |
| 62 | func GetNewContextFromGlobalContxt(msg string) context.Context { |
| 63 | return retConstructedContxt(ctxGlobal, msg) |
| 64 | } |
| 65 | |
| 66 | // GetNewContextFromContxt returns new context from passed context |
| 67 | func GetNewContextFromContxt(ctx context.Context, msg string) context.Context { |
| 68 | return retConstructedContxt(ctx, msg) |
| 69 | } |