diff --git a/cp_mirror_test.go b/cp_mirror_test.go index c0d93c70..cc789fd6 100644 --- a/cp_mirror_test.go +++ b/cp_mirror_test.go @@ -86,14 +86,12 @@ func (s *TestSuite) TestMirror(c *C) { // reset back console.IsExited = false - err = app.Run([]string{os.Args[0], "mirror", filepath.Join(source, ".."), filepath.Join(target, "random")}) + err = app.Run([]string{os.Args[0], "mirror", source + "..", filepath.Join(target, "random")}) c.Assert(err, IsNil) // in case of invalid arguments both are set - c.Assert(console.IsError, Equals, true) c.Assert(console.IsExited, Equals, true) // reset back - console.IsError = false console.IsExited = false } diff --git a/diff-main.go b/diff-main.go index 9755e6fe..b29c4dde 100644 --- a/diff-main.go +++ b/diff-main.go @@ -38,10 +38,13 @@ USAGE: EXAMPLES: 1. Compare foo.ogg on a local filesystem with bar.ogg on Amazon AWS cloud storage. - $ mc {{.Name}} foo.ogg https://s3.amazonaws.com/jukebox/bar.ogg + $ mc {{.Name}} foo.ogg https://bucketName.s3.amazonaws.com/jukebox/bar.ogg - 2. Compare two different folders on a local filesystem. + 2. Compare two different folders on a local filesystem with out recursion. $ mc {{.Name}} ~/Photos /Media/Backup/Photos + + 2. Compare two different folders recursively. + $ mc {{.Name}} ~/Photos/... https://bucketName.s3.amazonaws.com/Photos `, } @@ -69,14 +72,14 @@ func doDiffMain(firstURL, secondURL string, recursive bool) <-chan diffMessage { // doDiffInRoutine run diff in a go-routine sending back messages over all channel. func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diffMessage) { defer close(ch) - firstClnt, firstContent, err := url2Stat(firstURL) + _, firstContent, err := url2Stat(firstURL) if err != nil { ch <- diffMessage{ Error: err.Trace(firstURL), } return } - secondClnt, secondContent, err := url2Stat(secondURL) + _, secondContent, err := url2Stat(secondURL) if err != nil { ch <- diffMessage{ Error: err.Trace(secondURL), @@ -100,12 +103,7 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diffMes } return } - // definitely first and second target are folders - if recursive { - diffFoldersRecursive(firstClnt, secondClnt, ch) - return - } - diffFolders(firstClnt, secondClnt, ch) + diffFolders(firstURL, secondURL, recursive, ch) } // mainDiff main for 'diff'. @@ -140,5 +138,4 @@ func mainDiff(ctx *cli.Context) { if !globalQuietFlag && !globalJSONFlag { console.Eraseline() } - console.Println(console.Colorize("DiffMessage", "Done.")) } diff --git a/diff.go b/diff.go index 9906e447..16675f2e 100644 --- a/diff.go +++ b/diff.go @@ -18,7 +18,6 @@ package main import ( "encoding/json" - "path/filepath" "strings" "github.com/minio/mc/pkg/client" @@ -126,83 +125,51 @@ func diffObjects(firstContent, secondContent *client.Content) *diffMessage { return nil } -// diffFolders - diff of contents of two folders only top level content. -// -// 3: diff(d1, d2) -> []diff(d1/f, d2/f) -> VALID -func diffFolders(firstClnt, secondClnt client.Client, outCh chan<- diffMessage) { - recursive := false - // Range on the List to consume incoming content - for contentCh := range firstClnt.List(recursive, false) { - if contentCh.Err != nil { - outCh <- diffMessage{ - Error: contentCh.Err.Trace(firstClnt.GetURL().String()), - } - continue - } - // Store incoming content - newFirstContent := contentCh.Content - newFirstURLStr := newFirstContent.URL.String() - // Construct the second URL. - newSecondURL := secondClnt.GetURL() - // Need to verify the same path from first URL, construct the second URL - newSecondURL.Path = filepath.Join(newSecondURL.Path, filepath.Base(contentCh.Content.URL.Path)) - newSecondURLStr := newSecondURL.String() - // Send a stat to verify - _, newSecondContent, err := url2Stat(newSecondURLStr) - if err != nil { - outCh <- diffMessage{ - FirstURL: newFirstURLStr, - SecondURL: newSecondURLStr, - Diff: "only-in-first", - } - continue - } - diffMsg := diffObjects(newFirstContent, newSecondContent) - if diffMsg != nil { - outCh <- *diffMsg - continue - } - } // Reached EOF -} +// calculate difference between two folders +// recursive - indicates whether the difference should be calculated at the top +// level or if it should recurse into sub-directories +func diffFolders(sourceURL string, targetURL string, recursive bool, outCh chan<- diffMessage) { + // source and targets are always directories + sourceSeparator := string(client.NewURL(sourceURL).Separator) + if !strings.HasSuffix(sourceURL, sourceSeparator) { + sourceURL = sourceURL + sourceSeparator + } + targetSeparator := string(client.NewURL(targetURL).Separator) + if !strings.HasSuffix(targetURL, targetSeparator) { + targetURL = targetURL + targetSeparator + } -// diffFoldersRecursive diff folders for all files recursively. -// -// 4: diff(d1..., d2) -> []diff(d1/f, d2/f) -> VALID. -func diffFoldersRecursive(firstClnt, secondClnt client.Client, outCh chan<- diffMessage) { - var scanBar scanBarFunc - if !globalQuietFlag && !globalJSONFlag { // set up progress bar - scanBar = scanBarFactory() + sourceClient, err := url2Client(sourceURL) + if err != nil { + outCh <- diffMessage{Error: err.Trace(sourceURL)} + return } - recursive := true - firstListCh := firstClnt.List(recursive, false) // Copy first list channel. - for firstContentCh := range firstListCh { - if firstContentCh.Err != nil { - outCh <- diffMessage{Error: firstContentCh.Err.Trace()} + difference, err := objectDifferenceFactory(targetURL, recursive) + if err != nil { + outCh <- diffMessage{Error: err.Trace(targetURL)} + return + } + for sourceContent := range sourceClient.List(recursive, false) { + if sourceContent.Err != nil { + outCh <- diffMessage{Error: sourceContent.Err.Trace()} continue } - if firstContentCh.Content.Type.IsDir() { - // Skip directories there is no concept of directories on S3. + if sourceContent.Content.Type.IsDir() { continue } - firstContent := firstContentCh.Content - secondURL := secondClnt.GetURL() - secondURL.Path = filepath.Join(secondURL.Path, - strings.TrimPrefix(firstContent.URL.Path, url2Dir(firstClnt.GetURL().Path))) - _, secondContent, err := url2Stat(secondURL.String()) + suffix := strings.TrimPrefix(sourceContent.Content.URL.String(), sourceURL) + differ, err := difference(suffix, sourceContent.Content.Type, sourceContent.Content.Size) if err != nil { - outCh <- diffMessage{ - FirstURL: firstContent.URL.String(), - SecondURL: secondURL.String(), - Diff: "only-in-first", - } + outCh <- diffMessage{Error: err.Trace()} continue } - if diffMsg := diffObjects(firstContent, secondContent); diffMsg != nil { - outCh <- *diffMsg + if differ == differNone { continue } - if !globalQuietFlag && !globalJSONFlag { // set up progress bar - scanBar(firstContent.URL.String()) + outCh <- diffMessage{ + FirstURL: sourceContent.Content.URL.String(), + SecondURL: urlJoinPath(targetURL, suffix), + Diff: differ, } } } diff --git a/diff_test.go b/diff_test.go index 116c0a5a..05add3b4 100644 --- a/diff_test.go +++ b/diff_test.go @@ -59,32 +59,49 @@ func (s *TestSuite) TestDiffDirs(c *C) { /// filesystem root1, e := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(e, IsNil) + subDir1 := filepath.Join(root1, "subDir") + e = os.Mkdir(subDir1, 0755) + c.Assert(e, IsNil) defer os.RemoveAll(root1) root2, e := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(e, IsNil) + subDir2 := filepath.Join(root2, "subDir") + e = os.Mkdir(subDir2, 0755) defer os.RemoveAll(root2) var err *probe.Error for i := 0; i < 10; i++ { - objectPath := filepath.Join(root1, "object"+strconv.Itoa(i)) + objectPath1 := filepath.Join(root1, "object"+strconv.Itoa(i)) + objectPath2 := filepath.Join(subDir1, "object"+strconv.Itoa(i)) + data := "hello" dataLen := len(data) - err = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data))) + err = putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data))) + c.Assert(err, IsNil) + err = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(err, IsNil) } for i := 0; i < 10; i++ { - objectPath := filepath.Join(root2, "object"+strconv.Itoa(i)) + objectPath1 := filepath.Join(root2, "object"+strconv.Itoa(i)) + objectPath2 := filepath.Join(subDir2, "object"+strconv.Itoa(i)) data := "hello" dataLen := len(data) - err = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data))) + err = putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data))) + c.Assert(err, IsNil) + err = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(err, IsNil) } + // non-recursive for diff := range doDiffMain(root1, root2, false) { c.Assert(diff.Error, IsNil) } + // recursive + for diff := range doDiffMain(root1, root2, true) { + c.Assert(diff.Error, IsNil) + } } func (s *TestSuite) TestDiffContext(c *C) { diff --git a/difference.go b/difference.go new file mode 100644 index 00000000..f0e4d2e6 --- /dev/null +++ b/difference.go @@ -0,0 +1,88 @@ +/* + * 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 main + +import ( + "os" + + "github.com/minio/mc/pkg/client" + "github.com/minio/minio-xl/pkg/probe" +) + +// objectDifference function finds the difference between object on source and target +// it takes suffix string, type and size on the source +// objectDifferenceFactory returns objectDifference function +type objectDifference func(string, os.FileMode, int64) (string, *probe.Error) + +const ( + differSize string = "size" // differs in size + differOnlyFirst string = "only-in-first" // only on source + differType string = "type" // differs in type, ex file/directory + differNone string = "" // does not differ +) + +// objectDifferenceFactory returns objectDifference function to check for difference +// between sourceURL and targetURL +// for usage reference check diff and mirror commands +func objectDifferenceFactory(targetURL string, recursive bool) (objectDifference, *probe.Error) { + clnt, err := url2Client(targetURL) + if err != nil { + return nil, err.Trace(targetURL) + } + isIncomplete := false + ch := clnt.List(recursive, isIncomplete) + current := targetURL + reachedEOF := false + ok := false + var content client.ContentOnChannel + + difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) { + if reachedEOF { + // would mean the suffix is not on target + return differOnlyFirst, nil + } + expected := urlJoinPath(targetURL, suffix) + for { + if expected < current { + return differOnlyFirst, nil // not available in the target + } + if expected == current { + tgtType := content.Content.Type + tgtSize := content.Content.Size + if srcType.IsRegular() && !tgtType.IsRegular() { + // Type differes. Source is never a directory + return differType, nil + } + if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize { + // regular files differing in size + return differSize, nil + } + return differNone, nil // available in the target + } + content, ok = <-ch + if content.Err != nil { + return "", content.Err.Trace() + } + if !ok { + reachedEOF = true + return differOnlyFirst, nil + } + current = content.Content.URL.String() + } + } + return difference, nil +} diff --git a/mirror-url.go b/mirror-url.go index 4afb48fb..fbad96b4 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -18,6 +18,7 @@ package main import ( "fmt" + "path/filepath" "strings" "github.com/minio/cli" @@ -98,137 +99,86 @@ func checkMirrorSyntax(ctx *cli.Context) { } } -func getContent(ch <-chan client.ContentOnChannel) (c *client.Content) { - for rv := range ch { - if rv.Err != nil { - continue - } - if rv.Content.Type.IsDir() { - // ignore directories. - continue - } - c = rv.Content - break - } - return -} - -func getTargetContent(srcContent *client.Content, targetContent *client.Content, targetCh <-chan client.ContentOnChannel, targetClnt client.Client) (c *client.Content) { - if srcContent == nil { - // nothing to do for empty source content. - return - } - - if targetContent == nil { - c = getContent(targetCh) - } else { - c = targetContent - } - - for ; c != nil; c = getContent(targetCh) { - // Remove prefix so that we can properly validate. - targetURL := strings.TrimPrefix(c.URL.Path, targetClnt.GetURL().Path) - sourceURL := strings.TrimPrefix(srcContent.URL.Path, string(srcContent.URL.Separator)) - if sourceURL <= targetURL { - break - } - } - return -} - func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan<- mirrorURLs) { defer close(mirrorURLsCh) + sourceURL = stripRecursiveURL(sourceURL) + sourceBaseDir := "" - newSourceURL := stripRecursiveURL(sourceURL) - if strings.HasSuffix(newSourceURL, "/") == false { - newSourceURL = newSourceURL + "/" + // source and targets are always directories + sourceSeparator := string(client.NewURL(sourceURL).Separator) + if !strings.HasSuffix(sourceURL, sourceSeparator) { + // if source is dir1/dir2/dir3 and target is dir4/dir5/dir6 then we should copy dir3/* into dir4/dir5/dir6/dir3/ + // if source is dir1/dir2/dir3/ and target is dir4/dir5/dir6 then we should copy dir3/* into dir4/dir5/dir6/ + // sourceBaseDir is used later for this purpose + sourceBaseDir = filepath.Base(sourceURL) + sourceURL = sourceURL + sourceSeparator + } + for i, url := range targetURLs { + targetSeparator := string(client.NewURL(url).Separator) + if !strings.HasSuffix(url, targetSeparator) { + targetURLs[i] = url + targetSeparator + } } - sourceClient, err := url2Client(newSourceURL) + // array of objectDifference functions corresponding to their targetURL + objectDifferenceArray := make([]objectDifference, len(targetURLs)) + + for i := range targetURLs { + var err *probe.Error + objectDifferenceArray[i], err = objectDifferenceFactory(targetURLs[i], true) + if err != nil { + mirrorURLsCh <- mirrorURLs{Error: err.Trace()} + return + } + } + + sourceClient, err := url2Client(sourceURL) if err != nil { mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceURL)} return } - targetLen := len(targetURLs) - newTargetURLs := make([]string, targetLen) - targetClients := make([]client.Client, targetLen) - for i, targetURL := range targetURLs { - targetClient, targetContent, err := url2Stat(targetURL) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)} - return + for sourceContent := range sourceClient.List(true, false) { + if sourceContent.Err != nil { + mirrorURLsCh <- mirrorURLs{Error: sourceContent.Err.Trace()} + continue } - // targets have to be directory. - if !targetContent.Type.IsDir() { - mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace(newSourceURL)} - return + if sourceContent.Content.Type.IsDir() { + continue } - // special case, be extremely careful before changing this behavior - will lead to data loss. - 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)} - return + suffix := strings.TrimPrefix(sourceContent.Content.URL.String(), sourceURL) + if sourceBaseDir != "" { + suffix = urlJoinPath(sourceBaseDir, suffix) } - targetClients[i] = targetClient - newTargetURLs[i] = newTargetURL - } - - targetChs := make([]<-chan client.ContentOnChannel, targetLen) - for i, targetClient := range targetClients { - targetChs[i] = targetClient.List(true, false) - } - targetContents := make([]*client.Content, targetLen) - - srcCh := sourceClient.List(true, false) - for srcContent := getContent(srcCh); srcContent != nil; srcContent = getContent(srcCh) { - var mirrorTargets []*client.Content - for i := range targetChs { - targetContents[i] = getTargetContent(srcContent, targetContents[i], targetChs[i], targetClients[i]) - - // Remove prefix so that we can properly validate. - var newTargetURLPath string - if targetContents[i] != nil { - newTargetURLPath = strings.TrimPrefix(targetContents[i].URL.Path, targetClients[i].GetURL().Path) - } - // Trim any preceding separators. - newSourceURLPath := strings.TrimPrefix(srcContent.URL.Path, string(srcContent.URL.Separator)) - // either target reached EOF or target does not have source content. - if targetContents[i] == nil || newSourceURLPath != newTargetURLPath { - targetURL := client.NewURL(urlJoinPath(newTargetURLs[i], srcContent.URL.String())) - mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL}) + targetContents := []*client.Content{} + for i, difference := range objectDifferenceArray { + differ, err := difference(suffix, sourceContent.Content.Type, sourceContent.Content.Size) + if err != nil { + mirrorURLsCh <- mirrorURLs{Error: err.Trace()} continue } - - if newSourceURLPath == newTargetURLPath { - // source and target have same content type. - if srcContent.Type.IsRegular() && targetContents[i].Type.IsRegular() { - if srcContent.Size != targetContents[i].Size { - if !mirrorIsForce { - mirrorURLsCh <- mirrorURLs{ - Error: errOverWriteNotAllowed(targetContents[i].URL.String()).Trace(srcContent.URL.String()), - } - continue - } - targetURL := client.NewURL(urlJoinPath(newTargetURLs[i], srcContent.URL.String())) - mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL}) - } - continue - } - if srcContent.Type.IsRegular() && !targetContents[i].Type.IsRegular() { - // but type mismatches, error condition fail and continue. - mirrorURLsCh <- mirrorURLs{ - Error: errInvalidTarget(targetContents[i].URL.String()).Trace(srcContent.URL.String()), - } - continue - } + if differ == differNone { + // no difference, continue + continue } + if differ == differType { + mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)} + continue + } + if differ == differSize && !mirrorIsForce { + // size differs and force not set + mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.Content.URL.String())} + continue + } + // either available only in source or size differs and force is set + targetPath := urlJoinPath(targetURLs[i], suffix) + targetContent := client.Content{URL: *client.NewURL(targetPath)} + targetContents = append(targetContents, &targetContent) } - if len(mirrorTargets) > 0 { + if len(targetContents) > 0 { mirrorURLsCh <- mirrorURLs{ - SourceContent: srcContent, - TargetContents: mirrorTargets, + SourceContent: sourceContent.Content, + TargetContents: targetContents, } } }