:mc: resumable downloads and support incomplete files on file system.

This commit is contained in:
Harshavardhana
2015-11-28 18:00:53 -08:00
committed by Harshavardhana
parent 6d542975be
commit 1badfc8a04
37 changed files with 1186 additions and 990 deletions
+2 -2
View File
@@ -39,11 +39,11 @@ lint:
cyclo:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gocyclo -over 30 .
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 .
deadcode:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 deadcode
#@GO15VENDOREXPERIMENT=1 deadcode
build: verifiers
@echo "Installing mc:"
+13 -3
View File
@@ -25,7 +25,7 @@ import (
// accountingReader - implements and inherits io.ReadCloser interface for accounter.
type accountingReader struct {
io.ReadCloser
io.ReadSeeker
acct *accounter
}
@@ -114,16 +114,26 @@ func (a *accounter) Add(n int64) int64 {
}
// Instantiate a new proxy reader for accounter.
func (a *accounter) NewProxyReader(r io.ReadCloser) *accountingReader {
func (a *accounter) NewProxyReader(r io.ReadSeeker) *accountingReader {
return &accountingReader{r, a}
}
// Read implement Reader which internally updates current value.
func (a *accountingReader) Read(p []byte) (n int, err error) {
n, err = a.ReadCloser.Read(p)
n, err = a.ReadSeeker.Read(p)
if err != nil {
return
}
a.acct.Add(int64(n))
return
}
// Seek implement Seeker.
func (a *accountingReader) Seek(offset int64, whence int) (n int64, err error) {
n, err = a.ReadSeeker.Seek(offset, whence)
if err != nil {
return
}
a.acct.Add(n)
return
}
+3 -7
View File
@@ -17,11 +17,9 @@
package main
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"syscall"
@@ -82,10 +80,10 @@ func checkCatSyntax(ctx *cli.Context) {
// catURL displays contents of a URL to stdout.
func catURL(sourceURL string) *probe.Error {
var reader io.ReadCloser
var reader io.ReadSeeker
switch sourceURL {
case "-":
reader = ioutil.NopCloser(bufio.NewReader(os.Stdin))
reader = os.Stdin
default:
sourceClnt, err := url2Client(sourceURL)
if err != nil {
@@ -93,13 +91,11 @@ func catURL(sourceURL string) *probe.Error {
}
// Ignore size, since os.Stat() would not return proper size all the
// time for local filesystem for example /proc files.
reader, _, err = sourceClnt.Get(0, 0)
reader, err = sourceClnt.Get(0, 0)
if err != nil {
return err.Trace(sourceURL)
}
}
defer reader.Close()
return catOut(reader).Trace(sourceURL)
}
+2 -3
View File
@@ -35,12 +35,11 @@ func (s *TestSuite) TestCat(c *C) {
objectPath := filepath.Join(root, "object1")
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
dataLen := len(data)
var err *probe.Error
err = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
err = putTarget(objectPath, bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
var sourceURLs []string
+6 -5
View File
@@ -21,7 +21,6 @@ import (
"os"
"runtime"
"strings"
"sync"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
@@ -49,27 +48,28 @@ func isTargetURLDir(targetURL string) bool {
}
// getSource gets a reader from URL
func getSource(sourceURL string) (reader io.ReadCloser, length int64, err *probe.Error) {
func getSource(sourceURL string) (reader io.ReadSeeker, err *probe.Error) {
sourceClnt, err := url2Client(sourceURL)
if err != nil {
return nil, 0, err.Trace(sourceURL)
return nil, err.Trace(sourceURL)
}
return sourceClnt.Get(0, 0)
}
// putTarget writes to URL from reader. If length=-1, read until EOF.
func putTarget(targetURL string, length int64, reader io.Reader) *probe.Error {
func putTarget(targetURL string, reader io.ReadSeeker) *probe.Error {
targetClnt, err := url2Client(targetURL)
if err != nil {
return err.Trace(targetURL)
}
err = targetClnt.Put(length, reader)
err = targetClnt.Put(reader)
if err != nil {
return err.Trace(targetURL)
}
return nil
}
/*
// putTargets writes to URL from reader. If length=-1, read until EOF.
func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Error {
var tgtReaders []*io.PipeReader
@@ -143,6 +143,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Erro
return nil // success.
}
*/
// getNewClient gives a new client interface
func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) {
+4 -9
View File
@@ -39,20 +39,18 @@ func (s *TestSuite) TestCommonMethods(c *C) {
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
dataLen := len(data)
err := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
err := putTarget(objectPath, bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
c.Assert(isTargetURLDir(objectPathServer), Equals, false)
c.Assert(isTargetURLDir(server.URL+"/bucket"), Equals, true)
reader, size, err := getSource(objectPathServer)
reader, err := getSource(objectPathServer)
c.Assert(err, IsNil)
c.Assert(size, Not(Equals), 0)
var results bytes.Buffer
_, e = io.CopyN(&results, reader, int64(size))
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte(data), DeepEquals, results.Bytes())
@@ -60,9 +58,6 @@ func (s *TestSuite) TestCommonMethods(c *C) {
c.Assert(err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
_, _, err = getSource(objectPathServer + "invalid")
c.Assert(err, Not(IsNil))
_, _, err = url2Stat(objectPath + "invalid")
c.Assert(err, Not(IsNil))
+5 -7
View File
@@ -145,17 +145,17 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
}
reader, length, err := getSource(cpURLs.SourceContent.URL.String())
reader, err := getSource(cpURLs.SourceContent.URL.String())
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(length)
progressReader.ErrorGet(cpURLs.SourceContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.SourceContent.URL.String())
statusCh <- cpURLs
return
}
var newReader io.ReadCloser
var newReader io.ReadSeeker
if globalQuiet || globalJSON {
printMsg(copyMessage{
Source: cpURLs.SourceContent.URL.String(),
@@ -174,11 +174,9 @@ func doCopy(cpURLs copyURLs, progressReader *barSend, accountingReader *accounte
// set up progress
newReader = progressReader.NewProxyReader(reader)
}
defer newReader.Close()
if err := putTarget(cpURLs.TargetContent.URL.String(), length, newReader); err != nil {
if err := putTarget(cpURLs.TargetContent.URL.String(), newReader); err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorPut(length)
progressReader.ErrorPut(cpURLs.TargetContent.Size)
}
cpURLs.Error = err.Trace(cpURLs.TargetContent.URL.String())
statusCh <- cpURLs
+7 -7
View File
@@ -146,13 +146,13 @@ func findClosestCommands(command string) []string {
func registerApp() *cli.App {
// Register all the commands (refer flags.go)
registerCmd(lsCmd) // List contents of a bucket.
registerCmd(mbCmd) // Make a bucket.
registerCmd(catCmd) // Display contents of a file.
registerCmd(pipeCmd) // Write contents of stdin to a file.
registerCmd(shareCmd) // Share documents via URL.
registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination.
registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations.
registerCmd(lsCmd) // List contents of a bucket.
registerCmd(mbCmd) // Make a bucket.
registerCmd(catCmd) // Display contents of a file.
// registerCmd(pipeCmd) // Write contents of stdin to a file.
registerCmd(shareCmd) // Share documents via URL.
registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination.
// registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations.
registerCmd(diffCmd) // Computer differences between two files or folders.
registerCmd(rmCmd) // Remove a file or bucket
registerCmd(accessCmd) // Set access permissions.
+6 -3
View File
@@ -1,3 +1,5 @@
package main
/*
* Minio Client, (C) 2015 Minio, Inc.
*
@@ -12,7 +14,7 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
@@ -134,10 +136,10 @@ func doMirror(sURLs mirrorURLs, progressReader *barSend, accountingReader *accou
progressReader.SetCaption(sURLs.SourceContent.URL.String() + ": ")
}
reader, length, err := getSource(sURLs.SourceContent.URL.String())
reader, err := getSource(sURLs.SourceContent.URL.String())
if err != nil {
if !globalQuiet && !globalJSON {
progressReader.ErrorGet(int64(length))
progressReader.ErrorGet(int64(sURLs.SourceContent.Size))
}
sURLs.Error = err.Trace(sURLs.SourceContent.URL.String())
statusCh <- sURLs
@@ -399,3 +401,4 @@ func mainMirror(ctx *cli.Context) {
doMirrorSession(session)
session.Delete()
}
*/
+3 -1
View File
@@ -1,3 +1,5 @@
package main
/*
* Minio Client, (C) 2015 Minio, Inc.
*
@@ -12,7 +14,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
@@ -97,3 +98,4 @@ func mainPipe(ctx *cli.Context) {
err = pipe(URLs)
fatalIf(err.Trace(URLs...), "Unable to write to one or more targets.")
}
*/
+2 -2
View File
@@ -36,8 +36,8 @@ type Client interface {
SetBucketAccess(access string) *probe.Error
// I/O operations
Get(offset, length int64) (body io.ReadCloser, size int64, err *probe.Error)
Put(size int64, data io.Reader) *probe.Error
Get(offset, length int64) (body io.ReadSeeker, err *probe.Error)
Put(data io.ReadSeeker) *probe.Error
// I/O operations with expiration
ShareDownload(expires time.Duration) (string, *probe.Error)
+252 -148
View File
@@ -35,6 +35,10 @@ type fsClient struct {
PathURL *client.URL
}
const (
partSuffix = ".part.mc"
)
// New - instantiate a new fs client.
func New(path string) (client.Client, *probe.Error) {
if strings.TrimSpace(path) == "" {
@@ -61,130 +65,146 @@ func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
fpath = fpath + "."
}
// Resolve symlinks.
fpath, err := filepath.EvalSymlinks(fpath)
if err != nil {
if os.IsPermission(err) {
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
// On windows there are directory symlinks which are called junction files.
// These files carry special meaning on windows they cannot be,
// accessed with regular operations.
lfi, lerr := os.Lstat(fpath)
if lerr != nil {
if os.IsPermission(lerr) {
lfi, le := os.Lstat(fpath)
if le != nil {
if os.IsPermission(le) {
return nil, probe.NewError(client.PathInsufficientPermission{Path: fpath})
}
return nil, probe.NewError(lerr)
return nil, probe.NewError(le)
}
return lfi, nil
}
}
if os.IsNotExist(err) {
if os.IsNotExist(e) {
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
}
if os.IsPermission(err) {
if os.IsPermission(e) {
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
st, err := os.Stat(fpath)
if err != nil {
if os.IsPermission(err) {
st, e := os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
// On windows there are directory symlinks which are called junction files.
// These files carry special meaning on windows they cannot be,
// accessed with regular operations.
lst, lerr := os.Lstat(fpath)
if lerr != nil {
if os.IsPermission(lerr) {
lst, le := os.Lstat(fpath)
if le != nil {
if os.IsPermission(le) {
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
return nil, probe.NewError(lerr)
return nil, probe.NewError(le)
}
return lst, nil
}
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
if os.IsNotExist(err) {
if os.IsNotExist(e) {
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
}
if os.IsPermission(err) {
if os.IsPermission(e) {
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
return st, nil
}
// Put - create a new file.
func (f *fsClient) Put(size int64, data io.Reader) *probe.Error {
func (f *fsClient) Put(data io.ReadSeeker) *probe.Error {
objectDir, _ := filepath.Split(f.PathURL.Path)
objectPath := f.PathURL.Path
objectPartPath := objectPath + partSuffix
if objectDir != "" {
// Create any missing top level directories.
if err := os.MkdirAll(objectDir, 0700); err != nil {
if os.IsPermission(err) {
return probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
if e := os.MkdirAll(objectDir, 0700); e != nil {
if os.IsPermission(e) {
return probe.NewError(client.PathInsufficientPermission{
Path: f.PathURL.Path,
})
}
return probe.NewError(err)
return probe.NewError(e)
}
}
fs, err := os.Create(objectPath)
if err != nil {
if os.IsPermission(err) {
return probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
return probe.NewError(err)
}
defer fs.Close()
// even if size is zero try to read from source.
if size > 0 {
_, err = io.CopyN(fs, data, int64(size))
if err != nil {
return probe.NewError(err)
var partFile *os.File
st, e := os.Stat(objectPath + partSuffix)
if e != nil {
if !os.IsNotExist(e) {
return probe.NewError(e)
}
partFile, e = os.OpenFile(objectPartPath, os.O_CREATE|os.O_WRONLY, 0600)
} else {
// Size could be 0 for virtual files on certain filesystems,
// for example /proc, so read till EOF for such files.
_, err = io.Copy(fs, data)
if err != nil {
return probe.NewError(err)
if st != nil {
// Seek to the location where the previous copy was left off.
if _, e = data.Seek(st.Size(), 0); e != nil {
return probe.NewError(e)
}
}
partFile, e = os.OpenFile(objectPartPath, os.O_APPEND|os.O_WRONLY, 0600)
}
if e != nil {
if os.IsPermission(e) {
return probe.NewError(client.PathInsufficientPermission{
Path: f.PathURL.Path,
})
}
return probe.NewError(e)
}
_, e = io.Copy(partFile, data)
if e != nil {
return probe.NewError(e)
}
partFile.Close()
if e = os.Rename(objectPartPath, objectPath); e != nil {
return probe.NewError(e)
}
return nil
}
// ShareDownload - share download not implemented for filesystem.
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "ShareDownload", APIType: "filesystem"})
return "", probe.NewError(client.APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
})
}
// ShareUpload - share upload not implemented for filesystem.
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
return nil, probe.NewError(client.APINotImplemented{API: "ShareUpload", APIType: "filesystem"})
return nil, probe.NewError(client.APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
})
}
// get - convenience wrapper.
func (f *fsClient) get() (io.ReadCloser, int64, *probe.Error) {
func (f *fsClient) get() (io.ReadSeeker, *probe.Error) {
body, e := os.Open(f.PathURL.Path)
if e != nil {
if os.IsPermission(e) {
return nil, 0, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
return nil, probe.NewError(client.PathInsufficientPermission{
Path: f.PathURL.Path,
})
}
return nil, 0, probe.NewError(e)
return nil, probe.NewError(e)
}
content, err := f.getFSMetadata()
if err != nil {
return nil, content.Size, err.Trace(f.PathURL.Path)
}
return body, content.Size, nil
return body, nil
}
// Get download an full or part object from bucket.
// returns a reader, length and nil for no errors.
func (f *fsClient) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error) {
func (f *fsClient) Get(offset, length int64) (io.ReadSeeker, *probe.Error) {
if offset < 0 || length < 0 {
return nil, 0, probe.NewError(client.InvalidRange{Offset: offset})
return nil, probe.NewError(client.InvalidRange{Offset: offset})
}
tmppath := f.PathURL.Path
@@ -195,29 +215,29 @@ func (f *fsClient) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error
}
// Resolve symlinks.
_, err := filepath.EvalSymlinks(tmppath)
if err != nil {
if os.IsNotExist(err) {
return nil, length, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
_, e := filepath.EvalSymlinks(tmppath)
if e != nil {
if os.IsNotExist(e) {
return nil, probe.NewError(client.PathNotFound{
Path: f.PathURL.Path,
})
}
if os.IsPermission(err) {
return nil, length, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
if os.IsPermission(e) {
return nil, probe.NewError(client.PathInsufficientPermission{
Path: f.PathURL.Path,
})
}
return nil, length, probe.NewError(err)
return nil, probe.NewError(e)
}
if offset == 0 && length == 0 {
return f.get()
}
body, err := os.Open(f.PathURL.Path)
if err != nil {
return nil, length, probe.NewError(err)
body, e := os.Open(f.PathURL.Path)
if e != nil {
return nil, probe.NewError(e)
}
_, err = io.CopyN(ioutil.Discard, body, int64(offset))
if err != nil {
return nil, length, probe.NewError(err)
}
return body, length, nil
return io.NewSectionReader(body, offset, length), nil
}
// Remove - remove the path.
@@ -225,98 +245,120 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error {
if incomplete {
return nil
}
err := os.Remove(f.PathURL.Path)
return probe.NewError(err)
e := os.Remove(f.PathURL.Path)
return probe.NewError(e)
}
// List - list files and folders.
func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
contentCh := make(chan *client.Content)
if incomplete {
go func() {
defer close(contentCh)
}()
return contentCh
}
switch recursive {
case true:
go f.listRecursiveInRoutine(contentCh)
go f.listRecursiveInRoutine(contentCh, incomplete)
default:
go f.listInRoutine(contentCh)
go f.listInRoutine(contentCh, incomplete)
}
return contentCh
}
// listPrefixes - list all files for any given prefix.
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content) {
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
dirName := filepath.Dir(prefix)
files, err := ioutil.ReadDir(dirName)
if err != nil {
contentCh <- &client.Content{Err: probe.NewError(err)}
files, e := ioutil.ReadDir(dirName)
if e != nil {
contentCh <- &client.Content{Err: probe.NewError(e)}
return
}
pathURL := *f.PathURL
for _, fi := range files {
file := filepath.Join(dirName, fi.Name())
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
st, err := os.Stat(file)
if err != nil {
if os.IsPermission(err) {
st, e := os.Stat(file)
if e != nil {
if os.IsPermission(e) {
// On windows there are folder symlinks
// which are called junction files which
// carry special meaning on windows
// - which cannot be accessed with regular operations
if runtime.GOOS == "windows" {
newPath := filepath.Join(prefix, fi.Name())
lfi, lerr := os.Lstat(newPath)
if lerr != nil {
if os.IsPermission(lerr) {
lfi, le := os.Lstat(newPath)
if le != nil {
if os.IsPermission(le) {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: newPath}),
Err: probe.NewError(client.PathInsufficientPermission{
Path: newPath,
}),
}
continue
}
if os.IsNotExist(lerr) {
if os.IsNotExist(le) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: pathURL.Path}),
Err: probe.NewError(client.BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
contentCh <- &client.Content{
Err: probe.NewError(lerr),
Err: probe.NewError(le),
}
continue
}
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
continue
}
} else {
if strings.HasSuffix(lfi.Name(), partSuffix) {
continue
}
}
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
Err: probe.NewError(client.PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
Err: probe.NewError(client.PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
}
}
if os.IsNotExist(err) {
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: pathURL.Path}),
Err: probe.NewError(client.BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if err != nil {
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
continue
}
}
if strings.HasPrefix(file, prefix) {
if incomplete {
if !strings.HasSuffix(st.Name(), partSuffix) {
continue
}
} else {
if strings.HasSuffix(st.Name(), partSuffix) {
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
Time: st.ModTime(),
@@ -328,6 +370,15 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content)
}
}
if strings.HasPrefix(file, prefix) {
if incomplete {
if !strings.HasSuffix(fi.Name(), partSuffix) {
continue
}
} else {
if strings.HasSuffix(fi.Name(), partSuffix) {
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
Time: fi.ModTime(),
@@ -340,7 +391,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content)
return
}
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) {
// close the channel when the function returns.
defer close(contentCh)
@@ -353,7 +404,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
if _, ok := err.ToGoError().(client.PathNotFound); ok {
// If file does not exist treat it like a prefix and list all prefixes if any.
prefix := fpath
f.listPrefixes(prefix, contentCh)
f.listPrefixes(prefix, contentCh, incomplete)
return
}
// For all other errors we return genuine error back to the caller.
@@ -364,42 +415,51 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
// Now if the file exists and doesn't end with a separator ('/') do not traverse it.
// If the directory doesn't end with a separator, do not traverse it.
if !strings.HasSuffix(fpath, string(pathURL.Separator)) && fst.Mode().IsDir() && fpath != "." {
f.listPrefixes(fpath, contentCh)
f.listPrefixes(fpath, contentCh, incomplete)
return
}
// If we really see the directory.
switch fst.Mode().IsDir() {
case true:
files, err := ioutil.ReadDir(fpath)
files, e := ioutil.ReadDir(fpath)
if err != nil {
contentCh <- &client.Content{Err: probe.NewError(err)}
contentCh <- &client.Content{Err: probe.NewError(e)}
return
}
for _, file := range files {
fi := file
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
fi, err = os.Stat(filepath.Join(fpath, fi.Name()))
if os.IsPermission(err) {
fi, e = os.Stat(filepath.Join(fpath, fi.Name()))
if os.IsPermission(e) {
// On windows there are folder symlinks
// which are called junction files which
// carry special meaning on windows
// - which cannot be accessed with regular operations
if runtime.GOOS == "windows" {
newPath := filepath.Join(fpath, fi.Name())
lfi, lerr := os.Lstat(newPath)
if lerr != nil {
if os.IsPermission(lerr) {
lfi, le := os.Lstat(newPath)
if le != nil {
if os.IsPermission(le) {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: newPath}),
}
continue
}
contentCh <- &client.Content{
Err: probe.NewError(lerr),
Err: probe.NewError(le),
}
continue
}
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
continue
}
} else {
if strings.HasSuffix(lfi.Name(), partSuffix) {
continue
}
}
pathURL := *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
@@ -417,20 +477,29 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
continue
}
}
if os.IsNotExist(err) {
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}),
}
continue
}
if err != nil {
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
continue
}
}
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
if incomplete {
if !strings.HasSuffix(fi.Name(), partSuffix) {
continue
}
} else {
if strings.HasSuffix(fi.Name(), partSuffix) {
continue
}
}
pathURL := *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, fi.Name())
contentCh <- &client.Content{
@@ -443,6 +512,15 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
}
}
default:
if incomplete {
if !strings.HasSuffix(fst.Name(), partSuffix) {
return
}
} else {
if strings.HasSuffix(fst.Name(), partSuffix) {
return
}
}
contentCh <- &client.Content{
URL: pathURL,
Time: fst.ModTime(),
@@ -453,13 +531,13 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content) {
}
}
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content) {
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) {
// close channels upon return.
defer close(contentCh)
var dirName string
var filePrefix string
pathURL := *f.PathURL
visitFS := func(fp string, fi os.FileInfo, err error) error {
visitFS := func(fp string, fi os.FileInfo, e error) error {
// If file path ends with os.PathSeparator and equals to root path, skip it.
if strings.HasSuffix(fp, string(pathURL.Separator)) {
if fp == dirName {
@@ -478,7 +556,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content) {
if filePrefix != "." {
if !strings.HasPrefix(fp, filePrefix) &&
!strings.HasPrefix(filePrefix, fp) {
if err == nil {
if e == nil {
if fi.IsDir() {
return ErrSkipDir
}
@@ -493,35 +571,43 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content) {
}
}
}
if err != nil {
if e != nil {
// If operation is not permitted, we throw quickly back.
if strings.Contains(err.Error(), "operation not permitted") {
if strings.Contains(e.Error(), "operation not permitted") {
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
return nil
}
if os.IsPermission(err) {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
// On windows there are folder symlinks which are called junction files.
// These files carry special meaning on windows which cannot be
// accessed with regular operations.
lfi, lerr := os.Lstat(fp)
if lerr != nil {
lfi, le := os.Lstat(fp)
if le != nil {
contentCh <- &client.Content{
Err: probe.NewError(lerr),
Err: probe.NewError(le),
}
return nil
}
pathURL := *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, dirName)
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
return nil
}
} else {
if strings.HasSuffix(lfi.Name(), partSuffix) {
return nil
}
}
contentCh <- &client.Content{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(err),
Err: probe.NewError(e),
}
} else {
contentCh <- &client.Content{
@@ -530,63 +616,81 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content) {
}
return nil
}
return err
return e
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
fi, err = os.Stat(fp)
if err != nil {
if os.IsPermission(err) {
fi, e = os.Stat(fp)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
// On windows there are folder symlinks which are called junction files.
// These files carry special meaning on windows which cannot be
// accessed with regular operations.
lfi, lerr := os.Lstat(fp)
if lerr != nil {
if os.IsPermission(lerr) {
lfi, le := os.Lstat(fp)
if le != nil {
if os.IsPermission(le) {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: fp}),
}
return nil
}
contentCh <- &client.Content{
Err: probe.NewError(lerr),
Err: probe.NewError(le),
}
return nil
}
pathURL := *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, dirName)
if incomplete {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
return nil
}
} else {
if !strings.HasSuffix(lfi.Name(), partSuffix) {
return nil
}
}
contentCh <- &client.Content{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(err),
Err: probe.NewError(e),
}
return nil
}
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
return nil
}
// Ignore in-accessible broken symlinks.
if os.IsNotExist(err) {
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: fp}),
}
return nil
}
// Ignore symlink loops.
if strings.Contains(err.Error(), "too many levels of symbolic links") {
if strings.Contains(e.Error(), "too many levels of symbolic links") {
contentCh <- &client.Content{
Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}),
}
return nil
}
return err
return e
}
}
if fi.Mode().IsRegular() || fi.Mode().IsDir() {
if incomplete {
if !strings.HasSuffix(fi.Name(), partSuffix) {
return nil
}
} else {
if strings.HasSuffix(fi.Name(), partSuffix) {
return nil
}
}
contentCh <- &client.Content{
URL: *client.NewURL(fp),
Time: fi.ModTime(),
@@ -614,19 +718,19 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content) {
filePrefix = pathURL.Path
}
// Walks invokes our custom function.
err := Walk(dirName, visitFS)
if err != nil {
e := Walk(dirName, visitFS)
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
}
}
// MakeBucket - create a new bucket.
func (f *fsClient) MakeBucket() *probe.Error {
err := os.MkdirAll(f.PathURL.Path, 0775)
if err != nil {
return probe.NewError(err)
e := os.MkdirAll(f.PathURL.Path, 0775)
if e != nil {
return probe.NewError(e)
}
return nil
}
@@ -645,7 +749,7 @@ func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
func (f *fsClient) getFSMetadata() (content *client.Content, err *probe.Error) {
st, err := f.fsStat()
if err != nil {
return nil, err.Trace()
return nil, err.Trace(f.PathURL.String())
}
content = new(client.Content)
content.URL = *f.PathURL
+11 -16
View File
@@ -45,16 +45,15 @@ func (s *MySuite) TestList(c *C) {
c.Assert(err, IsNil)
data := "hello"
dataLen := len(data)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
objectPath = filepath.Join(root, "object2")
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
fsc, err = fs.New(root)
@@ -76,7 +75,7 @@ func (s *MySuite) TestList(c *C) {
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
fsc, err = fs.New(root)
@@ -180,9 +179,7 @@ func (s *MySuite) TestPut(c *C) {
c.Assert(err, IsNil)
data := "hello"
dataLen := len(data)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
}
@@ -196,15 +193,14 @@ func (s *MySuite) TestGet(c *C) {
c.Assert(err, IsNil)
data := "hello"
dataLen := len(data)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
reader, size, err := fsc.Get(0, 0)
reader, err := fsc.Get(0, 0)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.CopyN(&results, reader, int64(size))
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte(data), DeepEquals, results.Bytes())
@@ -220,15 +216,14 @@ func (s *MySuite) TestGetRange(c *C) {
c.Assert(err, IsNil)
data := "hello world"
dataLen := len(data)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
reader, size, err := fsc.Get(0, 5)
reader, err := fsc.Get(0, 5)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.CopyN(&results, reader, int64(size))
_, e = io.Copy(&results, reader)
c.Assert(e, IsNil)
c.Assert([]byte("hello"), DeepEquals, results.Bytes())
}
@@ -245,7 +240,7 @@ func (s *MySuite) TestStatObject(c *C) {
data := "hello"
dataLen := len(data)
err = fsc.Put(int64(dataLen), bytes.NewReader([]byte(data)))
err = fsc.Put(bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
content, err := fsc.Stat()
+13 -9
View File
@@ -85,19 +85,19 @@ func (c *s3Client) GetURL() client.URL {
}
// Get - get object.
func (c *s3Client) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error) {
func (c *s3Client) Get(offset, length int64) (io.ReadSeeker, *probe.Error) {
bucket, object := c.url2BucketAndObject()
reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length)
reader, err := c.api.GetPartialObject(bucket, object, offset, length)
if err != nil {
errResponse := minio.ToErrorResponse(err)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return nil, 0, probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()})
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()})
}
}
return nil, length, probe.NewError(err)
return nil, probe.NewError(err)
}
return reader, metadata.Size, nil
return reader, nil
}
// Remove - remove object or bucket.
@@ -154,21 +154,25 @@ func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentT
}
// Put - put object.
func (c *s3Client) Put(size int64, data io.Reader) *probe.Error {
func (c *s3Client) Put(data io.ReadSeeker) *probe.Error {
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
// for a multipart upload and there is no need to cross verify,
// invidual parts are properly verified fully in transit and also upon completion
// of the multipart request.
bucket, object := c.url2BucketAndObject()
err := c.api.PutObject(bucket, object, "application/octet-stream", size, data)
err := c.api.PutObject(bucket, object, "application/octet-stream", data)
if err != nil {
errResponse := minio.ToErrorResponse(err)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()})
return probe.NewError(client.PathInsufficientPermission{
Path: c.hostURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return probe.NewError(client.ObjectAlreadyExists{Object: object})
return probe.NewError(client.ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "InvalidArgument" {
return probe.NewError(client.ObjectMissing{})
+3 -5
View File
@@ -184,7 +184,7 @@ func (s *MySuite) TestObjectOperations(c *C) {
s3c, err := New(conf)
c.Assert(err, IsNil)
err = s3c.Put(int64(len(object.data)), bytes.NewReader(object.data))
err = s3c.Put(bytes.NewReader(object.data))
c.Assert(err, IsNil)
content, err := s3c.Stat()
@@ -192,12 +192,10 @@ func (s *MySuite) TestObjectOperations(c *C) {
c.Assert(content.Size, Equals, int64(len(object.data)))
c.Assert(content.Type.IsRegular(), Equals, true)
reader, size, err := s3c.Get(0, 0)
c.Assert(size, Equals, int64(len(object.data)))
reader, err := s3c.Get(0, 0)
var buffer bytes.Buffer
{
_, err := io.CopyN(&buffer, reader, int64(size))
_, err := io.Copy(&buffer, reader)
c.Assert(err, IsNil)
c.Assert(buffer.Bytes(), DeepEquals, object.data)
}
+13 -6
View File
@@ -42,20 +42,27 @@ const (
// proxyReader progress bar proxy reader for barSend inherits io.ReadCloser.
type proxyReader struct {
io.ReadCloser
io.ReadSeeker
bar *barSend
}
// Read proxy Read sends progress for each Read operation.
func (r *proxyReader) Read(p []byte) (n int, err error) {
n, err = r.ReadCloser.Read(p)
n, err = r.ReadSeeker.Read(p)
if err != nil {
return
}
r.bar.Progress(int64(n))
return
}
// Close proxy Close closes the internal ReadCloser.
func (r *proxyReader) Close() (err error) {
return r.ReadCloser.Close()
func (r *proxyReader) Seek(offset int64, whence int) (n int64, err error) {
n, err = r.ReadSeeker.Seek(offset, whence)
if err != nil {
return
}
r.bar.Progress(n)
return
}
// barMsg progress bar message for a given operation.
@@ -71,7 +78,7 @@ type barSend struct {
}
// Instantiate a new progress bar proxy reader.
func (b *barSend) NewProxyReader(r io.ReadCloser) *proxyReader {
func (b *barSend) NewProxyReader(r io.ReadSeeker) *proxyReader {
return &proxyReader{r, b}
}
+1 -1
View File
@@ -153,7 +153,7 @@ func sessionExecute(s *sessionV5) {
case "cp":
doCopySession(s)
case "mirror":
doMirrorSession(s)
//doMirrorSession(s)
}
}
+1 -1
View File
@@ -116,7 +116,7 @@ func getReleaseUpdate(updateURL string) {
clnt, err := url2Client(updateURL)
fatalIf(err.Trace(updateURL), "Unable to initalize update URL.")
data, _, err := clnt.Get(0, 0)
data, err := clnt.Get(0, 0)
fatalIf(err.Trace(updateURL), "Unable to read from update URL ‘"+updateURL+"’.")
if mcVersion == "UNOFFICIAL.GOGET" {
+83
View File
@@ -0,0 +1,83 @@
## Ubuntu (Kylin) 14.04
### Build Dependencies
This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
##### Install Git, GCC
```sh
$ sudo apt-get install git build-essential
```
##### Install Go 1.5+
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
```sh
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
$ mkdir -p ${HOME}/bin/
$ mkdir -p ${HOME}/go/
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
```
##### Setup GOROOT and GOPATH
Add the following exports to your ``~/.bashrc``. Environment variable GOROOT specifies the location of your golang binaries
and GOPATH specifies the location of your project workspace.
```sh
export GOROOT=${HOME}/bin/go
export GOPATH=${HOME}/go
export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin
```
```sh
$ source ~/.bashrc
```
##### Testing it all
```sh
$ go env
```
## OS X (Yosemite) 10.10
### Build Dependencies
This installation document assumes OS X Yosemite 10.10+ on x86-64 platform.
##### Install brew
```sh
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
##### Install Git, Python
```sh
$ brew install git python
```
##### Install Go 1.5+
Install golang binaries using `brew`
```sh
$ brew install go
$ mkdir -p $HOME/go
```
##### Setup GOROOT and GOPATH
Add the following exports to your ``~/.bash_profile``. Environment variable GOROOT specifies the location of your golang binaries
and GOPATH specifies the location of your project workspace.
```sh
export GOPATH=${HOME}/go
export GOVERSION=$(brew list go | head -n 1 | cut -d '/' -f 6)
export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec
export PATH=$PATH:${GOPATH}/bin
```
##### Source the new enviornment
```sh
$ source ~/.bash_profile
```
##### Testing it all
```sh
$ go env
```
+3 -3
View File
@@ -73,9 +73,9 @@ func main() {
* [ListIncompleteUploads(bucket, prefix, recursive) <-chan ObjectMultipartStat](examples/s3/listincompleteuploads.go)
### Object Level
* [PutObject(bucket, object, size, io.Reader) error](examples/s3/putobject.go)
* [GetObject(bucket, object) (io.Reader, ObjectStat, error)](examples/s3/getobject.go)
* [GetPartialObject(bucket, object, offset, length) (io.Reader, ObjectStat, error)](examples/s3/getpartialobject.go)
* [PutObject(bucket, object, contentType, io.ReadSeeker) error](examples/s3/putobject.go)
* [GetObject(bucket, object) (io.ReadSeeker, error)](examples/s3/getobject.go)
* [GetPartialObject(bucket, object, offset, length) (io.ReadSeeker, error)](examples/s3/getpartialobject.go)
* [StatObject(bucket, object) (ObjectStat, error)](examples/s3/statobject.go)
* [RemoveObject(bucket, object) error](examples/s3/removeobject.go)
* [RemoveIncompleteUpload(bucket, object) <-chan error](examples/s3/removeincompleteupload.go)
+94
View File
@@ -0,0 +1,94 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"io"
"time"
)
// BucketStat container for bucket metadata.
type BucketStat struct {
// The name of the bucket.
Name string
// Date the bucket was created.
CreationDate time.Time
// Error
Err error
}
// ObjectStat container for object metadata.
type ObjectStat struct {
ETag string
Key string
LastModified time.Time
Size int64
ContentType string
Owner struct {
DisplayName string
ID string
}
// The class of storage used to store the object.
StorageClass string
// Error
Err error
}
// ObjectMultipartStat container for multipart object metadata.
type ObjectMultipartStat struct {
// Date and time at which the multipart upload was initiated.
Initiated time.Time `type:"timestamp" timestampFormat:"iso8601"`
Initiator initiator
Owner owner
StorageClass string
// Key of the object for which the multipart upload was initiated.
Key string
Size int64
// Upload ID that identifies the multipart upload.
UploadID string `xml:"UploadId"`
// Error
Err error
}
// partMetadata - container for each partMetadata.
type partMetadata struct {
MD5Sum []byte
Sha256Sum []byte
ReadCloser io.ReadCloser
Size int64
Number int // partMetadata number.
// Error
Err error
}
// putObjectMetadata - container for each single PUT operation.
type putObjectMetadata struct {
MD5Sum []byte
Sha256Sum []byte
ReadCloser io.ReadCloser
Size int64
ContentType string
}
+117 -157
View File
@@ -17,69 +17,19 @@
package minio
import (
"encoding/hex"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// BucketStat container for bucket metadata.
type BucketStat struct {
// The name of the bucket.
Name string
// Date the bucket was created.
CreationDate time.Time
// Error
Err error
}
// ObjectStat container for object metadata.
type ObjectStat struct {
ETag string
Key string
LastModified time.Time
Size int64
ContentType string
Owner struct {
DisplayName string
ID string
}
// The class of storage used to store the object.
StorageClass string
Err error
}
// ObjectMultipartStat container for multipart object metadata.
type ObjectMultipartStat struct {
// Date and time at which the multipart upload was initiated.
Initiated time.Time `type:"timestamp" timestampFormat:"iso8601"`
Initiator initiator
Owner owner
StorageClass string
// Key of the object for which the multipart upload was initiated.
Key string
Size int64
// Upload ID that identifies the multipart upload.
UploadID string `xml:"UploadId"`
Err error
}
// s3 region map used by bucket location constraint if necessary.
var regions = map[string]string{
"s3-fips-us-gov-west-1.amazonaws.com": "us-gov-west-1",
@@ -154,8 +104,6 @@ type Config struct {
// Optional field. If empty, region is determined automatically.
// Set to override default behavior.
Region string
// Specify this to get server response in non XML style if server supports it
AcceptType string
/// Really Advanced options
//
@@ -186,6 +134,14 @@ const (
LibraryVersion = "0.2.5"
)
// isAnonymous - True if config doesn't have access and secret keys.
func (c *Config) isAnonymous() bool {
if c.AccessKeyID != "" && c.SecretAccessKey != "" {
return false
}
return true
}
// setBucketRegion fetches the region and updates config,
// additionally it also constructs a proper endpoint based on that region.
func (c *Config) setBucketRegion() {
@@ -344,15 +300,15 @@ func (a API) PresignedGetObject(bucket, object string, expires time.Duration) (s
}
// GetObject retrieve object. retrieves full object, if you need ranges use GetPartialObject.
func (a API) GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error) {
func (a API) GetObject(bucket, object string) (io.ReadSeeker, error) {
if err := invalidBucketError(bucket); err != nil {
return nil, ObjectStat{}, err
return nil, err
}
if err := invalidObjectError(object); err != nil {
return nil, ObjectStat{}, err
return nil, err
}
// get object
return a.getObject(bucket, object, 0, 0)
return newObjectReadSeeker(a, bucket, object), nil
}
// GetPartialObject retrieve partial object.
@@ -360,15 +316,15 @@ func (a API) GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error)
// Takes range arguments to download the specified range bytes of an object.
// Setting offset and length = 0 will download the full object.
// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.
func (a API) GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error) {
func (a API) GetPartialObject(bucket, object string, offset, length int64) (io.ReadSeeker, error) {
if err := invalidBucketError(bucket); err != nil {
return nil, ObjectStat{}, err
return nil, err
}
if err := invalidObjectError(object); err != nil {
return nil, ObjectStat{}, err
return nil, err
}
// get partial object.
return a.getObject(bucket, object, offset, length)
return newObjectReadSeeker(a, bucket, object), nil
}
// completedParts is a wrapper to make parts sortable by their part numbers.
@@ -418,14 +374,14 @@ func calculatePartSize(objectSize int64) int64 {
}
// Initiate a fresh multipart upload
func (a API) newObjectUpload(bucket, object, contentType string, size int64, data io.Reader) error {
func (a API) newObjectUpload(bucket, object, contentType string, size int64, data io.ReadSeeker) error {
// Initiate a new multipart upload request.
initMultipartUploadResult, err := a.initiateMultipartUpload(bucket, object)
if err != nil {
return err
}
uploadID := initMultipartUploadResult.UploadID
complMultipartUpload := completeMultipartUpload{}
var totalLength int64
// Calculate optimal part size for a given size.
partSize := calculatePartSize(size)
@@ -438,42 +394,32 @@ func (a API) newObjectUpload(bucket, object, contentType string, size int64, dat
// Allocate a new wait group
wg := new(sync.WaitGroup)
for p := range chopper(data, partSize, nil) {
// This check is primarily for last part.
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes.
if p.Len < partSize && size > 0 {
expectedPartLen := size - totalLength
if expectedPartLen != p.Len {
return ErrorResponse{
Code: "UnexpectedShortRead",
Message: "Data read ‘" + strconv.FormatInt(expectedPartLen, 10) + "’ is not equal to expected size ‘" + strconv.FormatInt(p.Len, 10) + "’",
Resource: separator + bucket + separator + object,
}
}
}
partNumber := 1
for part := range partsManager(data, partSize) {
// Limit to 4 parts a given time.
mpQueueCh <- struct{}{}
// Account for all parts uploaded simultaneousy.
wg.Add(1)
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p piece) {
part.Number = partNumber
go func(errCh chan<- error, mpQueueCh <-chan struct{}, part partMetadata) {
defer wg.Done()
defer func() {
<-mpQueueCh
}()
if p.Err != nil {
errCh <- p.Err
if part.Err != nil {
errCh <- part.Err
return
}
var complPart completePart
complPart, err = a.uploadPart(bucket, object, uploadID, p.MD5Sum, p.Num, p.Len, p.ReadSeeker)
complPart, err = a.uploadPart(bucket, object, uploadID, part)
if err != nil {
errCh <- err
return
}
complMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart)
errCh <- nil
}(errCh, mpQueueCh, p)
totalLength += p.Len
}(errCh, mpQueueCh, part)
partNumber++
}
wg.Wait()
if err := <-errCh; err != nil {
@@ -487,38 +433,38 @@ func (a API) newObjectUpload(bucket, object, contentType string, size int64, dat
return nil
}
func (a API) listObjectPartsRecursive(bucket, object, uploadID string) <-chan partMetadata {
partCh := make(chan partMetadata, 1000)
go a.listObjectPartsRecursiveInRoutine(bucket, object, uploadID, partCh)
return partCh
func (a API) listObjectPartsRecursive(bucket, object, uploadID string) <-chan objectPartMetadata {
objectPartCh := make(chan objectPartMetadata, 1000)
go a.listObjectPartsRecursiveInRoutine(bucket, object, uploadID, objectPartCh)
return objectPartCh
}
func (a API) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string, ch chan<- partMetadata) {
func (a API) listObjectPartsRecursiveInRoutine(bucket, object, uploadID string, ch chan<- objectPartMetadata) {
defer close(ch)
listObjPartsResult, err := a.listObjectParts(bucket, object, uploadID, 0, 1000)
if err != nil {
ch <- partMetadata{
ch <- objectPartMetadata{
Err: err,
}
return
}
for _, uploadedPart := range listObjPartsResult.Parts {
ch <- uploadedPart
for _, uploadedObjectPart := range listObjPartsResult.ObjectParts {
ch <- uploadedObjectPart
}
for {
if !listObjPartsResult.IsTruncated {
break
}
listObjPartsResult, err = a.listObjectParts(bucket, object,
uploadID, listObjPartsResult.NextPartNumberMarker, 1000)
nextPartNumberMarker := listObjPartsResult.NextPartNumberMarker
listObjPartsResult, err = a.listObjectParts(bucket, object, uploadID, nextPartNumberMarker, 1000)
if err != nil {
ch <- partMetadata{
ch <- objectPartMetadata{
Err: err,
}
return
}
for _, uploadedPart := range listObjPartsResult.Parts {
ch <- uploadedPart
for _, uploadedObjectPart := range listObjPartsResult.ObjectParts {
ch <- uploadedObjectPart
}
}
}
@@ -536,27 +482,24 @@ func (a API) getTotalMultipartSize(bucket, object, uploadID string) (int64, erro
}
// continue previously interrupted multipart upload object at `uploadID`
func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, data io.Reader) error {
var skipPieces []skipPiece
func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, data io.ReadSeeker) error {
var seekOffset int64
partNumber := 1
completeMultipartUpload := completeMultipartUpload{}
var totalLength int64
for part := range a.listObjectPartsRecursive(bucket, object, uploadID) {
if part.Err != nil {
return part.Err
for objPart := range a.listObjectPartsRecursive(bucket, object, uploadID) {
if objPart.Err != nil {
return objPart.Err
}
// partNumbers are sorted in listObjectParts.
if partNumber != objPart.PartNumber {
break
}
var completedPart completePart
completedPart.PartNumber = part.PartNumber
completedPart.ETag = part.ETag
completedPart.PartNumber = objPart.PartNumber
completedPart.ETag = objPart.ETag
completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, completedPart)
md5SumBytes, err := hex.DecodeString(strings.Trim(part.ETag, "\"")) // trim off the odd double quotes
if err != nil {
return err
}
totalLength += part.Size
skipPieces = append(skipPieces, skipPiece{
md5sum: md5SumBytes,
pieceNumber: part.PartNumber,
})
seekOffset += objPart.Size // Add seek Offset for future Seek to skip entries.
partNumber++ // Update partNumber sequentially to verify and skip.
}
// Calculate the optimal part size for a given size.
@@ -570,41 +513,33 @@ func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, d
// Allocate a new wait group.
wg := new(sync.WaitGroup)
for p := range chopper(data, partSize, skipPieces) {
// This check is primarily for last part.
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes.
if p.Len < partSize && size > 0 {
expectedPartLen := size - totalLength
if expectedPartLen != p.Len {
return ErrorResponse{
Code: "UnexpectedShortRead",
Message: "Data read ‘" + strconv.FormatInt(expectedPartLen, 10) + "’ is not equal to expected size ‘" + strconv.FormatInt(p.Len, 10) + "’",
Resource: separator + bucket + separator + object,
}
}
}
if _, err := data.Seek(seekOffset, 0); err != nil {
return err
}
for part := range partsManager(data, partSize) {
// Limit to 4 parts a given time.
mpQueueCh <- struct{}{}
// Account for all parts uploaded simultaneousy.
wg.Add(1)
go func(errCh chan<- error, mpQueueCh <-chan struct{}, p piece) {
part.Number = partNumber
go func(errCh chan<- error, mpQueueCh <-chan struct{}, part partMetadata) {
defer wg.Done()
defer func() {
<-mpQueueCh
}()
if p.Err != nil {
errCh <- p.Err
if part.Err != nil {
errCh <- part.Err
return
}
completedPart, err := a.uploadPart(bucket, object, uploadID, p.MD5Sum, p.Num, p.Len, p.ReadSeeker)
complPart, err := a.uploadPart(bucket, object, uploadID, part)
if err != nil {
errCh <- err
return
}
completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, completedPart)
completeMultipartUpload.Parts = append(completeMultipartUpload.Parts, complPart)
errCh <- nil
}(errCh, mpQueueCh, p)
totalLength += p.Len
}(errCh, mpQueueCh, part)
partNumber++
}
wg.Wait()
if err := <-errCh; err != nil {
@@ -626,7 +561,8 @@ func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, d
// - For size equal to 0Bytes PutObject automatically does single Put operation.
// - For size larger than 5MB PutObject automatically does resumable multipart operation.
// - For size input as -1 PutObject treats it as a stream and does multipart operation until
// input stream reaches EOF.
// input stream reaches EOF. Maximum object size that can be uploaded through this operation
// will be 5GB.
//
// NOTE: if you are using Google Cloud Storage. Then there is no resumable multipart
// upload support yet. Currently PutObject will behave like a single PUT operation and would
@@ -634,17 +570,31 @@ func (a API) continueObjectUpload(bucket, object, uploadID string, size int64, d
//
// For un-authenticated requests S3 doesn't allow multipart upload, so we fall back to single
// PUT operation.
func (a API) PutObject(bucket, object, contentType string, size int64, data io.Reader) error {
func (a API) PutObject(bucket, object, contentType string, data io.ReadSeeker) error {
if err := invalidBucketError(bucket); err != nil {
return err
}
if err := invalidArgumentError(object); err != nil {
return err
}
// for un-authenticated requests do not initiate multipart operation.
// NOTE: S3 doesn't allow unauthenticated multipart requests.
if a.config.AccessKeyID == "" || a.config.SecretAccessKey == "" {
_, err := a.putObjectUnAuthenticated(bucket, object, contentType, size, data)
size, err := getReaderSize(data)
if err != nil {
return err
}
// NOTE: S3 doesn't allow anonymous multipart requests.
if a.config.isAnonymous() && size == -1 {
return invalidArgumentError("")
}
// For anonymous requests do not initiate multipart operation.
if a.config.isAnonymous() {
putObjMetadata := putObjectMetadata{
MD5Sum: nil,
Sha256Sum: nil,
ReadCloser: ioutil.NopCloser(data),
Size: size,
ContentType: contentType,
}
_, err := a.putObject(bucket, object, putObjMetadata)
if err != nil {
return err
}
@@ -660,32 +610,42 @@ func (a API) PutObject(bucket, object, contentType string, size int64, data io.R
Resource: separator + bucket + separator + object,
}
}
if _, err := a.putObject(bucket, object, contentType, nil, size, NewReadSeekCloser(data)); err != nil {
putObjMetadata := putObjectMetadata{
MD5Sum: nil,
Sha256Sum: nil,
ReadCloser: ioutil.NopCloser(data),
Size: size,
ContentType: contentType,
}
// NOTE: with Google Cloud Storage, Content-MD5 is deliberately skipped.
if _, err := a.putObject(bucket, object, putObjMetadata); err != nil {
return err
}
return nil
}
switch {
case size < minimumPartSize && size >= 0:
// Single Part use case, use PutObject directly.
for part := range chopper(data, minimumPartSize, nil) {
if part.Err != nil {
return part.Err
}
// This verifies if the part.Len was an unexpected read i.e if we lost few bytes
if part.Len != size {
return ErrorResponse{
Code: "MethodUnexpectedEOF",
Message: "Data read is less than the requested size",
Resource: separator + bucket + separator + object,
}
}
_, err := a.putObject(bucket, object, contentType, part.MD5Sum, part.Len, part.ReadSeeker)
if err != nil {
return err
}
return nil
dataBytes, err := ioutil.ReadAll(data)
if err != nil {
return err
}
// Seek back the data to its original position.
if _, err := data.Seek(0, 0); err != nil {
return err
}
putObjMetadata := putObjectMetadata{
MD5Sum: sumMD5(dataBytes),
Sha256Sum: sum256(dataBytes),
ReadCloser: ioutil.NopCloser(data),
Size: size,
ContentType: contentType,
}
// Single Part use case, use PutObject directly.
_, err = a.putObject(bucket, object, putObjMetadata)
if err != nil {
return err
}
return nil
case size >= minimumPartSize || size == -1:
var inProgress bool
var inProgressUploadID string
+3 -9
View File
@@ -160,7 +160,7 @@ func TestObjectOperations(t *testing.T) {
t.Fatal("Error")
}
data := []byte("Hello, World")
err = a.PutObject("bucket", "object", "", int64(len(data)), bytes.NewReader(data))
err = a.PutObject("bucket", "object", "", bytes.NewReader(data))
if err != nil {
t.Fatal("Error")
}
@@ -175,16 +175,10 @@ func TestObjectOperations(t *testing.T) {
t.Fatal("Error")
}
reader, metadata, err := a.GetObject("bucket", "object")
reader, err := a.GetObject("bucket", "object")
if err != nil {
t.Fatal("Error")
}
if metadata.Key != "object" {
t.Fatal("Error")
}
if metadata.ETag != "9af2f8218b150c351ad802c6f3d66abe" {
t.Fatal("Error")
}
var buffer bytes.Buffer
_, err = io.Copy(&buffer, reader)
@@ -244,7 +238,7 @@ func TestPresignedURL(t *testing.T) {
func TestErrorResponse(t *testing.T) {
errorResponse := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>AccessDenied</Code><Message>Access Denied</Message><Resource>/mybucket/myphoto.jpg</Resource><RequestId>F19772218238A85A</RequestId><HostId>GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD</HostId></Error>")
errorReader := bytes.NewReader(errorResponse)
err := minio.BodyToErrorResponse(errorReader, "application/xml")
err := minio.BodyToErrorResponse(errorReader)
if err == nil {
t.Fatal("Error")
}
-135
View File
@@ -1,135 +0,0 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"bytes"
"crypto/md5"
"io"
)
// piece - container for each piece
type piece struct {
MD5Sum []byte
ReadSeeker io.ReadSeeker
Err error
Len int64
Num int // part number
}
// skipPiece - container for skip piece
type skipPiece struct {
md5sum []byte
pieceNumber int
}
// chopper reads from io.Reader, partitions the data into pieces of given pieceSize, and sends
// each piece as io.ReadSeeker to the caller over a channel
//
// This method runs until an EOF or an error occurs. Before returning, the channel is always closed.
//
// Additionally this function also skips list of pieces if provided
func chopper(reader io.Reader, pieceSize int64, skipPieces []skipPiece) <-chan piece {
ch := make(chan piece, 3)
go chopperInRoutine(reader, pieceSize, skipPieces, ch)
return ch
}
func chopperInRoutine(reader io.Reader, pieceSize int64, skipPieces []skipPiece, ch chan<- piece) {
defer close(ch)
p := make([]byte, pieceSize)
n, err := io.ReadFull(reader, p)
if err == io.EOF || err == io.ErrUnexpectedEOF {
// short read, only single piece return.
m := md5.Sum(p[0:n])
ch <- piece{
MD5Sum: m[:],
ReadSeeker: bytes.NewReader(p[0:n]),
Err: nil,
Len: int64(n),
Num: 1,
}
return
}
// unknown error considered catastrophic error, return here.
if err != nil {
ch <- piece{
ReadSeeker: nil,
Err: err,
Num: 0,
}
return
}
// send the first piece
var num = 1
md5SumBytes := md5.Sum(p)
sp := skipPiece{
pieceNumber: num,
md5sum: md5SumBytes[:],
}
if !isPieceNumberUploaded(sp, skipPieces) {
ch <- piece{
MD5Sum: md5SumBytes[:],
ReadSeeker: bytes.NewReader(p),
Err: nil,
Len: int64(n),
Num: num,
}
}
for err == nil {
var n int
p := make([]byte, pieceSize)
n, err = io.ReadFull(reader, p)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error
ch <- piece{
ReadSeeker: nil,
Err: err,
Num: 0,
}
return
}
}
num++
md5SumBytes := md5.Sum(p[0:n])
sp := skipPiece{
pieceNumber: num,
md5sum: md5SumBytes[:],
}
if isPieceNumberUploaded(sp, skipPieces) {
continue
}
ch <- piece{
MD5Sum: md5SumBytes[:],
ReadSeeker: bytes.NewReader(p[0:n]),
Err: nil,
Len: int64(n),
Num: num,
}
}
}
// to verify if piece is already uploaded
func isPieceNumberUploaded(piece skipPiece, skipPieces []skipPiece) bool {
for _, p := range skipPieces {
if p.pieceNumber == piece.pieceNumber && bytes.Equal(p.md5sum, piece.md5sum) {
return true
}
}
return false
}
+78
View File
@@ -0,0 +1,78 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/xml"
"io"
"os"
)
// xmlDecoder provide decoded value in xml.
func xmlDecoder(body io.Reader, v interface{}) error {
d := xml.NewDecoder(body)
return d.Decode(v)
}
// getReaderSize provides size of io.ReadSeeker, return -1 after exhausting all conditions.
func getReaderSize(data io.ReadSeeker) (int64, error) {
var size int64
switch ft := data.(type) {
case *os.File:
st, err := ft.Stat()
if err != nil {
return 0, err
}
size = st.Size()
case *objectReadSeeker:
st, err := ft.Stat()
if err != nil {
return 0, err
}
size = st.Size
case *bytes.Reader:
size = ft.Size()
default:
return -1, nil
}
return size, nil
}
// sum256 calculate sha256 sum for an input byte array.
func sum256(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
// sumMD5 calculate md5 sum for an input byte array.
func sumMD5(data []byte) []byte {
hash := md5.New()
hash.Write(data)
return hash.Sum(nil)
}
// sumHMAC calculate hmac between two input byte array.
func sumHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
-115
View File
@@ -1,115 +0,0 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"encoding/xml"
"io"
"strings"
"time"
)
// decoder provides a unified decoding method interface
type decoder interface {
Decode(v interface{}) error
}
// acceptTypeDecoder provide decoded value in given acceptType
func acceptTypeDecoder(body io.Reader, acceptType string, v interface{}) error {
var d decoder
switch {
case acceptType == "application/xml":
d = xml.NewDecoder(body)
case acceptType == "application/json":
d = json.NewDecoder(body)
default:
d = xml.NewDecoder(body)
}
return d.Decode(v)
}
// sum256Reader calculate sha256 sum for an input read seeker
func sum256Reader(reader io.ReadSeeker) ([]byte, error) {
h := sha256.New()
var err error
start, _ := reader.Seek(0, 1)
defer reader.Seek(start, 0)
for err == nil {
length := 0
byteBuffer := make([]byte, 1024*1024)
length, err = reader.Read(byteBuffer)
byteBuffer = byteBuffer[0:length]
h.Write(byteBuffer)
}
if err != io.EOF {
return nil, err
}
return h.Sum(nil), nil
}
// sum256 calculate sha256 sum for an input byte array
func sum256(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
// sumHMAC calculate hmac between two input byte array
func sumHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
// getSigningKey hmac seed to calculate final signature
func getSigningKey(secret, region string, t time.Time) []byte {
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
regionbytes := sumHMAC(date, []byte(region))
service := sumHMAC(regionbytes, []byte("s3"))
signingKey := sumHMAC(service, []byte("aws4_request"))
return signingKey
}
// getSignature final signature in hexadecimal form
func getSignature(signingKey []byte, stringToSign string) string {
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
}
// getScope generate a string of a specific date, an AWS region, and a service
func getScope(region string, t time.Time) string {
scope := strings.Join([]string{
t.Format(yyyymmdd),
region,
"s3",
"aws4_request",
}, "/")
return scope
}
// getCredential generate a credential string
func getCredential(accessKeyID, region string, t time.Time) string {
scope := getScope(region, t)
return accessKeyID + "/" + scope
}
@@ -96,9 +96,9 @@ func (e ErrorResponse) Error() string {
}
// BodyToErrorResponse returns a new encoded ErrorResponse structure
func BodyToErrorResponse(errBody io.Reader, acceptType string) error {
func BodyToErrorResponse(errBody io.Reader) error {
var errorResponse ErrorResponse
err := acceptTypeDecoder(errBody, acceptType, &errorResponse)
err := xmlDecoder(errBody, &errorResponse)
if err != nil {
return err
}
+3 -3
View File
@@ -35,9 +35,9 @@ type CloudStorageAPI interface {
ListIncompleteUploads(bucket, prefix string, recursive bool) <-chan ObjectMultipartStat
// Object Read/Write/Stat operations
GetObject(bucket, object string) (io.ReadCloser, ObjectStat, error)
GetPartialObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error)
PutObject(bucket, object, contentType string, size int64, data io.Reader) error
GetObject(bucket, object string) (io.ReadSeeker, error)
GetPartialObject(bucket, object string, offset, length int64) (io.ReadSeeker, error)
PutObject(bucket, object, contentType string, data io.ReadSeeker) error
StatObject(bucket, object string) (ObjectStat, error)
RemoveObject(bucket, object string) error
RemoveIncompleteUpload(bucket, object string) <-chan error
+94 -39
View File
@@ -16,23 +16,37 @@
package minio
import "io"
import (
"io"
"io/ioutil"
"os"
"sync"
)
type readSeekCloser struct {
r io.Reader
type objectReadSeeker struct {
// mutex.
mutex *sync.Mutex
s3API API
reader io.ReadCloser
isRead bool
stat ObjectStat
offset int64
bucketName string
objectName string
}
// NewReadSeekCloser wraps an io.Reader returning a ReadSeekCloser
func NewReadSeekCloser(r io.Reader) ReadSeekCloser {
return &readSeekCloser{r}
}
// ReadSeekCloser is the container
// that groups the basic Seek and Close methods.
type ReadSeekCloser interface {
io.Reader
io.Closer
io.Seeker
// newObjectReadSeeker wraps getObject request returning a io.ReadSeeker.
func newObjectReadSeeker(api API, bucket, object string) *objectReadSeeker {
return &objectReadSeeker{
mutex: new(sync.Mutex),
reader: nil,
isRead: false,
s3API: api,
offset: 0,
bucketName: bucket,
objectName: object,
}
}
// Read reads up to len(p) bytes into p. It returns the number of bytes
@@ -49,14 +63,30 @@ type ReadSeekCloser interface {
// a non-zero number of bytes at the end of the input stream may
// return either err == EOF or err == nil. The next Read should
// return 0, EOF.
//
// If no io.Reader found nothing will be done.
func (r *readSeekCloser) Read(p []byte) (int, error) {
switch t := r.r.(type) {
case io.Reader:
return t.Read(p)
func (r *objectReadSeeker) Read(p []byte) (int, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
if !r.isRead {
reader, _, err := r.s3API.getObject(r.bucketName, r.objectName, r.offset, 0)
if err != nil {
return 0, err
}
r.reader = reader
r.isRead = true
}
return 0, nil
n, err := r.reader.Read(p)
if err == io.EOF {
io.Copy(ioutil.Discard, r.reader)
r.reader.Close()
return n, err
}
if err != nil {
io.Copy(ioutil.Discard, r.reader)
r.reader.Close()
return 0, err
}
return n, nil
}
// Seek sets the offset for the next Read or Write to offset,
@@ -66,26 +96,51 @@ func (r *readSeekCloser) Read(p []byte) (int, error) {
// start of the file and an error, if any.
//
// Seeking to an offset before the start of the file is an error.
//
// If no io.Seeker found nothing will be done.
func (r *readSeekCloser) Seek(offset int64, whence int) (int64, error) {
switch t := r.r.(type) {
case io.Seeker:
return t.Seek(offset, whence)
}
return int64(0), nil
// TODO: whence value of '1' and '2' are not implemented yet.
func (r *objectReadSeeker) Seek(offset int64, whence int) (int64, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.offset = offset
return offset, nil
}
// Close closes the ReadSeekCloser.
//
// The behavior of Close after the first call is undefined.
// Specific implementations may document their own behavior.
//
// If no io.Closer found nothing will be done.
func (r *readSeekCloser) Close() error {
switch t := r.r.(type) {
case io.Closer:
return t.Close()
// Stat returns the ObjectStat structure describing object. If there is any error it will be of type ErrorResponse.
func (r *objectReadSeeker) Stat() (ObjectStat, error) {
objectSt, err := r.s3API.headObject(r.bucketName, r.objectName)
r.stat = objectSt
return r.stat, err
}
// tempFile - temporary file.
type tempFile struct {
*os.File
mutex *sync.Mutex
}
// newTemplFile returns a new unused file.
func newTempFile(prefix string) (*tempFile, error) {
file, err := ioutil.TempFile("/tmp", prefix)
if err != nil {
return nil, err
}
return &tempFile{
File: file,
mutex: new(sync.Mutex),
}, nil
}
// Close - closer.
func (t *tempFile) Close() error {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.File != nil {
if err := t.File.Close(); err != nil {
return err
}
if err := os.Remove(t.File.Name()); err != nil {
return err
}
t.File = nil
}
return nil
}
+115
View File
@@ -0,0 +1,115 @@
/*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"crypto/md5"
"crypto/sha256"
"hash"
"io"
)
// partsManager reads from io.Reader, partitions data into individual partMetadata{}, backed by a
// temporary file which deletes itself upon Close().
//
// This method runs until an EOF or an error occurs. Before returning, the channel is always closed.
func partsManager(reader io.Reader, partSize int64) <-chan partMetadata {
ch := make(chan partMetadata, 3)
go partsManagerInRoutine(reader, partSize, ch)
return ch
}
func partsManagerInRoutine(reader io.Reader, partSize int64, ch chan<- partMetadata) {
defer close(ch)
tmpFile, err := newTempFile("multiparts$")
if err != nil {
ch <- partMetadata{
Err: err,
}
return
}
var hashMD5 hash.Hash
var hashSha256 hash.Hash
var writer io.Writer
hashMD5 = md5.New()
hashSha256 = sha256.New()
mwwriter := io.MultiWriter(hashMD5, hashSha256)
writer = io.MultiWriter(tmpFile, mwwriter)
n, err := io.CopyN(writer, reader, partSize)
if err == io.EOF || err == io.ErrUnexpectedEOF {
// Seek back to beginning.
tmpFile.Seek(0, 0)
// short read, only single partMetadata return.
ch <- partMetadata{
MD5Sum: hashMD5.Sum(nil),
Sha256Sum: hashSha256.Sum(nil),
ReadCloser: tmpFile,
Size: n,
Err: nil,
}
return
}
// unknown error considered catastrophic error, return here.
if err != nil {
ch <- partMetadata{
Err: err,
}
return
}
// Seek back to beginning.
tmpFile.Seek(0, 0)
ch <- partMetadata{
MD5Sum: hashMD5.Sum(nil),
Sha256Sum: hashSha256.Sum(nil),
ReadCloser: tmpFile,
Size: n,
Err: nil,
}
for err == nil {
var n int64
tmpFile, err = newTempFile("multiparts$")
if err != nil {
ch <- partMetadata{
Err: err,
}
return
}
hashMD5 = md5.New()
hashSha256 = sha256.New()
mwwriter := io.MultiWriter(hashMD5, hashSha256)
writer = io.MultiWriter(tmpFile, mwwriter)
n, err = io.CopyN(writer, reader, partSize)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error
ch <- partMetadata{
Err: err,
}
return
}
}
// Seek back to beginning.
tmpFile.Seek(0, 0)
ch <- partMetadata{
MD5Sum: hashMD5.Sum(nil),
Sha256Sum: hashSha256.Sum(nil),
ReadCloser: tmpFile,
Size: n,
Err: nil,
}
}
}
@@ -34,16 +34,16 @@ import (
// PreSignV2 - presign the request in following style.
// https://${S3_BUCKET}.s3.amazonaws.com/${S3_OBJECT}?AWSAccessKeyId=${S3_ACCESS_KEY}&Expires=${TIMESTAMP}&Signature=${SIGNATURE}
func (r *Request) PreSignV2() (string, error) {
if r.config.AccessKeyID == "" || r.config.SecretAccessKey == "" {
return "", errors.New("presign requires accesskey and secretkey")
if r.config.isAnonymous() {
return "", errors.New("presigning cannot be done with anonymous credentials")
}
// Add date if not present
d := time.Now().UTC()
// Add date if not present
if date := r.Get("Date"); date == "" {
r.Set("Date", d.Format(http.TimeFormat))
}
epochExpires := d.Unix() + r.expires
var path string
// Encode URL path.
if r.config.isVirtualHostedStyle {
for k, v := range regions {
if v == r.config.Region {
@@ -56,18 +56,28 @@ func (r *Request) PreSignV2() (string, error) {
} else {
path = getURLEncodedPath(r.req.URL.Path)
}
signText := fmt.Sprintf("%s\n\n\n%d\n%s", r.req.Method, epochExpires, path)
// Find epoch expires when the request will expire.
epochExpires := d.Unix() + r.expires
// get string to sign.
stringToSign := fmt.Sprintf("%s\n\n\n%d\n%s", r.req.Method, epochExpires, path)
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
hm.Write([]byte(signText))
hm.Write([]byte(stringToSign))
// calculate signature.
signature := base64.StdEncoding.EncodeToString(hm.Sum(nil))
query := r.req.URL.Query()
if r.config.Region != "google" {
query.Set("AWSAccessKeyId", r.config.AccessKeyID)
} else {
// Handle specially for Google Cloud Storage.
if r.config.Region == "google" {
query.Set("GoogleAccessId", r.config.AccessKeyID)
} else {
query.Set("AWSAccessKeyId", r.config.AccessKeyID)
}
// Fill in Expires and Signature for presigned query.
query.Set("Expires", strconv.FormatInt(epochExpires, 10))
query.Set("Signature", base64.StdEncoding.EncodeToString(hm.Sum(nil)))
query.Set("Signature", signature)
r.req.URL.RawQuery = query.Encode()
return r.req.URL.String(), nil
@@ -99,15 +109,20 @@ func (r *Request) PostPresignSignatureV2(policyBase64 string) string {
// SignV2 sign the request before Do() (AWS Signature Version 2).
func (r *Request) SignV2() {
// Initial time.
d := time.Now().UTC()
// Add date if not present.
if date := r.Get("Date"); date == "" {
r.Set("Date", time.Now().UTC().Format(http.TimeFormat))
r.Set("Date", d.Format(http.TimeFormat))
}
// Calculate HMAC for secretAccessKey.
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
hm.Write([]byte(r.getStringToSignV2()))
// prepare auth header.
// Calculate HMAC for secretAccessKey.
stringToSign := r.getStringToSignV2()
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
hm.Write([]byte(stringToSign))
// Prepare auth header.
authHeader := new(bytes.Buffer)
authHeader.WriteString(fmt.Sprintf("AWS %s:", r.config.AccessKeyID))
encoder := base64.NewEncoder(base64.StdEncoding, authHeader)
@@ -69,23 +69,43 @@ var ignoredHeaders = map[string]bool{
"User-Agent": true,
}
// getSigningKey hmac seed to calculate final signature
func getSigningKey(secret, region string, t time.Time) []byte {
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
regionbytes := sumHMAC(date, []byte(region))
service := sumHMAC(regionbytes, []byte("s3"))
signingKey := sumHMAC(service, []byte("aws4_request"))
return signingKey
}
// getSignature final signature in hexadecimal form
func getSignature(signingKey []byte, stringToSign string) string {
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
}
// getScope generate a string of a specific date, an AWS region, and a service
func getScope(region string, t time.Time) string {
scope := strings.Join([]string{
t.Format(yyyymmdd),
region,
"s3",
"aws4_request",
}, "/")
return scope
}
// getCredential generate a credential string
func getCredential(accessKeyID, region string, t time.Time) string {
scope := getScope(region, t)
return accessKeyID + "/" + scope
}
// getHashedPayload get the hexadecimal value of the SHA256 hash of the request payload
func (r *Request) getHashedPayload() string {
hash := func() string {
switch {
case r.expires != 0:
return "UNSIGNED-PAYLOAD"
case r.body == nil:
return hex.EncodeToString(sum256([]byte{}))
default:
sum256Bytes, _ := sum256Reader(r.body)
return hex.EncodeToString(sum256Bytes)
}
}
hashedPayload := hash()
if hashedPayload != "UNSIGNED-PAYLOAD" {
r.req.Header.Set("X-Amz-Content-Sha256", hashedPayload)
if r.expires != 0 {
return "UNSIGNED-PAYLOAD"
}
hashedPayload := r.req.Header.Get("X-Amz-Content-Sha256")
return hashedPayload
}
@@ -149,7 +169,7 @@ func (r *Request) getSignedHeaders() string {
// <SignedHeaders>\n
// <HashedPayload>
//
func (r *Request) getCanonicalRequest(hashedPayload string) string {
func (r *Request) getCanonicalRequest() string {
r.req.URL.RawQuery = strings.Replace(r.req.URL.Query().Encode(), "+", "%20", -1)
canonicalRequest := strings.Join([]string{
r.req.Method,
@@ -157,7 +177,7 @@ func (r *Request) getCanonicalRequest(hashedPayload string) string {
r.req.URL.RawQuery,
r.getCanonicalHeaders(),
r.getSignedHeaders(),
hashedPayload,
r.getHashedPayload(),
}, "\n")
return canonicalRequest
}
@@ -173,10 +193,33 @@ func (r *Request) getStringToSignV4(canonicalRequest string, t time.Time) string
// PreSignV4 presign the request, in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
func (r *Request) PreSignV4() (string, error) {
if r.config.AccessKeyID == "" && r.config.SecretAccessKey == "" {
return "", errors.New("presign requires accesskey and secretkey")
if r.config.isAnonymous() {
return "", errors.New("presigning cannot be done with anonymous credentials")
}
r.SignV4()
// Initial time.
t := time.Now().UTC()
// Get all signed headers.
signedHeaders := r.getSignedHeaders()
// Get string to sign from canonical request.
stringToSign := r.getStringToSignV4(r.getCanonicalRequest(), t)
// get credential string.
credential := getCredential(r.config.AccessKeyID, r.config.Region, t)
// get hmac signing key.
signingKey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t)
// calculate signature.
signature := getSignature(signingKey, stringToSign)
query := r.req.URL.Query()
query.Set("X-Amz-Algorithm", authHeader)
query.Set("X-Amz-Date", t.Format(iso8601DateFormat))
query.Set("X-Amz-Expires", strconv.FormatInt(r.expires, 10))
query.Set("X-Amz-SignedHeaders", signedHeaders)
query.Set("X-Amz-Credential", credential)
r.req.URL.RawQuery = query.Encode()
r.req.URL.RawQuery += "&X-Amz-Signature=" + signature
return r.req.URL.String(), nil
}
@@ -189,45 +232,30 @@ func (r *Request) PostPresignSignatureV4(policyBase64 string, t time.Time) strin
// SignV4 sign the request before Do(), in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.
func (r *Request) SignV4() {
query := r.req.URL.Query()
if r.expires != 0 {
query.Set("X-Amz-Algorithm", authHeader)
}
func (r *Request) SignV4(presign bool) {
// Initial time.
t := time.Now().UTC()
// Add date if not present
if r.expires != 0 {
query.Set("X-Amz-Date", t.Format(iso8601DateFormat))
query.Set("X-Amz-Expires", strconv.FormatInt(r.expires, 10))
} else {
r.Set("X-Amz-Date", t.Format(iso8601DateFormat))
}
// Set x-amz-date.
r.Set("X-Amz-Date", t.Format(iso8601DateFormat))
hashedPayload := r.getHashedPayload()
// Get all signed headers.
signedHeaders := r.getSignedHeaders()
if r.expires != 0 {
query.Set("X-Amz-SignedHeaders", signedHeaders)
}
// Get string to sign from canonical request.
stringToSign := r.getStringToSignV4(r.getCanonicalRequest(), t)
// get credential string.
credential := getCredential(r.config.AccessKeyID, r.config.Region, t)
if r.expires != 0 {
query.Set("X-Amz-Credential", credential)
r.req.URL.RawQuery = query.Encode()
}
canonicalRequest := r.getCanonicalRequest(hashedPayload)
stringToSign := r.getStringToSignV4(canonicalRequest, t)
// get hmac signing key.
signingKey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t)
// calculate signature.
signature := getSignature(signingKey, stringToSign)
if r.expires != 0 {
r.req.URL.RawQuery += "&X-Amz-Signature=" + signature
} else {
// final Authorization header
parts := []string{
authHeader + " Credential=" + credential,
"SignedHeaders=" + signedHeaders,
"Signature=" + signature,
}
auth := strings.Join(parts, ", ")
r.Set("Authorization", auth)
// if regular request, construct the final authorization header.
parts := []string{
authHeader + " Credential=" + credential,
"SignedHeaders=" + signedHeaders,
"Signature=" + signature,
}
auth := strings.Join(parts, ", ")
r.Set("Authorization", auth)
}
@@ -17,38 +17,50 @@
package minio
import (
"encoding/base64"
"encoding/hex"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"unicode/utf8"
)
// operation - rest operation
// operation - rest operation.
type operation struct {
HTTPServer string
HTTPMethod string
HTTPPath string
}
// Request - a http request
// Request - a http request.
type Request struct {
req *http.Request
config *Config
body io.ReadSeeker
expires int64
}
// Do - start the request
// requestMetadata a http request metadata.
type requestMetadata struct {
body io.ReadCloser
contentType string
contentLength int64
sha256PayloadBytes []byte
md5SumPayloadBytes []byte
}
// Do - start the request.
func (r *Request) Do() (resp *http.Response, err error) {
if r.config.AccessKeyID != "" && r.config.SecretAccessKey != "" {
// if not an anonymous request, calculate relevant signature.
if !r.config.isAnonymous() {
if r.config.Signature.isV2() {
// if signature version '2' requested, use that.
r.SignV2()
}
if r.config.Signature.isV4() || r.config.Signature.isLatest() {
r.SignV4()
// Not a presigned request, set behavior to default.
presign := false
r.SignV4(presign)
}
}
transport := http.DefaultTransport
@@ -66,16 +78,17 @@ func (r *Request) Do() (resp *http.Response, err error) {
return transport.RoundTrip(r.req)
}
// Set - set additional headers if any
// Set - set additional headers if any.
func (r *Request) Set(key, value string) {
r.req.Header.Set(key, value)
}
// Get - get header values
// Get - get header values.
func (r *Request) Get(key string) string {
return r.req.Header.Get(key)
}
// path2BucketAndObject - extract bucket and object names from URL path.
func path2BucketAndObject(path string) (bucketName, objectName string) {
pathSplits := strings.SplitN(path, "?", 2)
splits := strings.SplitN(pathSplits[0], separator, 3)
@@ -154,6 +167,7 @@ func getURLEncodedPath(pathName string) string {
return encodedPathname
}
// getRequetURL - get a properly encoded request URL.
func (op *operation) getRequestURL(config Config) (url string) {
// parse URL for the combination of HTTPServer + HTTPPath
url = op.HTTPServer + separator
@@ -202,63 +216,17 @@ func newPresignedRequest(op *operation, config *Config, expires int64) (*Request
// set UserAgent
req.Header.Set("User-Agent", config.userAgent)
// set Accept header for response encoding style, if available
if config.AcceptType != "" {
req.Header.Set("Accept", config.AcceptType)
}
// save for subsequent use
r := new(Request)
r.config = config
r.expires = expires
r.req = req
r.body = nil
return r, nil
}
// newUnauthenticatedRequest - instantiate a new unauthenticated request
func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*Request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
method = "POST"
}
u := op.getRequestURL(*config)
// get a new HTTP request, for the requested method
req, err := http.NewRequest(method, u, nil)
if err != nil {
return nil, err
}
// set UserAgent
req.Header.Set("User-Agent", config.userAgent)
// set Accept header for response encoding style, if available
if config.AcceptType != "" {
req.Header.Set("Accept", config.AcceptType)
}
// add body
switch {
case body == nil:
req.Body = nil
default:
req.Body = ioutil.NopCloser(body)
}
// save for subsequent use
r := new(Request)
r.req = req
r.config = config
return r, nil
}
// newRequest - instantiate a new request
func newRequest(op *operation, config *Config, body io.ReadSeeker) (*Request, error) {
func newRequest(op *operation, config *Config, metadata requestMetadata) (*Request, error) {
// if no method default to POST
method := op.HTTPMethod
if method == "" {
@@ -275,24 +243,39 @@ func newRequest(op *operation, config *Config, body io.ReadSeeker) (*Request, er
// set UserAgent
req.Header.Set("User-Agent", config.userAgent)
// set Accept header for response encoding style, if available
if config.AcceptType != "" {
req.Header.Set("Accept", config.AcceptType)
}
// add body
switch {
case body == nil:
case metadata.body == nil:
req.Body = nil
default:
req.Body = ioutil.NopCloser(body)
req.Body = metadata.body
}
// save for subsequent use
r := new(Request)
r.config = config
r.req = req
r.body = body
// Set contentType for the request.
if metadata.contentType != "" {
r.Set("Content-Type", metadata.contentType)
}
// set incoming content-length.
if metadata.contentLength > 0 {
r.req.ContentLength = metadata.contentLength
}
// set sha256 sum for signature calculation only with signature version '4'.
if r.config.Signature.isV4() || r.config.Signature.isLatest() {
r.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{})))
if metadata.sha256PayloadBytes != nil {
r.Set("X-Amz-Content-Sha256", hex.EncodeToString(metadata.sha256PayloadBytes))
}
}
// set md5Sum for in transit corruption detection.
if metadata.md5SumPayloadBytes != nil {
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(metadata.md5SumPayloadBytes))
}
return r, nil
}
@@ -90,8 +90,8 @@ type initiator struct {
DisplayName string
}
// partMetadata container for particular part of an object
type partMetadata struct {
// objectPartMetadata container for particular part of an object
type objectPartMetadata struct {
// Part number identifies the part.
PartNumber int
@@ -124,7 +124,7 @@ type listObjectPartsResult struct {
// Indicates whether the returned list of parts is truncated.
IsTruncated bool
Parts []partMetadata `xml:"Part"`
ObjectParts []objectPartMetadata `xml:"Part"`
EncodingType string
}
@@ -165,7 +165,9 @@ type createBucketConfiguration struct {
Location string `xml:"LocationConstraint"`
}
// grant container for the grantee and his or her permissions.
type grant struct {
// grantee container for DisplayName and ID of the person being granted permissions.
Grantee struct {
ID string
DisplayName string
@@ -176,7 +178,9 @@ type grant struct {
Permission string
}
// accessControlPolicy contains the elements providing ACL permissions for a bucket.
type accessControlPolicy struct {
// accessControlList container for ACL information.
AccessControlList struct {
Grant []grant
}
+45 -110
View File
@@ -18,8 +18,6 @@ package minio
import (
"bytes"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
@@ -64,38 +62,34 @@ func (a s3API) putBucketRequest(bucket, acl, location string) (*Request, error)
HTTPMethod: "PUT",
HTTPPath: separator + bucket,
}
var createBucketConfigBuffer *bytes.Reader
var createBucketConfigBuffer *bytes.Buffer
// If location is set use it and create proper bucket configuration.
switch {
case location != "":
createBucketConfig := new(createBucketConfiguration)
createBucketConfig.Location = location
var createBucketConfigBytes []byte
switch {
case a.config.AcceptType == "application/xml":
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
case a.config.AcceptType == "application/json":
createBucketConfigBytes, err = json.Marshal(createBucketConfig)
default:
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
}
createBucketConfigBytes, err := xml.Marshal(createBucketConfig)
if err != nil {
return nil, err
}
createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
createBucketConfigBuffer = bytes.NewBuffer(createBucketConfigBytes)
}
switch {
case createBucketConfigBuffer == nil:
r, err = newRequest(op, a.config, nil)
r, err = newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
default:
r, err = newRequest(op, a.config, createBucketConfigBuffer)
rmetadata := requestMetadata{
body: ioutil.NopCloser(createBucketConfigBuffer),
contentLength: int64(createBucketConfigBuffer.Len()),
sha256PayloadBytes: sum256(createBucketConfigBuffer.Bytes()),
}
r, err = newRequest(op, a.config, rmetadata)
if err != nil {
return nil, err
}
r.req.ContentLength = int64(createBucketConfigBuffer.Len())
}
// by default bucket is private
switch {
@@ -143,7 +137,7 @@ func (a s3API) putBucket(bucket, acl, location string) error {
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return BodyToErrorResponse(resp.Body, a.config.AcceptType)
return BodyToErrorResponse(resp.Body)
}
}
return nil
@@ -156,7 +150,7 @@ func (a s3API) putBucketACLRequest(bucket, acl string) (*Request, error) {
HTTPMethod: "PUT",
HTTPPath: separator + bucket + "?acl",
}
req, err := newRequest(op, a.config, nil)
req, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -190,7 +184,7 @@ func (a s3API) putBucketACL(bucket, acl string) error {
}
return errorResponse
}
return BodyToErrorResponse(resp.Body, a.config.AcceptType)
return BodyToErrorResponse(resp.Body)
}
}
return nil
@@ -203,7 +197,7 @@ func (a s3API) getBucketACLRequest(bucket string) (*Request, error) {
HTTPMethod: "GET",
HTTPPath: separator + bucket + "?acl",
}
req, err := newRequest(op, a.config, nil)
req, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -236,11 +230,11 @@ func (a s3API) getBucketACL(bucket string) (accessControlPolicy, error) {
}
return accessControlPolicy{}, errorResponse
}
return accessControlPolicy{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return accessControlPolicy{}, BodyToErrorResponse(resp.Body)
}
}
policy := accessControlPolicy{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &policy)
err = xmlDecoder(resp.Body, &policy)
if err != nil {
return accessControlPolicy{}, err
}
@@ -269,7 +263,7 @@ func (a s3API) getBucketLocationRequest(bucket string) (*Request, error) {
HTTPMethod: "GET",
HTTPPath: separator + bucket + "?location",
}
req, err := newRequest(op, a.config, nil)
req, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -289,11 +283,11 @@ func (a s3API) getBucketLocation(bucket string) (string, error) {
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", BodyToErrorResponse(resp.Body, a.config.AcceptType)
return "", BodyToErrorResponse(resp.Body)
}
}
var locationConstraint string
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &locationConstraint)
err = xmlDecoder(resp.Body, &locationConstraint)
if err != nil {
return "", err
}
@@ -326,7 +320,7 @@ func (a s3API) listObjectsRequest(bucket, marker, prefix, delimiter string, maxk
HTTPMethod: "GET",
HTTPPath: separator + bucket + *query,
}
r, err := newRequest(op, a.config, nil)
r, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -372,11 +366,11 @@ func (a s3API) listObjects(bucket, marker, prefix, delimiter string, maxkeys int
}
return listBucketResult{}, errorResponse
}
return listBucketResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return listBucketResult{}, BodyToErrorResponse(resp.Body)
}
}
listBucketResult := listBucketResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listBucketResult)
err = xmlDecoder(resp.Body, &listBucketResult)
if err != nil {
return listBucketResult, err
}
@@ -391,7 +385,7 @@ func (a s3API) headBucketRequest(bucket string) (*Request, error) {
HTTPMethod: "HEAD",
HTTPPath: separator + bucket,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// headBucket useful to determine if a bucket exists and you have permission to access it.
@@ -463,7 +457,7 @@ func (a s3API) deleteBucketRequest(bucket string) (*Request, error) {
HTTPMethod: "DELETE",
HTTPPath: separator + bucket,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// deleteBucket deletes the bucket named in the URI.
@@ -544,93 +538,34 @@ func (a s3API) deleteBucket(bucket string) error {
/// Object Read/Write/Stat Operations
// putObjectUnAuthenticatedRequest - putObjectUnauthenticated request.
func (a s3API) putObjectUnAuthenticatedRequest(bucket, object, contentType string,
size int64, body io.Reader) (*Request, error) {
if strings.TrimSpace(contentType) == "" {
contentType = "application/octet-stream"
}
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
HTTPPath: separator + bucket + separator + object,
}
r, err := newUnauthenticatedRequest(op, a.config, body)
if err != nil {
return nil, err
}
// Content-MD5 is not set, since its not calculated.
r.Set("Content-Type", contentType)
r.req.ContentLength = size
return r, nil
}
// putObjectUnAuthenticated - add an object to a bucket anonymously.
// NOTE: You must have WRITE permissions on a bucket to add an object to it. Bucket should have 'public-read-write' ACL.
func (a s3API) putObjectUnAuthenticated(bucket, object, contentType string,
size int64, body io.Reader) (ObjectStat, error) {
req, err := a.putObjectUnAuthenticatedRequest(bucket, object, contentType, size, body)
if err != nil {
return ObjectStat{}, err
}
resp, err := req.Do()
defer closeResp(resp)
if err != nil {
return ObjectStat{}, err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
// handle 301 sepcifically in case of wrong regions during path style.
if resp.StatusCode == http.StatusMovedPermanently {
region, _ := a.getBucketLocation(bucket)
endPoint := getEndpoint(region)
errorResponse := ErrorResponse{
Code: "PermanentRedirect",
Message: "The bucket you are attempting to access must be addressed using the specified endpoint https://" + endPoint + ". Send all future requests to this endpoint.",
Resource: separator + bucket,
RequestID: resp.Header.Get("x-amz-request-id"),
HostID: resp.Header.Get("x-amz-id-2"),
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
}
return ObjectStat{}, errorResponse
}
return ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
}
}
var metadata ObjectStat
metadata.ETag = strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
return metadata, nil
}
// putObjectRequest wrapper creates a new PutObject request.
func (a s3API) putObjectRequest(bucket, object, contentType string,
md5SumBytes []byte, size int64, body io.ReadSeeker) (*Request, error) {
if strings.TrimSpace(contentType) == "" {
contentType = "application/octet-stream"
func (a s3API) putObjectRequest(bucket, object string, putObjMetadata putObjectMetadata) (*Request, error) {
if strings.TrimSpace(putObjMetadata.ContentType) == "" {
putObjMetadata.ContentType = "application/octet-stream"
}
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
HTTPPath: separator + bucket + separator + object,
}
r, err := newRequest(op, a.config, body)
rmetadata := requestMetadata{
body: putObjMetadata.ReadCloser,
contentLength: putObjMetadata.Size,
contentType: putObjMetadata.ContentType,
sha256PayloadBytes: putObjMetadata.Sha256Sum,
md5SumPayloadBytes: putObjMetadata.MD5Sum,
}
r, err := newRequest(op, a.config, rmetadata)
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5.
if md5SumBytes != nil {
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
}
r.Set("Content-Type", contentType)
r.req.ContentLength = size
return r, nil
}
// putObject - add an object to a bucket.
// NOTE: You must have WRITE permissions on a bucket to add an object to it.
func (a s3API) putObject(bucket, object, contentType string,
md5SumBytes []byte, size int64, body io.ReadSeeker) (ObjectStat, error) {
req, err := a.putObjectRequest(bucket, object, contentType, md5SumBytes, size, body)
func (a s3API) putObject(bucket, object string, putObjMetadata putObjectMetadata) (ObjectStat, error) {
req, err := a.putObjectRequest(bucket, object, putObjMetadata)
if err != nil {
return ObjectStat{}, err
}
@@ -655,7 +590,7 @@ func (a s3API) putObject(bucket, object, contentType string,
}
return ObjectStat{}, errorResponse
}
return ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return ObjectStat{}, BodyToErrorResponse(resp.Body)
}
}
var metadata ObjectStat
@@ -766,7 +701,7 @@ func (a s3API) getObjectRequest(bucket, object string, offset, length int64) (*R
HTTPMethod: "GET",
HTTPPath: separator + bucket + separator + object,
}
r, err := newRequest(op, a.config, nil)
r, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -820,7 +755,7 @@ func (a s3API) getObject(bucket, object string, offset, length int64) (io.ReadCl
}
return nil, ObjectStat{}, errorResponse
default:
return nil, ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return nil, ObjectStat{}, BodyToErrorResponse(resp.Body)
}
}
md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
@@ -856,7 +791,7 @@ func (a s3API) deleteObjectRequest(bucket, object string) (*Request, error) {
HTTPMethod: "DELETE",
HTTPPath: separator + bucket + separator + object,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// deleteObject deletes a given object from a bucket.
@@ -889,7 +824,7 @@ func (a s3API) headObjectRequest(bucket, object string) (*Request, error) {
HTTPMethod: "HEAD",
HTTPPath: separator + bucket + separator + object,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// headObject retrieves metadata from an object without returning the object itself.
@@ -1000,7 +935,7 @@ func (a s3API) listBucketsRequest() (*Request, error) {
HTTPMethod: "GET",
HTTPPath: separator,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// listBuckets list of all buckets owned by the authenticated sender of the request.
@@ -1026,11 +961,11 @@ func (a s3API) listBuckets() (listAllMyBucketsResult, error) {
}
}
if resp.StatusCode != http.StatusOK {
return listAllMyBucketsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return listAllMyBucketsResult{}, BodyToErrorResponse(resp.Body)
}
}
listAllMyBucketsResult := listAllMyBucketsResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listAllMyBucketsResult)
err = xmlDecoder(resp.Body, &listAllMyBucketsResult)
if err != nil {
return listAllMyBucketsResult, err
}
+36 -46
View File
@@ -18,12 +18,9 @@ package minio
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
)
@@ -57,7 +54,7 @@ func (a s3API) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, pr
HTTPMethod: "GET",
HTTPPath: separator + bucket + query,
}
r, err := newRequest(op, a.config, nil)
r, err := newRequest(op, a.config, requestMetadata{})
if err != nil {
return nil, err
}
@@ -87,15 +84,14 @@ func (a s3API) listMultipartUploads(bucket, keymarker, uploadIDMarker, prefix, d
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return listMultipartUploadsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return listMultipartUploadsResult{}, BodyToErrorResponse(resp.Body)
}
}
listMultipartUploadsResult := listMultipartUploadsResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listMultipartUploadsResult)
err = xmlDecoder(resp.Body, &listMultipartUploadsResult)
if err != nil {
return listMultipartUploadsResult, err
}
// close body while returning, along with any error.
return listMultipartUploadsResult, nil
}
@@ -106,7 +102,7 @@ func (a s3API) initiateMultipartRequest(bucket, object string) (*Request, error)
HTTPMethod: "POST",
HTTPPath: separator + bucket + separator + object + "?uploads",
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// initiateMultipartUpload initiates a multipart upload and returns an upload ID.
@@ -122,11 +118,11 @@ func (a s3API) initiateMultipartUpload(bucket, object string) (initiateMultipart
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return initiateMultipartUploadResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return initiateMultipartUploadResult{}, BodyToErrorResponse(resp.Body)
}
}
initiateMultipartUploadResult := initiateMultipartUploadResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &initiateMultipartUploadResult)
err = xmlDecoder(resp.Body, &initiateMultipartUploadResult)
if err != nil {
return initiateMultipartUploadResult, err
}
@@ -140,25 +136,20 @@ func (a s3API) completeMultipartUploadRequest(bucket, object, uploadID string, c
HTTPMethod: "POST",
HTTPPath: separator + bucket + separator + object + "?uploadId=" + uploadID,
}
var completeMultipartUploadBytes []byte
var err error
switch {
case a.config.AcceptType == "application/xml":
completeMultipartUploadBytes, err = xml.Marshal(complete)
case a.config.AcceptType == "application/json":
completeMultipartUploadBytes, err = json.Marshal(complete)
default:
completeMultipartUploadBytes, err = xml.Marshal(complete)
}
completeMultipartUploadBytes, err := xml.Marshal(complete)
if err != nil {
return nil, err
}
completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
r, err := newRequest(op, a.config, completeMultipartUploadBuffer)
completeMultipartUploadBuffer := bytes.NewBuffer(completeMultipartUploadBytes)
rmetadata := requestMetadata{
body: ioutil.NopCloser(completeMultipartUploadBuffer),
contentLength: int64(completeMultipartUploadBuffer.Len()),
sha256PayloadBytes: sum256(completeMultipartUploadBuffer.Bytes()),
}
r, err := newRequest(op, a.config, rmetadata)
if err != nil {
return nil, err
}
r.req.ContentLength = int64(completeMultipartUploadBuffer.Len())
return r, nil
}
@@ -175,11 +166,11 @@ func (a s3API) completeMultipartUpload(bucket, object, uploadID string, c comple
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return completeMultipartUploadResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return completeMultipartUploadResult{}, BodyToErrorResponse(resp.Body)
}
}
completeMultipartUploadResult := completeMultipartUploadResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &completeMultipartUploadResult)
err = xmlDecoder(resp.Body, &completeMultipartUploadResult)
if err != nil {
return completeMultipartUploadResult, err
}
@@ -193,7 +184,7 @@ func (a s3API) abortMultipartUploadRequest(bucket, object, uploadID string) (*Re
HTTPMethod: "DELETE",
HTTPPath: separator + bucket + separator + object + "?uploadId=" + uploadID,
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted.
@@ -262,7 +253,7 @@ func (a s3API) listObjectPartsRequest(bucket, object, uploadID string, partNumbe
HTTPMethod: "GET",
HTTPPath: separator + bucket + separator + object + resourceQuery(),
}
return newRequest(op, a.config, nil)
return newRequest(op, a.config, requestMetadata{})
}
// listObjectParts (List Parts)
@@ -284,11 +275,11 @@ func (a s3API) listObjectParts(bucket, object, uploadID string, partNumberMarker
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return listObjectPartsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return listObjectPartsResult{}, BodyToErrorResponse(resp.Body)
}
}
listObjectPartsResult := listObjectPartsResult{}
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listObjectPartsResult)
err = xmlDecoder(resp.Body, &listObjectPartsResult)
if err != nil {
return listObjectPartsResult, err
}
@@ -296,36 +287,32 @@ func (a s3API) listObjectParts(bucket, object, uploadID string, partNumberMarker
}
// uploadPartRequest wrapper creates a new UploadPart request.
func (a s3API) uploadPartRequest(bucket, object, uploadID string,
md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (*Request, error) {
func (a s3API) uploadPartRequest(bucket, object, uploadID string, uploadingPart partMetadata) (*Request, error) {
op := &operation{
HTTPServer: a.config.Endpoint,
HTTPMethod: "PUT",
HTTPPath: separator + bucket + separator + object +
"?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID,
"?partNumber=" + strconv.Itoa(uploadingPart.Number) + "&uploadId=" + uploadID,
}
r, err := newRequest(op, a.config, body)
rmetadata := requestMetadata{
body: uploadingPart.ReadCloser,
contentLength: uploadingPart.Size,
sha256PayloadBytes: uploadingPart.Sha256Sum,
md5SumPayloadBytes: uploadingPart.MD5Sum,
}
r, err := newRequest(op, a.config, rmetadata)
if err != nil {
return nil, err
}
// set Content-MD5 as base64 encoded md5.
if md5SumBytes != nil {
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
}
r.req.ContentLength = size
return r, nil
}
// uploadPart uploads a part in a multipart upload.
func (a s3API) uploadPart(bucket, object, uploadID string,
md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (completePart, error) {
req, err := a.uploadPartRequest(bucket, object, uploadID, md5SumBytes, partNumber, size, body)
func (a s3API) uploadPart(bucket, object, uploadID string, uploadingPart partMetadata) (completePart, error) {
req, err := a.uploadPartRequest(bucket, object, uploadID, uploadingPart)
if err != nil {
return completePart{}, err
}
cPart := completePart{}
cPart.PartNumber = partNumber
cPart.ETag = "\"" + hex.EncodeToString(md5SumBytes) + "\""
// initiate the request.
resp, err := req.Do()
@@ -335,8 +322,11 @@ func (a s3API) uploadPart(bucket, object, uploadID string,
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return completePart{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
return completePart{}, BodyToErrorResponse(resp.Body)
}
}
cPart := completePart{}
cPart.PartNumber = uploadingPart.Number
cPart.ETag = resp.Header.Get("ETag")
return cPart, nil
}
+2 -2
View File
@@ -29,8 +29,8 @@
},
{
"path": "github.com/minio/minio-go",
"revision": "bf8996055bebd547d940b8579d2ec05f2d37ede8",
"revisionTime": "2015-11-23T14:07:27-08:00"
"revision": "c2c61c7f6b480303a474b43deb8fbd05ec974c41",
"revisionTime": "2015-11-28T11:01:09-08:00"
},
{
"path": "github.com/minio/minio-xl/pkg/atomic",