You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

parseutils.go 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2025 The HuaTuo 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. package parseutil
  15. import (
  16. "bufio"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "strings"
  21. )
  22. // ReadUint read single value in file
  23. func ReadUint(path string) (uint64, error) {
  24. v, err := os.ReadFile(path)
  25. if err != nil {
  26. return 0, err
  27. }
  28. return strconv.ParseUint(strings.TrimSpace(string(v)), 10, 64)
  29. }
  30. // ReadInt64 read single value in file
  31. func ReadInt(path string) (int64, error) {
  32. v, err := os.ReadFile(path)
  33. if err != nil {
  34. return 0, err
  35. }
  36. return strconv.ParseInt(strings.TrimSpace(string(v)), 10, 64)
  37. }
  38. func parseKV(raw string) (string, uint64, error) {
  39. parts := strings.Fields(raw)
  40. switch len(parts) {
  41. case 2:
  42. v, err := strconv.ParseUint(parts[1], 10, 64)
  43. if err != nil {
  44. return "", 0, err
  45. }
  46. return parts[0], v, nil
  47. default:
  48. return "", 0, fmt.Errorf("invalid format")
  49. }
  50. }
  51. // RawKV parse the kv cgroup file
  52. func RawKV(path string) (map[string]uint64, error) {
  53. f, err := os.Open(path)
  54. if err != nil {
  55. return nil, err
  56. }
  57. defer f.Close()
  58. var (
  59. raw = make(map[string]uint64)
  60. sc = bufio.NewScanner(f)
  61. )
  62. for sc.Scan() {
  63. key, v, err := parseKV(sc.Text())
  64. if err != nil {
  65. return nil, err
  66. }
  67. raw[key] = v
  68. }
  69. if err := sc.Err(); err != nil {
  70. return nil, err
  71. }
  72. return raw, nil
  73. }
  74. func KV(path string) (string, uint64, error) {
  75. f, err := os.Open(path)
  76. if err != nil {
  77. return "", 0, err
  78. }
  79. defer f.Close()
  80. scanner := bufio.NewScanner(f)
  81. scanner.Scan()
  82. if err := scanner.Err(); err != nil {
  83. return "", 0, err
  84. }
  85. return parseKV(scanner.Text())
  86. }

HUATUO(华佗)是由滴滴开源并依托 CCF 开源发展委员会孵化的云原生操作系统可观测性项目,专注于为复杂云原生环境提供操作系统内核级深度观测能力