fs/s3: move the code for fs and s3 out to the top-level.

Now the interface moves to the top level - fixes #1604
This commit is contained in:
Harshavardhana
2016-02-16 11:27:42 -08:00
parent 220bf92a3c
commit fe5b2f97e3
36 changed files with 728 additions and 853 deletions
+2 -27
View File
@@ -14,12 +14,9 @@
* limitations under the License.
*/
package client
package main
import (
"fmt"
"strconv"
)
import "fmt"
/// Collection of standard errors
@@ -33,15 +30,6 @@ func (e APINotImplemented) Error() string {
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
}
// InvalidRange - invalid range requested
type InvalidRange struct {
Offset int64
}
func (e InvalidRange) Error() string {
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
}
// GenericBucketError - generic bucket operations error
type GenericBucketError struct {
Bucket string
@@ -75,12 +63,6 @@ func (e BucketNameEmpty) Error() string {
return "Bucket name cannot be empty."
}
// GenericObjectError - generic object operations error
type GenericObjectError struct {
Bucket string
Object string
}
// ObjectAlreadyExists - typed return for MethodNotAllowed
type ObjectAlreadyExists struct {
Object string
@@ -90,13 +72,6 @@ func (e ObjectAlreadyExists) Error() string {
return "Object ‘" + e.Object + "’ already exists."
}
// InvalidObjectName - object requested is invalid
type InvalidObjectName GenericObjectError
func (e InvalidObjectName) Error() string {
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
}
// BucketNameTopLevel - generic error
type BucketNameTopLevel struct{}
+164 -67
View File
@@ -14,44 +14,45 @@
* limitations under the License.
*/
package fs
package main
import (
"io"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"io/ioutil"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/minio/pkg/ioutils"
"github.com/minio/minio/pkg/probe"
)
// filesystem client
type fsClient struct {
PathURL *client.URL
PathURL *clientURL
}
const (
partSuffix = ".part.mc"
partSuffix = ".part.minio"
)
// New - instantiate a new fs client.
func New(path string) (client.Client, *probe.Error) {
// fsNew - instantiate a new fs
func fsNew(path string) (Client, *probe.Error) {
if strings.TrimSpace(path) == "" {
return nil, probe.NewError(client.EmptyPath{})
return nil, probe.NewError(EmptyPath{})
}
return &fsClient{
PathURL: client.NewURL(normalizePath(path)),
PathURL: newURL(normalizePath(path)),
}, nil
}
// URL get url.
func (f *fsClient) GetURL() client.URL {
func (f *fsClient) GetURL() clientURL {
return *f.PathURL
}
@@ -71,7 +72,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
if e == nil {
// If the destination exists and is not a regular file.
if !st.Mode().IsRegular() {
return 0, probe.NewError(client.PathIsNotRegular{
return 0, probe.NewError(PathIsNotRegular{
Path: objectPath,
})
}
@@ -143,7 +144,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
// corruption return here.
if readAtSize != writtenSize {
// Unexpected write (less data was written than expected).
return 0, probe.NewError(client.UnexpectedShortWrite{
return 0, probe.NewError(UnexpectedShortWrite{
InputSize: readAtSize,
WriteSize: writtenSize,
})
@@ -194,14 +195,14 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
if size > 0 {
// Unexpected EOF reached (less data was written than expected).
if totalWritten < size {
return totalWritten, probe.NewError(client.UnexpectedEOF{
return totalWritten, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: totalWritten,
})
}
// Unexpected ExcessRead (more data was written than expected).
if totalWritten > size {
return totalWritten, probe.NewError(client.UnexpectedExcessRead{
return totalWritten, probe.NewError(UnexpectedExcessRead{
TotalSize: size,
TotalWritten: totalWritten,
})
@@ -217,7 +218,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
// ShareDownload - share download not implemented for filesystem.
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(client.APINotImplemented{
return "", probe.NewError(APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
})
@@ -225,7 +226,7 @@ func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
// 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{
return nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
})
@@ -266,8 +267,8 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error {
}
// List - list files and folders.
func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
contentCh := make(chan *client.Content)
func (f *fsClient) List(recursive, incomplete bool) <-chan *clientContent {
contentCh := make(chan *clientContent)
switch recursive {
case true:
go f.listRecursiveInRoutine(contentCh, incomplete)
@@ -277,13 +278,50 @@ func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
return contentCh
}
// byDirName implements sort.Interface.
type byDirName []os.FileInfo
func (f byDirName) Len() int { return len(f) }
func (f byDirName) Less(i, j int) bool {
// For directory add an ending separator fortrue lexical
// order.
if f[i].Mode().IsDir() {
return f[i].Name()+string(filepath.Separator) < f[j].Name()
}
// For directory add an ending separator for true lexical
// order.
if f[j].Mode().IsDir() {
return f[i].Name() < f[j].Name()+string(filepath.Separator)
}
return f[i].Name() < f[j].Name()
}
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// readDir reads the directory named by dirname and returns
// a list of sorted directory entries.
func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
}
// listPrefixes - list all files for any given prefix.
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, incomplete bool) {
dirName := filepath.Dir(prefix)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: err.Trace(dirName),
}
return
@@ -303,7 +341,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
newPath := filepath.Join(prefix, fi.Name())
lfi, le := f.handleWindowsSymlinks(newPath)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(newPath),
}
continue
@@ -318,19 +356,19 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
}
}
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(client.PathInsufficientPermission{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
@@ -338,15 +376,15 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
}
}
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
@@ -362,8 +400,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
contentCh <- &clientContent{
URL: *newURL(file),
Time: st.ModTime(),
Size: st.Size(),
Type: st.Mode(),
@@ -382,8 +420,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
continue
}
}
contentCh <- &client.Content{
URL: *client.NewURL(file),
contentCh <- &clientContent{
URL: *newURL(file),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
@@ -394,7 +432,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
return
}
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) {
func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete bool) {
// close the channel when the function returns.
defer close(contentCh)
@@ -404,14 +442,14 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
fst, err := f.fsStat()
if err != nil {
if _, ok := err.ToGoError().(client.PathNotFound); ok {
if _, ok := err.ToGoError().(PathNotFound); ok {
// If file does not exist treat it like a prefix and list all prefixes if any.
prefix := fpath
f.listPrefixes(prefix, contentCh, incomplete)
return
}
// For all other errors we return genuine error back to the caller.
contentCh <- &client.Content{Err: err.Trace(fpath)}
contentCh <- &clientContent{Err: err.Trace(fpath)}
return
}
@@ -427,7 +465,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
case true:
files, e := readDir(fpath)
if err != nil {
contentCh <- &client.Content{Err: probe.NewError(e)}
contentCh <- &clientContent{Err: probe.NewError(e)}
return
}
for _, file := range files {
@@ -443,7 +481,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
newPath := filepath.Join(fpath, fi.Name())
lfi, le := f.handleWindowsSymlinks(newPath)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(newPath),
}
continue
@@ -459,29 +497,29 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
Type: lfi.Mode(),
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
}
continue
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
}
continue
}
}
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}),
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{Path: file.Name()}),
}
continue
}
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
@@ -499,7 +537,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
pathURL = *f.PathURL
pathURL.Path = filepath.Join(pathURL.Path, fi.Name())
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: fi.ModTime(),
Size: fi.Size(),
@@ -518,7 +556,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
return
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: fst.ModTime(),
Size: fst.Size(),
@@ -528,7 +566,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
}
}
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) {
func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) {
// close channels upon return.
defer close(contentCh)
var dirName string
@@ -555,7 +593,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
!strings.HasPrefix(filePrefix, fp) {
if e == nil {
if fi.IsDir() {
return errSkipDir
return ioutils.ErrSkipDir
}
return nil
}
@@ -571,7 +609,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if e != nil {
// If operation is not permitted, we throw quickly back.
if strings.Contains(e.Error(), "operation not permitted") {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return nil
@@ -580,7 +618,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if runtime.GOOS == "windows" {
lfi, le := f.handleWindowsSymlinks(fp)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(fp),
}
return nil
@@ -596,7 +634,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
@@ -604,8 +642,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
Err: probe.NewError(e),
}
} else {
contentCh <- &client.Content{
Err: probe.NewError(client.PathInsufficientPermission{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{Path: fp}),
}
}
return nil
@@ -619,7 +657,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
if runtime.GOOS == "windows" {
lfi, le := f.handleWindowsSymlinks(fp)
if le != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: le.Trace(fp),
}
return nil
@@ -635,7 +673,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: pathURL,
Time: lfi.ModTime(),
Size: lfi.Size(),
@@ -644,22 +682,22 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
}
return nil
}
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return nil
}
// Ignore in-accessible broken symlinks.
if os.IsNotExist(e) {
contentCh <- &client.Content{
Err: probe.NewError(client.BrokenSymlink{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{Path: fp}),
}
return nil
}
// Ignore symlink loops.
if strings.Contains(e.Error(), "too many levels of symbolic links") {
contentCh <- &client.Content{
Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}),
contentCh <- &clientContent{
Err: probe.NewError(TooManyLevelsSymlink{Path: fp}),
}
return nil
}
@@ -676,8 +714,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
return nil
}
}
contentCh <- &client.Content{
URL: *client.NewURL(fp),
contentCh <- &clientContent{
URL: *newURL(fp),
Time: fi.ModTime(),
Size: fi.Size(),
Type: fi.Mode(),
@@ -703,9 +741,9 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
filePrefix = pathURL.Path
}
// walks invokes our custom function.
e := walk(dirName, visitFS)
e := ioutils.FTW(dirName, visitFS)
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
}
@@ -722,24 +760,83 @@ func (f *fsClient) MakeBucket(region string) *probe.Error {
// GetBucketACL - get bucket access.
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
return "", probe.NewError(APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
}
// SetBucketAccess - set bucket access.
func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
return probe.NewError(APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
}
// Stat - get metadata from path.
func (f *fsClient) Stat() (content *client.Content, err *probe.Error) {
func (f *fsClient) Stat() (content *clientContent, err *probe.Error) {
st, err := f.fsStat()
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
content = new(client.Content)
content = &clientContent{}
content.URL = *f.PathURL
content.Size = st.Size()
content.Time = st.ModTime()
content.Type = st.Mode()
return content, nil
}
// toClientError error constructs a typed client error for known filesystem errors.
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsPermission(e) {
return probe.NewError(PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(PathNotFound{Path: fpath})
}
return probe.NewError(e)
}
// handle windows symlinks - eg: junction files.
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
// 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.
file, e := os.Lstat(fpath)
if e != nil {
err := f.toClientError(e, fpath)
return nil, err.Trace(fpath)
}
return file, nil
}
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(f.PathURL.Path)
}
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e := os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(fpath)
}
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
}
+23 -32
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package fs_test
package main
import (
"bytes"
@@ -22,28 +22,19 @@ import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test list files in a folder.
func (s *MySuite) TestList(c *C) {
func (s *TestSuite) TestList(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
// Create multiple files.
objectPath := filepath.Join(root, "object1")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -55,7 +46,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(n, Equals, int64(len(data)))
objectPath = filepath.Join(root, "object2")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
@@ -63,11 +54,11 @@ func (s *MySuite) TestList(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
// Verify previously create files and list them.
var contents []*client.Content
var contents []*clientContent
for content := range fsClient.List(false, false) {
if content.Err != nil {
err = content.Err
@@ -81,7 +72,7 @@ func (s *MySuite) TestList(c *C) {
// Create another file.
objectPath = filepath.Join(root, "test1/newObject1")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
@@ -89,7 +80,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
@@ -105,7 +96,7 @@ func (s *MySuite) TestList(c *C) {
c.Assert(len(contents), Equals, 1)
c.Assert(contents[0].Type.IsDir(), Equals, true)
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
@@ -139,27 +130,27 @@ func (s *MySuite) TestList(c *C) {
}
// Test put bucket aka 'mkdir()' operation.
func (s *MySuite) TestPutBucket(c *C) {
func (s *TestSuite) TestPutBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
}
// Test stat bucket aka 'stat()' operation.
func (s *MySuite) TestStatBucket(c *C) {
func (s *TestSuite) TestStatBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
@@ -168,13 +159,13 @@ func (s *MySuite) TestStatBucket(c *C) {
}
// Test bucket acl fails for directories.
func (s *MySuite) TestBucketACLFails(c *C) {
func (s *TestSuite) TestBucketACLFails(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
c.Assert(err, IsNil)
@@ -187,13 +178,13 @@ func (s *MySuite) TestBucketACLFails(c *C) {
}
// Test creating a file.
func (s *MySuite) TestPut(c *C) {
func (s *TestSuite) TestPut(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -205,13 +196,13 @@ func (s *MySuite) TestPut(c *C) {
}
// Test read a file.
func (s *MySuite) TestGet(c *C) {
func (s *TestSuite) TestGet(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -231,13 +222,13 @@ func (s *MySuite) TestGet(c *C) {
}
// Test get range in a file.
func (s *MySuite) TestGetRange(c *C) {
func (s *TestSuite) TestGetRange(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello world"
@@ -260,13 +251,13 @@ func (s *MySuite) TestGetRange(c *C) {
}
// Test stat file.
func (s *MySuite) TestStatObject(c *C) {
func (s *TestSuite) TestStatObject(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package main
import (
"net/http"
@@ -25,16 +25,16 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV2 - tracing structure
type TraceV2 struct{}
// traceV2 - tracing structure for signature version '2'.
type traceV2 struct{}
// NewTraceV2 - initialize Trace structure
func NewTraceV2() httptracer.HTTPTracer {
return TraceV2{}
// newTraceV2 - initialize Trace structure
func newTraceV2() httptracer.HTTPTracer {
return traceV2{}
}
// Request - Trace HTTP Request
func (t TraceV2) Request(req *http.Request) (err error) {
func (t traceV2) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
if strings.TrimSpace(origAuth) != "" {
@@ -57,7 +57,7 @@ func (t TraceV2) Request(req *http.Request) (err error) {
}
// Response - Trace HTTP Response
func (t TraceV2) Response(res *http.Response) (err error) {
func (t traceV2) Response(res *http.Response) (err error) {
var resTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package main
import (
"net/http"
@@ -26,16 +26,16 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV4 - tracing structure
type TraceV4 struct{}
// traceV4 - tracing structure for signature version '4'.
type traceV4 struct{}
// NewTraceV4 - initialize Trace structure
func NewTraceV4() httptracer.HTTPTracer {
return TraceV4{}
// newTraceV4 - initialize Trace structure
func newTraceV4() httptracer.HTTPTracer {
return traceV4{}
}
// Request - Trace HTTP Request
func (t TraceV4) Request(req *http.Request) (err error) {
func (t traceV4) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
if strings.TrimSpace(origAuth) != "" {
@@ -66,7 +66,7 @@ func (t TraceV4) Request(req *http.Request) (err error) {
}
// Response - Trace HTTP Response
func (t TraceV4) Response(res *http.Response) (err error) {
func (t traceV4) Response(res *http.Response) (err error) {
var resTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
+61 -62
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package main
import (
"errors"
@@ -29,7 +29,6 @@ import (
"sync"
"time"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/minio-go"
"github.com/minio/minio/pkg/probe"
@@ -38,27 +37,27 @@ import (
// S3 client
type s3Client struct {
mutex *sync.Mutex
targetURL *client.URL
api minio.CloudStorageClient
targetURL *clientURL
api *minio.Client
virtualStyle bool
}
// newFactory encloses New function with client cache.
func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
clientCache := make(map[uint32]minio.CloudStorageClient)
func newFactory() func(config *Config) (Client, *probe.Error) {
clientCache := make(map[uint32]*minio.Client)
mutex := &sync.Mutex{}
// Return New function.
return func(config *client.Config) (client.Client, *probe.Error) {
return func(config *Config) (Client, *probe.Error) {
// Creates a parsed URL.
targetURL := client.NewURL(config.HostURL)
targetURL := newURL(config.HostURL)
// By default enable HTTPs.
inSecure := false
if targetURL.Scheme == "http" {
inSecure = true
}
// Instantiate s3 client.
// Instantiate s3
s3Clnt := &s3Client{}
// Allocate a new mutex.
s3Clnt.mutex = new(sync.Mutex)
@@ -88,10 +87,10 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api minio.CloudStorageClient
var api *minio.Client
found := false
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new minio client.
// Not found. Instantiate a new minio
var e error
if config.Signature == "S3v2" {
// if Signature version '2' use NewV2 directly.
@@ -112,10 +111,10 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
if config.Debug {
transport := http.DefaultTransport
if config.Signature == "S3v4" {
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
transport = httptracer.GetNewTraceTransport(newTraceV4(), http.DefaultTransport)
}
if config.Signature == "S3v2" {
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
transport = httptracer.GetNewTraceTransport(newTraceV2(), http.DefaultTransport)
}
// Set custom transport.
api.SetCustomTransport(transport)
@@ -128,12 +127,12 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
}
}
// New returns an initialized s3Client structure. If debug is enabled,
// s3New returns an initialized s3Client structure. If debug is enabled,
// it also enables an internal trace transport.
var New = newFactory()
var s3New = newFactory()
// GetURL get url.
func (c *s3Client) GetURL() client.URL {
func (c *s3Client) GetURL() clientURL {
return *c.targetURL
}
@@ -144,7 +143,7 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) {
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "AccessDenied" {
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()})
return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()})
}
return nil, probe.NewError(e)
}
@@ -165,28 +164,28 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
return n, probe.NewError(client.UnexpectedEOF{
return n, probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if errResponse.Code == "AccessDenied" {
return n, probe.NewError(client.PathInsufficientPermission{
return n, probe.NewError(PathInsufficientPermission{
Path: c.targetURL.String(),
})
}
if errResponse.Code == "MethodNotAllowed" {
return n, probe.NewError(client.ObjectAlreadyExists{
return n, probe.NewError(ObjectAlreadyExists{
Object: object,
})
}
if errResponse.Code == "NoSuchBucket" {
return n, probe.NewError(client.BucketDoesNotExist{
return n, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidArgument" {
return n, probe.NewError(client.ObjectMissing{})
return n, probe.NewError(ObjectMissing{})
}
return n, probe.NewError(e)
}
@@ -233,7 +232,7 @@ func isValidBucketName(bucketName string) *probe.Error {
func (c *s3Client) MakeBucket(region string) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(client.BucketNameTopLevel{})
return probe.NewError(BucketNameTopLevel{})
}
if err := isValidBucketName(bucket); err != nil {
return err.Trace(bucket)
@@ -249,10 +248,10 @@ func (c *s3Client) MakeBucket(region string) *probe.Error {
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
bucket, object := c.url2BucketAndObject()
if object != "" {
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
return "", probe.NewError(InvalidBucketName{Bucket: filepath.Join(bucket, object)})
}
if bucket == "" {
return "", probe.NewError(client.BucketNameEmpty{})
return "", probe.NewError(BucketNameEmpty{})
}
bucketACL, e := c.api.GetBucketACL(bucket)
if e != nil {
@@ -265,10 +264,10 @@ func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
return probe.NewError(InvalidBucketName{Bucket: filepath.Join(bucket, object)})
}
if bucket == "" {
return probe.NewError(client.BucketNameEmpty{})
return probe.NewError(BucketNameEmpty{})
}
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
if e != nil {
@@ -278,9 +277,9 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
}
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata.
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
func (c *s3Client) Stat() (*clientContent, *probe.Error) {
c.mutex.Lock()
objectMetadata := new(client.Content)
objectMetadata := &clientContent{}
bucket, object := c.url2BucketAndObject()
switch {
// valid case for 'ls -r s3/'
@@ -291,7 +290,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
return nil, probe.NewError(e)
}
c.mutex.Unlock()
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
return &clientContent{URL: *c.targetURL, Type: os.ModeDir}, nil
}
if object != "" {
metadata, e := c.api.StatObject(bucket, object)
@@ -309,12 +308,12 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
if objectStat.Err != nil {
return nil, probe.NewError(objectStat.Err)
}
content := client.Content{}
content := clientContent{}
content.URL = *c.targetURL
content.Type = os.ModeDir
return &content, nil
}
return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path})
return nil, probe.NewError(PathNotFound{Path: c.targetURL.Path})
}
return nil, probe.NewError(e)
}
@@ -330,7 +329,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
c.mutex.Unlock()
return nil, probe.NewError(e)
}
bucketMetadata := new(client.Content)
bucketMetadata := &clientContent{}
bucketMetadata.URL = *c.targetURL
bucketMetadata.Type = os.ModeDir
c.mutex.Unlock()
@@ -390,11 +389,11 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
/// Bucket API operations.
// List - list at delimited path, if not recursive.
func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
func (c *s3Client) List(recursive, incomplete bool) <-chan *clientContent {
c.mutex.Lock()
defer c.mutex.Unlock()
contentCh := make(chan *client.Content)
contentCh := make(chan *clientContent)
if incomplete {
if recursive {
go c.listIncompleteRecursiveInRoutine(contentCh)
@@ -411,7 +410,7 @@ func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
return contentCh
}
func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listIncompleteInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -419,7 +418,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -428,12 +427,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket with - incoming object key.
url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key)
@@ -459,12 +458,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
isRecursive := false
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket with - incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
@@ -488,7 +487,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
}
}
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -496,7 +495,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -505,14 +504,14 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
for _, bucket := range buckets {
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
url := *c.targetURL
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = object.Size
content.Time = object.Initiated
@@ -524,7 +523,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
isRecursive := true
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
@@ -535,7 +534,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
if c.virtualStyle {
url.Path = filepath.Join(string(url.Separator), object.Key)
}
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = object.Size
content.Time = object.Initiated
@@ -545,7 +544,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
}
}
func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -553,7 +552,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -561,7 +560,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
for _, bucket := range buckets {
url := *c.targetURL
url.Path = filepath.Join(url.Path, bucket.Name)
content := new(client.Content)
content := &clientContent{}
content.URL = url
content.Size = 0
content.Time = bucket.CreationDate
@@ -571,11 +570,11 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
e := c.api.BucketExists(b)
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
}
content := new(client.Content)
content := &clientContent{}
content.URL = *c.targetURL
content.Type = os.ModeDir
contentCh <- content
@@ -583,7 +582,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
metadata, e := c.api.StatObject(b, o)
switch e.(type) {
case nil:
content := new(client.Content)
content := &clientContent{}
content.URL = *c.targetURL
content.Time = metadata.LastModified
content.Size = metadata.Size
@@ -593,12 +592,12 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
isRecursive := false
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
return
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
@@ -623,7 +622,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
}
}
func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
func (c *s3Client) listRecursiveInRoutine(contentCh chan *clientContent) {
defer close(contentCh)
// get bucket and object from URL.
b, o := c.url2BucketAndObject()
@@ -631,7 +630,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
case b == "" && o == "":
buckets, err := c.api.ListBuckets()
if err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(err),
}
return
@@ -639,7 +638,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
for _, bucket := range buckets {
bucketURL := *c.targetURL
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
contentCh <- &client.Content{
contentCh <- &clientContent{
URL: bucketURL,
Type: os.ModeDir,
Time: bucket.CreationDate,
@@ -647,12 +646,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
isRecursive := true
for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
content := &clientContent{}
objectURL := *c.targetURL
objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key)
content.URL = objectURL
@@ -666,12 +665,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
isRecursive := true
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
if object.Err != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(object.Err),
}
continue
}
content := new(client.Content)
content := &clientContent{}
url := *c.targetURL
// Join bucket and incoming object key.
url.Path = filepath.Join(string(url.Separator), b, object.Key)
+10 -19
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package main
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
import (
@@ -23,11 +23,8 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/minio/mc/pkg/client"
. "gopkg.in/check.v1"
)
@@ -168,26 +165,20 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test bucket operations.
func (s *MySuite) TestBucketOperations(c *C) {
func (s *TestSuite) TestBucketOperations(c *C) {
bucket := bucketHandler(bucketHandler{
resource: "/bucket/",
})
server := httptest.NewServer(bucket)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + bucket.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1")
@@ -197,7 +188,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -206,7 +197,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
conf.HostURL = server.URL + "/bucket"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -215,7 +206,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
conf.HostURL = server.URL + "/bucket/"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
@@ -225,7 +216,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
}
// Test all object operations.
func (s *MySuite) TestObjectOperations(c *C) {
func (s *TestSuite) TestObjectOperations(c *C) {
object := objectHandler(objectHandler{
resource: "/bucket/object",
data: []byte("Hello, World"),
@@ -233,12 +224,12 @@ func (s *MySuite) TestObjectOperations(c *C) {
server := httptest.NewServer(object)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + object.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
var reader io.Reader
+6 -6
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package client
package main
import (
"io"
@@ -27,8 +27,8 @@ import (
// Client - client interface
type Client interface {
// Common operations
Stat() (content *Content, err *probe.Error)
List(recursive, incomplete bool) <-chan *Content
Stat() (content *clientContent, err *probe.Error)
List(recursive, incomplete bool) <-chan *clientContent
// Bucket operations
MakeBucket(region string) *probe.Error
@@ -47,12 +47,12 @@ type Client interface {
Remove(incomplete bool) *probe.Error
// GetURL returns back internal url
GetURL() URL
GetURL() clientURL
}
// Content container for content metadata
type Content struct {
URL URL
type clientContent struct {
URL clientURL
Time time.Time
Size int64
Type os.FileMode
+6 -9
View File
@@ -23,15 +23,12 @@ import (
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
"github.com/minio/mc/pkg/client/s3"
"github.com/minio/minio/pkg/probe"
)
// Check if the target URL represents folder. It may or may not exist yet.
func isTargetURLDir(targetURL string) bool {
targetURLParse := client.NewURL(targetURL)
targetURLParse := newURL(targetURL)
_, targetContent, err := url2Stat(targetURL)
if err != nil {
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
@@ -101,12 +98,12 @@ func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe
// newClientFromAlias gives a new client interface for matching
// alias entry in the mc config file. If no matching host config entry
// is found, fs client is returned.
func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) {
func newClientFromAlias(alias string, urlStr string) (Client, *probe.Error) {
hostCfg := mustGetHostConfig(alias)
if hostCfg == nil {
// No matching host config. So we treat it like a
// filesystem.
fsClient, err := fs.New(urlStr)
fsClient, err := fsNew(urlStr)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
@@ -115,7 +112,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
// We have a valid alias and hostConfig. We populate the
// credentials from the match found in the config file.
s3Config := new(client.Config)
s3Config := new(Config)
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
@@ -125,7 +122,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
s3Config.HostURL = urlStr
s3Config.Debug = globalDebug
s3Client, err := s3.New(s3Config)
s3Client, err := s3New(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
@@ -136,7 +133,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
var urlRgx = regexp.MustCompile("^https?://")
// newClient gives a new client interface
func newClient(aliasedURL string) (client.Client, *probe.Error) {
func newClient(aliasedURL string) (Client, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
+1 -2
View File
@@ -20,7 +20,6 @@ import (
"fmt"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/quick"
)
@@ -132,7 +131,7 @@ func fixConfigV6ForHosts() {
newCfgV6.Aliases[k] = v
}
url := new(client.URL)
url := &clientURL{}
// Copy hosts.
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
// Already fixed - Copy and move on.
+17 -3
View File
@@ -1,10 +1,24 @@
/*
* Minio Client (C) 2015, 2016 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 main
import (
"regexp"
"strings"
"github.com/minio/mc/pkg/client"
)
// isValidSecretKey - validate secret key.
@@ -30,7 +44,7 @@ func isValidHostURL(hostURL string) bool {
if strings.TrimSpace(hostURL) == "" {
return false
}
url := client.NewURL(hostURL)
url := newURL(hostURL)
if url.Scheme != "https" && url.Scheme != "http" {
return false
}
+6 -7
View File
@@ -29,7 +29,6 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
@@ -313,17 +312,17 @@ func doCopySession(session *sessionV6) {
switch cpURLs.Error.ToGoError().(type) {
// Handle this specifically for filesystem related
// errors.
case client.BrokenSymlink:
case BrokenSymlink:
continue
case client.TooManyLevelsSymlink:
case TooManyLevelsSymlink:
continue
case client.PathNotFound:
case PathNotFound:
continue
case client.PathInsufficientPermission:
case PathInsufficientPermission:
continue
case client.ObjectAlreadyExists:
case ObjectAlreadyExists:
continue
case client.BucketDoesNotExist:
case BucketDoesNotExist:
continue
}
// For critical errors we should exit. Session
+1 -2
View File
@@ -20,7 +20,6 @@ import (
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
)
func checkCopySyntax(ctx *cli.Context) {
@@ -40,7 +39,7 @@ func checkCopySyntax(ctx *cli.Context) {
/****** Generic Invalid Rules *******/
// Check if bucket name is passed for URL type arguments.
url := client.NewURL(tgtURL)
url := newURL(tgtURL)
if url.Host != "" {
// This check is for type URL.
if !isURLVirtualHostStyle(url.Host) {
+19 -20
View File
@@ -20,15 +20,14 @@ import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
type copyURLs struct {
SourceAlias string
SourceContent *client.Content
SourceContent *clientContent
TargetAlias string
TargetContent *client.Content
TargetContent *clientContent
Error *probe.Error `json:"-"`
}
@@ -57,7 +56,7 @@ const (
copyURLsTypeD
)
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
@@ -90,11 +89,11 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
@@ -116,21 +115,21 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
return copyURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
TargetContent: &clientContent{URL: *newURL(targetURL)},
}
}
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
@@ -152,19 +151,19 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := client.NewURL(targetURL)
targetURLParse := newURL(targetURL)
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
}
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
// Extract alias before fiddling with the URL.
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
copyURLsCh := make(chan copyURLs)
@@ -197,7 +196,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
@@ -210,7 +209,7 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
}
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
@@ -224,7 +223,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
return copyURLsCh
}
// prepareCopyURLs - prepares target and source URLs for copying.
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
+3 -4
View File
@@ -23,7 +23,6 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
)
@@ -144,11 +143,11 @@ func checkDiffSyntax(ctx *cli.Context) {
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string) {
// Source and targets are always directories
sourceSeparator := string(client.NewURL(firstURL).Separator)
sourceSeparator := string(newURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(client.NewURL(secondURL).Separator)
targetSeparator := string(newURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
@@ -173,7 +172,7 @@ func doDiffMain(firstURL, secondURL string) {
if sourceContent.Err != nil {
switch sourceContent.Err.ToGoError().(type) {
// Handle this specifically for filesystem related errors.
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
default:
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
+1 -2
View File
@@ -19,7 +19,6 @@ package main
import (
"os"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
@@ -49,7 +48,7 @@ func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *
current := targetURL
reachedEOF := false
ok := false
var content *client.Content
var content *clientContent
difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) {
if reachedEOF {
@@ -16,7 +16,7 @@
* limitations under the License.
*/
package fs
package main
func normalizePath(path string) string {
return path
@@ -16,7 +16,7 @@
* limitations under the License.
*/
package fs
package main
import (
"path/filepath"
+1 -2
View File
@@ -21,7 +21,6 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
)
@@ -127,7 +126,7 @@ func mainList(ctx *cli.Context) {
}
for _, targetURL := range args {
var clnt client.Client
var clnt Client
clnt, err := newClient(targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
+6 -7
View File
@@ -25,7 +25,6 @@ import (
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
)
@@ -67,7 +66,7 @@ func (c contentMessage) JSON() string {
}
// parseContent parse client Content container into printer struct.
func parseContent(c *client.Content) contentMessage {
func parseContent(c *clientContent) contentMessage {
content := contentMessage{}
content.Time = c.Time.Local()
@@ -105,7 +104,7 @@ func parseContent(c *client.Content) contentMessage {
}
// doList - list all entities inside a folder.
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
func doList(clnt Client, isRecursive, isIncomplete bool) *probe.Error {
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
@@ -115,16 +114,16 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case client.BrokenSymlink:
case BrokenSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case client.PathNotFound:
case PathNotFound:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
case client.PathInsufficientPermission:
case PathInsufficientPermission:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
+6 -7
View File
@@ -28,7 +28,6 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
"github.com/minio/pb"
@@ -297,17 +296,17 @@ func doMirrorSession(session *sessionV6) {
switch sURLs.Error.ToGoError().(type) {
// Handle this specifically for filesystem related
// errors.
case client.BrokenSymlink:
case BrokenSymlink:
continue
case client.TooManyLevelsSymlink:
case TooManyLevelsSymlink:
continue
case client.PathNotFound:
case PathNotFound:
continue
case client.PathInsufficientPermission:
case PathInsufficientPermission:
continue
case client.ObjectAlreadyExists:
case ObjectAlreadyExists:
continue
case client.BucketDoesNotExist:
case BucketDoesNotExist:
continue
}
// For critical errors we should exit. Session
+8 -9
View File
@@ -21,15 +21,14 @@ import (
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
type mirrorURLs struct {
SourceAlias string
SourceContent *client.Content
SourceContent *clientContent
TargetAlias string
TargetContent *client.Content
TargetContent *clientContent
Error *probe.Error `json:"-"`
}
@@ -75,7 +74,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
}
url := client.NewURL(tgtURL)
url := newURL(tgtURL)
if url.Host != "" {
if !isURLVirtualHostStyle(url.Host) {
if url.Path == string(url.Separator) {
@@ -85,19 +84,19 @@ func checkMirrorSyntax(ctx *cli.Context) {
}
}
_, _, err = url2Stat(tgtURL)
// we die on any error other than client.PathNotFound - destination directory need not exist.
if _, ok := err.ToGoError().(client.PathNotFound); !ok {
// we die on any error other than PathNotFound - destination directory need not exist.
if _, ok := err.ToGoError().(PathNotFound); !ok {
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL))
}
}
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
// source and targets are always directories
sourceSeparator := string(client.NewURL(sourceURL).Separator)
sourceSeparator := string(newURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
sourceURL = sourceURL + sourceSeparator
}
targetSeparator := string(client.NewURL(targetURL).Separator)
targetSeparator := string(newURL(targetURL).Separator)
if !strings.HasSuffix(targetURL, targetSeparator) {
targetURL = targetURL + targetSeparator
}
@@ -151,7 +150,7 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
}
// either available only in source or size differs and force is set
targetPath := urlJoinPath(targetURL, suffix)
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
targetContent := &clientContent{URL: *newURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
-69
View File
@@ -1,69 +0,0 @@
/*
* Minio Client (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 client
import (
"testing"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestURLParse(c *C) {
u := NewURL("http://s3.example.com")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/")
c.Assert(u.SchemeSeparator, Equals, "://")
u = NewURL("http://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/path/new")
c.Assert(u.SchemeSeparator, Equals, "://")
u = NewURL(":::://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, ":::://s3.example.com/path/new")
c.Assert(u.SchemeSeparator, Equals, "")
u = NewURL("localhost:9000")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "localhost:9000")
c.Assert(u.SchemeSeparator, Equals, "")
}
func (s *MySuite) TestPathParse(c *C) {
u := NewURL("path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "path/test")
c.Assert(u.SchemeSeparator, Equals, "")
u = NewURL("/path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "/path/test")
c.Assert(u.SchemeSeparator, Equals, "")
}
-1
View File
@@ -1 +0,0 @@
*#
-86
View File
@@ -1,86 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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 fs
import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
// toClientError error constructs a typed client error for known filesystem errors.
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsPermission(e) {
return probe.NewError(client.PathInsufficientPermission{Path: fpath})
}
if os.IsNotExist(e) {
return probe.NewError(client.PathNotFound{Path: fpath})
}
return probe.NewError(e)
}
// handle windows symlinks - eg: junction files.
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
// 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.
file, e := os.Lstat(fpath)
if e != nil {
err := f.toClientError(e, fpath)
return nil, err.Trace(fpath)
}
return file, nil
}
// fsStat - wrapper function to get file stat.
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
fpath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(f.PathURL.Path)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e := os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
if runtime.GOOS == "windows" {
return f.handleWindowsSymlinks(fpath)
}
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
}
return st, nil
}
-168
View File
@@ -1,168 +0,0 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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 fs
import (
"errors"
"os"
"path/filepath"
"sort"
)
// byDirName implements sort.Interface.
type byDirName []os.FileInfo
func (f byDirName) Len() int { return len(f) }
func (f byDirName) Less(i, j int) bool {
// For directory add an ending separator fortrue lexical order.
if f[i].Mode().IsDir() {
return f[i].Name()+string(filepath.Separator) < f[j].Name()
}
// For directory add an ending separator for true lexical order.
if f[j].Mode().IsDir() {
return f[i].Name() < f[j].Name()+string(filepath.Separator)
}
return f[i].Name() < f[j].Name()
}
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// readDir reads the directory named by dirname and returns
// a list of sorted directory entries.
func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
}
// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDirNames(dirname string) ([]string, error) {
names, e := readDirUnsortedNames(dirname)
if e != nil {
return nil, e
}
sort.Strings(names)
return names, nil
}
// getRealName - gets the proper filename for sorting purposes
// Readdir() filters out directory names without separators, add
// them back for proper sorting results.
func getRealName(info os.FileInfo) string {
if info.IsDir() {
// Make sure directory has its end separator.
return info.Name() + string(filepath.Separator)
}
return info.Name()
}
// readDirUnsortedNames reads the directory named by dirname and
// return a unsorted list of directory entries.
func readDirUnsortedNames(dirname string) ([]string, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
nameInfos, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
var names []string
for _, nameInfo := range nameInfos {
names = append(names, getRealName(nameInfo))
}
return names, nil
}
// walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func walk(root string, walkFn walkFunc) error {
info, e := os.Lstat(root)
if e != nil {
return walkFn(root, nil, e)
}
return walkInternal(root, info, walkFn)
}
// WalkFunc is the type of the function called for each file or directory
// visited by Walk. The path argument contains the argument to Walk as a
// prefix; that is, if Walk is called with "dir", which is a directory
// containing the file "a", the walk function will be called with argument
// "dir/a". The info argument is the os.FileInfo for the named path.
type walkFunc func(path string, info os.FileInfo, e error) error
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
// the directory named in the call is to be skipped. It is not returned
// as an error by any function.
var errSkipDir = errors.New("skip this directory")
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
// the file named in the call is to be skipped. It is not returned
// as an error by any function.
var errSkipFile = errors.New("skip this file")
// walkInternal recursively descends path, calling w.
func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error {
e := walkFn(path, info, nil)
if e != nil {
if info.Mode().IsDir() && e == errSkipDir {
return nil
}
if info.Mode().IsRegular() && e == errSkipFile {
return nil
}
return e
}
if !info.IsDir() {
return nil
}
names, e := readDirNames(path)
if e != nil {
return walkFn(path, info, e)
}
for _, name := range names {
filename := filepath.Join(path, name)
fileInfo, e := os.Lstat(filename)
if e != nil {
if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile {
return e
}
} else {
e = walkInternal(filename, fileInfo, walkFn)
if e != nil {
if e == errSkipDir || e == errSkipFile {
return nil
}
return e
}
}
}
return nil
}
-162
View File
@@ -1,162 +0,0 @@
/*
* Minio Client (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 client
import (
"bytes"
"path/filepath"
"regexp"
"runtime"
"strings"
)
// URL client url structure
type URL struct {
Type URLType
Scheme string
Host string
Path string
SchemeSeparator string
Separator rune
}
// URLType - enum of different url types
type URLType int
// enum types
const (
Object = iota // Minio and S3 compatible cloud storage
Filesystem // POSIX compatible file systems
)
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
// If so, return scheme, path; else return "", rawurl.
func getScheme(rawurl string) (scheme, path string) {
urlSplits := strings.Split(rawurl, "://")
if len(urlSplits) == 2 {
scheme, uri := urlSplits[0], "//"+urlSplits[1]
// ignore numbers in scheme
validScheme := regexp.MustCompile("^[a-zA-Z]+$")
if uri != "" {
if validScheme.MatchString(scheme) {
return scheme, uri
}
}
}
return "", rawurl
}
// Assuming s is of the form [s delimiter s].
// If so, return s, [delimiter]s or return s, s if cutdelimiter == true
// If no delimiter found return s, "".
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
i := strings.Index(s, delimiter)
if i < 0 {
// if delimiter not found return as is.
return s, ""
}
// if delimiter should be removed, remove it.
if cutdelimiter {
return s[0:i], s[i+len(delimiter):]
}
// return split strings with delimiter
return s[0:i], s[i:]
}
// getHost - extract host from authority string, we do not support ftp style username@ yet.
func getHost(authority string) (host string) {
i := strings.LastIndex(authority, "@")
if i >= 0 {
// TODO support, username@password style userinfo, useful for ftp support.
return
}
return authority
}
// NewURL returns an abstracted URL for filesystems and object storage.
func NewURL(urlStr string) *URL {
scheme, rest := getScheme(urlStr)
rest, _ = splitSpecial(rest, "?", true)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
authority, rest = splitSpecial(rest[2:], "/", false)
if rest == "" {
rest = "/"
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &URL{
Scheme: scheme,
Type: Object,
Host: host,
Path: rest,
SchemeSeparator: "://",
Separator: '/',
}
}
}
return &URL{
Type: Filesystem,
Path: rest,
Separator: filepath.Separator,
}
}
// JoinURLs join two input urls and returns a url
func JoinURLs(url1, url2 *URL) *URL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
return url1
}
// String convert URL into its canonical form.
func (u URL) String() string {
var buf bytes.Buffer
// if fileystem no translation needed, return as is.
if u.Type == Filesystem {
return u.Path
}
// if Object convert from any non standard paths to a supported URL path style.
if u.Type == Object {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
if h := u.Host; h != "" {
buf.WriteString(h)
}
switch runtime.GOOS {
case "windows":
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
buf.WriteByte('/')
}
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
default:
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
buf.WriteByte('/')
}
buf.WriteString(u.Path)
}
}
return buf.String()
}
+2 -3
View File
@@ -22,7 +22,6 @@ import (
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
@@ -101,7 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
}
for _, targetURL := range ctx.Args() {
url := client.NewURL(targetURL)
url := newURL(targetURL)
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
fatalIf(errInvalidArgument().Trace(targetURL),
"Use --recursive option to generate curl command for prefixes.")
@@ -111,7 +110,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
// makeCurlCmd constructs curl command-line.
func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string {
URL := client.NewURL(key)
URL := newURL(key)
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator)
if !isBucketVirtualStyle(URL.Host) {
postURL = postURL + uploadInfo["bucket"]
+145 -6
View File
@@ -17,14 +17,153 @@
package main
import (
"bytes"
"mime"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
)
// url client url structure
type clientURL struct {
Type clientURLType
Scheme string
Host string
Path string
SchemeSeparator string
Separator rune
}
// clientURLType - enum of different url types
type clientURLType int
// enum types
const (
objectStorage = iota // Minio and S3 compatible cloud storage
fileSystem // POSIX compatible file systems
)
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
// If so, return scheme, path; else return "", rawurl.
func getScheme(rawurl string) (scheme, path string) {
urlSplits := strings.Split(rawurl, "://")
if len(urlSplits) == 2 {
scheme, uri := urlSplits[0], "//"+urlSplits[1]
// ignore numbers in scheme
validScheme := regexp.MustCompile("^[a-zA-Z]+$")
if uri != "" {
if validScheme.MatchString(scheme) {
return scheme, uri
}
}
}
return "", rawurl
}
// Assuming s is of the form [s delimiter s].
// If so, return s, [delimiter]s or return s, s if cutdelimiter == true
// If no delimiter found return s, "".
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
i := strings.Index(s, delimiter)
if i < 0 {
// if delimiter not found return as is.
return s, ""
}
// if delimiter should be removed, remove it.
if cutdelimiter {
return s[0:i], s[i+len(delimiter):]
}
// return split strings with delimiter
return s[0:i], s[i:]
}
// getHost - extract host from authority string, we do not support ftp style username@ yet.
func getHost(authority string) (host string) {
i := strings.LastIndex(authority, "@")
if i >= 0 {
// TODO support, username@password style userinfo, useful for ftp support.
return
}
return authority
}
// newURL returns an abstracted URL for filesystems and object storage.
func newURL(urlStr string) *clientURL {
scheme, rest := getScheme(urlStr)
rest, _ = splitSpecial(rest, "?", true)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
authority, rest = splitSpecial(rest[2:], "/", false)
if rest == "" {
rest = "/"
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &clientURL{
Scheme: scheme,
Type: objectStorage,
Host: host,
Path: rest,
SchemeSeparator: "://",
Separator: '/',
}
}
}
return &clientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
}
}
// joinURLs join two input urls and returns a url
func joinURLs(url1, url2 *clientURL) *clientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
if strings.HasSuffix(url1Path, "/") {
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
} else {
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
}
return url1
}
// String convert URL into its canonical form.
func (u clientURL) String() string {
var buf bytes.Buffer
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
return u.Path
}
// if objectStorage convert from any non standard paths to a supported URL path style.
if u.Type == objectStorage {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
if h := u.Host; h != "" {
buf.WriteString(h)
}
switch runtime.GOOS {
case "windows":
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
buf.WriteByte('/')
}
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
default:
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
buf.WriteByte('/')
}
buf.WriteString(u.Path)
}
}
return buf.String()
}
func isURLVirtualHostStyle(hostURL string) bool {
matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL)
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL)
@@ -33,13 +172,13 @@ func isURLVirtualHostStyle(hostURL string) bool {
// urlJoinPath Join a path to existing URL.
func urlJoinPath(url1, url2 string) string {
u1 := client.NewURL(url1)
u2 := client.NewURL(url2)
return client.JoinURLs(u1, u2).String()
u1 := newURL(url1)
u2 := newURL(url2)
return joinURLs(u1, u2).String()
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
@@ -92,7 +231,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
// guessURLContentType - guess content-type of the URL.
// on failure just return 'application/octet-stream'.
func guessURLContentType(urlStr string) string {
url := client.NewURL(urlStr)
url := newURL(urlStr)
contentType := mime.TypeByExtension(filepath.Ext(url.Path))
if contentType == "" {
contentType = "application/octet-stream"
+3 -1
View File
@@ -14,7 +14,9 @@
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
- Run `go fmt`
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
- Make sure `go test -short -race ./...` and `go build` completes.
- Make sure `go test -race ./...` and `go build` completes.
NOTE: go test runs functional tests and requires you to have a AWS S3 account. Set them as environment variables
``ACCESS_KEY`` and ``SECRET_KEY``. To run shorter version of the tests please use ``go test -short -race ./...``
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
- `minio-go` project is strictly conformant with Golang style
+12 -48
View File
@@ -78,7 +78,7 @@ const (
// NewV2 - instantiate minio client with Amazon S3 signature version
// '2' compatibility.
func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -90,7 +90,7 @@ func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool)
// NewV4 - instantiate minio client with Amazon S3 signature version
// '4' compatibility.
func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -102,7 +102,7 @@ func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool)
// New - instantiate minio client Client, adds automatic verification
// of signature.
func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -112,7 +112,7 @@ func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (C
if isGoogleEndpoint(clnt.endpointURL) {
clnt.signature = SignatureV2
}
// If Amazon S3 set to signature v2.
// If Amazon S3 set to signature v2.n
if isAmazonEndpoint(clnt.endpointURL) {
clnt.signature = SignatureV4
}
@@ -138,7 +138,14 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, insecure bool) (*
clnt.endpointURL = endpointURL
// Instantiate http client and bucket location cache.
clnt.httpClient = &http.Client{}
clnt.httpClient = &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
clnt.bucketLocCache = newBucketLocationCache()
// Return.
@@ -493,46 +500,3 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que
return u, nil
}
// CloudStorageClient - Cloud Storage Client interface.
type CloudStorageClient interface {
// Bucket Read/Write/Stat operations.
MakeBucket(bucketName string, cannedACL BucketACL, location string) error
BucketExists(bucketName string) error
RemoveBucket(bucketName string) error
SetBucketACL(bucketName string, cannedACL BucketACL) error
GetBucketACL(bucketName string) (BucketACL, error)
ListBuckets() ([]BucketInfo, error)
ListObjects(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectInfo
ListIncompleteUploads(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo
// Object Read/Write/Stat operations.
GetObject(bucketName, objectName string) (reader *Object, err error)
PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error)
StatObject(bucketName, objectName string) (ObjectInfo, error)
RemoveObject(bucketName, objectName string) error
RemoveIncompleteUpload(bucketName, objectName string) error
// File to Object API.
FPutObject(bucketName, objectName, filePath, contentType string) (n int64, err error)
FGetObject(bucketName, objectName, filePath string) error
// PutObjectWithProgress for progress.
PutObjectWithProgress(bucketName, objectName string, reader io.Reader, contentType string, progress io.Reader) (n int64, err error)
// Presigned operations.
PresignedGetObject(bucketName, objectName string, expires time.Duration, reqParams url.Values) (presignedURL string, err error)
PresignedPutObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error)
PresignedPostPolicy(*PostPolicy) (formData map[string]string, err error)
// Application info.
SetAppInfo(appName, appVersion string)
// Set custom transport.
SetCustomTransport(customTransport http.RoundTripper)
// HTTP tracing methods.
TraceOn(traceOutput io.Writer)
TraceOff()
}
+7 -1
View File
@@ -1017,7 +1017,13 @@ func TestFunctionalV2(t *testing.T) {
if err != nil {
t.Fatal("Error: ", err)
}
httpClient := &http.Client{}
httpClient := &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
resp, err = httpClient.Do(req)
if err != nil {
t.Fatal("Error: ", err)
+7 -1
View File
@@ -1045,7 +1045,13 @@ func TestFunctional(t *testing.T) {
if err != nil {
t.Fatal("Error: ", err)
}
httpClient := &http.Client{}
httpClient := &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
resp, err = httpClient.Do(req)
if err != nil {
t.Fatal("Error: ", err)
+143
View File
@@ -0,0 +1,143 @@
/*
* Minio 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 ioutils
import (
"errors"
"io"
"os"
"path/filepath"
"sort"
)
// IsDirEmpty Check if a directory is empty
func IsDirEmpty(dirname string) (status bool, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if _, err = f.Readdirnames(1); err == io.EOF {
status = true
err = nil
}
}
return
}
// FTW walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func FTW(root string, walkFn FTWFunc) error {
info, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(root, info, walkFn)
}
// byName implements sort.Interface for sorting os.FileInfo list.
type byName []os.FileInfo
func (f byName) Len() int { return len(f) }
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f byName) Less(i, j int) bool {
n1 := f[i].Name()
if f[i].IsDir() {
n1 = n1 + string(os.PathSeparator)
}
n2 := f[j].Name()
if f[i].IsDir() {
n2 = n2 + string(os.PathSeparator)
}
return n1 < n2
}
// readDir reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDir(dirname string) (fi []os.FileInfo, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if fi, err = f.Readdir(-1); fi != nil {
sort.Sort(byName(fi))
}
}
return
}
// FTWFunc is the type of the function called for each file or directory
// visited by Walk. The path argument contains the argument to Walk as a
// prefix; that is, if Walk is called with "dir", which is a directory
// containing the file "a", the walk function will be called with argument
// "dir/a". The info argument is the os.FileInfo for the named path.
type FTWFunc func(path string, info os.FileInfo, err error) error
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
// the directory named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipDir = errors.New("skip this directory")
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
// the file named in the call is to be skipped. It is not returned
// as an error by any function.
var ErrSkipFile = errors.New("skip this file")
// ErrDirNotEmpty is used to throw error on directories which have atleast one regular
// file or a symlink left
var ErrDirNotEmpty = errors.New("directory not empty")
// walk recursively descends path, calling walkFn.
func walk(path string, info os.FileInfo, walkFn FTWFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.Mode().IsDir() && err == ErrSkipDir {
return nil
}
if info.Mode().IsRegular() && err == ErrSkipFile {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
fis, err := readDir(path)
if err != nil {
return walkFn(path, info, err)
}
for _, fileInfo := range fis {
filename := filepath.Join(path, fileInfo.Name())
if err != nil {
if err := walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile {
return err
}
} else {
err = walk(filename, fileInfo, walkFn)
if err != nil {
if err == ErrSkipDir || err == ErrSkipFile {
return nil
}
return err
}
}
}
return nil
}
+43
View File
@@ -0,0 +1,43 @@
/*
* Minio Cloud Storage, (C) 2016 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 ioutils_test
import (
"io/ioutil"
"os"
"testing"
"github.com/minio/minio/pkg/ioutils"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestIoutils(c *C) {
path, err := ioutil.TempDir(os.TempDir(), "minio-ioutils_test")
c.Assert(err, IsNil)
defer os.RemoveAll(path)
status, err := ioutils.IsDirEmpty(path)
c.Assert(err, IsNil)
c.Assert(status, Equals, true)
}
+7 -2
View File
@@ -39,14 +39,19 @@
},
{
"path": "github.com/minio/minio-go",
"revision": "280f16a52008d3ebba1bd64398b9b082e6738386",
"revisionTime": "2016-02-07T03:45:25-08:00"
"revision": "5576cd0f5a276b64973239ebe172aa8d2380f950",
"revisionTime": "2016-02-15T17:55:49-08:00"
},
{
"path": "github.com/minio/minio/pkg/atomic",
"revision": "f98675660bb2049dea7e39e5113f5af29b8f6815",
"revisionTime": "2016-02-11T15:54:02-08:00"
},
{
"path": "github.com/minio/minio/pkg/ioutils",
"revision": "eed0149657017f134fa8dacae9026bb816342a48",
"revisionTime": "2016-02-15T17:42:39-08:00"
},
{
"path": "github.com/minio/minio/pkg/probe",
"revision": "f98675660bb2049dea7e39e5113f5af29b8f6815",