From b9033d1cac0168086dc16525f9d466c5d6ed94b3 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sat, 7 Nov 2015 19:57:10 -0800 Subject: [PATCH] structure: Move client.Content to return a URL object This change is needed to avoid extensive string manipulation of URLs throughout the code base. A client interface sends back data as a proper URL object, this facilitates us to avoid unnecessary string manipulation by making code more cleaner. --- common-methods.go | 12 +- common_methods_test.go | 1 - cp-main.go | 18 +- cp-url.go | 19 +- diff.go | 69 ++- ls-main.go | 4 +- ls.go | 45 +- mirror-main.go | 18 +- mirror-url.go | 16 +- pkg/client/client.go | 7 +- pkg/client/fs/fs.go | 74 ++- pkg/client/fs/fs_test.go | 1 - pkg/client/{s3v4/s3v4.go => s3/s3.go} | 134 +++-- .../{s3v4/s3v4_test.go => s3/s3_test.go} | 7 +- pkg/client/{s3v2/trace.go => s3/trace_v2.go} | 16 +- pkg/client/{s3v4/trace.go => s3/trace_v4.go} | 16 +- pkg/client/s3v2/s3v2.go | 553 ------------------ pkg/client/s3v2/s3v2_test.go | 198 ------- pkg/client/url.go | 2 +- rm-main.go | 24 +- share-download-main.go | 6 +- share.go | 25 - update-main.go | 4 +- url.go | 14 - 24 files changed, 248 insertions(+), 1035 deletions(-) rename pkg/client/{s3v4/s3v4.go => s3/s3.go} (83%) rename pkg/client/{s3v4/s3v4_test.go => s3/s3_test.go} (96%) rename pkg/client/{s3v2/trace.go => s3/trace_v2.go} (83%) rename pkg/client/{s3v4/trace.go => s3/trace_v4.go} (87%) delete mode 100644 pkg/client/s3v2/s3v2.go delete mode 100644 pkg/client/s3v2/s3v2_test.go diff --git a/common-methods.go b/common-methods.go index b8b200d3..b0730691 100644 --- a/common-methods.go +++ b/common-methods.go @@ -25,8 +25,7 @@ import ( "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/client/fs" - "github.com/minio/mc/pkg/client/s3v2" - "github.com/minio/mc/pkg/client/s3v4" + "github.com/minio/mc/pkg/client/s3" "github.com/minio/minio-xl/pkg/probe" ) @@ -163,19 +162,14 @@ func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) } return auth.SecretAccessKey }() + s3Config.Signature = auth.API s3Config.AppName = "Minio" s3Config.AppVersion = mcVersion s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH} s3Config.HostURL = urlStr s3Config.Debug = globalDebugFlag - var s3Client client.Client - var err *probe.Error - if auth.API == "S3v2" { - s3Client, err = s3v2.New(s3Config) - } else { - s3Client, err = s3v4.New(s3Config) - } + s3Client, err := s3.New(s3Config) if err != nil { return nil, err.Trace() } diff --git a/common_methods_test.go b/common_methods_test.go index b712e589..7d401686 100644 --- a/common_methods_test.go +++ b/common_methods_test.go @@ -58,7 +58,6 @@ func (s *TestSuite) TestCommonMethods(c *C) { _, content, err := url2Stat(objectPathServer) c.Assert(err, IsNil) - c.Assert(content.Name, Equals, "object1") c.Assert(content.Type.IsRegular(), Equals, true) _, _, err = getSource(objectPathServer + "invalid") diff --git a/cp-main.go b/cp-main.go index ca9609bc..8e8feb2d 100644 --- a/cp-main.go +++ b/cp-main.go @@ -100,10 +100,10 @@ func doCopy(cpURLs copyURLs, progressReader interface{}, cpQueue <-chan bool, wg } if !globalQuietFlag && !globalJSONFlag { - progressReader.(*barSend).SetCaption(cpURLs.SourceContent.Name + ": ") + progressReader.(*barSend).SetCaption(cpURLs.SourceContent.URL.String() + ": ") } - reader, length, err := getSource(cpURLs.SourceContent.Name) + reader, length, err := getSource(cpURLs.SourceContent.URL.String()) if err != nil { if !globalQuietFlag && !globalJSONFlag { progressReader.(*barSend).ErrorGet(length) @@ -116,8 +116,8 @@ func doCopy(cpURLs copyURLs, progressReader interface{}, cpQueue <-chan bool, wg var newReader io.ReadCloser if globalQuietFlag || globalJSONFlag { printMsg(copyMessage{ - Source: cpURLs.SourceContent.Name, - Target: cpURLs.TargetContent.Name, + Source: cpURLs.SourceContent.URL.String(), + Target: cpURLs.TargetContent.URL.String(), Length: cpURLs.SourceContent.Size, }) newReader = progressReader.(*accounter).NewProxyReader(reader) @@ -127,7 +127,7 @@ func doCopy(cpURLs copyURLs, progressReader interface{}, cpQueue <-chan bool, wg } defer newReader.Close() - if err := putTarget(cpURLs.TargetContent.Name, length, newReader); err != nil { + if err := putTarget(cpURLs.TargetContent.URL.String(), length, newReader); err != nil { if !globalQuietFlag && !globalJSONFlag { progressReader.(*barSend).ErrorPut(length) } @@ -195,7 +195,7 @@ func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) { } fmt.Fprintln(dataFP, string(jsonData)) if !globalQuietFlag && !globalJSONFlag { - scanBar(cpURLs.SourceContent.Name) + scanBar(cpURLs.SourceContent.URL.String()) } totalBytes += cpURLs.SourceContent.Size @@ -258,14 +258,14 @@ func doCopySession(session *sessionV2) { return } if cpURLs.Error == nil { - session.Header.LastCopied = cpURLs.SourceContent.Name + session.Header.LastCopied = cpURLs.SourceContent.URL.String() session.Save() } else { // Print in new line and adjust to top so that we don't print over the ongoing progress bar if !globalQuietFlag && !globalJSONFlag { console.Eraseline() } - errorIf(cpURLs.Error.Trace(), fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.Name)) + errorIf(cpURLs.Error.Trace(), fmt.Sprintf("Failed to copy ‘%s’.", cpURLs.SourceContent.URL.String())) // all the cases which are handled where session should be saved are contained in the following // switch case, we shouldn't be saving sessions for all errors since some errors might need to be // reported to user properly. @@ -298,7 +298,7 @@ func doCopySession(session *sessionV2) { for scanner.Scan() { var cpURLs copyURLs json.Unmarshal([]byte(scanner.Text()), &cpURLs) - if isCopied(cpURLs.SourceContent.Name) { + if isCopied(cpURLs.SourceContent.URL.String()) { doCopyFake(cpURLs, progressReader) } else { // Wait for other copy routines to diff --git a/cp-url.go b/cp-url.go index 97aedcd2..8ef39f8b 100644 --- a/cp-url.go +++ b/cp-url.go @@ -235,8 +235,7 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { return copyURLs{Error: errInvalidSource(sourceURL).Trace()} } // All OK.. We can proceed. Type A - sourceContent.Name = sourceURL - return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}} + return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{URL: *client.NewURL(targetURL)}} } // SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A @@ -304,19 +303,9 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs { } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - sourceURLParse := client.NewURL(sourceURL) - targetURLParse := client.NewURL(targetURL) - - sourceURLDelimited := sourceURLParse.String()[:strings.LastIndex(sourceURLParse.String(), - string(sourceURLParse.Separator))+1] - sourceContentName := sourceContent.Content.Name - sourceContentURL := sourceURLDelimited + sourceContentName - sourceContentParse := client.NewURL(sourceContentURL) - - // Construct target path from recursive path of source without its prefix dir. - newTargetURLParse := *targetURLParse - newTargetURLParse.Path = filepath.Join(newTargetURLParse.Path, sourceContentName) - copyURLsCh <- prepareCopyURLsTypeA(sourceContentParse.String(), newTargetURLParse.String()) + newTargetURL := client.NewURL(targetURL) + newTargetURL.Path = filepath.Join(newTargetURL.Path, sourceContent.Content.URL.Path) + copyURLsCh <- prepareCopyURLsTypeA(sourceContent.Content.URL.String(), newTargetURL.String()) } }(sourceURL, targetURL, copyURLsCh) return copyURLsCh diff --git a/diff.go b/diff.go index 7dffa503..c5085bd3 100644 --- a/diff.go +++ b/diff.go @@ -137,7 +137,7 @@ func doDiffObjects(firstURL, secondURL string, ch chan DiffMessage) { } return } - if firstContent.Name == secondContent.Name { + if firstContent.URL.String() == secondContent.URL.String() { return } switch { @@ -169,19 +169,25 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan DiffMessage) { for contentCh := range firstClnt.List(false, false) { if contentCh.Err != nil { ch <- DiffMessage{ - Error: contentCh.Err.Trace(firstClnt.URL().String()), + Error: contentCh.Err.Trace(firstClnt.GetURL().String()), } return } - newFirstURL := urlJoinPath(firstClnt.URL().String(), contentCh.Content.Name) - newSecondURL := urlJoinPath(secondClnt.URL().String(), contentCh.Content.Name) - _, newFirstContent, errFirst := url2Stat(newFirstURL) - _, newSecondContent, errSecond := url2Stat(newSecondURL) + newFirstURLStr := contentCh.Content.URL.String() + + // Construct the second URL + newSecondURL := secondClnt.GetURL() + // Need to verify the same path from first URL, copy it here + newSecondURL.Path = contentCh.Content.URL.Path + newSecondURLStr := newSecondURL.String() + + _, newFirstContent, errFirst := url2Stat(newFirstURLStr) + _, newSecondContent, errSecond := url2Stat(newSecondURLStr) switch { case errFirst == nil && errSecond != nil: ch <- DiffMessage{ - FirstURL: newFirstURL, - SecondURL: newSecondURL, + FirstURL: newFirstURLStr, + SecondURL: newSecondURLStr, Diff: "only-in-first", } continue @@ -190,8 +196,8 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan DiffMessage) { case newFirstContent.Type.IsDir(): if !newSecondContent.Type.IsDir() { ch <- DiffMessage{ - FirstURL: newFirstURL, - SecondURL: newSecondURL, + FirstURL: newFirstURLStr, + SecondURL: newSecondURLStr, Diff: "type", } } @@ -199,21 +205,21 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan DiffMessage) { case newFirstContent.Type.IsRegular(): if !newSecondContent.Type.IsRegular() { ch <- DiffMessage{ - FirstURL: newFirstURL, - SecondURL: newSecondURL, + FirstURL: newFirstURLStr, + SecondURL: newSecondURLStr, Diff: "type", } continue } - doDiffObjects(newFirstURL, newSecondURL, ch) + doDiffObjects(newFirstURLStr, newSecondURLStr, ch) } } } // End of for-loop } func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan DiffMessage) { - firstURLDelimited := firstClnt.URL().String() - secondURLDelimited := secondClnt.URL().String() + firstURLDelimited := firstClnt.GetURL().String() + secondURLDelimited := secondClnt.GetURL().String() if strings.HasSuffix(firstURLDelimited, "/") == false { firstURLDelimited = firstURLDelimited + "/" } @@ -249,13 +255,16 @@ func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan DiffMessage) { f, fok = <-fch continue } - firstURL := firstURLDelimited + f.Content.Name - secondURL := secondURLDelimited + f.Content.Name + url := f.Content.URL + firstURLStr := url.String() + secondURL := secondClnt.GetURL() + secondURL.Path = url.Path + secondURLStr := secondURL.String() if sok == false { // Second list reached EOF ch <- DiffMessage{ - FirstURL: firstURL, - SecondURL: secondURL, + FirstURL: firstURLStr, + SecondURL: secondURLStr, Diff: "only-in-first", } f, fok = <-fch @@ -272,42 +281,42 @@ func dodiffRecursive(firstClnt, secondClnt client.Client, ch chan DiffMessage) { } fC := f.Content sC := s.Content - if fC.Name == sC.Name { + if fC.URL.Path == sC.URL.Path { if fC.Type.IsRegular() { if !sC.Type.IsRegular() { ch <- DiffMessage{ - FirstURL: firstURL, - SecondURL: secondURL, + FirstURL: firstURLStr, + SecondURL: secondURLStr, Diff: "type", } } } else if fC.Type.IsDir() { if !sC.Type.IsDir() { ch <- DiffMessage{ - FirstURL: firstURL, - SecondURL: secondURL, + FirstURL: firstURLStr, + SecondURL: secondURLStr, Diff: "type", } } } else if fC.Size != sC.Size { ch <- DiffMessage{ - FirstURL: firstURL, - SecondURL: secondURL, + FirstURL: firstURLStr, + SecondURL: secondURLStr, Diff: "size", } } f, fok = <-fch s, sok = <-sch } - if fC.Name < sC.Name { + if fC.URL.Path < sC.URL.Path { ch <- DiffMessage{ - FirstURL: firstURL, - SecondURL: secondURL, + FirstURL: firstURLStr, + SecondURL: secondURLStr, Diff: "only-in-first", } f, fok = <-fch } - if fC.Name > sC.Name { + if fC.URL.Path > sC.URL.Path { s, sok = <-sch } } diff --git a/ls-main.go b/ls-main.go index 7656a909..d2006812 100644 --- a/ls-main.go +++ b/ls-main.go @@ -136,7 +136,7 @@ func mainList(ctx *cli.Context) { fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") err = doListIncomplete(clnt, isURLRecursive(targetURL), len(targetURLs) > 1) - fatalIf(err.Trace(clnt.URL().String()), "Unable to list target ‘"+clnt.URL().String()+"’.") + fatalIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.") } } else { targetURLs, err = args2URLs(args) @@ -148,7 +148,7 @@ func mainList(ctx *cli.Context) { fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") err = doList(clnt, isURLRecursive(targetURL), len(targetURLs) > 1) - fatalIf(err.Trace(clnt.URL().String()), "Unable to list target ‘"+clnt.URL().String()+"’.") + fatalIf(err.Trace(clnt.GetURL().String()), "Unable to list target ‘"+clnt.GetURL().String()+"’.") } } diff --git a/ls.go b/ls.go index 678888ef..8a7f4052 100644 --- a/ls.go +++ b/ls.go @@ -20,7 +20,6 @@ import ( "encoding/json" "fmt" "os" - "path/filepath" "runtime" "strings" "time" @@ -84,20 +83,20 @@ func parseContent(c *client.Content) ContentMessage { content.Name = func() string { switch { case runtime.GOOS == "windows": - c.Name = strings.Replace(c.Name, "/", "\\", -1) - c.Name = strings.TrimSuffix(c.Name, "\\") + c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1) + c.URL.Path = strings.TrimSuffix(c.URL.Path, "\\") default: - c.Name = strings.TrimSuffix(c.Name, "/") + c.URL.Path = strings.TrimSuffix(c.URL.Path, "/") } if c.Type.IsDir() { switch { case runtime.GOOS == "windows": - return fmt.Sprintf("%s\\", c.Name) + return fmt.Sprintf("%s\\", c.URL.Path) default: - return fmt.Sprintf("%s/", c.Name) + return fmt.Sprintf("%s/", c.URL.Path) } } - return c.Name + return c.URL.Path }() return content } @@ -106,15 +105,9 @@ func parseContent(c *client.Content) ContentMessage { func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error { var err *probe.Error var parentContent *client.Content - urlStr := clnt.URL().String() - parentDir := url2Dir(urlStr) - parentClnt, err := url2Client(parentDir) + _, parentContent, err = url2Stat(clnt.GetURL().String()) if err != nil { - return err.Trace(clnt.URL().String()) - } - parentContent, err = parentClnt.Stat() - if err != nil { - return err.Trace(clnt.URL().String()) + return err.Trace(clnt.GetURL().String()) } for contentCh := range clnt.List(recursive, false) { if contentCh.Err != nil { @@ -144,8 +137,18 @@ func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error { err = contentCh.Err.Trace() break } - if multipleArgs && parentContent.Type.IsDir() { - contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name)) + // if not recursive trim prefixes + if !recursive { + if parentContent.Type.IsDir() { + prefix := func() string { + trimmedPrefix := strings.TrimSuffix(parentContent.URL.Path, string(parentContent.URL.Separator)) + string(parentContent.URL.Separator) + if trimmedPrefix == string(parentContent.URL.Path) { + return "" + } + return trimmedPrefix + }() + contentCh.Content.URL.Path = strings.TrimPrefix(contentCh.Content.URL.Path, prefix) + } } printMsg(parseContent(contentCh.Content)) } @@ -158,11 +161,6 @@ func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error { // doListIncomplete - list all incomplete uploads entities inside a folder. func doListIncomplete(clnt client.Client, recursive, multipleArgs bool) *probe.Error { var err *probe.Error - var parentContent *client.Content - parentContent, err = clnt.Stat() - if err != nil { - return err.Trace(clnt.URL().String()) - } for contentCh := range clnt.List(recursive, true) { if contentCh.Err != nil { switch contentCh.Err.ToGoError().(type) { @@ -187,9 +185,6 @@ func doListIncomplete(clnt client.Client, recursive, multipleArgs bool) *probe.E err = contentCh.Err.Trace() break } - if multipleArgs && parentContent.Type.IsDir() { - contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name)) - } printMsg(parseContent(contentCh.Content)) } if err != nil { diff --git a/mirror-main.go b/mirror-main.go index c7afe8da..156ecf9e 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -95,28 +95,28 @@ func doMirror(sURLs mirrorURLs, progressReader interface{}, mirrorQueueCh <-chan } if !globalQuietFlag && !globalJSONFlag { - progressReader.(*barSend).SetCaption(sURLs.SourceContent.Name + ": ") + progressReader.(*barSend).SetCaption(sURLs.SourceContent.URL.String() + ": ") } - reader, length, err := getSource(sURLs.SourceContent.Name) + reader, length, err := getSource(sURLs.SourceContent.URL.String()) if err != nil { if !globalQuietFlag && !globalJSONFlag { progressReader.(*barSend).ErrorGet(int64(length)) } - sURLs.Error = err.Trace(sURLs.SourceContent.Name) + sURLs.Error = err.Trace(sURLs.SourceContent.URL.String()) statusCh <- sURLs return } var targetURLs []string for _, targetContent := range sURLs.TargetContents { - targetURLs = append(targetURLs, targetContent.Name) + targetURLs = append(targetURLs, targetContent.URL.String()) } var newReader io.ReadCloser if globalQuietFlag || globalJSONFlag { printMsg(mirrorMessage{ - Source: sURLs.SourceContent.Name, + Source: sURLs.SourceContent.URL.String(), Targets: targetURLs, }) newReader = progressReader.(*accounter).NewProxyReader(reader) @@ -189,7 +189,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) { } fmt.Fprintln(dataFP, string(jsonData)) if !globalQuietFlag && !globalJSONFlag { - scanBar(sURLs.SourceContent.Name) + scanBar(sURLs.SourceContent.URL.String()) } totalBytes += sURLs.SourceContent.Size @@ -252,14 +252,14 @@ func doMirrorSession(session *sessionV2) { return } if sURLs.Error == nil { - session.Header.LastCopied = sURLs.SourceContent.Name + session.Header.LastCopied = sURLs.SourceContent.URL.String() session.Save() } else { // Print in new line and adjust to top so that we don't print over the ongoing progress bar if !globalQuietFlag && !globalJSONFlag { console.Eraseline() } - errorIf(sURLs.Error.Trace(), fmt.Sprintf("Failed to mirror ‘%s’.", sURLs.SourceContent.Name)) + errorIf(sURLs.Error.Trace(), fmt.Sprintf("Failed to mirror ‘%s’.", sURLs.SourceContent.URL.String())) // all the cases which are handled where session should be saved are contained in the following // switch case, we shouldn't be saving sessions for all errors since some errors might need to be // reported to user properly. @@ -293,7 +293,7 @@ func doMirrorSession(session *sessionV2) { for scanner.Scan() { var sURLs mirrorURLs json.Unmarshal([]byte(scanner.Text()), &sURLs) - if isCopied(sURLs.SourceContent.Name) { + if isCopied(sURLs.SourceContent.URL.String()) { doMirrorFake(sURLs, progressReader) } else { // Wait for other mirror routines to diff --git a/mirror-url.go b/mirror-url.go index 2587e5d3..1f5bd8f8 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -18,6 +18,7 @@ package main import ( "fmt" + "path/filepath" "strings" "github.com/minio/cli" @@ -66,7 +67,7 @@ func checkMirrorSyntax(ctx *cli.Context) { fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+newSrcURL+"’.") if !srcContent.Type.IsDir() { - fatalIf(errInvalidArgument().Trace(srcContent.Name, srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror.", srcURL)) + fatalIf(errInvalidArgument().Trace(srcContent.URL.String(), srcContent.Type.String()), fmt.Sprintf("Source ‘%s’ is not a folder. Only folders are supported by mirror.", srcURL)) } if len(tgtURLs) == 0 && tgtURLs == nil { @@ -126,7 +127,7 @@ func getTargetContent(srcContent *client.Content, targetContent *client.Content, } for ; c != nil; c = getContent(targetCh) { - if srcContent.Name <= c.Name { + if srcContent.URL.Path <= c.URL.Path { break } } @@ -162,7 +163,7 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan return } // special case, be extremely careful before changing this behavior - will lead to data loss - newTargetURL := strings.TrimSuffix(targetURL, string(targetClient.URL().Separator)) + string(targetClient.URL().Separator) + newTargetURL := strings.TrimSuffix(targetURL, string(targetClient.GetURL().Separator)) + string(targetClient.GetURL().Separator) targetClient, err = url2Client(newTargetURL) if err != nil { mirrorURLsCh <- mirrorURLs{Error: err.Trace(newTargetURL)} @@ -185,8 +186,9 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan targetContents[i] = getTargetContent(srcContent, targetContents[i], targetChs[i]) // either target reached EOF or target does not have source content - if targetContents[i] == nil || srcContent.Name != targetContents[i].Name { - mirrorTargets = append(mirrorTargets, &client.Content{Name: newTargetURLs[i] + srcContent.Name}) + if targetContents[i] == nil || srcContent.URL.Path != targetContents[i].URL.Path { + targetURL := client.NewURL(filepath.Join(newTargetURLs[i], srcContent.URL.Path)) + mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL}) continue } @@ -194,7 +196,8 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan if srcContent.Type.IsRegular() && targetContents[i].Type.IsRegular() { // but size mismatches if srcContent.Size != targetContents[i].Size { - mirrorTargets = append(mirrorTargets, &client.Content{Name: newTargetURLs[i] + srcContent.Name}) + targetURL := client.NewURL(filepath.Join(newTargetURLs[i], srcContent.URL.Path)) + mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL}) } continue } @@ -203,7 +206,6 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan // TODO: add error } if len(mirrorTargets) > 0 { - srcContent.Name = newSourceURL + srcContent.Name mirrorURLsCh <- mirrorURLs{ SourceContent: srcContent, TargetContents: mirrorTargets, diff --git a/pkg/client/client.go b/pkg/client/client.go index 8ec30f90..421efd90 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -46,8 +46,8 @@ type Client interface { // Delete operations Remove(incomplete bool) *probe.Error - // URL returns back internal url - URL() *URL + // GetURL returns back internal url + GetURL() URL } // ContentOnChannel - List contents on channel @@ -58,7 +58,7 @@ type ContentOnChannel struct { // Content container for content metadata type Content struct { - Name string + URL URL Time time.Time Size int64 Type os.FileMode @@ -68,6 +68,7 @@ type Content struct { type Config struct { AccessKeyID string SecretAccessKey string + Signature string HostURL string AppName string AppVersion string diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index 88507d4b..cbdd270e 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -31,7 +31,7 @@ import ( ) type fsClient struct { - Path string + PathURL *client.URL } // New - instantiate a new fs client @@ -40,23 +40,23 @@ func New(path string) (client.Client, *probe.Error) { return nil, probe.NewError(client.EmptyPath{}) } return &fsClient{ - Path: normalizePath(path), + PathURL: client.NewURL(normalizePath(path)), }, nil } // URL get url -func (f *fsClient) URL() *client.URL { - return client.NewURL(f.Path) +func (f *fsClient) GetURL() client.URL { + return *f.PathURL } /// Object operations // fsStat - wrapper function to get file stat func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) { - fpath := f.Path + fpath := f.PathURL.Path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(fpath, string(f.URL().Separator)) { + if strings.HasSuffix(fpath, string(f.PathURL.Separator)) { fpath = fpath + "." } // Resolve symlinks @@ -102,8 +102,8 @@ func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) { // Put - create a new file func (f *fsClient) Put(size int64, data io.Reader) *probe.Error { - objectDir, _ := filepath.Split(f.Path) - objectPath := f.Path + objectDir, _ := filepath.Split(f.PathURL.Path) + objectPath := f.PathURL.Path if objectDir != "" { if err := os.MkdirAll(objectDir, 0700); err != nil { return probe.NewError(err) @@ -134,13 +134,13 @@ func (f *fsClient) Put(size int64, data io.Reader) *probe.Error { // get - download an object from bucket func (f *fsClient) get() (io.ReadCloser, int64, *probe.Error) { - body, err := os.Open(f.Path) + body, err := os.Open(f.PathURL.Path) if err != nil { return nil, 0, probe.NewError(err) } content, perr := f.getFSMetadata() if perr != nil { - return nil, content.Size, perr.Trace(f.Path) + return nil, content.Size, perr.Trace(f.PathURL.Path) } return body, content.Size, nil } @@ -161,10 +161,10 @@ func (f *fsClient) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error return nil, 0, probe.NewError(client.InvalidRange{Offset: offset}) } - tmppath := f.Path + tmppath := f.PathURL.Path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(tmppath, string(f.URL().Separator)) { + if strings.HasSuffix(tmppath, string(f.PathURL.Separator)) { tmppath = tmppath + "." } @@ -179,7 +179,7 @@ func (f *fsClient) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error if offset == 0 && length == 0 { return f.get() } - body, err := os.Open(f.Path) + body, err := os.Open(f.PathURL.Path) if err != nil { return nil, length, probe.NewError(err) @@ -195,7 +195,7 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error { if incomplete { return nil } - err := os.Remove(f.Path) + err := os.Remove(f.PathURL.Path) return probe.NewError(err) } @@ -220,10 +220,11 @@ func (f *fsClient) List(recursive, incomplete bool) <-chan client.ContentOnChann func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { defer close(contentCh) - fpath := f.Path + pathURL := *f.PathURL + fpath := pathURL.Path // Golang strips trailing / if you clean(..) or // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(fpath, string(f.URL().Separator)) { + if strings.HasSuffix(fpath, string(pathURL.Separator)) { fpath = fpath + "." } @@ -231,7 +232,7 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { if err != nil { contentCh <- client.ContentOnChannel{ Content: nil, - Err: err.Trace(f.Path), + Err: err.Trace(fpath), } return } @@ -279,9 +280,11 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { } continue } + pathURL := *f.PathURL + pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) contentCh <- client.ContentOnChannel{ Content: &client.Content{ - Name: lfi.Name(), + URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), Type: lfi.Mode(), @@ -313,8 +316,10 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { } } if fi.Mode().IsRegular() || fi.Mode().IsDir() { + pathURL := *f.PathURL + pathURL.Path = filepath.Join(pathURL.Path, fi.Name()) content := &client.Content{ - Name: fi.Name(), + URL: pathURL, Time: fi.ModTime(), Size: fi.Size(), Type: fi.Mode(), @@ -327,7 +332,7 @@ func (f *fsClient) listInRoutine(contentCh chan client.ContentOnChannel) { } default: content := &client.Content{ - Name: f.Path, + URL: pathURL, Time: fst.ModTime(), Size: fst.Size(), Type: fst.Mode(), @@ -343,9 +348,10 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel defer close(contentCh) var dirName string var filePrefix string + pathURL := *f.PathURL visitFS := func(fp string, fi os.FileInfo, err error) error { // if file path ends with os.PathSeparator and equals to root path, skip it. - if strings.HasSuffix(fp, string(f.URL().Separator)) { + if strings.HasSuffix(fp, string(pathURL.Separator)) { if fp == dirName { return nil } @@ -392,9 +398,11 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel } return nil } + pathURL := *f.PathURL + pathURL.Path = filepath.Join(pathURL.Path, dirName) contentCh <- client.ContentOnChannel{ Content: &client.Content{ - Name: strings.TrimPrefix(fp, dirName), + URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), Type: lfi.Mode(), @@ -428,9 +436,11 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel } return nil } + pathURL := *f.PathURL + pathURL.Path = filepath.Join(pathURL.Path, dirName) contentCh <- client.ContentOnChannel{ Content: &client.Content{ - Name: strings.TrimPrefix(fp, dirName), + URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), Type: lfi.Mode(), @@ -464,7 +474,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel } if fi.Mode().IsRegular() || fi.Mode().IsDir() { content := &client.Content{ - Name: strings.TrimPrefix(fp, dirName), + URL: *client.NewURL(fp), Time: fi.ModTime(), Size: fi.Size(), Type: fi.Mode(), @@ -479,18 +489,18 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel // No prefix to be filtered by default. filePrefix = "" // if f.Path ends with os.PathSeparator - assuming it to be a directory and moving on. - if strings.HasSuffix(f.Path, string(f.URL().Separator)) { - dirName = f.Path + if strings.HasSuffix(pathURL.Path, string(pathURL.Separator)) { + dirName = pathURL.Path } else { // if not a directory, take base path to navigate through WalkFunc. - dirName = filepath.Dir(f.Path) - if !strings.HasSuffix(dirName, string(f.URL().Separator)) { + dirName = filepath.Dir(pathURL.Path) + if !strings.HasSuffix(dirName, string(pathURL.Separator)) { // basepath truncates the os.PathSeparator, add it deligently - useful for trimming // file path inside WalkFunc - dirName = dirName + string(f.URL().Separator) + dirName = dirName + string(pathURL.Separator) } // filePrefix is kept for filtering incoming contents through WalkFunc. - filePrefix = f.Path + filePrefix = pathURL.Path } err := filepath.Walk(dirName, visitFS) if err != nil { @@ -503,7 +513,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan client.ContentOnChannel // MakeBucket - create a new bucket func (f *fsClient) MakeBucket() *probe.Error { - err := os.MkdirAll(f.Path, 0775) + err := os.MkdirAll(f.PathURL.Path, 0775) if err != nil { return probe.NewError(err) } @@ -527,7 +537,7 @@ func (f *fsClient) getFSMetadata() (content *client.Content, err *probe.Error) { return nil, err.Trace() } content = new(client.Content) - content.Name = f.Path + content.URL = *f.PathURL content.Size = st.Size() content.Time = st.ModTime() content.Type = st.Mode() diff --git a/pkg/client/fs/fs_test.go b/pkg/client/fs/fs_test.go index 2a8f218a..3e3de015 100644 --- a/pkg/client/fs/fs_test.go +++ b/pkg/client/fs/fs_test.go @@ -259,6 +259,5 @@ func (s *MySuite) TestStatObject(c *C) { content, perr := fsc.Stat() c.Assert(perr, IsNil) - c.Assert(content.Name, Equals, objectPath) c.Assert(content.Size, Equals, int64(dataLen)) } diff --git a/pkg/client/s3v4/s3v4.go b/pkg/client/s3/s3.go similarity index 83% rename from pkg/client/s3v4/s3v4.go rename to pkg/client/s3/s3.go index 3fcf9683..02ac787e 100644 --- a/pkg/client/s3v4/s3v4.go +++ b/pkg/client/s3/s3.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3v4 +package s3 import ( "errors" @@ -23,6 +23,7 @@ import ( "os" "path/filepath" "strings" + "sync" "time" "github.com/minio/mc/pkg/client" @@ -32,6 +33,7 @@ import ( ) type s3Client struct { + mu *sync.Mutex api minio.API hostURL *client.URL } @@ -41,13 +43,24 @@ func New(config *client.Config) (client.Client, *probe.Error) { u := client.NewURL(config.HostURL) transport := http.DefaultTransport if config.Debug == true { - transport = httptracer.GetNewTraceTransport(NewTrace(), http.DefaultTransport) + if config.Signature == "S3v4" { + transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport) + } + if config.Signature == "S3v2" { + transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport) + } } s3Conf := minio.Config{ AccessKeyID: config.AccessKeyID, SecretAccessKey: config.SecretAccessKey, Transport: transport, Endpoint: u.Scheme + u.SchemeSeparator + u.Host, + Signature: func() minio.SignatureType { + if config.Signature == "S3v2" { + return minio.SignatureV2 + } + return minio.SignatureV4 + }(), } s3Conf.AccessKeyID = config.AccessKeyID s3Conf.SecretAccessKey = config.SecretAccessKey @@ -58,12 +71,12 @@ func New(config *client.Config) (client.Client, *probe.Error) { if err != nil { return nil, probe.NewError(err) } - return &s3Client{api: api, hostURL: u}, nil + return &s3Client{api: api, hostURL: u, mu: new(sync.Mutex)}, nil } -// URL get url -func (c *s3Client) URL() *client.URL { - return c.hostURL +// GetURL get url +func (c *s3Client) GetURL() client.URL { + return *c.hostURL } // Get - get object @@ -192,6 +205,7 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error { // Stat - send a 'HEAD' on a bucket or object to get its metadata func (c *s3Client) Stat() (*client.Content, *probe.Error) { + c.mu.Lock() objectMetadata := new(client.Content) bucket, object := c.url2BucketAndObject() switch { @@ -199,10 +213,12 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) { case bucket == "" && object == "": for bucket := range c.api.ListBuckets() { if bucket.Err != nil { + c.mu.Unlock() return nil, probe.NewError(bucket.Err) } } - return &client.Content{Type: os.ModeDir}, nil + c.mu.Unlock() + return &client.Content{URL: *c.hostURL, Type: os.ModeDir}, nil } if object != "" { metadata, err := c.api.StatObject(bucket, object) @@ -210,32 +226,37 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) { errResponse := minio.ToErrorResponse(err) if errResponse != nil { if errResponse.Code == "NoSuchKey" { + c.mu.Unlock() for content := range c.List(false, false) { if content.Err != nil { return nil, content.Err.Trace() } + content.Content.URL = *c.hostURL content.Content.Type = os.ModeDir - content.Content.Name = object content.Content.Size = 0 return content.Content, nil } } } + c.mu.Unlock() return nil, probe.NewError(err) } - objectMetadata.Name = metadata.Key + objectMetadata.URL = *c.hostURL objectMetadata.Time = metadata.LastModified objectMetadata.Size = metadata.Size objectMetadata.Type = os.FileMode(0664) + c.mu.Unlock() return objectMetadata, nil } err := c.api.BucketExists(bucket) if err != nil { + c.mu.Unlock() return nil, probe.NewError(err) } bucketMetadata := new(client.Content) - bucketMetadata.Name = bucket + bucketMetadata.URL = *c.hostURL bucketMetadata.Type = os.ModeDir + c.mu.Unlock() return bucketMetadata, nil } @@ -246,9 +267,13 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { // // For the time being this check is introduced for S3, // if you have custom virtual styled hosts please. list them below - match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host) - switch { - case match == true: + matchS3, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host) + if matchS3 { + hostSplits := strings.SplitN(c.hostURL.Host, ".", 2) + path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path + } + matchGoogle, _ := filepath.Match("*.storage.googleapis.com", c.hostURL.Host) + if matchGoogle { hostSplits := strings.SplitN(c.hostURL.Host, ".", 2) path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path } @@ -271,6 +296,9 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { // List - list at delimited path, if not recursive func (c *s3Client) List(recursive, incomplete bool) <-chan client.ContentOnChannel { + c.mu.Lock() + defer c.mu.Unlock() + contentCh := make(chan client.ContentOnChannel) if incomplete { if recursive { @@ -301,8 +329,10 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan client.ContentOnChanne } return } + url := *c.hostURL + url.Path = filepath.Join(url.Path, bucket.Stat.Name) content := new(client.Content) - content.Name = bucket.Stat.Name + content.URL = url content.Size = 0 content.Time = bucket.Stat.CreationDate content.Type = os.ModeDir @@ -321,17 +351,18 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan client.ContentOnChanne return } content := new(client.Content) - normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator) - normalizedKey := object.Stat.Key - if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix) - } - content.Name = normalizedKey switch { case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)): + // We need to keep the trailing Separator, do not use filepath.Join() + url := *c.hostURL + url.Path = url.Path + object.Stat.Key + content.URL = url content.Time = time.Now() content.Type = os.ModeDir default: + url := *c.hostURL + url.Path = filepath.Join(url.Path, object.Stat.Key) + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.Initiated content.Type = os.ModeTemporary @@ -366,7 +397,9 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan client.Conten return } content := new(client.Content) - content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key) + url := *c.hostURL + url.Path = filepath.Join(url.Path, bucket.Stat.Name, object.Stat.Key) + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.Initiated content.Type = os.ModeTemporary @@ -385,22 +418,10 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan client.Conten } return } + url := *c.hostURL + url.Path = filepath.Join(url.Path, object.Stat.Key) content := new(client.Content) - normalizedKey := object.Stat.Key - switch { - case o == "": - // if no prefix provided and also URL is not delimited then we add bucket back into object name - if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 { - if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b { - normalizedKey = filepath.Join(b, object.Stat.Key) - } - } - default: - if strings.HasSuffix(o, string(c.hostURL.Separator)) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, o) - } - } - content.Name = normalizedKey + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.Initiated content.Type = os.ModeTemporary @@ -425,8 +446,10 @@ func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { } return } + url := *c.hostURL + url.Path = filepath.Join(url.Path, bucket.Stat.Name) content := new(client.Content) - content.Name = bucket.Stat.Name + content.URL = url content.Size = 0 content.Time = bucket.Stat.CreationDate content.Type = os.ModeDir @@ -440,7 +463,7 @@ func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { switch err.(type) { case nil: content := new(client.Content) - content.Name = metadata.Key + content.URL = *c.hostURL content.Time = metadata.LastModified content.Size = metadata.Size content.Type = os.FileMode(0664) @@ -458,17 +481,18 @@ func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { return } content := new(client.Content) - normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator) - normalizedKey := object.Stat.Key - if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix) - } - content.Name = normalizedKey switch { case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)): + // We need to keep the trailing Separator, do not use filepath.Join() + url := *c.hostURL + url.Path = strings.TrimSuffix(url.Path, string(c.hostURL.Separator)) + string(c.hostURL.Separator) + strings.TrimPrefix(object.Stat.Key, o) + content.URL = url content.Time = time.Now() content.Type = os.ModeDir default: + url := *c.hostURL + url.Path = filepath.Join(url.Path, strings.TrimPrefix(object.Stat.Key, o)) + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.LastModified content.Type = os.FileMode(0664) @@ -504,7 +528,9 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel return } content := new(client.Content) - content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key) + url := *c.hostURL + url.Path = filepath.Join(url.Path, bucket.Stat.Name, object.Stat.Key) + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.LastModified content.Type = os.FileMode(0664) @@ -524,21 +550,9 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel return } content := new(client.Content) - normalizedKey := object.Stat.Key - switch { - case o == "": - // if no prefix provided and also URL is not delimited then we add bucket back into object name - if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 { - if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b { - normalizedKey = filepath.Join(b, object.Stat.Key) - } - } - default: - if strings.HasSuffix(o, string(c.hostURL.Separator)) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, o) - } - } - content.Name = normalizedKey + url := *c.hostURL + url.Path = filepath.Join(url.Path, strings.TrimPrefix(object.Stat.Key, o)) + content.URL = url content.Size = object.Stat.Size content.Time = object.Stat.LastModified content.Type = os.FileMode(0664) diff --git a/pkg/client/s3v4/s3v4_test.go b/pkg/client/s3/s3_test.go similarity index 96% rename from pkg/client/s3v4/s3v4_test.go rename to pkg/client/s3/s3_test.go index 414eea58..83b862a0 100644 --- a/pkg/client/s3v4/s3v4_test.go +++ b/pkg/client/s3/s3_test.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3v4 +package s3 // bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests import ( @@ -143,13 +143,12 @@ func (s *MySuite) TestBucketOperations(c *C) { err = s3c.SetBucketAccess("public-read-write") c.Assert(err, IsNil) - conf.HostURL = server.URL + string(s3c.URL().Separator) + conf.HostURL = server.URL + string(s3c.GetURL().Separator) s3c, err = New(conf) c.Assert(err, IsNil) for content := range s3c.List(false, false) { c.Assert(content.Err, IsNil) - c.Assert(content.Content.Name, Equals, "bucket") c.Assert(content.Content.Type.IsDir(), Equals, true) } @@ -159,7 +158,6 @@ func (s *MySuite) TestBucketOperations(c *C) { for content := range s3c.List(false, false) { c.Assert(content.Err, IsNil) - c.Assert(content.Content.Name, Equals, "object") c.Assert(content.Content.Type.IsRegular(), Equals, true) } } @@ -182,7 +180,6 @@ func (s *MySuite) TestObjectOperations(c *C) { content, err := s3c.Stat() c.Assert(err, IsNil) - c.Assert(content.Name, Equals, "object") c.Assert(content.Size, Equals, int64(len(object.data))) c.Assert(content.Type.IsRegular(), Equals, true) diff --git a/pkg/client/s3v2/trace.go b/pkg/client/s3/trace_v2.go similarity index 83% rename from pkg/client/s3v2/trace.go rename to pkg/client/s3/trace_v2.go index 39672756..a396061d 100644 --- a/pkg/client/s3v2/trace.go +++ b/pkg/client/s3/trace_v2.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3v2 +package s3 import ( "net/http" @@ -25,16 +25,16 @@ import ( "github.com/minio/mc/pkg/httptracer" ) -// Trace - tracing structure -type Trace struct{} +// TraceV2 - tracing structure +type TraceV2 struct{} -// NewTrace - initialize Trace structure -func NewTrace() httptracer.HTTPTracer { - return Trace{} +// NewTraceV2 - initialize Trace structure +func NewTraceV2() httptracer.HTTPTracer { + return TraceV2{} } // Request - Trace HTTP Request -func (t Trace) 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 Trace) Request(req *http.Request) (err error) { } // Response - Trace HTTP Response -func (t Trace) Response(res *http.Response) (err error) { +func (t TraceV2) Response(res *http.Response) (err error) { resTrace, err := httputil.DumpResponse(res, false) // Only display header if err == nil { console.Debug(string(resTrace)) diff --git a/pkg/client/s3v4/trace.go b/pkg/client/s3/trace_v4.go similarity index 87% rename from pkg/client/s3v4/trace.go rename to pkg/client/s3/trace_v4.go index a36b1a42..777ed5c1 100644 --- a/pkg/client/s3v4/trace.go +++ b/pkg/client/s3/trace_v4.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3v4 +package s3 import ( "net/http" @@ -26,16 +26,16 @@ import ( "github.com/minio/mc/pkg/httptracer" ) -// Trace - tracing structure -type Trace struct{} +// TraceV4 - tracing structure +type TraceV4 struct{} -// NewTrace - initialize Trace structure -func NewTrace() httptracer.HTTPTracer { - return Trace{} +// NewTraceV4 - initialize Trace structure +func NewTraceV4() httptracer.HTTPTracer { + return TraceV4{} } // Request - Trace HTTP Request -func (t Trace) 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 Trace) Request(req *http.Request) (err error) { } // Response - Trace HTTP Response -func (t Trace) Response(res *http.Response) (err error) { +func (t TraceV4) Response(res *http.Response) (err error) { resTrace, err := httputil.DumpResponse(res, false) // Only display header if err == nil { console.Debug(string(resTrace)) diff --git a/pkg/client/s3v2/s3v2.go b/pkg/client/s3v2/s3v2.go deleted file mode 100644 index eb7bc92a..00000000 --- a/pkg/client/s3v2/s3v2.go +++ /dev/null @@ -1,553 +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 s3v2 - -import ( - "errors" - "io" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - "github.com/minio/mc/pkg/client" - "github.com/minio/mc/pkg/httptracer" - "github.com/minio/minio-go" - "github.com/minio/minio-xl/pkg/probe" -) - -type s3Client struct { - api minio.API - hostURL *client.URL -} - -// New returns an initialized s3Client structure. if debug use a internal trace transport -func New(config *client.Config) (client.Client, *probe.Error) { - u := client.NewURL(config.HostURL) - transport := http.DefaultTransport - if config.Debug == true { - transport = httptracer.GetNewTraceTransport(NewTrace(), http.DefaultTransport) - } - s3Conf := minio.Config{ - AccessKeyID: config.AccessKeyID, - SecretAccessKey: config.SecretAccessKey, - Transport: transport, - Endpoint: u.Scheme + u.SchemeSeparator + u.Host, - Signature: minio.SignatureV2, - } - s3Conf.AccessKeyID = config.AccessKeyID - s3Conf.SecretAccessKey = config.SecretAccessKey - s3Conf.Transport = transport - s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...) - s3Conf.Endpoint = u.Scheme + u.SchemeSeparator + u.Host - api, err := minio.New(s3Conf) - if err != nil { - return nil, probe.NewError(err) - } - return &s3Client{api: api, hostURL: u}, nil -} - -// URL get url -func (c *s3Client) URL() *client.URL { - return c.hostURL -} - -// Get - get object -func (c *s3Client) Get(offset, length int64) (io.ReadCloser, int64, *probe.Error) { - bucket, object := c.url2BucketAndObject() - reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length) - if err != nil { - return nil, length, probe.NewError(err) - } - return reader, metadata.Size, nil -} - -// Remove - remove object or bucket -func (c *s3Client) Remove(incomplete bool) *probe.Error { - bucket, object := c.url2BucketAndObject() - if incomplete { - errCh := c.api.RemoveIncompleteUpload(bucket, object) - return probe.NewError(<-errCh) - } - var err error - if object == "" { - err = c.api.RemoveBucket(bucket) - } else { - err = c.api.RemoveObject(bucket, object) - } - return probe.NewError(err) -} - -// Share - get a usable get object url to share -func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { - bucket, object := c.url2BucketAndObject() - presignedURL, err := c.api.PresignedGetObject(bucket, object, expires) - if err != nil { - return "", probe.NewError(err) - } - return presignedURL, nil -} - -func (c *s3Client) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) { - bucket, object := c.url2BucketAndObject() - p := minio.NewPostPolicy() - if err := p.SetExpires(time.Now().UTC().Add(expires)); err != nil { - return nil, probe.NewError(err) - } - if strings.TrimSpace(contentType) != "" || contentType != "" { - // No need to check for errors here, we have trimmed off the spaces - p.SetContentType(contentType) - } - if err := p.SetBucket(bucket); err != nil { - return nil, probe.NewError(err) - } - if recursive { - if err := p.SetKeyStartsWith(object); err != nil { - return nil, probe.NewError(err) - } - } else { - if err := p.SetKey(object); err != nil { - return nil, probe.NewError(err) - } - } - m, err := c.api.PresignedPostPolicy(p) - return m, probe.NewError(err) -} - -// Put - put object -func (c *s3Client) Put(size int64, data io.Reader) *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 - bucket, object := c.url2BucketAndObject() - err := c.api.PutObject(bucket, object, "application/octet-stream", size, data) - if err != nil { - errResponse := minio.ToErrorResponse(err) - if errResponse != nil { - if errResponse.Code == "MethodNotAllowed" { - return probe.NewError(client.ObjectAlreadyExists{Object: object}) - } - } - return probe.NewError(err) - } - return nil -} - -// MakeBucket - make a new bucket -func (c *s3Client) MakeBucket() *probe.Error { - bucket, object := c.url2BucketAndObject() - if object != "" { - return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()}) - } - if bucket == "" { - return probe.NewError(errors.New("Bucket name is empty.")) - } - - err := c.api.MakeBucket(bucket, minio.BucketACL("private")) - if err != nil { - return probe.NewError(err) - } - return nil -} - -// GetBucketAccess get canned acl on a bucket -func (c *s3Client) GetBucketAccess() (acl string, error *probe.Error) { - bucket, object := c.url2BucketAndObject() - if object != "" { - return "", probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()}) - } - bucketACL, err := c.api.GetBucketACL(bucket) - if err != nil { - return "", probe.NewError(err) - } - return bucketACL.String(), nil -} - -// SetBucketAccess set canned acl on a bucket -func (c *s3Client) SetBucketAccess(acl string) *probe.Error { - bucket, object := c.url2BucketAndObject() - if object != "" { - return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()}) - } - err := c.api.SetBucketACL(bucket, minio.BucketACL(acl)) - if err != nil { - return probe.NewError(err) - } - return nil -} - -// Stat - send a 'HEAD' on a bucket or object to get its metadata -func (c *s3Client) Stat() (*client.Content, *probe.Error) { - objectMetadata := new(client.Content) - bucket, object := c.url2BucketAndObject() - switch { - // valid case for s3/... - case bucket == "" && object == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - return nil, probe.NewError(bucket.Err) - } - } - return &client.Content{Type: os.ModeDir}, nil - } - if object != "" { - metadata, err := c.api.StatObject(bucket, object) - if err != nil { - errResponse := minio.ToErrorResponse(err) - if errResponse != nil { - if errResponse.Code == "NoSuchKey" { - for content := range c.List(false, false) { - if content.Err != nil { - return nil, content.Err.Trace() - } - content.Content.Type = os.ModeDir - content.Content.Name = object - content.Content.Size = 0 - return content.Content, nil - } - } - } - return nil, probe.NewError(err) - } - objectMetadata.Name = metadata.Key - objectMetadata.Time = metadata.LastModified - objectMetadata.Size = metadata.Size - objectMetadata.Type = os.FileMode(0664) - return objectMetadata, nil - } - err := c.api.BucketExists(bucket) - if err != nil { - return nil, probe.NewError(err) - } - bucketMetadata := new(client.Content) - bucketMetadata.Name = bucket - bucketMetadata.Type = os.ModeDir - return bucketMetadata, nil -} - -// url2BucketAndObject gives bucketName and objectName from URL path -func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { - path := c.hostURL.Path - // Convert any virtual host styled requests - // - // For the time being this check is introduced for S3, - // if you have custom virtual styled hosts please. list them below - match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host) - switch { - case match == true: - hostSplits := strings.SplitN(c.hostURL.Host, ".", 2) - path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path - } - - splits := strings.SplitN(path, string(c.hostURL.Separator), 3) - switch len(splits) { - case 0, 1: - bucketName = "" - objectName = "" - case 2: - bucketName = splits[1] - objectName = "" - case 3: - bucketName = splits[1] - objectName = splits[2] - } - return bucketName, objectName -} - -/// Bucket API operations - -// List - list at delimited path, if not recursive -func (c *s3Client) List(recursive, incomplete bool) <-chan client.ContentOnChannel { - contentCh := make(chan client.ContentOnChannel) - if incomplete { - if recursive { - go c.listIncompleteRecursiveInRoutine(contentCh) - } else { - go c.listIncompleteInRoutine(contentCh) - } - } else { - if recursive { - go c.listRecursiveInRoutine(contentCh) - } else { - go c.listInRoutine(contentCh) - } - } - return contentCh -} - -func (c *s3Client) listIncompleteInRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - b, o := c.url2BucketAndObject() - switch { - case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(bucket.Err), - } - return - } - content := new(client.Content) - content.Name = bucket.Stat.Name - content.Size = 0 - content.Time = bucket.Stat.CreationDate - content.Type = os.ModeDir - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - default: - for object := range c.api.ListIncompleteUploads(b, o, false) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator) - normalizedKey := object.Stat.Key - if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix) - } - content.Name = normalizedKey - switch { - case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)): - content.Time = time.Now() - content.Type = os.ModeDir - default: - content.Size = object.Stat.Size - content.Time = object.Stat.Initiated - content.Type = os.ModeTemporary - } - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } -} - -func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - b, o := c.url2BucketAndObject() - switch { - case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(bucket.Err), - } - return - } - for object := range c.api.ListIncompleteUploads(bucket.Stat.Name, o, true) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key) - content.Size = object.Stat.Size - content.Time = object.Stat.Initiated - content.Type = os.ModeTemporary - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } - default: - for object := range c.api.ListIncompleteUploads(b, o, true) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - normalizedKey := object.Stat.Key - switch { - case o == "": - // if no prefix provided and also URL is not delimited then we add bucket back into object name - if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 { - if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b { - normalizedKey = filepath.Join(b, object.Stat.Key) - } - } - default: - if strings.HasSuffix(o, string(c.hostURL.Separator)) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, o) - } - } - content.Name = normalizedKey - content.Size = object.Stat.Size - content.Time = object.Stat.Initiated - content.Type = os.ModeTemporary - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } -} - -func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - b, o := c.url2BucketAndObject() - switch { - case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(bucket.Err), - } - return - } - content := new(client.Content) - content.Name = bucket.Stat.Name - content.Size = 0 - content.Time = bucket.Stat.CreationDate - content.Type = os.ModeDir - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - default: - metadata, err := c.api.StatObject(b, o) - switch err.(type) { - case nil: - content := new(client.Content) - content.Name = metadata.Key - content.Time = metadata.LastModified - content.Size = metadata.Size - content.Type = os.FileMode(0664) - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - default: - for object := range c.api.ListObjects(b, o, false) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator) - normalizedKey := object.Stat.Key - if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix) - } - content.Name = normalizedKey - switch { - case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)): - content.Time = time.Now() - content.Type = os.ModeDir - default: - content.Size = object.Stat.Size - content.Time = object.Stat.LastModified - content.Type = os.FileMode(0664) - } - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } - } -} - -func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - b, o := c.url2BucketAndObject() - switch { - case b == "" && o == "": - for bucket := range c.api.ListBuckets() { - if bucket.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(bucket.Err), - } - return - } - for object := range c.api.ListObjects(bucket.Stat.Name, o, true) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key) - content.Size = object.Stat.Size - content.Time = object.Stat.LastModified - content.Type = os.FileMode(0664) - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } - default: - for object := range c.api.ListObjects(b, o, true) { - if object.Err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: probe.NewError(object.Err), - } - return - } - content := new(client.Content) - normalizedKey := object.Stat.Key - switch { - case o == "": - // if no prefix provided and also URL is not delimited then we add bucket back into object name - if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 { - if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b { - normalizedKey = filepath.Join(b, object.Stat.Key) - } - } - default: - if strings.HasSuffix(o, string(c.hostURL.Separator)) { - normalizedKey = strings.TrimPrefix(object.Stat.Key, o) - } - } - content.Name = normalizedKey - content.Size = object.Stat.Size - content.Time = object.Stat.LastModified - content.Type = os.FileMode(0664) - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } -} diff --git a/pkg/client/s3v2/s3v2_test.go b/pkg/client/s3v2/s3v2_test.go deleted file mode 100644 index 2da53313..00000000 --- a/pkg/client/s3v2/s3v2_test.go +++ /dev/null @@ -1,198 +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 s3v2 - -// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests -import ( - "bytes" - "io" - "net/http" - "net/http/httptest" - "strconv" - "testing" - "time" - - "github.com/minio/mc/pkg/client" - - . "gopkg.in/check.v1" -) - -type bucketHandler struct { - resource string -} - -func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - switch { - case r.URL.Path == "/": - response := []byte("bucket2015-05-20T23:05:09.230Zminiominio") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - case r.URL.Path == "/bucket": - response := []byte("259d04a13802ae09c7e41be50ccc6baaobject2015-05-21T18:24:21.097Z22061miniominioSTANDARDfalse1000testbucket") - w.Header().Set("Content-Length", strconv.Itoa(len(response))) - w.Write(response) - } - case r.Method == "PUT": - switch { - case r.URL.Path == h.resource: - _, ok := r.URL.Query()["acl"] - if ok { - if r.Header.Get("x-amz-acl") != "public-read-write" { - w.WriteHeader(http.StatusNotImplemented) - } - } - w.WriteHeader(http.StatusOK) - default: - w.WriteHeader(http.StatusBadRequest) - } - case r.Method == "HEAD": - switch { - case r.URL.Path == h.resource: - w.WriteHeader(http.StatusOK) - default: - w.WriteHeader(http.StatusForbidden) - } - } -} - -// objectHandler is an http.Handler that verifies object responses and validates incoming requests -type objectHandler struct { - resource string - data []byte -} - -func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "PUT": - length, err := strconv.Atoi(r.Header.Get("Content-Length")) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - var buffer bytes.Buffer - _, err = io.CopyN(&buffer, r.Body, int64(length)) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - if !bytes.Equal(h.data, buffer.Bytes()) { - w.WriteHeader(http.StatusInternalServerError) - return - } - w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") - w.WriteHeader(http.StatusOK) - case r.Method == "HEAD": - if r.URL.Path != h.resource { - w.WriteHeader(http.StatusNotFound) - return - } - w.Header().Set("Content-Length", strconv.Itoa(len(h.data))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) - w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") - w.WriteHeader(http.StatusOK) - case r.Method == "GET": - if r.URL.Path != h.resource { - w.WriteHeader(http.StatusNotFound) - return - } - w.Header().Set("Content-Length", strconv.Itoa(len(h.data))) - w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat)) - w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe") - w.WriteHeader(http.StatusOK) - io.Copy(w, bytes.NewReader(h.data)) - } -} - -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestBucketOperations(c *C) { - bucket := bucketHandler(bucketHandler{ - resource: "/bucket", - }) - server := httptest.NewServer(bucket) - defer server.Close() - - conf := new(client.Config) - conf.HostURL = server.URL + bucket.resource - s3c, err := New(conf) - c.Assert(err, IsNil) - - err = s3c.MakeBucket() - c.Assert(err, IsNil) - - err = s3c.SetBucketAccess("public-read-write") - c.Assert(err, IsNil) - - conf.HostURL = server.URL + string(s3c.URL().Separator) - s3c, err = New(conf) - c.Assert(err, IsNil) - - for content := range s3c.List(false, false) { - c.Assert(content.Err, IsNil) - c.Assert(content.Content.Name, Equals, "bucket") - c.Assert(content.Content.Type.IsDir(), Equals, true) - } - - conf.HostURL = server.URL + "/bucket" - s3c, err = New(conf) - c.Assert(err, IsNil) - - for content := range s3c.List(false, false) { - c.Assert(content.Err, IsNil) - c.Assert(content.Content.Name, Equals, "object") - c.Assert(content.Content.Type.IsRegular(), Equals, true) - } -} - -func (s *MySuite) TestObjectOperations(c *C) { - object := objectHandler(objectHandler{ - resource: "/bucket/object", - data: []byte("Hello, World"), - }) - server := httptest.NewServer(object) - defer server.Close() - - conf := new(client.Config) - conf.HostURL = server.URL + object.resource - s3c, err := New(conf) - c.Assert(err, IsNil) - - err = s3c.Put(int64(len(object.data)), bytes.NewReader(object.data)) - c.Assert(err, IsNil) - - content, err := s3c.Stat() - c.Assert(err, IsNil) - c.Assert(content.Name, Equals, "object") - 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))) - - var buffer bytes.Buffer - { - _, err := io.CopyN(&buffer, reader, int64(size)) - c.Assert(err, IsNil) - c.Assert(buffer.Bytes(), DeepEquals, object.data) - } -} diff --git a/pkg/client/url.go b/pkg/client/url.go index 1bf6c459..168e660c 100644 --- a/pkg/client/url.go +++ b/pkg/client/url.go @@ -118,7 +118,7 @@ func NewURL(urlStr string) *URL { } // String convert URL into its canonical form. -func (u *URL) String() string { +func (u URL) String() string { var buf bytes.Buffer // if fileystem no translation needed, return as is. if u.Type == Filesystem { diff --git a/rm-main.go b/rm-main.go index fb7b2ca2..2d733f1d 100644 --- a/rm-main.go +++ b/rm-main.go @@ -19,7 +19,6 @@ package main import ( "encoding/json" "fmt" - "path/filepath" "strings" "github.com/fatih/color" @@ -103,20 +102,20 @@ func rmList(url string) <-chan rmListOnChannel { } return nil, false } - if !ok || !strings.HasPrefix(entry.Content.Name, currentDir) { + if !ok || !strings.HasPrefix(entry.Content.URL.Path, currentDir) { return entry.Content, ok } if entry.Content.Type.IsRegular() { rmListCh <- rmListOnChannel{ - keyName: entry.Content.Name, + keyName: entry.Content.URL.String(), err: nil, } } if entry.Content.Type.IsDir() { var content *client.Content - content, ok = depthFirst(entry.Content.Name) + content, ok = depthFirst(entry.Content.URL.String()) rmListCh <- rmListOnChannel{ - keyName: entry.Content.Name, + keyName: entry.Content.URL.String(), err: nil, } entry = client.ContentOnChannel{ @@ -149,24 +148,21 @@ func rmSingle(url string, rmPrint rmPrinterFunc) { } func rmAll(url string, rmPrint rmPrinterFunc) { - urlDir := url2Dir(url) for rmListCh := range rmList(url) { if rmListCh.err != nil { // if rmList throws an error die here. fatalIf(rmListCh.err.Trace(), "Unable to list : "+url+" .") } - newURL := client.NewURL(urlDir) - newURL.Path = filepath.Join(newURL.Path, rmListCh.keyName) - newClnt, err := url2Client(newURL.String()) + newClnt, err := url2Client(rmListCh.keyName) if err != nil { - errorIf(err.Trace(newURL.String()), "Unable to create client object : "+newURL.String()+" .") + errorIf(err.Trace(rmListCh.keyName), "Unable to create client object : "+rmListCh.keyName+" .") continue } err = newClnt.Remove(false) if err == nil { rmPrint(rmMessage{rmListCh.keyName}) } - errorIf(err.Trace(newURL.String()), "Unable to remove : "+newURL.String()+" .") + errorIf(err.Trace(rmListCh.keyName), "Unable to remove : "+rmListCh.keyName+" .") } } @@ -190,10 +186,8 @@ func rmAllIncompleteUploads(url string, rmPrint rmPrinterFunc) { errorIf(err.Trace(url), "Unable to get client object for "+url+" .") return } - urlDir := url2Dir(url) for entry := range clnt.List(true, true) { - newURL := client.NewURL(urlDir) - newURL.Path = filepath.Join(newURL.Path, entry.Content.Name) + newURL := entry.Content.URL newClnt, err := url2Client(newURL.String()) if err != nil { errorIf(err.Trace(newURL.String()), "Unable to create client object : "+newURL.String()+" .") @@ -201,7 +195,7 @@ func rmAllIncompleteUploads(url string, rmPrint rmPrinterFunc) { } err = newClnt.Remove(true) if err == nil { - rmPrint(rmMessage{entry.Content.Name}) + rmPrint(rmMessage{newURL.String()}) } errorIf(err.Trace(newURL.String()), "Unable to remove : "+newURL.String()+" .") } diff --git a/share-download-main.go b/share-download-main.go index 1dffd5a0..0da3859f 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -110,7 +110,7 @@ func doShareDownloadURL(targetURL string, recursive bool, expires time.Duration) return contentCh.Err.Trace() } var newClnt client.Client - newClnt, err = url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name)) + newClnt, err = url2Client(contentCh.Content.URL.String()) if err != nil { return err.Trace() } @@ -122,12 +122,12 @@ func doShareDownloadURL(targetURL string, recursive bool, expires time.Duration) shareMessage := ShareMessage{ Expiry: expires, DownloadURL: sharedURL, - Key: newClnt.URL().String(), + Key: newClnt.GetURL().String(), } shareMessageV3 := ShareMessageV3{ Expiry: expires, DownloadURL: sharedURL, - Key: newClnt.URL().String(), + Key: newClnt.GetURL().String(), } sURLs.URLs = append(sURLs.URLs, struct { Date time.Time diff --git a/share.go b/share.go index b0e5e437..e2b873e2 100644 --- a/share.go +++ b/share.go @@ -192,31 +192,6 @@ func createSharedURLsDataFile() *probe.Error { return nil } -func getNewTargetURL(targetParser *client.URL, name string) string { - match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host) - if match { - targetParser.Path = string(targetParser.Separator) + name - } else { - targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name - } - return targetParser.String() -} - -// this code is necessary since, share only operates on cloud storage URLs not filesystem -func path2Bucket(u *client.URL) (bucketName string) { - pathSplits := strings.SplitN(u.Path, "?", 2) - splits := strings.SplitN(pathSplits[0], string(u.Separator), 3) - switch len(splits) { - case 0, 1: - bucketName = "" - case 2: - bucketName = splits[1] - case 3: - bucketName = splits[1] - } - return bucketName -} - // this code is necessary since, share only operates on cloud storage URLs not filesystem func isObjectKeyPresent(url string) bool { u := client.NewURL(url) diff --git a/update-main.go b/update-main.go index e1dda2ab..bcd1c3e1 100644 --- a/update-main.go +++ b/update-main.go @@ -164,7 +164,7 @@ func getExperimentalUpdate() { fatalIf(errDummy().Trace(), "Unable to validate any experimental update available at this time. Please open an issue at https://github.com/minio/mc/issues") } - mcExperimentalURLParse := clnt.URL() + mcExperimentalURLParse := clnt.GetURL() downloadURL := (mcExperimentalURLParse.Scheme + "://" + mcExperimentalURLParse.Host + string(mcExperimentalURLParse.Separator) + @@ -210,7 +210,7 @@ func getReleaseUpdate() { fatalIf(errDummy().Trace(), "Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues") } - mcUpdateURLParse := clnt.URL() + mcUpdateURLParse := clnt.GetURL() downloadURL := mcUpdateURLParse.Scheme + "://" + mcUpdateURLParse.Host + string(mcUpdateURLParse.Separator) + updates.Platforms[runtime.GOOS] updateMessage := UpdateMessage{ Download: downloadURL, diff --git a/url.go b/url.go index 5e362a37..5ee0ae67 100644 --- a/url.go +++ b/url.go @@ -85,17 +85,3 @@ func url2Stat(urlStr string) (client client.Client, content *client.Content, err } return client, content, nil } - -// just like filepath.Dir but always has a trailing url.Seperator -func url2Dir(urlStr string) string { - url := client.NewURL(urlStr) - if strings.HasSuffix(urlStr, string(url.Separator)) { - return urlStr - } - lastIndex := strings.LastIndex(urlStr, string(url.Separator)) - dirname := urlStr[:lastIndex+1] - if dirname == "" { - return "." - } - return dirname -}