Files

124 lines
2.7 KiB
Go
Raw Permalink Normal View History

package arrange
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
)
// Problem is something Verify found wrong with a file in the content store.
type Problem struct {
Path string
Kind string // "corrupt", "orphan", "stale", or "error"
Err error
}
func (p Problem) Error() string {
if p.Err != nil {
return fmt.Sprintf("%s: %q: %v", p.Kind, p.Path, p.Err)
}
return fmt.Sprintf("%s: %q", p.Kind, p.Path)
}
// Verify rehashes every file in root's content store with workers goroutines
// and reports any whose hash doesn't match its name (corrupt), that nothing in
// the date tree links to (orphan), or that a crashed run left behind (stale).
// It only reads. The returned func reports how many files were checked once
// the channel is drained.
func Verify(root string, workers int) (<-chan Problem, func() int) {
paths := make(chan string)
out := make(chan Problem)
var checked int
var mu sync.Mutex
go func() {
err := filepath.WalkDir(filepath.Join(root, "content"), func(path string, d fs.DirEntry, err error) error {
if err != nil {
out <- Problem{Path: path, Kind: "error", Err: err}
return nil
}
if d.IsDir() {
return nil
}
if strings.HasPrefix(d.Name(), ".tmp-") {
out <- Problem{Path: path, Kind: "stale"}
return nil
}
paths <- path
return nil
})
if err != nil {
out <- Problem{Path: root, Kind: "error", Err: err}
}
close(paths)
}()
var wg sync.WaitGroup
wg.Add(workers)
for w := 0; w < workers; w++ {
go func() {
defer wg.Done()
for path := range paths {
if p, ok := verifyFile(path); !ok {
out <- p
}
mu.Lock()
checked++
mu.Unlock()
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out, func() int {
mu.Lock()
defer mu.Unlock()
return checked
}
}
// verifyFile checks one content file; ok is false if p describes a problem.
func verifyFile(path string) (p Problem, ok bool) {
p.Path = path
base := filepath.Base(path)
hexname := filepath.Base(filepath.Dir(path)) + strings.TrimSuffix(base, filepath.Ext(base))
newHash := HashByName(hexname)
if newHash == nil {
p.Kind, p.Err = "error", fmt.Errorf("not a content address")
return p, false
}
f, err := os.Open(path)
if err != nil {
p.Kind, p.Err = "error", err
return p, false
}
defer f.Close()
h := newHash()
if _, err := io.Copy(h, f); err != nil {
p.Kind, p.Err = "error", err
return p, false
}
if got := fmt.Sprintf("%x", h.Sum(nil)); got != hexname {
p.Kind, p.Err = "corrupt", fmt.Errorf("contents hash to %s", got)
return p, false
}
if fi, err := f.Stat(); err == nil {
if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Nlink < 2 {
p.Kind = "orphan"
return p, false
}
}
return p, true
}