2017-12-13 23:46:52 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2018-01-16 22:30:10 +00:00
|
|
|
"context"
|
2018-05-29 21:15:13 +00:00
|
|
|
"io"
|
2017-12-13 23:46:52 +00:00
|
|
|
"io/ioutil"
|
2018-05-29 21:15:13 +00:00
|
|
|
"os"
|
2017-12-13 23:46:52 +00:00
|
|
|
|
2018-02-09 19:39:48 +00:00
|
|
|
"github.com/containerd/continuity/fs"
|
2017-12-13 23:46:52 +00:00
|
|
|
"github.com/moby/buildkit/snapshot"
|
|
|
|
)
|
|
|
|
|
2018-05-29 21:15:13 +00:00
|
|
|
type ReadRequest struct {
|
|
|
|
Filename string
|
|
|
|
Range *FileRange
|
|
|
|
}
|
|
|
|
|
|
|
|
type FileRange struct {
|
|
|
|
Offset int
|
|
|
|
Length int
|
|
|
|
}
|
|
|
|
|
|
|
|
func ReadFile(ctx context.Context, ref ImmutableRef, req ReadRequest) ([]byte, error) {
|
2017-12-21 06:49:39 +00:00
|
|
|
mount, err := ref.Mount(ctx, true)
|
2017-12-13 23:46:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
lm := snapshot.LocalMounter(mount)
|
|
|
|
|
|
|
|
root, err := lm.Mount()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if lm != nil {
|
|
|
|
lm.Unmount()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-05-29 21:15:13 +00:00
|
|
|
fp, err := fs.RootPath(root, req.Filename)
|
2017-12-13 23:46:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-05-29 21:15:13 +00:00
|
|
|
var dt []byte
|
|
|
|
|
|
|
|
if req.Range == nil {
|
|
|
|
dt, err = ioutil.ReadFile(fp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
f, err := os.Open(fp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
dt, err = ioutil.ReadAll(io.NewSectionReader(f, int64(req.Range.Offset), int64(req.Range.Length)))
|
|
|
|
f.Close()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-12-13 23:46:52 +00:00
|
|
|
}
|
2018-05-29 21:15:13 +00:00
|
|
|
|
2017-12-13 23:46:52 +00:00
|
|
|
if err := lm.Unmount(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
lm = nil
|
|
|
|
return dt, err
|
|
|
|
}
|