2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-22 21:05:10 +00:00

Change List() implementation for all backends

This commit is contained in:
Alexander Neumann 2018-01-20 19:34:38 +01:00
parent dd91b13ff3
commit e9ea268847
12 changed files with 363 additions and 329 deletions

View File

@ -242,7 +242,11 @@ func (be *Backend) Stat(ctx context.Context, h restic.Handle) (restic.FileInfo,
return restic.FileInfo{}, errors.Wrap(err, "blob.GetProperties") return restic.FileInfo{}, errors.Wrap(err, "blob.GetProperties")
} }
return restic.FileInfo{Size: int64(blob.Properties.ContentLength)}, nil fi := restic.FileInfo{
Size: int64(blob.Properties.ContentLength),
Name: h.Name,
}
return fi, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -271,17 +275,15 @@ func (be *Backend) Remove(ctx context.Context, h restic.Handle) error {
return errors.Wrap(err, "client.RemoveObject") return errors.Wrap(err, "client.RemoveObject")
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (be *Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (be *Backend) List(ctx context.Context, t restic.FileType) <-chan string {
debug.Log("listing %v", t) debug.Log("listing %v", t)
ch := make(chan string)
prefix, _ := be.Basedir(t) prefix, _ := be.Basedir(t)
// make sure prefix ends with a slash // make sure prefix ends with a slash
if prefix[len(prefix)-1] != '/' { if !strings.HasSuffix(prefix, "/") {
prefix += "/" prefix += "/"
} }
@ -290,53 +292,57 @@ func (be *Backend) List(ctx context.Context, t restic.FileType) <-chan string {
Prefix: prefix, Prefix: prefix,
} }
go func() { for {
defer close(ch) be.sem.GetToken()
obj, err := be.container.ListBlobs(params)
be.sem.ReleaseToken()
for { if err != nil {
be.sem.GetToken() return err
obj, err := be.container.ListBlobs(params)
be.sem.ReleaseToken()
if err != nil {
return
}
debug.Log("got %v objects", len(obj.Blobs))
for _, item := range obj.Blobs {
m := strings.TrimPrefix(item.Name, prefix)
if m == "" {
continue
}
select {
case ch <- path.Base(m):
case <-ctx.Done():
return
}
}
if obj.NextMarker == "" {
break
}
params.Marker = obj.NextMarker
} }
}()
return ch debug.Log("got %v objects", len(obj.Blobs))
for _, item := range obj.Blobs {
m := strings.TrimPrefix(item.Name, prefix)
if m == "" {
continue
}
fi := restic.FileInfo{
Name: path.Base(m),
Size: item.Properties.ContentLength,
}
if ctx.Err() != nil {
return ctx.Err()
}
err := fn(fi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
if obj.NextMarker == "" {
break
}
params.Marker = obj.NextMarker
}
return ctx.Err()
} }
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error { func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error {
for key := range be.List(ctx, restic.DataFile) { return be.List(ctx, t, func(fi restic.FileInfo) error {
err := be.Remove(ctx, restic.Handle{Type: restic.DataFile, Name: key}) return be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// Delete removes all restic keys in the bucket. It will not remove the bucket itself. // Delete removes all restic keys in the bucket. It will not remove the bucket itself.

View File

@ -228,7 +228,7 @@ func (be *b2Backend) Stat(ctx context.Context, h restic.Handle) (bi restic.FileI
debug.Log("Attrs() err %v", err) debug.Log("Attrs() err %v", err)
return restic.FileInfo{}, errors.Wrap(err, "Stat") return restic.FileInfo{}, errors.Wrap(err, "Stat")
} }
return restic.FileInfo{Size: info.Size}, nil return restic.FileInfo{Size: info.Size, Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -262,66 +262,76 @@ func (be *b2Backend) Remove(ctx context.Context, h restic.Handle) error {
// List returns a channel that yields all names of blobs of type t. A // List returns a channel that yields all names of blobs of type t. A
// goroutine is started for this. If the channel done is closed, sending // goroutine is started for this. If the channel done is closed, sending
// stops. // stops.
func (be *b2Backend) List(ctx context.Context, t restic.FileType) <-chan string { func (be *b2Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
debug.Log("List %v", t) debug.Log("List %v", t)
ch := make(chan string)
prefix, _ := be.Basedir(t)
cur := &b2.Cursor{Prefix: prefix}
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() { for {
defer close(ch) be.sem.GetToken()
defer cancel() objs, c, err := be.bucket.ListCurrentObjects(ctx, be.listMaxItems, cur)
be.sem.ReleaseToken()
prefix, _ := be.Basedir(t) if err != nil && err != io.EOF {
cur := &b2.Cursor{Prefix: prefix} debug.Log("List: %v", err)
return err
for {
be.sem.GetToken()
objs, c, err := be.bucket.ListCurrentObjects(ctx, be.listMaxItems, cur)
be.sem.ReleaseToken()
if err != nil && err != io.EOF {
// TODO: return err to caller once err handling in List() is improved
debug.Log("List: %v", err)
return
}
debug.Log("returned %v items", len(objs))
for _, obj := range objs {
// Skip objects returned that do not have the specified prefix.
if !strings.HasPrefix(obj.Name(), prefix) {
continue
}
m := path.Base(obj.Name())
if m == "" {
continue
}
select {
case ch <- m:
case <-ctx.Done():
return
}
}
if err == io.EOF {
return
}
cur = c
} }
}()
return ch debug.Log("returned %v items", len(objs))
for _, obj := range objs {
// Skip objects returned that do not have the specified prefix.
if !strings.HasPrefix(obj.Name(), prefix) {
continue
}
m := path.Base(obj.Name())
if m == "" {
continue
}
if ctx.Err() != nil {
return ctx.Err()
}
attrs, err := obj.Attrs(ctx)
if err != nil {
return err
}
fi := restic.FileInfo{
Name: m,
Size: attrs.Size,
}
err = fn(fi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
if err == io.EOF {
return ctx.Err()
}
cur = c
}
return ctx.Err()
} }
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (be *b2Backend) removeKeys(ctx context.Context, t restic.FileType) error { func (be *b2Backend) removeKeys(ctx context.Context, t restic.FileType) error {
debug.Log("removeKeys %v", t) debug.Log("removeKeys %v", t)
for key := range be.List(ctx, t) { return be.List(ctx, t, func(fi restic.FileInfo) error {
err := be.Remove(ctx, restic.Handle{Type: t, Name: key}) return be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// Delete removes all restic keys in the bucket. It will not remove the bucket itself. // Delete removes all restic keys in the bucket. It will not remove the bucket itself.

View File

@ -333,7 +333,7 @@ func (be *Backend) Stat(ctx context.Context, h restic.Handle) (bi restic.FileInf
return restic.FileInfo{}, errors.Wrap(err, "service.Objects.Get") return restic.FileInfo{}, errors.Wrap(err, "service.Objects.Get")
} }
return restic.FileInfo{Size: int64(obj.Size)}, nil return restic.FileInfo{Size: int64(obj.Size), Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -370,69 +370,72 @@ func (be *Backend) Remove(ctx context.Context, h restic.Handle) error {
return errors.Wrap(err, "client.RemoveObject") return errors.Wrap(err, "client.RemoveObject")
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (be *Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (be *Backend) List(ctx context.Context, t restic.FileType) <-chan string {
debug.Log("listing %v", t) debug.Log("listing %v", t)
ch := make(chan string)
prefix, _ := be.Basedir(t) prefix, _ := be.Basedir(t)
// make sure prefix ends with a slash // make sure prefix ends with a slash
if prefix[len(prefix)-1] != '/' { if !strings.HasSuffix(prefix, "/") {
prefix += "/" prefix += "/"
} }
go func() { ctx, cancel := context.WithCancel(ctx)
defer close(ch) defer cancel()
listReq := be.service.Objects.List(be.bucketName).Prefix(prefix).MaxResults(int64(be.listMaxItems)) listReq := be.service.Objects.List(be.bucketName).Context(ctx).Prefix(prefix).MaxResults(int64(be.listMaxItems))
for { for {
be.sem.GetToken() be.sem.GetToken()
obj, err := listReq.Do() obj, err := listReq.Do()
be.sem.ReleaseToken() be.sem.ReleaseToken()
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "error listing %v: %v\n", prefix, err) return err
return
}
debug.Log("returned %v items", len(obj.Items))
for _, item := range obj.Items {
m := strings.TrimPrefix(item.Name, prefix)
if m == "" {
continue
}
select {
case ch <- path.Base(m):
case <-ctx.Done():
return
}
}
if obj.NextPageToken == "" {
break
}
listReq.PageToken(obj.NextPageToken)
} }
}()
return ch debug.Log("returned %v items", len(obj.Items))
for _, item := range obj.Items {
m := strings.TrimPrefix(item.Name, prefix)
if m == "" {
continue
}
if ctx.Err() != nil {
return ctx.Err()
}
fi := restic.FileInfo{
Name: path.Base(m),
Size: int64(item.Size),
}
err := fn(fi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
if obj.NextPageToken == "" {
break
}
listReq.PageToken(obj.NextPageToken)
}
return ctx.Err()
} }
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error { func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error {
for key := range be.List(ctx, restic.DataFile) { return be.List(ctx, t, func(fi restic.FileInfo) error {
err := be.Remove(ctx, restic.Handle{Type: restic.DataFile, Name: key}) return be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// Delete removes all restic keys in the bucket. It will not remove the bucket itself. // Delete removes all restic keys in the bucket. It will not remove the bucket itself.

View File

@ -191,7 +191,7 @@ func (b *Local) Stat(ctx context.Context, h restic.Handle) (restic.FileInfo, err
return restic.FileInfo{}, errors.Wrap(err, "Stat") return restic.FileInfo{}, errors.Wrap(err, "Stat")
} }
return restic.FileInfo{Size: fi.Size()}, nil return restic.FileInfo{Size: fi.Size(), Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -226,13 +226,13 @@ func isFile(fi os.FileInfo) bool {
return fi.Mode()&(os.ModeType|os.ModeCharDevice) == 0 return fi.Mode()&(os.ModeType|os.ModeCharDevice) == 0
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. // error occurs (or fn returns an error), List stops and returns it.
func (b *Local) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error { func (b *Local) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
debug.Log("List %v", t) debug.Log("List %v", t)
basedir, subdirs := b.Basedir(t) basedir, subdirs := b.Basedir(t)
err := fs.Walk(basedir, func(path string, fi os.FileInfo, err error) error { return fs.Walk(basedir, func(path string, fi os.FileInfo, err error) error {
debug.Log("walk on %v\n", path) debug.Log("walk on %v\n", path)
if err != nil { if err != nil {
return err return err
@ -257,24 +257,17 @@ func (b *Local) List(ctx context.Context, t restic.FileType, fn func(restic.File
Size: fi.Size(), Size: fi.Size(),
} }
if ctx.Err() != nil {
return ctx.Err()
}
err = fn(rfi) err = fn(rfi)
if err != nil { if err != nil {
return err return err
} }
if ctx.Err() != nil { return ctx.Err()
return ctx.Err()
}
return nil
}) })
if err != nil {
debug.Log("Walk %v", err)
return err
}
return ctx.Err()
} }
// Delete removes the repository and all files. // Delete removes the repository and all files.

View File

@ -143,7 +143,7 @@ func (be *MemoryBackend) Stat(ctx context.Context, h restic.Handle) (restic.File
return restic.FileInfo{}, errNotFound return restic.FileInfo{}, errNotFound
} }
return restic.FileInfo{Size: int64(len(e))}, nil return restic.FileInfo{Size: int64(len(e)), Name: h.Name}, nil
} }
// Remove deletes a file from the backend. // Remove deletes a file from the backend.
@ -177,6 +177,10 @@ func (be *MemoryBackend) List(ctx context.Context, t restic.FileType, fn func(re
Size: int64(len(buf)), Size: int64(len(buf)),
} }
if ctx.Err() != nil {
return ctx.Err()
}
err := fn(fi) err := fn(fi)
if err != nil { if err != nil {
return err return err

View File

@ -241,6 +241,7 @@ func (b *restBackend) Stat(ctx context.Context, h restic.Handle) (restic.FileInf
bi := restic.FileInfo{ bi := restic.FileInfo{
Size: resp.ContentLength, Size: resp.ContentLength,
Name: h.Name,
} }
return bi, nil return bi, nil
@ -291,12 +292,9 @@ func (b *restBackend) Remove(ctx context.Context, h restic.Handle) error {
return errors.Wrap(resp.Body.Close(), "Close") return errors.Wrap(resp.Body.Close(), "Close")
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (b *restBackend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (b *restBackend) List(ctx context.Context, t restic.FileType) <-chan string {
ch := make(chan string)
url := b.Dirname(restic.Handle{Type: t}) url := b.Dirname(restic.Handle{Type: t})
if !strings.HasSuffix(url, "/") { if !strings.HasSuffix(url, "/") {
url += "/" url += "/"
@ -306,41 +304,38 @@ func (b *restBackend) List(ctx context.Context, t restic.FileType) <-chan string
resp, err := ctxhttp.Get(ctx, b.client, url) resp, err := ctxhttp.Get(ctx, b.client, url)
b.sem.ReleaseToken() b.sem.ReleaseToken()
if resp != nil {
defer func() {
_, _ = io.Copy(ioutil.Discard, resp.Body)
e := resp.Body.Close()
if err == nil {
err = errors.Wrap(e, "Close")
}
}()
}
if err != nil { if err != nil {
close(ch) return errors.Wrap(err, "Get")
return ch
} }
dec := json.NewDecoder(resp.Body) dec := json.NewDecoder(resp.Body)
var list []string var list []string
if err = dec.Decode(&list); err != nil { if err = dec.Decode(&list); err != nil {
close(ch) return errors.Wrap(err, "Decode")
return ch
} }
go func() { for _, m := range list {
defer close(ch) fi, err := b.Stat(ctx, restic.Handle{Name: m, Type: t})
for _, m := range list { if err != nil {
select { return err
case ch <- m:
case <-ctx.Done():
return
}
} }
}()
return ch if ctx.Err() != nil {
return ctx.Err()
}
fi.Name = m
err = fn(fi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
return ctx.Err()
} }
// Close closes all open files. // Close closes all open files.
@ -352,14 +347,9 @@ func (b *restBackend) Close() error {
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (b *restBackend) removeKeys(ctx context.Context, t restic.FileType) error { func (b *restBackend) removeKeys(ctx context.Context, t restic.FileType) error {
for key := range b.List(ctx, restic.DataFile) { return b.List(ctx, t, func(fi restic.FileInfo) error {
err := b.Remove(ctx, restic.Handle{Type: restic.DataFile, Name: key}) return b.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// Delete removes all data in the backend. // Delete removes all data in the backend.

View File

@ -365,7 +365,7 @@ func (be *Backend) Stat(ctx context.Context, h restic.Handle) (bi restic.FileInf
return restic.FileInfo{}, errors.Wrap(err, "Stat") return restic.FileInfo{}, errors.Wrap(err, "Stat")
} }
return restic.FileInfo{Size: fi.Size}, nil return restic.FileInfo{Size: fi.Size, Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -402,54 +402,59 @@ func (be *Backend) Remove(ctx context.Context, h restic.Handle) error {
return errors.Wrap(err, "client.RemoveObject") return errors.Wrap(err, "client.RemoveObject")
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (be *Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (be *Backend) List(ctx context.Context, t restic.FileType) <-chan string {
debug.Log("listing %v", t) debug.Log("listing %v", t)
ch := make(chan string)
prefix, recursive := be.Basedir(t) prefix, recursive := be.Basedir(t)
// make sure prefix ends with a slash // make sure prefix ends with a slash
if prefix[len(prefix)-1] != '/' { if !strings.HasSuffix(prefix, "/") {
prefix += "/" prefix += "/"
} }
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// NB: unfortunately we can't protect this with be.sem.GetToken() here. // NB: unfortunately we can't protect this with be.sem.GetToken() here.
// Doing so would enable a deadlock situation (gh-1399), as ListObjects() // Doing so would enable a deadlock situation (gh-1399), as ListObjects()
// starts its own goroutine and returns results via a channel. // starts its own goroutine and returns results via a channel.
listresp := be.client.ListObjects(be.cfg.Bucket, prefix, recursive, ctx.Done()) listresp := be.client.ListObjects(be.cfg.Bucket, prefix, recursive, ctx.Done())
go func() { for obj := range listresp {
defer close(ch) m := strings.TrimPrefix(obj.Key, prefix)
for obj := range listresp { if m == "" {
m := strings.TrimPrefix(obj.Key, prefix) continue
if m == "" {
continue
}
select {
case ch <- path.Base(m):
case <-ctx.Done():
return
}
} }
}()
return ch fi := restic.FileInfo{
Name: path.Base(m),
Size: obj.Size,
}
if ctx.Err() != nil {
return ctx.Err()
}
err := fn(fi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
return ctx.Err()
} }
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error { func (be *Backend) removeKeys(ctx context.Context, t restic.FileType) error {
for key := range be.List(ctx, restic.DataFile) { return be.List(ctx, restic.DataFile, func(fi restic.FileInfo) error {
err := be.Remove(ctx, restic.Handle{Type: restic.DataFile, Name: key}) return be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// Delete removes all restic keys in the bucket. It will not remove the bucket itself. // Delete removes all restic keys in the bucket. It will not remove the bucket itself.

View File

@ -56,9 +56,10 @@ func TestLayout(t *testing.T) {
} }
datafiles := make(map[string]bool) datafiles := make(map[string]bool)
for id := range be.List(context.TODO(), restic.DataFile) { err = be.List(context.TODO(), restic.DataFile, func(fi restic.FileInfo) error {
datafiles[id] = false datafiles[fi.Name] = false
} return nil
})
if len(datafiles) == 0 { if len(datafiles) == 0 {
t.Errorf("List() returned zero data files") t.Errorf("List() returned zero data files")

View File

@ -376,7 +376,7 @@ func (r *SFTP) Stat(ctx context.Context, h restic.Handle) (restic.FileInfo, erro
return restic.FileInfo{}, errors.Wrap(err, "Lstat") return restic.FileInfo{}, errors.Wrap(err, "Lstat")
} }
return restic.FileInfo{Size: fi.Size()}, nil return restic.FileInfo{Size: fi.Size(), Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -408,47 +408,54 @@ func (r *SFTP) Remove(ctx context.Context, h restic.Handle) error {
return r.c.Remove(r.Filename(h)) return r.c.Remove(r.Filename(h))
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (r *SFTP) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (r *SFTP) List(ctx context.Context, t restic.FileType) <-chan string {
debug.Log("List %v", t) debug.Log("List %v", t)
ch := make(chan string) basedir, subdirs := r.Basedir(t)
walker := r.c.Walk(basedir)
go func() { for walker.Step() {
defer close(ch) if walker.Err() != nil {
return walker.Err()
basedir, subdirs := r.Basedir(t)
walker := r.c.Walk(basedir)
for walker.Step() {
if walker.Err() != nil {
continue
}
if walker.Path() == basedir {
continue
}
if walker.Stat().IsDir() && !subdirs {
walker.SkipDir()
continue
}
if !walker.Stat().Mode().IsRegular() {
continue
}
select {
case ch <- path.Base(walker.Path()):
case <-ctx.Done():
return
}
} }
}()
return ch if walker.Path() == basedir {
continue
}
if walker.Stat().IsDir() && !subdirs {
walker.SkipDir()
continue
}
fi := walker.Stat()
if !fi.Mode().IsRegular() {
continue
}
debug.Log("send %v\n", path.Base(walker.Path()))
rfi := restic.FileInfo{
Name: path.Base(walker.Path()),
Size: fi.Size(),
}
if ctx.Err() != nil {
return ctx.Err()
}
err := fn(rfi)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}
return ctx.Err()
} }
var closeTimeout = 2 * time.Second var closeTimeout = 2 * time.Second

View File

@ -6,7 +6,6 @@ import (
"io" "io"
"net/http" "net/http"
"path" "path"
"path/filepath"
"strings" "strings"
"time" "time"
@ -203,7 +202,7 @@ func (be *beSwift) Stat(ctx context.Context, h restic.Handle) (bi restic.FileInf
return restic.FileInfo{}, errors.Wrap(err, "conn.Object") return restic.FileInfo{}, errors.Wrap(err, "conn.Object")
} }
return restic.FileInfo{Size: obj.Bytes}, nil return restic.FileInfo{Size: obj.Bytes, Name: h.Name}, nil
} }
// Test returns true if a blob of the given type and name exists in the backend. // Test returns true if a blob of the given type and name exists in the backend.
@ -237,61 +236,62 @@ func (be *beSwift) Remove(ctx context.Context, h restic.Handle) error {
return errors.Wrap(err, "conn.ObjectDelete") return errors.Wrap(err, "conn.ObjectDelete")
} }
// List returns a channel that yields all names of blobs of type t. A // List runs fn for each file in the backend which has the type t. When an
// goroutine is started for this. If the channel done is closed, sending // error occurs (or fn returns an error), List stops and returns it.
// stops. func (be *beSwift) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
func (be *beSwift) List(ctx context.Context, t restic.FileType) <-chan string {
debug.Log("listing %v", t) debug.Log("listing %v", t)
ch := make(chan string)
prefix, _ := be.Basedir(t) prefix, _ := be.Basedir(t)
prefix += "/" prefix += "/"
go func() { err := be.conn.ObjectsWalk(be.container, &swift.ObjectsOpts{Prefix: prefix},
defer close(ch) func(opts *swift.ObjectsOpts) (interface{}, error) {
be.sem.GetToken()
newObjects, err := be.conn.Objects(be.container, opts)
be.sem.ReleaseToken()
err := be.conn.ObjectsWalk(be.container, &swift.ObjectsOpts{Prefix: prefix}, if err != nil {
func(opts *swift.ObjectsOpts) (interface{}, error) { return nil, errors.Wrap(err, "conn.ObjectNames")
be.sem.GetToken() }
newObjects, err := be.conn.ObjectNames(be.container, opts) for _, obj := range newObjects {
be.sem.ReleaseToken() m := path.Base(strings.TrimPrefix(obj.Name, prefix))
if m == "" {
continue
}
fi := restic.FileInfo{
Name: m,
Size: obj.Bytes,
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
err := fn(fi)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "conn.ObjectNames") return nil, err
} }
for _, obj := range newObjects {
m := filepath.Base(strings.TrimPrefix(obj, prefix))
if m == "" {
continue
}
select { if ctx.Err() != nil {
case ch <- m: return nil, ctx.Err()
case <-ctx.Done():
return nil, io.EOF
}
} }
return newObjects, nil }
}) return newObjects, nil
})
if err != nil { if err != nil {
debug.Log("ObjectsWalk returned error: %v", err) return err
} }
}()
return ch return ctx.Err()
} }
// Remove keys for a specified backend type. // Remove keys for a specified backend type.
func (be *beSwift) removeKeys(ctx context.Context, t restic.FileType) error { func (be *beSwift) removeKeys(ctx context.Context, t restic.FileType) error {
for key := range be.List(ctx, t) { return be.List(ctx, t, func(fi restic.FileInfo) error {
err := be.Remove(ctx, restic.Handle{Type: t, Name: key}) return be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})
if err != nil { })
return err
}
}
return nil
} }
// IsNotExist returns true if the error is caused by a not existing file. // IsNotExist returns true if the error is caused by a not existing file.

View File

@ -249,17 +249,17 @@ func (s *Suite) TestList(t *testing.T) {
b := s.open(t) b := s.open(t)
defer s.close(t, b) defer s.close(t, b)
list1 := restic.NewIDSet() list1 := make(map[restic.ID]int64)
for i := 0; i < numTestFiles; i++ { for i := 0; i < numTestFiles; i++ {
data := []byte(fmt.Sprintf("random test blob %v", i)) data := test.Random(rand.Int(), rand.Intn(100)+55)
id := restic.Hash(data) id := restic.Hash(data)
h := restic.Handle{Type: restic.DataFile, Name: id.String()} h := restic.Handle{Type: restic.DataFile, Name: id.String()}
err := b.Save(context.TODO(), h, bytes.NewReader(data)) err := b.Save(context.TODO(), h, bytes.NewReader(data))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
list1.Insert(id) list1[id] = int64(len(data))
} }
t.Logf("wrote %v files", len(list1)) t.Logf("wrote %v files", len(list1))
@ -272,7 +272,7 @@ func (s *Suite) TestList(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(fmt.Sprintf("max-%v", test.maxItems), func(t *testing.T) { t.Run(fmt.Sprintf("max-%v", test.maxItems), func(t *testing.T) {
list2 := restic.NewIDSet() list2 := make(map[restic.ID]int64)
type setter interface { type setter interface {
SetListMaxItems(int) SetListMaxItems(int)
@ -288,7 +288,7 @@ func (s *Suite) TestList(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
list2.Insert(id) list2[id] = fi.Size
return nil return nil
}) })
@ -298,9 +298,22 @@ func (s *Suite) TestList(t *testing.T) {
t.Logf("loaded %v IDs from backend", len(list2)) t.Logf("loaded %v IDs from backend", len(list2))
if !list1.Equals(list2) { for id, size := range list1 {
t.Errorf("lists are not equal, list1 %d entries, list2 %d entries", size2, ok := list2[id]
len(list1), len(list2)) if !ok {
t.Errorf("id %v not returned by List()", id.Str())
}
if size != size2 {
t.Errorf("wrong size for id %v returned: want %v, got %v", id.Str(), size, size2)
}
}
for id := range list2 {
_, ok := list1[id]
if !ok {
t.Errorf("extra id %v returned by List()", id.Str())
}
} }
}) })
} }
@ -349,8 +362,8 @@ func (s *Suite) TestListCancel(t *testing.T) {
return nil return nil
}) })
if err != context.Canceled { if errors.Cause(err) != context.Canceled {
t.Fatalf("expected error not found, want %v, got %v", context.Canceled, err) t.Fatalf("expected error not found, want %v, got %v", context.Canceled, errors.Cause(err))
} }
}) })
@ -404,7 +417,7 @@ func (s *Suite) TestListCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO()) ctx, cancel := context.WithCancel(context.TODO())
defer cancel() defer cancel()
timeout := 500 * time.Millisecond timeout := 200 * time.Millisecond
ctxTimeout, _ := context.WithTimeout(ctx, timeout) ctxTimeout, _ := context.WithTimeout(ctx, timeout)
@ -414,7 +427,7 @@ func (s *Suite) TestListCancel(t *testing.T) {
i++ i++
// wait until the context is cancelled // wait until the context is cancelled
time.Sleep(timeout) time.Sleep(timeout + 200*time.Millisecond)
return nil return nil
}) })
@ -487,8 +500,12 @@ func (s *Suite) TestSave(t *testing.T) {
fi, err := b.Stat(context.TODO(), h) fi, err := b.Stat(context.TODO(), h)
test.OK(t, err) test.OK(t, err)
if fi.Name != h.Name {
t.Errorf("Stat() returned wrong name, want %q, got %q", h.Name, fi.Name)
}
if fi.Size != int64(len(data)) { if fi.Size != int64(len(data)) {
t.Fatalf("Stat() returned different size, want %q, got %d", len(data), fi.Size) t.Errorf("Stat() returned different size, want %q, got %d", len(data), fi.Size)
} }
err = b.Remove(context.TODO(), h) err = b.Remove(context.TODO(), h)

View File

@ -15,7 +15,7 @@ type Backend struct {
SaveFn func(ctx context.Context, h restic.Handle, rd io.Reader) error SaveFn func(ctx context.Context, h restic.Handle, rd io.Reader) error
LoadFn func(ctx context.Context, h restic.Handle, length int, offset int64) (io.ReadCloser, error) LoadFn func(ctx context.Context, h restic.Handle, length int, offset int64) (io.ReadCloser, error)
StatFn func(ctx context.Context, h restic.Handle) (restic.FileInfo, error) StatFn func(ctx context.Context, h restic.Handle) (restic.FileInfo, error)
ListFn func(ctx context.Context, t restic.FileType) <-chan string ListFn func(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error
RemoveFn func(ctx context.Context, h restic.Handle) error RemoveFn func(ctx context.Context, h restic.Handle) error
TestFn func(ctx context.Context, h restic.Handle) (bool, error) TestFn func(ctx context.Context, h restic.Handle) (bool, error)
DeleteFn func(ctx context.Context) error DeleteFn func(ctx context.Context) error
@ -77,14 +77,12 @@ func (m *Backend) Stat(ctx context.Context, h restic.Handle) (restic.FileInfo, e
} }
// List items of type t. // List items of type t.
func (m *Backend) List(ctx context.Context, t restic.FileType) <-chan string { func (m *Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {
if m.ListFn == nil { if m.ListFn == nil {
ch := make(chan string) return nil
close(ch)
return ch
} }
return m.ListFn(ctx, t) return m.ListFn(ctx, t, fn)
} }
// Remove data from the backend. // Remove data from the backend.