fds_linux.go 818 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package metrics
  4. import (
  5. "io/fs"
  6. "sync"
  7. "go4.org/mem"
  8. "tailscale.com/util/dirwalk"
  9. )
  10. // counter is a reusable counter for counting file descriptors.
  11. type counter struct {
  12. n int
  13. // cb is the (*counter).count method value. Creating it allocates,
  14. // so we have to save it away and use a sync.Pool to keep currentFDs
  15. // amortized alloc-free.
  16. cb func(name mem.RO, de fs.DirEntry) error
  17. }
  18. var counterPool = &sync.Pool{New: func() any {
  19. c := new(counter)
  20. c.cb = c.count
  21. return c
  22. }}
  23. func (c *counter) count(name mem.RO, de fs.DirEntry) error {
  24. c.n++
  25. return nil
  26. }
  27. func currentFDs() int {
  28. c := counterPool.Get().(*counter)
  29. defer counterPool.Put(c)
  30. c.n = 0
  31. dirwalk.WalkShallow(mem.S("/proc/self/fd"), c.cb)
  32. return c.n
  33. }