| 1 | package corerepo |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "math" |
| 6 | |
| 7 | context "context" |
| 8 | |
| 9 | "github.com/ipfs/kubo/core" |
| 10 | fsrepo "github.com/ipfs/kubo/repo/fsrepo" |
| 11 | |
| 12 | humanize "github.com/dustin/go-humanize" |
| 13 | ) |
| 14 | |
| 15 | // SizeStat wraps information about the repository size and its limit. |
| 16 | type SizeStat struct { |
| 17 | RepoSize uint64 // size in bytes |
| 18 | StorageMax uint64 // size in bytes |
| 19 | } |
| 20 | |
| 21 | // Stat wraps information about the objects stored on disk. |
| 22 | type Stat struct { |
| 23 | SizeStat |
| 24 | NumObjects uint64 |
| 25 | RepoPath string |
| 26 | Version string |
| 27 | } |
| 28 | |
| 29 | // NoLimit represents the value for unlimited storage |
| 30 | const NoLimit uint64 = math.MaxUint64 |
| 31 | |
| 32 | // RepoStat returns a *Stat object with all the fields set. |
| 33 | func RepoStat(ctx context.Context, n *core.IpfsNode) (Stat, error) { |
| 34 | sizeStat, err := RepoSize(ctx, n) |
| 35 | if err != nil { |
| 36 | return Stat{}, err |
| 37 | } |
| 38 | |
| 39 | allKeys, err := n.Blockstore.AllKeysChan(ctx) |
| 40 | if err != nil { |
| 41 | return Stat{}, err |
| 42 | } |
| 43 | |
| 44 | count := uint64(0) |
| 45 | for range allKeys { |
| 46 | count++ |
| 47 | } |
| 48 | |
| 49 | path, err := fsrepo.BestKnownPath() |
| 50 | if err != nil { |
| 51 | return Stat{}, err |
| 52 | } |
| 53 | |
| 54 | return Stat{ |
| 55 | SizeStat: SizeStat{ |
| 56 | RepoSize: sizeStat.RepoSize, |
| 57 | StorageMax: sizeStat.StorageMax, |
| 58 | }, |
| 59 | NumObjects: count, |
| 60 | RepoPath: path, |
| 61 | Version: fmt.Sprintf("fs-repo@%d", fsrepo.RepoVersion), |
| 62 | }, nil |
| 63 | } |
| 64 | |
| 65 | // RepoSize returns a *Stat object with the RepoSize and StorageMax fields set. |
| 66 | func RepoSize(ctx context.Context, n *core.IpfsNode) (SizeStat, error) { |
| 67 | r := n.Repo |
| 68 | |
| 69 | cfg, err := r.Config() |
| 70 | if err != nil { |
| 71 | return SizeStat{}, err |
| 72 | } |
| 73 | |
| 74 | usage, err := r.GetStorageUsage(ctx) |
| 75 | if err != nil { |
| 76 | return SizeStat{}, err |
| 77 | } |
| 78 | |
| 79 | storageMax := NoLimit |
| 80 | if cfg.Datastore.StorageMax != "" { |
| 81 | storageMax, err = humanize.ParseBytes(cfg.Datastore.StorageMax) |
| 82 | if err != nil { |
| 83 | return SizeStat{}, err |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | return SizeStat{ |
| 88 | RepoSize: usage, |
| 89 | StorageMax: storageMax, |
| 90 | }, nil |
| 91 | } |