|
| 1 | +// Copyright 2024 TiKV Project Authors. |
| 2 | +// |
| 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 | +package caller |
| 16 | + |
| 17 | +import ( |
| 18 | + "os" |
| 19 | + "path/filepath" |
| 20 | + "runtime" |
| 21 | + "strings" |
| 22 | +) |
| 23 | + |
| 24 | +type ( |
| 25 | + // Caller ID can be understood as a binary file; it is a process. |
| 26 | + ID string |
| 27 | + // Caller component refers to the components within the process. |
| 28 | + Component string |
| 29 | +) |
| 30 | + |
| 31 | +const ( |
| 32 | + // TestID is used for test. |
| 33 | + TestID ID = "test" |
| 34 | + // TestComponent is used for test. |
| 35 | + TestComponent Component = "test" |
| 36 | +) |
| 37 | + |
| 38 | +var processName ID |
| 39 | + |
| 40 | +func init() { |
| 41 | + processName = ID(filepath.Base(os.Args[0])) |
| 42 | +} |
| 43 | + |
| 44 | +// GetCallerID returns the name of the currently running process |
| 45 | +func GetCallerID() ID { |
| 46 | + return processName |
| 47 | +} |
| 48 | + |
| 49 | +// GetComponent returns the package path of the calling function |
| 50 | +// The argument upperLayer specifies the number of stack frames to ascend. |
| 51 | +// NOTE: This function is time-consuming and please do not use it in high qps scenarios. |
| 52 | +func GetComponent(upperLayer int) Component { |
| 53 | + // Get the program counter for the calling function |
| 54 | + pc, _, _, ok := runtime.Caller(upperLayer + 1) |
| 55 | + if !ok { |
| 56 | + return "unknown" |
| 57 | + } |
| 58 | + |
| 59 | + // Retrieve the full function name, including the package path |
| 60 | + fullFuncName := runtime.FuncForPC(pc).Name() |
| 61 | + |
| 62 | + // Separates the package and function |
| 63 | + lastSlash := strings.LastIndex(fullFuncName, ".") |
| 64 | + |
| 65 | + // Extract the package name |
| 66 | + return Component(fullFuncName[:lastSlash]) |
| 67 | +} |
0 commit comments