fileutils_linux.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package fileutils
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os"
  7. "github.com/containerd/containerd/tracing"
  8. "github.com/containerd/log"
  9. "golang.org/x/sys/unix"
  10. )
  11. // GetTotalUsedFds Returns the number of used File Descriptors by
  12. // reading it via /proc filesystem.
  13. func GetTotalUsedFds(ctx context.Context) int {
  14. ctx, span := tracing.StartSpan(ctx, "GetTotalUsedFds")
  15. defer span.End()
  16. name := fmt.Sprintf("/proc/%d/fd", os.Getpid())
  17. // Fast-path for Linux 6.2 (since [f1f1f2569901ec5b9d425f2e91c09a0e320768f3]).
  18. // From the [Linux docs]:
  19. //
  20. // "The number of open files for the process is stored in 'size' member of
  21. // stat() output for /proc/<pid>/fd for fast access."
  22. //
  23. // [Linux docs]: https://docs.kernel.org/filesystems/proc.html#proc-pid-fd-list-of-symlinks-to-open-files:
  24. // [f1f1f2569901ec5b9d425f2e91c09a0e320768f3]: https://github.com/torvalds/linux/commit/f1f1f2569901ec5b9d425f2e91c09a0e320768f3
  25. var stat unix.Stat_t
  26. if err := unix.Stat(name, &stat); err == nil && stat.Size > 0 {
  27. return int(stat.Size)
  28. }
  29. f, err := os.Open(name)
  30. if err != nil {
  31. log.G(ctx).WithError(err).Error("Error listing file descriptors")
  32. return -1
  33. }
  34. defer f.Close()
  35. var fdCount int
  36. for {
  37. select {
  38. case <-ctx.Done():
  39. log.G(ctx).WithError(ctx.Err()).Error("Context cancelled while counting file descriptors")
  40. return -1
  41. default:
  42. }
  43. names, err := f.Readdirnames(100)
  44. fdCount += len(names)
  45. if err == io.EOF {
  46. break
  47. } else if err != nil {
  48. log.G(ctx).WithError(err).Error("Error listing file descriptors")
  49. return -1
  50. }
  51. }
  52. // Note that the slow path has 1 more file-descriptor, due to the open
  53. // file-handle for /proc/<pid>/fd during the calculation.
  54. return fdCount
  55. }