blob: f50b38e352880c1d47ddf9e92d407696ae347625 [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001// Copyright 2018 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package procfs
15
16import (
17 "bufio"
18 "errors"
19 "io"
20 "os"
21 "strconv"
22 "strings"
23)
24
25// NetDevSNMP6 is parsed from files in /proc/net/dev_snmp6/ or /proc/<PID>/net/dev_snmp6/.
26// The outer map's keys are interface names and the inner map's keys are stat names.
27//
28// If you'd like a total across all interfaces, please use the Snmp6() method of the Proc type.
29type NetDevSNMP6 map[string]map[string]uint64
30
31// Returns kernel/system statistics read from interface files within the /proc/net/dev_snmp6/
32// directory.
33func (fs FS) NetDevSNMP6() (NetDevSNMP6, error) {
34 return newNetDevSNMP6(fs.proc.Path("net/dev_snmp6"))
35}
36
37// Returns kernel/system statistics read from interface files within the /proc/<PID>/net/dev_snmp6/
38// directory.
39func (p Proc) NetDevSNMP6() (NetDevSNMP6, error) {
40 return newNetDevSNMP6(p.path("net/dev_snmp6"))
41}
42
43// newNetDevSNMP6 creates a new NetDevSNMP6 from the contents of the given directory.
44func newNetDevSNMP6(dir string) (NetDevSNMP6, error) {
45 netDevSNMP6 := make(NetDevSNMP6)
46
47 // The net/dev_snmp6 folders contain one file per interface
48 ifaceFiles, err := os.ReadDir(dir)
49 if err != nil {
50 // On systems with IPv6 disabled, this directory won't exist.
51 // Do nothing.
52 if errors.Is(err, os.ErrNotExist) {
53 return netDevSNMP6, err
54 }
55 return netDevSNMP6, err
56 }
57
58 for _, iFaceFile := range ifaceFiles {
59 f, err := os.Open(dir + "/" + iFaceFile.Name())
60 if err != nil {
61 return netDevSNMP6, err
62 }
63 defer f.Close()
64
65 netDevSNMP6[iFaceFile.Name()], err = parseNetDevSNMP6Stats(f)
66 if err != nil {
67 return netDevSNMP6, err
68 }
69 }
70
71 return netDevSNMP6, nil
72}
73
74func parseNetDevSNMP6Stats(r io.Reader) (map[string]uint64, error) {
75 m := make(map[string]uint64)
76
77 scanner := bufio.NewScanner(r)
78 for scanner.Scan() {
79 stat := strings.Fields(scanner.Text())
80 if len(stat) < 2 {
81 continue
82 }
83 key, val := stat[0], stat[1]
84
85 // Expect stat name to contain "6" or be "ifIndex"
86 if strings.Contains(key, "6") || key == "ifIndex" {
87 v, err := strconv.ParseUint(val, 10, 64)
88 if err != nil {
89 return m, err
90 }
91
92 m[key] = v
93 }
94 }
95 return m, scanner.Err()
96}