1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
|
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package btrfs
import (
"bufio"
"fmt"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/prometheus/procfs"
"github.com/prometheus/procfs/internal/fs"
"github.com/prometheus/procfs/internal/util"
)
// FS represents the pseudo-filesystem sys, which provides an interface to
// kernel data structures.
type FS struct {
sys *fs.FS
}
// NewDefaultFS returns a new Bcache using the default sys fs mount point. It will error
// if the mount point can't be read.
func NewDefaultFS() (FS, error) {
return NewFS(fs.DefaultSysMountPoint)
}
// NewFS returns a new Btrfs filesystem using the given sys fs mount point. It will error
// if the mount point can't be read.
func NewFS(mountPoint string) (FS, error) {
if strings.TrimSpace(mountPoint) == "" {
mountPoint = fs.DefaultSysMountPoint
}
sys, err := fs.NewFS(mountPoint)
if err != nil {
return FS{}, err
}
return FS{&sys}, nil
}
// Stats retrieves Btrfs filesystem runtime statistics for each mounted Btrfs filesystem.
func (fs FS) Stats() ([]*Stats, error) {
matches, err := filepath.Glob(fs.sys.Path("fs/btrfs/*-*"))
if err != nil {
return nil, err
}
stats := make([]*Stats, 0, len(matches))
for _, uuidPath := range matches {
s, err := GetStats(uuidPath)
if err != nil {
return nil, err
}
// Set the UUID from the path when it could not be retrieved from the filesystem.
if s.UUID == "" {
s.UUID = filepath.Base(uuidPath)
}
stats = append(stats, s)
}
return stats, nil
}
// GetStats collects all Btrfs statistics from sysfs.
func GetStats(uuidPath string) (*Stats, error) {
r := &reader{path: uuidPath}
s := r.readFilesystemStats()
if r.err != nil {
return nil, r.err
}
return s, nil
}
type reader struct {
path string
err error
devCount int
}
// readFile reads a file relative to the path of the reader.
// Non-existing files are ignored.
func (r *reader) readFile(n string) string {
b, err := util.SysReadFile(path.Join(r.path, n))
if err != nil && !os.IsNotExist(err) {
r.err = err
}
return strings.TrimSpace(string(b))
}
// readValues reads a number of numerical values into an uint64 slice.
func (r *reader) readValue(n string) (v uint64) {
// Read value from file
s := r.readFile(n)
if r.err != nil {
return
}
// Convert number
v, _ = strconv.ParseUint(s, 10, 64)
return
}
// listFiles returns a list of files for a directory of the reader.
func (r *reader) listFiles(p string) []string {
files, err := os.ReadDir(path.Join(r.path, p))
if err != nil {
r.err = err
return nil
}
names := make([]string, len(files))
for i, f := range files {
names[i] = f.Name()
}
return names
}
// readAllocationStats reads Btrfs allocation data for the current path.
func (r *reader) readAllocationStats(d string) (a *AllocationStats) {
// Create a reader for this subdirectory
sr := &reader{path: path.Join(r.path, d), devCount: r.devCount}
// Get the stats
a = &AllocationStats{
// Read basic allocation stats
MayUseBytes: sr.readValue("bytes_may_use"),
PinnedBytes: sr.readValue("bytes_pinned"),
ReadOnlyBytes: sr.readValue("bytes_readonly"),
ReservedBytes: sr.readValue("bytes_reserved"),
UsedBytes: sr.readValue("bytes_used"),
DiskUsedBytes: sr.readValue("disk_used"),
DiskTotalBytes: sr.readValue("disk_total"),
Flags: sr.readValue("flags"),
TotalBytes: sr.readValue("total_bytes"),
TotalPinnedBytes: sr.readValue("total_bytes_pinned"),
Layouts: sr.readLayouts(),
}
// Pass any error back
r.err = sr.err
return
}
// readLayouts reads all Btrfs layout statistics for the current path.
func (r *reader) readLayouts() map[string]*LayoutUsage {
files, err := os.ReadDir(r.path)
if err != nil {
r.err = err
return nil
}
m := make(map[string]*LayoutUsage)
for _, f := range files {
if f.IsDir() {
m[f.Name()] = r.readLayout(f.Name())
}
}
return m
}
// readLayout reads the Btrfs layout statistics for an allocation layout.
func (r *reader) readLayout(p string) (l *LayoutUsage) {
l = new(LayoutUsage)
l.TotalBytes = r.readValue(path.Join(p, "total_bytes"))
l.UsedBytes = r.readValue(path.Join(p, "used_bytes"))
l.Ratio = r.calcRatio(p)
return
}
// calcRatio returns the calculated ratio for a layout mode.
func (r *reader) calcRatio(p string) float64 {
switch p {
case "single", "raid0":
return 1
case "dup", "raid1", "raid10":
return 2
case "raid1c3":
return 3
case "raid1c4":
return 4
case "raid5":
return float64(r.devCount) / (float64(r.devCount) - 1)
case "raid6":
return float64(r.devCount) / (float64(r.devCount) - 2)
default:
return 0
}
}
// readDeviceInfo returns the information for all devices associated with this filesystem.
func (r *reader) readDeviceInfo(d string) map[string]*Device {
devs := r.listFiles(d)
info := make(map[string]*Device, len(devs))
for _, n := range devs {
info[n] = &Device{
Size: procfs.SectorSize * r.readValue("devices/"+n+"/size"),
}
}
return info
}
// readFilesystemStats reads Btrfs statistics for a filesystem.
func (r *reader) readFilesystemStats() (s *Stats) {
// First get disk info, and add it to reader
devices := r.readDeviceInfo("devices")
r.devCount = len(devices)
s = &Stats{
// Read basic filesystem information
Label: r.readFile("label"),
UUID: r.readFile("metadata_uuid"),
Features: r.listFiles("features"),
CloneAlignment: r.readValue("clone_alignment"),
NodeSize: r.readValue("nodesize"),
QuotaOverride: r.readValue("quota_override"),
SectorSize: r.readValue("sectorsize"),
// Device info
Devices: devices,
// Read allocation data
Allocation: Allocation{
GlobalRsvReserved: r.readValue("allocation/global_rsv_reserved"),
GlobalRsvSize: r.readValue("allocation/global_rsv_size"),
Data: r.readAllocationStats("allocation/data"),
Metadata: r.readAllocationStats("allocation/metadata"),
System: r.readAllocationStats("allocation/system"),
},
// Read commit stats data
CommitStats: r.readCommitStats("commit_stats"),
}
return
}
// readCommitStats returns the commit_stats information for commit stats metrics.
func (r *reader) readCommitStats(p string) CommitStats {
stats := CommitStats{}
f, err := os.Open(path.Join(r.path, p))
if err != nil {
// if commit_stats not found. maybe btrfs version < 6.0
if !os.IsNotExist(err) {
r.err = err
}
return stats
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(scanner.Text())
// require <key> <value>
if len(parts) != 2 {
r.err = fmt.Errorf("invalid commit_stats line %q", line)
return stats
}
value, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
r.err = fmt.Errorf("error parsing commit_stats line: %w", err)
return stats
}
switch metricName := parts[0]; metricName {
case "commits":
stats.Commits = value
case "last_commit_ms":
stats.LastCommitMs = value
case "max_commit_ms":
stats.MaxCommitMs = value
case "total_commit_ms":
stats.TotalCommitMs = value
default:
continue
}
}
if err := scanner.Err(); err != nil {
r.err = fmt.Errorf("error scanning commit_stats file: %w", err)
return stats
}
return stats
}
|