du_unix.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // +build !windows
  2. /*
  3. Copyright The containerd Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  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. */
  14. package fs
  15. import (
  16. "context"
  17. "os"
  18. "path/filepath"
  19. "syscall"
  20. )
  21. type inode struct {
  22. // TODO(stevvooe): Can probably reduce memory usage by not tracking
  23. // device, but we can leave this right for now.
  24. dev, ino uint64
  25. }
  26. func newInode(stat *syscall.Stat_t) inode {
  27. return inode{
  28. // Dev is uint32 on darwin/bsd, uint64 on linux/solaris
  29. dev: uint64(stat.Dev), // nolint: unconvert
  30. // Ino is uint32 on bsd, uint64 on darwin/linux/solaris
  31. ino: uint64(stat.Ino), // nolint: unconvert
  32. }
  33. }
  34. func diskUsage(ctx context.Context, roots ...string) (Usage, error) {
  35. var (
  36. size int64
  37. inodes = map[inode]struct{}{} // expensive!
  38. )
  39. for _, root := range roots {
  40. if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
  41. if err != nil {
  42. return err
  43. }
  44. select {
  45. case <-ctx.Done():
  46. return ctx.Err()
  47. default:
  48. }
  49. inoKey := newInode(fi.Sys().(*syscall.Stat_t))
  50. if _, ok := inodes[inoKey]; !ok {
  51. inodes[inoKey] = struct{}{}
  52. size += fi.Size()
  53. }
  54. return nil
  55. }); err != nil {
  56. return Usage{}, err
  57. }
  58. }
  59. return Usage{
  60. Inodes: int64(len(inodes)),
  61. Size: size,
  62. }, nil
  63. }
  64. func diffUsage(ctx context.Context, a, b string) (Usage, error) {
  65. var (
  66. size int64
  67. inodes = map[inode]struct{}{} // expensive!
  68. )
  69. if err := Changes(ctx, a, b, func(kind ChangeKind, _ string, fi os.FileInfo, err error) error {
  70. if err != nil {
  71. return err
  72. }
  73. if kind == ChangeKindAdd || kind == ChangeKindModify {
  74. inoKey := newInode(fi.Sys().(*syscall.Stat_t))
  75. if _, ok := inodes[inoKey]; !ok {
  76. inodes[inoKey] = struct{}{}
  77. size += fi.Size()
  78. }
  79. return nil
  80. }
  81. return nil
  82. }); err != nil {
  83. return Usage{}, err
  84. }
  85. return Usage{
  86. Inodes: int64(len(inodes)),
  87. Size: size,
  88. }, nil
  89. }