From 0ab5e274569bd8c7b72dd7fcdd52606a3d6ff08f Mon Sep 17 00:00:00 2001 From: Winch Ram Date: Wed, 28 Oct 2015 10:33:17 +0530 Subject: [PATCH] mirror: refactor session creation Previously session creation was written in a way to work unsorted source and targets content, but reality is source and targets give contents in sorted order always. This patch fixes session creation to use pre-sorted source and targets content. Signed-off-by: Winch Ram --- cp_mirror_test.go | 25 +----- globals.go | 2 - mirror-url.go | 212 ++++++++++++++++++++++------------------------ sorted-list.go | 172 ------------------------------------- 4 files changed, 100 insertions(+), 311 deletions(-) delete mode 100644 sorted-list.go diff --git a/cp_mirror_test.go b/cp_mirror_test.go index 8fda8d27..8411de5a 100644 --- a/cp_mirror_test.go +++ b/cp_mirror_test.go @@ -16,12 +16,7 @@ package main -import ( - "os" - - "github.com/minio/mc/pkg/console" - . "gopkg.in/check.v1" -) +import . "gopkg.in/check.v1" func (s *TestSuite) TestCopyURLType(c *C) { sourceURLs := []string{server.URL + "/bucket/object1"} @@ -52,21 +47,3 @@ func (s *TestSuite) TestCopyURLType(c *C) { targetURL = "" c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid) } - -func (s *TestSuite) TestCopyContext(c *C) { - err := app.Run([]string{os.Args[0], "cp", server.URL + "/invalid...", server.URL + "/bucket"}) - c.Assert(err, IsNil) - c.Assert(console.IsError, Equals, true) - - // reset back - console.IsError = false -} - -func (s *TestSuite) TestMirrorContext(c *C) { - err := app.Run([]string{os.Args[0], "mirror", server.URL + "/invalid...", server.URL + "/bucket"}) - c.Assert(err, IsNil) - c.Assert(console.IsError, Equals, true) - - // reset back - console.IsError = false -} diff --git a/globals.go b/globals.go index 41a4b5ae..473836f3 100644 --- a/globals.go +++ b/globals.go @@ -37,8 +37,6 @@ const ( globalSessionDir = "session" globalSharedURLsDataDir = "share" - golbalSortedListDir = "sortedlist" - // default access and secret key // do not pass accesskeyid and secretaccesskey through cli // users should manually edit them, add a stub entry diff --git a/mirror-url.go b/mirror-url.go index 11a1666c..b7550b59 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -18,13 +18,10 @@ package main import ( "fmt" - "strconv" "strings" - "time" "github.com/minio/cli" "github.com/minio/mc/pkg/client" - "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" ) @@ -97,135 +94,124 @@ func checkMirrorSyntax(ctx *cli.Context) { } } -func deltaSourceTargets(sourceClnt client.Client, targetClnts []client.Client) <-chan mirrorURLs { - mirrorURLsCh := make(chan mirrorURLs) +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 + } - go func() { - defer close(mirrorURLsCh) - id := newRandomID(8) + c = rv.Content + break + } - doneCh := make(chan bool) - defer close(doneCh) - go func(doneCh <-chan bool) { - cursorCh := cursorAnimate() - for { - select { - case <-time.Tick(100 * time.Millisecond): - if !globalQuietFlag && !globalJSONFlag { - console.PrintC("\r" + "Scanning.. " + string(<-cursorCh)) - } - case <-doneCh: - return - } - } - }(doneCh) + return +} - sourceSortedList := sortedList{} - targetSortedList := make([]*sortedList, len(targetClnts)) +func getTargetContent(srcContent *client.Content, targetContent *client.Content, targetCh <-chan client.ContentOnChannel) (c *client.Content) { + if srcContent == nil { + // nothing to do for empty source content + return + } - surldelimited := sourceClnt.URL().String() - err := sourceSortedList.Create(sourceClnt, id+".src") + if targetContent == nil { + c = getContent(targetCh) + } else { + c = targetContent + } + + for ; c != nil; c = getContent(targetCh) { + if srcContent.Name <= c.Name { + break + } + } + + return +} + +func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan<- mirrorURLs) { + defer close(mirrorURLsCh) + + newSourceURL := stripRecursiveURL(sourceURL) + if strings.HasSuffix(newSourceURL, "/") == false { + newSourceURL = newSourceURL + "/" + } + sourceClient, err := url2Client(newSourceURL) + 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(), - } + mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)} return } - - turldelimited := make([]string, len(targetClnts)) - for i := range targetClnts { - turldelimited[i] = targetClnts[i].URL().String() - targetSortedList[i] = &sortedList{} - err := targetSortedList[i].Create(targetClnts[i], id+"."+strconv.Itoa(i)) - if err != nil { - // FIXME: do cleanup by calling Delete() - mirrorURLsCh <- mirrorURLs{ - Error: err.Trace(), - } - return - } + // targets have to be directory + if !targetContent.Type.IsDir() { + mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace()} + return } - for source := range sourceSortedList.List(true) { - if source.Content.Type.IsDir() { + // 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) + targetClient, err = url2Client(newTargetURL) + if err != nil { + mirrorURLsCh <- mirrorURLs{Error: err.Trace(newTargetURL)} + return + } + 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]) + + // 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}) continue } - targetContents := make([]*client.Content, 0, len(targetClnts)) - for i, t := range targetSortedList { - match, err := t.Match(source.Content) - if err != nil || match { - // continue on io.EOF or if the keys matches - // FIXME: handle other errors and ignore this target for future calls - continue - } - targetContents = append(targetContents, &client.Content{Name: turldelimited[i] + source.Content.Name}) - } - source.Content.Name = surldelimited + source.Content.Name - if len(targetContents) > 0 { - mirrorURLsCh <- mirrorURLs{ - SourceContent: source.Content, - TargetContents: targetContents, + + // source and target have same content + 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}) } + continue } + + // source and target have different content type + // TODO: add error } - if err := sourceSortedList.Delete(); err != nil { + if len(mirrorTargets) > 0 { + srcContent.Name = newSourceURL + srcContent.Name mirrorURLsCh <- mirrorURLs{ - Error: err.Trace(), + SourceContent: srcContent, + TargetContents: mirrorTargets, } } - for _, t := range targetSortedList { - if err := t.Delete(); err != nil { - mirrorURLsCh <- mirrorURLs{ - Error: err.Trace(), - } - } - } - doneCh <- true - if !globalQuietFlag && !globalJSONFlag { - console.Eraseline() - } - }() - return mirrorURLsCh + } } -// prepareMirrorURLs - prepares target and source URLs for mirroring. func prepareMirrorURLs(sourceURL string, targetURLs []string) <-chan mirrorURLs { mirrorURLsCh := make(chan mirrorURLs) - - go func() { - defer close(mirrorURLsCh) - sourceURL = stripRecursiveURL(sourceURL) - if strings.HasSuffix(sourceURL, "/") == false { - sourceURL = sourceURL + "/" - } - sourceClnt, err := url2Client(sourceURL) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceURL)} - return - } - targetClnts := make([]client.Client, len(targetURLs)) - for i, targetURL := range targetURLs { - targetClnt, targetContent, err := url2Stat(targetURL) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetURL)} - return - } - // if one of the targets is not dir exit - if !targetContent.Type.IsDir() { - mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace()} - return - } - // special case, be extremely careful before changing this behavior - will lead to data loss - newTargetURL := strings.TrimSuffix(targetURL, string(targetClnt.URL().Separator)) + string(targetClnt.URL().Separator) - targetClnt, err = url2Client(newTargetURL) - if err != nil { - mirrorURLsCh <- mirrorURLs{Error: err.Trace(newTargetURL)} - return - } - targetClnts[i] = targetClnt - } - for sURLs := range deltaSourceTargets(sourceClnt, targetClnts) { - mirrorURLsCh <- sURLs - } - }() + go deltaSourceTargets(sourceURL, targetURLs, mirrorURLsCh) return mirrorURLsCh } diff --git a/sorted-list.go b/sorted-list.go deleted file mode 100644 index 8266b041..00000000 --- a/sorted-list.go +++ /dev/null @@ -1,172 +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 main - -import ( - "encoding/gob" - "fmt" - "io" - "os" - "path/filepath" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio-xl/pkg/probe" -) - -type sortedList struct { - name string - file *os.File - dec *gob.Decoder - enc *gob.Encoder - current client.Content -} - -func getSortedListDir() (string, *probe.Error) { - configDir, err := getMcConfigDir() - if err != nil { - return "", err.Trace() - } - sortedListDir := filepath.Join(configDir, golbalSortedListDir) - return sortedListDir, nil -} - -func createSortedListDir() *probe.Error { - sortedListDir, err := getSortedListDir() - if err != nil { - return err.Trace() - } - if _, err := os.Stat(sortedListDir); err == nil { - return nil - } - if err := os.MkdirAll(sortedListDir, 0700); err != nil { - return probe.NewError(err) - } - return nil -} - -// Create create an on disk sorted file from clnt -func (sl *sortedList) Create(clnt client.Client, id string) *probe.Error { - var e error - if err := createSortedListDir(); err != nil { - return err.Trace() - } - sortedListDir, err := getSortedListDir() - if err != nil { - return err.Trace() - } - sl.name = filepath.Join(sortedListDir, id) - sl.file, e = os.OpenFile(sl.name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666) - if e != nil { - return probe.NewError(e) - } - sl.enc = gob.NewEncoder(sl.file) - sl.dec = gob.NewDecoder(sl.file) - for content := range clnt.List(true, false) { - if content.Err != nil { - switch err := content.Err.ToGoError().(type) { - case client.BrokenSymlink: - // FIXME: send the error to caller using channel - errorIf(content.Err.Trace(), fmt.Sprintf("Skipping broken symlink ‘%s’.", err.Path)) - continue - case client.TooManyLevelsSymlink: - // FIXME: send the error to caller using channel - errorIf(content.Err.Trace(), fmt.Sprintf("Skipping too many levels symlink ‘%s’.", err.Path)) - continue - } - if os.IsNotExist(content.Err.ToGoError()) || os.IsPermission(content.Err.ToGoError()) { - // FIXME: abstract this at fs.go layer - if content.Content != nil { - if content.Content.Type.IsDir() && (content.Content.Type&os.ModeSymlink == os.ModeSymlink) { - errorIf(content.Err.Trace(), fmt.Sprintf("Skipping broken folder symlink ‘%s’.", content.Content.Name)) - continue - } - errorIf(content.Err.Trace(), fmt.Sprintf("Skipping ‘%s’.", content.Content.Name)) - continue - } - errorIf(content.Err.Trace(), "Skipping unknown file.") - continue - } - return content.Err.Trace() - } - sl.enc.Encode(*content.Content) - } - if _, err := sl.file.Seek(0, os.SEEK_SET); err != nil { - return probe.NewError(err) - } - return nil -} - -// List list the entries from the sorted file -func (sl sortedList) List(recursive bool) <-chan client.ContentOnChannel { - ch := make(chan client.ContentOnChannel) - go func() { - defer close(ch) - for { - var c client.Content - err := sl.dec.Decode(&c) - if err == io.EOF { - break - } - if err != nil { - ch <- client.ContentOnChannel{Content: nil, Err: probe.NewError(err)} - break - } - ch <- client.ContentOnChannel{Content: &c, Err: nil} - } - }() - return ch -} - -func (sl *sortedList) Match(source *client.Content) (bool, *probe.Error) { - if len(sl.current.Name) == 0 { - // for the first time read - if err := sl.dec.Decode(&sl.current); err != nil { - if err != io.EOF { - return false, probe.NewError(err) - } - return false, nil - } - } - for { - if source.Name == sl.current.Name { - if source.Type.IsRegular() && sl.current.Type.IsRegular() && source.Size == sl.current.Size { - return true, nil - } - return false, nil - } - if source.Name < sl.current.Name { - return false, nil - } - // assign zero values to fields because if s.current's previous decode had non zero value - // fields it will not be over written if this loop's decode does not contain those fields - sl.current = client.Content{} - if err := sl.dec.Decode(&sl.current); err != nil { - return false, probe.NewError(err) - } - } -} - -// Delete close and delete the ondisk file -func (sl sortedList) Delete() *probe.Error { - if err := sl.file.Close(); err != nil { - return probe.NewError(err) - } - if err := os.Remove(sl.name); err != nil { - return probe.NewError(err) - } - return nil -}